Black FridaySpecial - USA & Europe - 100 MBPS: $999.00 instead of $2,000.00. Coupon: BLACKFRIDAY, until November 27.See the plan
WeProxy
Guide

AI Agent Web Scraping: Managing Proxies with WeProxy MCP and the REST API

11 min read

An AI agent gets proxy lines with the get_proxies tool on WeProxy MCP, writes the script and runs it. Rotating vs sticky, bulk proxies with count, formats and whitelist, refreshing the list over the REST API, 429 and the 120 calls per minute limit, quota checks and a Python example.

Key takeaways

  • The WeProxy AI Access MCP server does not open pages; it generates proxy lines with get_proxies and manages quota and the IP whitelist. The script the agent writes and runs fetches the pages.
  • Use rotating sessions for independent product pages and sticky sessions for login, cart and multi-step forms; sticky_minutes ranges from 1 to 1440, default 30.
  • get_proxies generates 1–1000 lines per call and generating lines is free; quota is only deducted for traffic that flows through a proxy.
  • The API limit is 120 calls per minute per key and proxy traffic does not count toward it; on a 429 from the API, wait for Retry-After.
  • The script should read the key from the WEPROXY_KEY environment variable, check quota with GET /v1/quota before starting and call get_proxies again after a top-up.

In AI agent web scraping, the agent fetches proxy lines with the get_proxies tool on the WeProxy AI Access MCP server, writes a Python script that uses those lines and runs the script in its own environment. The pages are opened by the script the agent wrote; the MCP server generates proxy lists and manages quota and the IP whitelist. Use a rotating session for independent product pages and a sticky session for step-by-step flows such as login or checkout. In long-running jobs, the script refreshes its proxy list from the REST API (https://mcp.weproxy.io/v1) on its own and checks the remaining quota before it starts.

The workflow here starts from an example request in the WeProxy AI Access documentation: “Write a Python script that scrapes these 50 product pages with US proxies.” In clients that can run code, such as Claude Code and Cursor, the request is handled in three steps: get proxies, write the script, run it. WeProxy AI Access currently works only with Premium Rotating Residential orders; support for other products is coming soon.

How do you set up the WeProxy MCP server?

Open your Premium Rotating Residential order in the client area, create a key starting with wpk_ on the “AI (MCP) / API” tab, pick your tool and copy the configuration. Each key is tied to a single order. In Claude Code, setup is one command: claude mcp add --transport http weproxy https://mcp.weproxy.io/mcp --header "Authorization: Bearer wpk_YOUR_KEY". Configurations for Cursor and Claude Desktop, the URL method for clients that cannot send headers, and the full tool list are in the WeProxy AI Access documentation. If you do not have an order yet, you can start with the 1 GB free trial. The keyless catalog MCP on the website is a separate server that only returns product and pricing information (MCP integration).

What steps does the agent take in the 50 product pages example?

When the user writes the request, the agent first decides what kind of job it is. The 50 product pages are independent of each other: each page is read with a single GET request and carries no cookies or session. So the agent calls get_proxies with country: "us", session: "rotating" and format: "http_url". The proxies array in the response contains ready-to-use lines; each line is a proxy URL shaped like http://user:[email protected]:1000.

Next, the agent writes a script, has it read the URL list from a file and runs it. In a well-built workflow, the agent does not paste proxy lines into the script. The lines contain a username and password and should not end up in code, logs or chat history. A sturdier approach is to let the script fetch the proxy list from the REST API itself at runtime. Saying so in the request is enough: “Don’t hardcode proxies; have the script fetch them from the REST API at runtime using the WEPROXY_KEY environment variable.”

Which tool handles which request:

User requestToolREST equivalent
“How much proxy quota do I have left?”get_quotaGET /v1/quota
“Write a Python script that scrapes these 50 product pages with US proxies.”get_proxiesPOST /v1/proxies
“Which regions are available for California?”list_statesGET /v1/countries/{country}/states
“Add my server’s IP to the whitelist: 203.0.113.10”add_whitelist_ipPOST /v1/whitelist
“How much traffic did I use this week?”get_usageGET /v1/usage?period=week

Rotating or sticky: how do you choose the session type?

In a rotating session, every request leaves from a new IP in the pool. It suits jobs that finish in one request, such as product pages, category listings and search results; if a request is blocked, the next attempt already goes out from a different IP. In a sticky session, the same IP is kept for sticky_minutes. The value ranges from 1 to 1440 minutes, and the API uses 30 when it is omitted. Flows where you log in, add items to a cart or fill in a multi-step form need every step to go out from the same IP. Otherwise the site may drop the session or ask for extra verification.

ScenarioSessionSuggested setting
Independent product pages, price and stock checksrotatingcount 10–50, random line per worker
Search results, category pagesrotatingRetry a failed request with a new line
Account page that requires loginstickysticky_minutes slightly longer than the flow
Cart, pre-checkout steps, multi-page formsstickyOne line per flow, no sharing between flows
Walking through a paginated list in orderstickyShort duration, e.g. 10 minutes

In the documentation example, a call with session: "sticky", sticky_minutes: 10 and count: 2 returns:

{
  "ok": true,
  "format": "http_url",
  "auth": "user_pass",
  "session": "sticky",
  "sticky_minutes": 10,
  "country": "us",
  "state": "",
  "count": 2,
  "proxies": [
    "http://USER-region-US-sid-AbCd1234-t-10:[email protected]:1000",
    "http://USER-region-US-sid-XyZw5678-t-10:[email protected]:1000"
  ]
}

The two lines have different sid values, and t-10 matches the requested 10 minutes. In a sticky script, give each concurrent flow its own line. If two flows share a line, both sessions appear from the same IP. The broader picture is in the sticky vs rotating guide.

A short example of a sticky session with httpx:

import os
import httpx

API = "https://mcp.weproxy.io/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['WEPROXY_KEY']}"}

resp = httpx.post(f"{API}/proxies", headers=HEADERS, timeout=30, json={
    "country": "us",
    "session": "sticky",
    "sticky_minutes": 15,
    "format": "http_url",
    "count": 1,
})
resp.raise_for_status()
proxy = resp.json()["proxies"][0]

with httpx.Client(proxy=proxy, timeout=30) as client:
    client.post("https://example.com/login", data={
        "username": os.environ["SITE_USER"],
        "password": os.environ["SITE_PASS"],
    })
    orders = client.get("https://example.com/account/orders")
    print(orders.status_code)

httpx.Client keeps cookies between requests, and the sticky line keeps the IP fixed. Login credentials are read from environment variables here as well.

Getting proxies in bulk with count and choosing a format

get_proxies generates between 1 and 1000 lines in a single call. Generating lines is free; quota is only deducted for traffic that flows through a proxy. So instead of one call per URL, get enough lines with a single call at the start of the job. A few dozen lines are usually enough for a rotating job, since the IP changes on every request anyway. For a sticky job, size the line count to the number of concurrent flows.

The format determines how the line is used in the script:

format valueLine shapeWhen
http_urlhttp://user:pass@host:portPython requests, httpx, Node.js; passed directly as the proxy URL
user:pass@host:port (default)No schemeTools that add http:// themselves
host:port:user:passColon-separatedList importers and antidetect browsers
host:port@user:passReversed orderTools that expect this shape
host:portNo credentialsServers added to the IP whitelist

In Python, http_url causes the fewest problems. The default format has no scheme, so passing it straight to the requests library raises an error. Format details are in the proxy formats guide.

If the scraper runs continuously on a server, the host:port format with an IP whitelist is cleaner. The line contains no username or password, so there is no password to leak into logs. You can add the server’s outbound IP by telling the agent “Add my server’s IP to the whitelist: 203.0.113.10”, which calls add_whitelist_ip, or directly over REST:

curl -X POST "https://mcp.weproxy.io/v1/whitelist" \
  -H "Authorization: Bearer $WEPROXY_KEY" \
  -H "Content-Type: application/json" \
  -d '{"ip": "203.0.113.10"}'

The whitelist accepts IPv4 and IPv6 addresses; list_whitelist shows registered addresses and remove_whitelist_ip deletes one. The trade-offs between username/password and whitelist are covered in the proxy authentication guide.

A Python script that gets proxies over the REST API

The script below is a simplified version of what the agent would write for the 50 product pages. It checks the quota, gets US rotating lines from the REST API, fetches pages with five worker threads, retries a failed request with another line and refreshes the list if proxy authentication is rejected. The key is not written into the code; it is read from the WEPROXY_KEY environment variable:

export WEPROXY_KEY="wpk_YOUR_KEY"
import os
import random
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed

import requests

API = "https://mcp.weproxy.io/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['WEPROXY_KEY']}"}
MIN_QUOTA_GB = 0.5
WORKERS = 5


def retry_after(resp, default=60):
    try:
        return int(resp.headers.get("Retry-After", default))
    except ValueError:
        return default


def api(method, path, **kwargs):
    for _ in range(3):
        r = requests.request(method, API + path, headers=HEADERS, timeout=30, **kwargs)
        if r.status_code == 429:
            time.sleep(retry_after(r))
            continue
        r.raise_for_status()
        return r.json()
    raise RuntimeError(f"{path}: API rate limit is still being exceeded")


class ProxyPool:
    def __init__(self, count=20):
        self.count = count
        self.lock = threading.Lock()
        self.last_refresh = 0.0
        self.proxies = []
        self.refresh(force=True)

    def refresh(self, force=False):
        with self.lock:
            if not force and time.monotonic() - self.last_refresh < 30:
                return
            data = api("POST", "/proxies", json={
                "country": "us",
                "session": "rotating",
                "format": "http_url",
                "count": self.count,
            })
            self.proxies = data["proxies"]
            self.last_refresh = time.monotonic()

    def pick(self):
        with self.lock:
            return random.choice(self.proxies)


def fetch(url, pool, attempts=4):
    for attempt in range(attempts):
        proxy = pool.pick()
        try:
            r = requests.get(url, proxies={"http": proxy, "https": proxy}, timeout=30)
        except requests.exceptions.ProxyError:
            pool.refresh()
            continue
        except requests.exceptions.RequestException:
            time.sleep(2 ** attempt)
            continue
        if r.status_code == 429:
            time.sleep(retry_after(r, default=5 * 2 ** attempt))
            continue
        if r.status_code >= 500:
            time.sleep(2 ** attempt)
            continue
        return r
    return None


def main():
    with open("urls.txt", encoding="utf-8") as f:
        urls = [line.strip() for line in f if line.strip()]

    quota = api("GET", "/quota")
    if quota["remaining_gb"] < MIN_QUOTA_GB:
        raise SystemExit(f"Remaining quota is low: {quota['remaining']}")

    pool = ProxyPool(count=20)
    os.makedirs("pages", exist_ok=True)

    with ThreadPoolExecutor(max_workers=WORKERS) as ex:
        futures = {ex.submit(fetch, url, pool): i for i, url in enumerate(urls)}
        for fut in as_completed(futures):
            i = futures[fut]
            r = fut.result()
            if r is None or r.status_code != 200:
                print("failed:", urls[i])
                continue
            with open(f"pages/{i:03d}.html", "w", encoding="utf-8") as out:
                out.write(r.text)

    print("Remaining quota:", api("GET", "/quota")["remaining"])


if __name__ == "__main__":
    main()

If ProxyPool.refresh is called a second time within 30 seconds, it does not send a new request. Even if all five workers hit a proxy error at once, only one call goes to the API. For HTTPS requests, ProxyError means the proxy rejected the connection or the authentication. Getting new lines helps in that case. For 429 and 5xx responses from the target site, waiting and retrying with another line is enough. Details on using proxies with requests, httpx and aiohttp are in How to Use a Proxy in Python.

Concurrency, retries and API limits

Two separate limits affect a scraper. The first is the WeProxy API limit: 120 calls per minute per key. get_proxies, get_quota and whitelist operations count toward it. Traffic passing through the proxies does not; fetching 50 or 5,000 pages does not change the number of API calls. The second is the target site’s limit: when a site receives too many requests in a short time it returns 429, and that code comes from the site, not from the proxy.

CodeSourceMeaningWhat the script should do
401WeProxy APIMissing or invalid key; an old key stops working after regenerationStop and check the key
403WeProxy APIOrder is not activeStop and check the order status in the client area
429WeProxy API120 calls per minute exceededWait for Retry-After (60 s)
400WeProxy APIInvalid parameter, e.g. count above 1000Fix the parameter
429Target siteThe site is throttling requestsWait and lower concurrency
5xx, timeoutTarget site or networkTemporary errorRetry with another line and a growing delay

Retrying on 401 and 403 does not change the outcome; the script should stop immediately on these codes. In the example above, raise_for_status() takes care of that. Start with low concurrency: five workers are enough for 50 pages. If 429 responses from the target start to increase, reduce the number of workers. How these codes map to different layers is explained in the proxy error codes guide.

Checking quota and refreshing proxy lines after a top-up

Premium Rotating Residential traffic is measured in GB. Before a large job, read the remaining quota with GET /v1/quota. The remaining_gb field in the response gives a number and remaining gives a readable string. In the example script, the job stops before it begins if quota is below the set threshold. In long jobs, repeating the same check every few hundred pages prevents a job from stopping halfway because the quota ran out. You can also ask the agent “How much proxy quota do I have left?” or “How much traffic did I use this week?” to see get_quota and get_usage results in the chat.

If the proxy account is renewed after you buy additional quota, previously generated lines may stop working. The API key stays the same; you only need to call get_proxies again. The ProxyError handler in the example script covers this case automatically: lines whose authentication is rejected are replaced with a new list. For scripts that store lines in a file, fetching the list from the API on every run is safer.

How can you save traffic?

Since quota is only deducted when data flows through a proxy, savings depend on how much data the script downloads. requests and httpx download only the HTML you ask for; images, fonts and scripts on the page are not loaded. The same job done with browser automation uses much more traffic per page. If you really need a browser, blocking images and media is covered in How to Use a Proxy with Playwright and Puppeteer.

Other ways to save traffic:

  • Do not download a page you have already saved. At startup, the script can skip URLs that already have a file in pages/.
  • If the site offers a JSON endpoint or a sitemap, read that instead of HTML; the response is usually much smaller.
  • Do not retry failed requests indefinitely. The four-attempt limit in the example keeps a permanently failing URL from eating into the quota.
  • After the job, check daily consumption with get_usage; if it is higher than expected, check how much data is downloaded per page.

Key security, robots.txt and terms of use

Store the wpk_ key like a password. Do not write it into code, a Git repository or files you share with the agent; keep it in the WEPROXY_KEY environment variable. If you suspect the key has leaked, use “Regenerate key” in the client area; the old key stops working immediately. When you ask the agent for a script, give it the environment variable name instead of pasting the key into the chat. The same rule applies to http_url lines: they contain the proxy username and password and should not be printed to logs.

Before scraping, check the site’s robots.txt file and terms of use, keep the request rate at a level the site can handle, and if you collect personal data, assess your GDPR obligations. Permitted and prohibited uses of WeProxy services are listed on the acceptable use page. For choosing an IP type for scraping, see the web scraping page; for every API parameter, see the WeProxy AI Access documentation.

Frequently asked questions

Does the WeProxy MCP server scrape web pages itself?

No. The WeProxy AI Access MCP server generates proxy lines (get_proxies), shows quota and usage, and manages the IP whitelist. Pages are opened by the script the agent writes and runs in a client that can execute code, such as Claude Code or Cursor. The script gets its proxies from get_proxies or directly from the REST API.

Should I use rotating or sticky sessions for scraping?

Rotating sessions suit jobs that finish in one request, such as product pages, categories and search results; every request leaves from a new IP. For login, cart and multi-step form flows, every step must go out from the same IP, so choose sticky. sticky_minutes ranges from 1 to 1440 minutes and defaults to 30. More in the sticky vs rotating guide.

Which proxy format should a Python script use?

For requests and httpx, format: "http_url" is the easiest option; the line is passed directly as the proxy URL. The default user:pass@host:port format has no scheme, so add http:// before passing it to requests. A scraper running on a server can use host:port, but the server’s IP must first be added to the whitelist with add_whitelist_ip.

Does the 120 calls per minute limit include proxy traffic?

No. The limit applies to WeProxy API calls per key: get_proxies, get_quota, whitelist and usage requests. Pages fetched through the proxies do not count. Since get_proxies returns up to 1000 lines per call, fetching the list once at the start of the job is enough. If the limit is exceeded, the API returns 429; wait for the time in the Retry-After header (60 s).

What should I do if proxy lines stop working after buying more quota?

If the proxy account is renewed after a top-up, old lines may stop working. The API key does not change; call the get_proxies tool or the POST /v1/proxies endpoint again to get new lines. You can check remaining quota with GET /v1/quota. All parameters are in the WeProxy AI Access documentation.

Get Started

Test Your Proxy Setup Today

Check connectivity with free tools or talk to sales to pick the right package.