cd /news/agent-protocols/how-to-build-an-mcp-server-and-when-… Β· home β€Ί topics β€Ί agent-protocols β€Ί article
[ARTICLE Β· art-175447] src=blog.apify.com β†— pub= topic=agent-protocols verified=true sentiment=Β· neutral

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

Teams should check for an existing MCP server before building their own, since a November 2026 probe of 300 randomly sampled remote servers from the official MCP Registry found about 9% were down or returned errors, according to Apify's guide. The guide recommends Agent Skills or a CLI when an agent only needs instructions or local tools, the Apify MCP server for web data from popular sites, and a vendor's official server for well-known SaaS tools, reserving custom MCP servers for proprietary data or business logic shared across several apps or people. Skills became an official MCP extension in September 2026, and the official MCP Registry listed more than 50,000 unique servers in November 2026.

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 playbook: Designing agent systems
by read36 min views2 publishedNov 24, 2026
How to build an MCP server (and when you don't need to)
Image: Blog (auto-discovered)

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, 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, 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 serverand 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, 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, 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 let a coding agent get web data, build Actors, and run them through the Apify CLI. The Apify plugin 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 , 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. ItsMCP 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 includes Apify. ChatGPT has a similar directory.
  3. The official MCP Registry , 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 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 (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 and anti-bot systems on the same sites and returned real content from all 10. Site-specific Actors, such as Amazon Product Scraper (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, which includes residential IPs.

To use these Actors from your agent, add the Apify MCP server to Cursor with this config, or follow the setup for other clients on 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, 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 becomes the tool's input schema, and its output schema tells the agent what the Actor returns before it runs. 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 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.

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.

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 are available for Python, TypeScript, C#, Go, Rust, Ruby, Java, and more. Apify has pre-built Python MCP server and TypeScript MCP server templates.

What you need

  • Python 3.11 or later and uv , the Python package and project manager
  • Node.js, to run MCP Inspector with npx
  • A free Apify account and its API token
  • The Apify CLI , 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 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.

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 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
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:
    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 {}
        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, andopen_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. WithToolError , 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. Socheck_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 toget_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 theextension support 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, socheck_price puts the next step in thenext field of the result.
  • Results are typed and short.check_price returns aPriceReport with a list ofPriceCheck 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 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 tolist_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 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 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 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 or the vendor's OAuth OAuth with your identity provider, which you set up OAuth through 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.

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):
    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:
        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, 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, 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 of the Actor. If that API is behind a company firewall, route the Actor's requests through a dedicated Apify Proxy group, which gives you static IP addresses that the firewall can allowlist.

Give a team or a third-party app a scoped token 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, 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, 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 (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. 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 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 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 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, 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 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
    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, which are memory multiplied by run time, at the rates on the Apify pricing page. 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 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 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, where agents connected to 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 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. 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 , notmcp.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 andmax_items ), and an outlier check before any alert (a price less than half or more than double yours usually means a wrongSKU-to-product mapping )
  • 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 toMCPServer Import MCPServer frommcp.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" tostreamable_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 throughmcp.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 and add it to the same URL.

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.

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.

── more in #agent-protocols 4 stories Β· sorted by recency
── more on @model context protocol 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain β€” perfect for shipping the agent you just read about.

$git push zahid main
β†’ Live at https://your-agent.zahid.host βœ“
Get free account β†’ Pricing
from €0/mo Β· no card required
LIVE [news/how-to-build-an-mcp-…] indexed:0 read:36min 2026-11-24 Β· β€”