# How to build an MCP server (and when you don't need to)

> Source: <https://blog.apify.com/build-mcp-server/>
> Published: 2026-11-24 00:00:00+00:00

**Recommendation:** Search the MCP Registry, vendor docs and app directories before writing a server, and verify publisher and uptime first, since about 9% of 300 sampled remote servers failed a single probe.
More in the playbook "Designing agent systems": <https://wpnews.pro/playbooks/agent-architecture>

A coding agent can build an MCP server in minutes, but by default that server runs only on your laptop. A team needs it hosted, popular sites often block requests from datacenter IPs, and a server for your use case may already exist.

MCP, short for [Model Context Protocol](https://blog.apify.com/mcp-for-beginners/), is the open standard that ChatGPT, Claude, Cursor, and other clients use to call tools and read data.

This guide shows you when to build an MCP server, then builds a price-check server with Python, [Amazon Product Scraper](https://apify.com/junglee/amazon-crawler), and Apify.

**The short answer**

• If the agent needs instructions or a workflow, write an Agent Skill, a folder of instructions for the agent. If it only runs local tools, a CLI is often enough.

• For web data from popular sites, use the

[Apify MCP server](https://apify.com/mcp)and its ready-to-run tools, which Apify calls Actors. A scraper you already have works as a tool once you deploy it as an Actor.

• For a popular SaaS tool, use the vendor's official MCP server when there is one.

• Build an MCP server when several apps or people need your proprietary data or business logic. Deploy it on Apify from the

[Python MCP server template](https://apify.com/templates/python-mcp-empty), and connect it to ChatGPT and Claude through the Apify MCP server.

## When you don't need to build an MCP server

An MCP server gives an agent live access to tools and data. Many agent tasks don't need that. Follow the questions in order to find the right option for your task.

### For instructions or local tools, use a skill or a CLI

If the agent only needs instructions, such as your coding conventions or a review checklist, an Agent Skill is enough. A skill is a folder that holds a `SKILL.md` file with instructions, plus optional supporting files such as scripts. In September 2026, [skills became an official MCP extension](https://modelcontextprotocol.io/extensions/skills/overview), so one skill can work across many clients.

If the agent only runs local tools, a CLI is often enough, because coding agents are good at running shell commands. MCP is better for remote services, because the server keeps the credentials and the agent never sees them.

Both options work with Apify Actors too. [Apify Agent Skills](https://docs.apify.com/agents/skills) let a coding agent get web data, build Actors, and run them through the [Apify CLI](https://docs.apify.com/cli). The [Apify plugin](https://docs.apify.com/agents/plugins) installs these skills together with the Apify MCP server in one step.

### For a well-known service, use an existing server

If the agent works with a well-known service or website, search these places for an existing server first.

1. [Apify Store](https://apify.com/store) , a marketplace of thousands of ready-to-run tools, which Apify calls Actors. They get web data and automate work on the web. Through the Apify MCP server, an agent can search the marketplace and run Actors from it. Its[MCP servers](https://apify.com/store/categories/mcp-servers) category includes thousands of Actors that run their own MCP server.
2. Your AI app's own directory. In Claude, MCP servers are called connectors, and Claude's [Connectors Directory](https://claude.com/docs/connectors/directory) includes Apify. ChatGPT has a similar directory.
3. The [official MCP Registry](https://registry.modelcontextprotocol.io/) , which listed more than 50k unique servers from vendors and the community in November 2026, including the Apify MCP server.
4. The vendor's docs, because many SaaS vendors, such as GitHub, publish an official MCP server.

A registry listing shows that a server exists. It's not a security review or an uptime guarantee. In a random sample of 300 remote servers from the registry, probed once in November 2026, about 9% were down or returned errors. So before you connect a server, check three things.

- **Who publishes it?** Prefer the vendor or a publisher you trust.
- **Is it maintained?** Look for recent releases and answered issues.
- **What can it do with your token?** Prefer read-only access, and use a scoped token with only the permissions it needs (least privilege).

### For web data, use ready-to-run tools

A fetch tool is easy to write, but reliably [bypassing anti-bot systems](https://blog.apify.com/crawl-without-getting-blocked/) on popular sites is much harder. To test this, a simple MCP fetch tool requested one page from each of 10 sites on the same day, with a plain HTTP GET request. The sites were Wikipedia, Amazon, Google, Instagram, LinkedIn, G2, Zillow, Indeed, Walmart, and TripAdvisor. A page counted as a success only if it contained real content, because some sites send a block page, a CAPTCHA, or a JavaScript challenge with a normal HTTP 200 response (a soft block).

| Approach | Sites that returned real content | 
|---|---|
| The fetch tool, from a residential IP | 5 of 10 | 
| The same tool, from datacenter network A without a proxy | 1 of 10 | 
| The same tool, from datacenter network B without a proxy | 3 of 10 | 
| The right Apify Actor per site ( [Web Fetch](https://apify.com/apify/web-fetch) (`apify/web-fetch` ) or a site-specific Actor) | 10 of 10 | 

The Walmart request below, sent from a datacenter IP with a browser user agent, got a CAPTCHA page with HTTP 200.

From datacenter IPs, which cloud servers use, the fetch tool failed on most of these sites. The Apify Actors handled [proxy rotation](https://blog.apify.com/rotating-proxies/) and anti-bot systems on the same sites and returned real content from all 10. Site-specific Actors, such as [Amazon Product Scraper](https://apify.com/junglee/amazon-crawler) (`junglee/amazon-crawler`), are maintained by the builders who publish them, so you don't have to maintain that code yourself. For a site that has no ready-to-run Actor, your tool can route its requests through [Apify Proxy](https://docs.apify.com/proxy), which includes residential IPs.

To use these Actors from your agent, [add the Apify MCP server to Cursor](https://blog.apify.com/how-to-add-mcp-server-to-cursor/) with this config, or follow the setup for other clients on [mcp.apify.com](https://mcp.apify.com/).

```
{
  "mcpServers": {
    "apify": {
      "url": "https://mcp.apify.com/?tools=apify/web-fetch,junglee/amazon-crawler"
    }
  }
}
```

The `tools` query parameter loads only the Actors you pick. On the first connection, you sign in to Apify with OAuth, or create a free Apify account.

For large crawls, such as every product on a site, a batch job works better than single tool calls. Run the Actor directly or on a [schedule](https://docs.apify.com/actors/running/schedules), and read the results from its dataset.

### For an existing scraper, deploy it as an Actor

If you already have a scraper or a script, deploy it as an Actor. The Apify MCP server then exposes it as an MCP tool, so you write no MCP code. The Actor's [input schema](https://blog.apify.com/apify-actor-input-schema-design/) becomes the tool's input schema, and its output schema tells the agent [what the Actor returns before it runs](https://blog.apify.com/your-ai-agent-used-to-guess-what-actors-return-now-it-knows-before-running-them/). The Apify MCP server also adds tools that check the run status and read the dataset. A coding agent with the `apify-actorization` skill from Apify Agent Skills can [convert a JavaScript, TypeScript, or Python project into an Actor](https://docs.apify.com/academy/build-and-publish/how-to/actorization) for you. If you publish the Actor in Apify Store, agents connected to mcp.apify.com can find it as a tool. For the details, read [What the Apify MCP server does to your Actor before an AI agent ever sees it](https://blog.apify.com/fixing-actors-invisible-to-agents/).

For example, the price check that this guide later builds as an MCP server also runs as a minimal plain Actor, `price-check-tool`, that returns the price for one stock-keeping unit (SKU). The Apify MCP server exposes it as a tool with `?tools=<username>/price-check-tool`. In the agent, the tool has one parameter, `sku`. Each call starts an Actor run, and the server tells the agent to read the result from the run's dataset.

This pattern, a run and then a dataset read, works well for batch work, such as a report or a crawl. Build an MCP server when the agent needs answers that combine your own data and logic, or several related tools that work together.

## Build your own MCP server when the data or the logic is yours

Build your own MCP server when the agent needs live access to proprietary data or business logic, such as an internal API, your own database, or your pricing rules and margins. If you're still choosing between an agent and a server, read [AI agent vs. MCP server](https://blog.apify.com/ai-agent-vs-mcp-server/).

The build steps use a price-check server for an e-commerce store as the example. Your product catalog and pricing rules are the proprietary data and logic, and Amazon Product Scraper gets current Amazon prices. You can use the same pattern with other Actors in Apify Store to combine your proprietary data with public web data from other sites.

## How to build an MCP server in Python

You build an MCP server in four steps. Set up the project, write the server, test it with MCP Inspector, and connect it to a client. Then host it on Apify for your team. Every step below was tested on SDK 2.3.0 in November 2026.

[Official MCP SDKs](https://modelcontextprotocol.io/docs/sdk) are available for Python, TypeScript, C#, Go, Rust, Ruby, Java, and more. Apify has pre-built [Python MCP server](https://apify.com/templates/python-mcp-empty) and [TypeScript MCP server](https://apify.com/templates/ts-mcp-empty) templates.

**What you need**

- Python 3.11 or later and [uv](https://docs.astral.sh/uv/) , the Python package and project manager
- Node.js, to run MCP Inspector with `npx`
- A [free Apify account](https://console.apify.com/sign-up) and its API token
- The [Apify CLI](https://docs.apify.com/cli/docs/installation) , for hosting on Apify

A coding agent such as Claude Code or Cursor can write a first version of this server in minutes. Your job is to review and test the result, with the code below as the reference implementation. The Python template includes an `AGENTS.md` file with instructions for coding agents.

If your data comes from an API with an OpenAPI spec, give the agent the spec. Ask for a few tools that match real workflows, not one tool per endpoint. Long tool lists reduce tool-selection accuracy, and one tool per endpoint can expose every write and delete endpoint to the agent.

**If you follow older tutorials**, note two breaking changes. [Version 2.0](https://github.com/modelcontextprotocol/python-sdk/releases/tag/v2.0.0) of the official Python SDK renamed `FastMCP` to `MCPServer`, so `from mcp.server.fastmcp import FastMCP` fails with `ModuleNotFoundError`. The `fastmcp` package on PyPI is a separate library. Since protocol version 2025-03-26, remote servers use Streamable HTTP, and the older [HTTP with Server-Sent Events (HTTP+SSE) transport is deprecated](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports).

### Step 1. Set up the project

Create the project, and add the official Python MCP SDK and the Apify API client as dependencies.

```
uv init price-check-mcp
cd price-check-mcp
uv add "mcp[cli]==2.3.0" "apify-client>=3"
```

The server calls an Actor, so it needs an Apify API token. Find the token in [Apify Console](https://console.apify.com/) under **Settings > API & Integrations**, and set it as the `APIFY_TOKEN` environment variable.

### Step 2. Write the server

Create `server.py` with the code below. `list_products` reads your products from a local SQLite database. In production, read them from your store's database or API. `check_price` compares your prices with current Amazon prices for one or more products. When a check takes more than 25 seconds, `check_price` returns a run ID, and the agent passes it to `get_price_check` to get the result. Each SKU maps to one fixed Amazon product page, identified by its ASIN, Amazon's product ID, so a SKU is always compared with the same Amazon product. The Actor returns the price shown on the product page, usually the featured offer (Buy Box). Prices can vary by delivery location, so add a `zipCode` value to `run_input` in `check_price` to match your market.

```
"""Price-check MCP server that compares your prices with Amazon prices, using an Actor from Apify Store."""

import asyncio
import os
import sqlite3
from contextlib import closing
from datetime import UTC, datetime, timedelta
from typing import Literal, NotRequired, TypedDict

from apify_client import ApifyClientAsync
from mcp.server import MCPServer
from mcp.server.caching import CacheHint
from mcp.server.mcpserver.exceptions import ToolError
from mcp.types import ToolAnnotations

DB_PATH = "products.db"
ACTOR = "junglee/amazon-crawler"  # Amazon Product Scraper in Apify Store
# A named key-value store that all runs of the server share. The hosted Actor runs with
# limited permissions, so it must create its own store, and local runs use a separate name.
CACHE = "price-checks" if os.environ.get("APIFY_IS_AT_HOME") else "price-checks-local"
ALERT_GAP = 0.05  # raise an alert when our price is more than 5% above Amazon
MAX_SKUS = 20  # one call checks at most this many products, so each run stays small

mcp = MCPServer(
    "price-check",
    subscriptions=False,  # no server-initiated messages, so no long-lived stream
    cache_hints={"tools/list": CacheHint(ttl_ms=3_600_000, scope="public")},  # clients may cache the tool list for an hour
)

class Product(TypedDict):
    sku: str
    name: str
    our_price: float

class PriceCheck(TypedDict):
    sku: str
    our_price: float
    amazon_price: float
    gap_percent: float
    alert: bool
    suspect: bool  # far from our price, so no alert until a person checks it
    source: str  # where the price was seen
    checked_at: str  # when the price was seen

class PriceReport(TypedDict):
    status: Literal["done", "running"]
    results: list[PriceCheck]  # checks that are ready
    missing: NotRequired[list[str]]  # SKUs with no price in this check, for example out of stock
    run_id: NotRequired[str]  # only while the remaining SKUs are running
    next: NotRequired[str]

_client: ApifyClientAsync | None = None  # one client, so calls reuse its connections

def apify() -> ApifyClientAsync:
    global _client
    if _client is None:
        token = os.environ.get("APIFY_TOKEN")
        if not token:
            raise ToolError("APIFY_TOKEN is not set. Add your Apify API token to the server environment.")
        _client = ApifyClientAsync(token)
    return _client

def db() -> sqlite3.Connection:
    # One connection per call, because tools run concurrently when many clients connect.
    return sqlite3.connect(DB_PATH)

def init_db() -> None:
    with closing(db()) as conn, conn:
        conn.execute(
            "CREATE TABLE IF NOT EXISTS products "
            "(sku TEXT PRIMARY KEY, name TEXT, our_price REAL, amazon_url TEXT)"
        )
        conn.executemany(
            "INSERT OR IGNORE INTO products VALUES (?, ?, ?, ?)",
            [
                ("ECHO-DOT-5", "Echo Dot (5th Gen)", 74.99, "https://www.amazon.com/dp/B09B8V1LZ3"),
                ("KINDLE-PW", "Kindle Paperwhite", 219.99, "https://www.amazon.com/dp/B0CFPJYX7P"),
            ],
        )

def products(skus: list[str]) -> dict[str, tuple[float, str]]:
    with closing(db()) as conn:
        rows = {sku: conn.execute("SELECT our_price, amazon_url FROM products WHERE sku = ?", (sku,)).fetchone() for sku in skus}
    unknown = [sku for sku, row in rows.items() if row is None]
    if unknown:
        raise ToolError(f"Unknown SKU {', '.join(unknown)}. Call list_products to see the SKUs.")
    return rows

_cache_id: str | None = None  # the store ID never changes, so fetch it once per process

async def cache():
    global _cache_id
    if _cache_id is None:
        _cache_id = (await apify().key_value_stores().get_or_create(name=CACHE)).id
    return apify().key_value_store(_cache_id)

async def read_run(run) -> PriceReport:
    status = getattr(run.status, "value", run.status)
    if status in ("READY", "RUNNING"):
        return {"status": "running", "results": [], "run_id": run.id, "next": "Call get_price_check with this run_id."}
    if status != "SUCCEEDED":
        raise ToolError(f"The price check ended with status {status}. Call check_price again.")
    with closing(db()) as conn:
        by_url = {url: (sku, price) for sku, price, url in conn.execute("SELECT sku, our_price, amazon_url FROM products")}
    page, run_input = await asyncio.gather(
        apify().dataset(run.default_dataset_id).list_items(clean=True),
        apify().key_value_store(run.default_key_value_store_id).get_record("INPUT"),
    )
    asked = [by_url[u["url"]][0] for u in run_input["value"]["categoryOrProductUrls"] if u["url"] in by_url]
    store, results = await cache(), []
    for item in page.items:
        if item.get("input") not in by_url:
            continue
        sku, price = by_url[item["input"]]
        amazon = (item.get("price") or {}).get("value")
        if amazon is None:
            continue
        gap = (price - amazon) / amazon
        suspect = not 0.5 <= amazon / price <= 2  # usually a wrong SKU-to-product mapping in our own data
        check: PriceCheck = {"sku": sku, "our_price": price, "amazon_price": amazon,
                             "gap_percent": round(gap * 100, 1), "alert": gap > ALERT_GAP and not suspect,
                             "suspect": suspect, "source": item["input"],
                             "checked_at": run.finished_at.isoformat(timespec="seconds")}
        results.append(check)
    await asyncio.gather(*(store.set_record(check["sku"], check) for check in results))
    found = {check["sku"] for check in results}
    missing = [sku for sku in asked if sku not in found]  # every SKU in the run is either a result or missing
    return {"status": "done", "results": results} | ({"missing": missing} if missing else {})

@mcp.tool(title="List products", annotations=ToolAnnotations(read_only_hint=True))
def list_products() -> list[Product]:
    """List the products we track, with their SKU and our current price."""
    with closing(db()) as conn:
        rows = conn.execute("SELECT sku, name, our_price FROM products").fetchall()
    return [{"sku": s, "name": n, "our_price": p} for s, n, p in rows]

@mcp.tool(title="Check prices", annotations=ToolAnnotations(read_only_hint=True, open_world_hint=True))
async def check_price(skus: list[str], max_age_minutes: int = 60) -> PriceReport:
    """Compare our price with the current Amazon price for one or more SKUs.

    Reuses checks made in the last max_age_minutes. Checks the rest in one run,
    and returns a run_id for get_price_check if that run takes more than 25 seconds.
    """
    if len(skus) > MAX_SKUS:
        raise ToolError(f"Check at most {MAX_SKUS} SKUs per call. Split the list into several calls.")
    rows = products(skus)
    store, fresh, stale = await cache(), [], []
    oldest = datetime.now(UTC) - timedelta(minutes=max_age_minutes)
    records = await asyncio.gather(*(store.get_record(sku) for sku in skus))
    for sku, record in zip(skus, records):
        value = record["value"] if record else {}
        # Reuse a cached check only if it is fresh and has every field.
        # Entries saved before a schema change are checked again.
        if PriceCheck.__required_keys__ <= value.keys() and datetime.fromisoformat(value["checked_at"]) > oldest:
            fresh.append(value)
        else:
            stale.append(sku)
    if not stale:
        return {"status": "done", "results": fresh}
    run = await apify().actor(ACTOR).start(
        run_input={"categoryOrProductUrls": [{"url": rows[sku][1]} for sku in stale], "maxItemsPerStartUrl": 1},
        max_items=len(stale),  # Apify charges for at most one result per SKU
        wait_for_finish=25,  # return before the client's tool-call timeout
    )
    report = await read_run(run)
    report["results"] = fresh + report["results"]
    return report

@mcp.tool(title="Get price check result", annotations=ToolAnnotations(read_only_hint=True))
async def get_price_check(run_id: str) -> PriceReport:
    """Get the result of a check_price call that returned a run_id."""
    return await read_run(await apify().run(run_id).get())

init_db()

if __name__ == "__main__":
    mcp.run(transport="stdio")
```

Note these details in the code:

- **Type hints, docstrings, and annotations define each tool.** Type hints and docstrings become the tool's schema and description, and the model reads them to pick a tool, so use the docstring to explain when to call it.`read_only_hint=True` marks a tool that only reads data, and`open_world_hint=True` marks one that calls external systems, such as the web. Clients can use these hints. The Claude app, for example, groups read-only tools so you can allow them all at once.
- **`ToolError` returns your message as a tool error.** A plain Python exception reaches the model only as a generic error. With`ToolError` , the model reads "Unknown SKU NOPE. Call list_products to see the SKUs." and can try again.
- **Long-running jobs return a run ID.** Each client has a tool-call timeout, and a web data request can take longer than that. So`check_price` waits up to 25 seconds, and if the run is still going, it returns the Actor's run ID. The run continues on Apify, and the agent passes the ID to`get_price_check` to get the result. This polling pattern works in any client that can call tools. The MCP tasks extension is the protocol's own feature for long-running operations. Check the[extension support matrix](https://modelcontextprotocol.io/extensions/client-matrix) before you rely on the tasks extension. A server can also send instructions when a client connects, but not every client passes them to the model, so`check_price` puts the next step in the`next` field of the result.
- **Results are typed and short.**`check_price` returns a`PriceReport` with a list of`PriceCheck` results. The SDK converts these types into an output schema, so agents know every field in advance, including where and when the price was seen. Because the tool returns only numbers and your own data, not page text,[prompt injections](https://blog.apify.com/prompt-injection-ai-web-scraping/) hidden in a web page can't reach the model through this tool. Return only the fields the agent needs, and paginate long lists. For a real catalog, add pagination to`list_products` .

The review checklist below covers the rest of the code, such as batching, the shared cache, and the outlier check.

### Step 3. Test the server with MCP Inspector and pytest

[MCP Inspector](https://modelcontextprotocol.io/docs/tools/inspector) is the official tool for testing and debugging MCP servers. It lists your tools and calls them directly, without a model.

MCP names each protocol version by a date. [Version 2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28) is stateless, while the 2025 versions are stateful and use sessions. Test your server on both, because clients use both. In tests in November 2026, Cursor 3.22, VS Code 1.144, and Claude Code 2.1 connected with protocol version 2025-11-25, and the Claude app with 2026-07-28. In the Inspector, `--protocol-era modern` tests 2026-07-28, and `--protocol-era legacy` tests the 2025 versions.

```
npx @modelcontextprotocol/inspector --cli -e APIFY_TOKEN=$APIFY_TOKEN uv run server.py --protocol-era modern --method tools/list
npx @modelcontextprotocol/inspector --cli -e APIFY_TOKEN=$APIFY_TOKEN uv run server.py --protocol-era legacy --method tools/list
```

The Inspector starts the server with a minimal environment, so `-e` passes the token. Both commands list `list_products`, `check_price`, and `get_price_check`. In a local (stdio) server, write nothing to stdout except the JSON-RPC messages, because even one extra `print()` corrupts them. Write logs to stderr instead.

To use the web UI instead, run the Inspector without `--cli`, connect to the server on the **Servers** tab, open **Tools**, pick a tool, and run it.

```
npx @modelcontextprotocol/inspector -e APIFY_TOKEN=$APIFY_TOKEN uv run server.py
```

The web UI lists the tools by the titles set in the code, and shows the result of each call.

For tests that run in CI on every commit, use `Client(mcp)`. It connects to the server over an in-memory transport inside pytest, with no subprocess. Save these tests as `test_server.py` next to `server.py`. Neither test needs an Apify token, because both stop before the server calls Apify.

```
"""Tests that run the server in memory, with no subprocess and no network."""

import pytest
from mcp import Client

from server import mcp

pytestmark = pytest.mark.anyio

async def test_lists_products():
    async with Client(mcp) as client:
        result = await client.call_tool("list_products", {})
    assert {p["sku"] for p in result.structured_content["result"]} == {"ECHO-DOT-5", "KINDLE-PW"}

async def test_unknown_sku_tells_the_model_what_to_do():
    async with Client(mcp) as client:
        result = await client.call_tool("check_price", {"skus": ["NOPE"]})
    assert result.is_error and "Call list_products" in result.content[0].text
```

Add pytest as a dev dependency with `uv add --dev pytest`, then run `uv run pytest`.

### Step 4. Connect the server to Cursor, VS Code, and Claude Code

For Cursor, add the server to the global config, `~/.cursor/mcp.json`.

```
{
  "mcpServers": {
    "price-check": {
      "command": "uv",
      "args": ["run", "--directory", "/path/to/price-check-mcp", "server.py"],
      "env": { "APIFY_TOKEN": "${env:APIFY_TOKEN}" }
    }
  }
}
```

In VS Code, put the same fields in the workspace config, `.vscode/mcp.json`, under `servers` instead of `mcpServers`, and add `"type": "stdio"`. For Claude Code, run this command.

```
claude mcp add price-check --scope project -e 'APIFY_TOKEN=${APIFY_TOKEN}' -- uv run --directory /path/to/price-check-mcp server.py
```

These configs read the token from your environment, so the token isn't stored in a file you might commit. The single quotes stop your shell from expanding `${APIFY_TOKEN}`, so Claude Code saves the variable reference and not the token value. Don't paste the token itself into the command, because Claude Code then saves it in plain text in `.mcp.json`.

Then ask the agent, "Is our Kindle price above Amazon's?" The agent typically calls `list_products` to find the SKU, then `check_price`, which returns a result like this.

```
{"status": "done", "results": [{"sku": "KINDLE-PW", "our_price": 219.99, "amazon_price": 199.99, "gap_percent": 10.0,
 "alert": true, "suspect": false, "source": "https://www.amazon.com/dp/B0CFPJYX7P", "checked_at": "2026-11-12T00:42:11+00:00"}]}
```

MCP Inspector tests protocol behavior, not tool selection. So also test with real questions from your team, in the apps they use. Run each question several times, because tool selection is non-deterministic. Automate these runs as evals, so they rerun after every change to a tool description.

## Where to host your MCP server

A local (stdio) server works for one person, but a team usually needs a remote server that clients reach over the internet through Streamable HTTP, the MCP transport for remote servers. Any cloud host can run one, but you often set up HTTPS, authentication, and scaling yourself. On Apify, your server runs as an Actor. The [server interface](https://docs.apify.com/actors/development/programming-interface/server-actors) makes it a web server with a stable public URL, bearer token authentication, and autoscaling. Runs stop after an idle timeout, so the server scales to zero, and you pay nothing while it's stopped.

|  | Use the Apify MCP server or a vendor's official server | Build and self-host | Build and host on Apify | 
|---|---|---|---|
| **Setup** | Add one URL | Write the server, then set up hosting, HTTPS, and authentication | Start from a template, add your tools, then run `apify push` | 
| **Authentication for ChatGPT and other apps** | [mcp.apify.com](https://mcp.apify.com/) or the vendor's OAuth | OAuth with your identity provider, which you set up | OAuth through [mcp.apify.com](https://mcp.apify.com/) | 
| **Maintenance** | Done by the Actor's builder or the vendor | You handle SDK changes, spec changes, and uptime | Apify runs hosting, HTTPS, and autoscaling. You update your tool code and SDK | 
| **Control** | The vendor runs the server | Full control of the hosting stack | You set memory, scaling, and the idle timeout, and `server.py` runs on any host | 
| **Cost** | Pay per use, or included in the vendor's plan | Hosting bill, plus the time to run HTTPS, authentication, and scaling | Free plan with $5 of usage a month, then compute units plus the Actors your tools call | 
| **Sites with anti-bot protection** | Handled by the Actor | Your own proxies, or Actors called with your token | Actors, with the token injected for you | 
| **Publish and monetize** | Doesn't apply | Your own listing and billing | Apify Store, with pay-per-event payouts | 

Apify works well for servers that combine proprietary data with public web data, because your tools can call Actors in Apify Store from the same account. ChatGPT and the Claude app connect from their vendors' clouds, so your server must be reachable from the internet, usually through a public HTTPS URL. Both apps support OAuth sign-in. On Apify, the server interface gives you the public HTTPS URL, and mcp.apify.com handles the OAuth flow. If you already have an MCP server and only need to deploy it, see [Build and deploy MCP servers in minutes](https://blog.apify.com/build-and-deploy-mcp-servers-typescript/).

### Host the server on Apify

Log in with `apify login`, and create the Actor from the Python MCP server template. Create it in a separate folder, such as `~/actors`, so the Actor keeps the name `price-check-mcp` without clashing with the local project. The template sets up the server interface and serves the MCP endpoint at `/mcp`:

```
mkdir -p ~/actors && cd ~/actors
apify create price-check-mcp --template python-mcp-empty
```

Copy your `server.py` into `price-check-mcp/my_actor`. These are the files you work with:

```
price-check-mcp/
├── .actor/actor.json      # Actor settings from the template
├── my_actor/
│   ├── main.py            # replace with the code below
│   └── server.py          # your server, unchanged
├── Dockerfile
└── requirements.txt
```

Replace `my_actor/main.py` with this code:

```
"""Run the price-check MCP server as an Apify Actor through the server interface."""

import uvicorn
from apify import Actor
from starlette.responses import Response

from .server import mcp

def without_get_stream(app):
    # This server sends no server-initiated messages, so it rejects the long-lived SSE stream that clients open with GET.
    # Rejecting it lets the run stop after the idle timeout once calls end.
    async def wrapped(scope, receive, send):
        if scope["type"] == "http" and scope["method"] == "GET" and scope["path"].rstrip("/") == "/mcp":
            await Response(status_code=405, headers={"Allow": "POST"})(scope, receive, send)
        else:
            await app(scope, receive, send)

    return wrapped

async def main() -> None:
    async with Actor:
        # Stateless mode lets any run answer any request, so horizontal scaling is safe.
        app = without_get_stream(mcp.streamable_http_app(stateless_http=True, host="0.0.0.0"))
        config = uvicorn.Config(app, host="0.0.0.0", port=Actor.configuration.web_server_port)
        await uvicorn.Server(config).serve()
```

`host="0.0.0.0"` appears twice in `main.py`. In `uvicorn.Config`, it makes the server listen on all network interfaces of the container. In `streamable_http_app`, it disables the SDK's localhost-only check. By default, the SDK accepts only requests whose Host header is localhost, as [protection against DNS rebinding](https://github.com/modelcontextprotocol/python-sdk/blob/v2.3.0/src/mcp/server/transport_security.py), and answers other requests with "421 Misdirected Request." On Apify, the gateway rejects any request without a valid token before it reaches your server. Your `server.py` runs on any host that has an Apify API token, and `main.py` holds the Apify-specific setup.

Set `requirements.txt` to these packages. The `pyjwt` line keeps the template's minimum version, which includes security fixes. Then run `apify push` to deploy.

```
apify>=4,<5
apify-client>=3
mcp==2.3.0
pyjwt>=2.12.0
uvicorn
```

The Actor's **Server** tab in Apify Console shows the MCP server URL, in the form `https://<username>--price-check-mcp.apify.actor/mcp`. Copy it from there, because an underscore in your username becomes a hyphen in this URL.

For Cursor, replace the local entry with the server URL and an `Authorization` header that reads the token from your environment. In VS Code, put the same entry under `servers` and add `"type": "http"`.

```
{
  "mcpServers": {
    "price-check": {
      "url": "https://<username>--price-check-mcp.apify.actor/mcp",
      "headers": { "Authorization": "Bearer ${env:APIFY_TOKEN}" }
    }
  }
}
```

For Claude Code, remove the local entry, then add the hosted one.

```
claude mcp remove price-check --scope project
claude mcp add --transport http price-check https://<username>--price-check-mcp.apify.actor/mcp --scope project --header 'Authorization: Bearer ${APIFY_TOKEN}'
```

Ask the same question as before, and Claude Code now calls the tools on the hosted server.

After each `apify push`, new runs start on the new build, and the current run keeps serving, so calls in progress aren't interrupted. During development, abort the current run in the Actor's **Runs** tab to switch to the new build at once. The run's log in the same tab shows every request the server received. The SDK also instruments every request by default with an OpenTelemetry span that includes the tool name, so you can track latency and errors per tool. Configure an OpenTelemetry exporter to send these traces to your observability backend.

## Run your MCP server in production

Before a team relies on the server, set up access, scaling, and cost limits. Then you can publish it for others to use. [Maven AGI's customer support agents](https://blog.apify.com/maven-agi-customer-support-case-study/), for example, run on company-approved data from Apify in production.

### Manage secrets and team access

Inside the Actor, Apify injects `APIFY_TOKEN` automatically, so the calls to Amazon Product Scraper need no extra setup. To read your products from your store's API instead of SQLite, store the API key as a [secret environment variable](https://docs.apify.com/actors/development/programming-interface/environment-variables) of the Actor. If that API is behind a company firewall, route the Actor's requests through a [dedicated Apify Proxy group](https://docs.apify.com/proxy/datacenter-proxy), which gives you static IP addresses that the firewall can allowlist.

Give a team or a third-party app a [scoped token](https://docs.apify.com/integrations/api#limited-permissions) that can only run this Actor. Create it in Apify Console under **Settings > API & Integrations** and enable **Limit token permissions**. Then add this Actor by its ID and give it the **Run** permission. Apify Console adds **Read** with it. The ID is in the Actor's URL in Apify Console. This token works on the server URL and through [mcp.apify.com](https://mcp.apify.com), and `check_price` still runs Amazon Product Scraper when called with it. The token can't read your other Actors, your runs, or your account details. Calls made with any of your tokens are billed to your account.

### Connect the server to ChatGPT and Claude through mcp.apify.com

The Apify MCP server at mcp.apify.com handles the OAuth sign-in that ChatGPT and the Claude app use, and passes their tool calls to your server. Open mcp.apify.com, add your server under **Preloaded Actors**, and pick the tool categories you want. The page generates the server URL and shows the config for each client.

The URL looks like this.

```
https://mcp.apify.com/?tools=actors,docs,apify/web-search,apify/web-fetch,<username>/price-check-mcp
```

The Apify MCP server runs Actors with [limited permissions](https://docs.apify.com/actors/running/permissions), the default for new Actors, so each Actor reaches only its own storages and the data it's given. Keep that default for your server.

One connection gives the agent your tools together with Apify's ready-to-run tools, such as [Web Search](https://apify.com/apify/web-search) (`apify/web-search`) and Web Fetch. In ChatGPT, go to **Plugins**, select **Add custom MCP server**, and paste the URL. In the Claude app, select **Add custom connector** and paste the same URL. The connector then lists your tools, with the Actor name as a prefix.

On the first connection, each person signs in with their own Apify account, so nobody pastes a token into the app. For a team, create the Actor in an [Apify organization account](https://docs.apify.com/account/collaboration/organization). Members pick the organization on the sign-in page, so they can run the Actor, and the runs are billed to the organization. Every app that signs in this way appears in Apify Console under **Settings > API & Integrations**, where you can revoke its access. The [Apify MCP server docs](https://docs.apify.com/mcp) say its telemetry doesn't collect conversations, tool arguments, API tokens, or personal data, and you can disable it.

Clients on the 2025 protocol versions and on 2026-07-28 can connect through mcp.apify.com. ChatGPT answered the question "Is our Kindle price above Amazon's?" by calling `check_price` and giving the price gap.

[OpenAI's guide to custom MCP servers](https://help.openai.com/en/articles/12584461-connecting-custom-mcp-servers-in-chatgpt) says ChatGPT keeps a frozen snapshot of the tool list. After you change a tool's parameters, a workspace admin can refresh the tool list in the app settings, or you can add the server again. The list of ChatGPT plans that can add custom MCP servers changes over time, so check that guide for your plan.

The `actors` category in the [mcp.apify.com](https://mcp.apify.com) URL also lets the agent discover and run Actors from Apify Store that you didn't preload. For example, an agent asked about Walmart prices can find and run a Walmart Actor from Apify Store automatically, with no code from you. For a team that should use only approved Actors, disable the `actors` category and preload only those Actors, as an allowlist.

### Make the server ready for concurrent clients

**Use stateless mode.** Apify scales the server horizontally by starting more runs as traffic grows, so several instances of your server can run at once. By default, the SDK runs a stateful server, which keeps each 2025-protocol session in memory on one instance. A request routed to another instance then gets "Session not found."

With `stateless_http=True`, which `main.py` already sets, the server runs in [stateless mode](https://blog.apify.com/mcp-stateless-migration/), and any run can answer any request. In a load test for this guide, the same 24 concurrent clients made 120 calls in each mode, three times. In stateless mode, all 120 calls succeeded every time. In stateful mode, at most 5 of the 120 succeeded, and the rest failed with "Session not found."

Stateless mode matters even for a small team. Apify starts another run when concurrent requests exceed the **Desired requests per run** setting, so a few concurrent calls can reach a second run while a `check_price` call waits up to 25 seconds. The price cache is stored in a [named key-value store](https://docs.apify.com/storage/key-value-store) for the same reason, so all runs share one cache.

**Run a load test.** Session errors like this appear under concurrent load, so a single client in MCP Inspector usually doesn't show them. This script makes one warm-up call first. Then it opens 24 concurrent sessions, calls `list_products` five times in each, and counts the successful calls, so it tests session handling without running 120 Amazon checks.

```
"""Open many concurrent MCP sessions and count the successful calls."""

import asyncio
import os
import sys

from mcp import Client
from mcp.client.streamable_http import create_mcp_http_client, streamable_http_client

URL = sys.argv[1]  # for example https://<username>--price-check-mcp.apify.actor/mcp
CLIENTS, CALLS = 24, 5

async def one_client(calls: int = CALLS) -> int:
    http = create_mcp_http_client(headers={"Authorization": f"Bearer {os.environ['APIFY_TOKEN']}"})
    ok = 0
    # mode="legacy" uses the 2025 protocol, which many clients still use
    async with Client(streamable_http_client(URL, http_client=http), mode="legacy") as client:
        for _ in range(calls):
            result = await client.call_tool("list_products", {})
            ok += not result.is_error
    return ok

async def main() -> None:
    await one_client(calls=1)  # warm-up call before the concurrent sessions
    results = await asyncio.gather(*(one_client() for _ in range(CLIENTS)), return_exceptions=True)
    ok = sum(r for r in results if isinstance(r, int))
    print(f"{ok} of {CLIENTS * CALLS} calls worked")

asyncio.run(main())
```

Save the script as `load_test.py` in your local project, where the MCP SDK is installed. With `APIFY_TOKEN` set, run it with your server's URL.

```
uv run load_test.py https://<username>--price-check-mcp.apify.actor/mcp
```

The script prints how many calls worked.

With a stateful server, the same 24 clients got at most 5 of the 120 calls through.

### Keep hosting costs low

**Set the memory and the idle timeout.** You pay for [compute units](https://docs.apify.com/actors/running/usage-and-resources), which are memory multiplied by run time, at the rates on the [Apify pricing page](https://apify.com/pricing). Two values in the **Server** section of the Actor's **Settings** tab control most of that cost. The first is **Memory**. The price-check server used at most 84 MB of RAM in testing, so 256 MB leaves enough free memory. The second is **Idle timeout**. A run stops when it gets no requests for that long. A longer timeout keeps the run active for the next call, and a shorter one saves compute units.

**Disable long-lived streams.** Some clients keep a stream open to receive server-initiated messages, and an open stream keeps the run from becoming idle. This server sends none, so `subscriptions=False` and the HTTP 405 response in `main.py` disable the stream in both protocol versions.

**Limit the data cost.** Hosting a server like this one costs little. A run with 256 MB uses 0.25 compute units per hour, which is $0.05 at the Free plan rate, so most of the bill comes from the products your tools check. Amazon Product Scraper uses pay-per-result pricing, as its [Store page](https://apify.com/junglee/amazon-crawler) shows. The Apify Free plan includes $5 of usage every month, enough for hundreds of price checks. For products that agents ask about all day, a higher `max_age_minutes` raises the cache hit rate. Each call checks at most 20 SKUs, so every run stays small, even when an agent calls the tool in a loop. With the `max_items` run option set to the number of SKUs, Apify charges for at most one result per SKU, even if the Actor returns more. A [usage limit](https://docs.apify.com/account/subscriptions#adjust-your-usage-limit) in Apify Console under **Billing > Limits** sets a maximum cost for the whole account.

### Publish and monetize the server

To share the server, [publish it in Apify Store](https://docs.apify.com/academy/build-and-publish/apify-store/how-store-works), where agents connected to [mcp.apify.com](https://mcp.apify.com) can discover it. Before you publish, write a description that leads with the job, for example "Compare your prices with current Amazon prices," because builders and agents see it when they search the marketplace. To charge for each tool call, set up [pay-per-event](https://docs.apify.com/actors/monetize) pricing and add an `Actor.charge()` call to each tool. It's the only Apify-specific code `server.py` needs. Each builder who calls it pays per call, and Apify sends you payouts. Agents can also pay for these calls without an Apify account, through Apify's [agentic payments](https://docs.apify.com/agents/payments). Agentic payments accept payment protocols such as x402 and the Machine Payments Protocol (MPP), as well as cards and Skyfire wallets.

## Review checklist for AI-generated server code

With the `apify-actor-development` skill from Apify Agent Skills, a coding agent can create, test, and deploy the server for you. Review its code with this checklist.

- A title and annotations on every tool
- Typed results, so each tool has an output schema
- Actionable error messages (`ToolError` )
- SDK 2.x imports (`from mcp.server import MCPServer` , not`mcp.server.fastmcp` )
- No `print()` to stdout in a stdio server
- A run ID and a polling tool for long-running jobs (over 25 seconds)
- Batched Actor runs (one per call, not per product), and a shared cache that reuses checks made in the last `max_age_minutes`
- A per-call cost limit (`MAX_SKUS` and`max_items` ), and an outlier check before any alert (a price less than half or more than double yours usually means a wrong[SKU-to-product mapping](https://blog.apify.com/product-matching-ai-pricing-intelligence-web-scraping/) )
- No database connection shared between concurrent calls (with PostgreSQL, use a connection pool)
- Long-lived streams turned off on a hosted server that sends no server-initiated messages (`subscriptions=False` and HTTP 405 for GET), so idle runs can stop
- `host="0.0.0.0"` only on a hosted server behind an authenticating gateway, so it accepts requests to its public URL
- In-memory tests in CI, and a smoke test against the deployed endpoint after each build
- Read-only tools by default, and separate tools for anything that sends data to external systems, so it's much harder for a prompt injection on a web page to exfiltrate private data

## Fix common MCP server errors

Most of these errors appear only after the server leaves your laptop, so local tests rarely catch them.

| Error | Cause | Fix | 
|---|---|---|
| `ModuleNotFoundError: No module named 'mcp.server.fastmcp'` | The code was written for SDK 1.x, and version 2.0 renamed `FastMCP` to`MCPServer` | Import `MCPServer` from`mcp.server` | 
| The client can't parse the server's messages | A `print()` writes to stdout in a stdio server | Write logs to stderr | 
| `421 Misdirected Request` | By default, the SDK accepts only requests whose Host header is localhost | Behind an authenticating gateway, pass `host="0.0.0.0"` to`streamable_http_app` | 
| `401` on the server URL | The request has no valid Apify token | Send an `Authorization: Bearer` header with your Apify token, or connect through[mcp.apify.com](https://mcp.apify.com/) | 
| `403 Insufficient permissions for the key-value store` | The Actor runs with limited permissions, so it can't open a store that your personal token created | Let the hosted Actor create its own store, as `server.py` does with a separate local name | 
| `Session not found` | A stateful 2025-protocol session lives on one instance, and the request reached another | Set `stateless_http=True` | 
| The run doesn't stop after the idle timeout | A client keeps a long-lived stream open | Set `subscriptions=False` and answer GET with HTTP 405 | 
| ChatGPT sends the old tool parameters | ChatGPT keeps a frozen snapshot of the tool list | Refresh the tool list in the app settings, or add the server again | 

## Final thoughts

Build an MCP server when the data or the logic is yours and an agent needs live access to it. For everything else, a skill, a CLI, the Apify MCP server, or the vendor's official server is often enough. A scraper you already have works as a tool once you deploy it as an Actor. When you do build, annotate your tools, use stateless mode, and run a load test before your team uses it. Client protocol versions, SDK releases, and the ChatGPT plans that allow custom servers change often, so recheck them before you build. Equip your agents with thousands of ready-to-run tools on mcp.apify.com, and when the data is yours, deploy your server from the [Python MCP server template](https://apify.com/templates/python-mcp-empty) and add it to the same URL.

[Sign up](https://console.apify.com/sign-up)

## FAQ

### Can I build my own MCP server?

Yes. This guide builds a price-check server that compares your prices with Amazon prices. It has three tools and under 200 lines of Python, built with the official MCP SDK. Before you build, search Apify Store and the MCP Registry, because a server for your use case may already exist.

### How do I start an MCP server?

A local MCP server starts when a client such as Cursor or Claude Code runs the command in its config, for example `uv run server.py`. A remote server runs on a host instead. On Apify, deploy it from the Python MCP server template, and Apify starts a run when the first request arrives.

### How do I host a custom MCP server?

Run your MCP server remotely over Streamable HTTP, in stateless mode so any instance can answer any request. On Apify, start from the Python or TypeScript MCP server template, add your tools, and run `apify push`. You get a stable URL, bearer token authentication, autoscaling, and OAuth through [mcp.apify.com](http://mcp.apify.com).

### How much does it cost to build an MCP server?

Building costs mostly your time, and a coding agent can write a first version in minutes. The Apify Free plan includes $5 of usage every month, enough for hundreds of price checks. Hosting is billed in compute units, which are memory multiplied by run time, and a server without traffic scales to zero.
