How-to › Expose your API to agents

How to build an MCP server in Python with the official MCP SDK#

Write a stdio MCP server on MCPServer from the official Python SDK, derive schemas from type hints, call your API asynchronously, and test it with a scripted client.

Audience
API producer
Level
beginner
Topic
Build an MCP server
Languages
Python
Verified

You copy a Python MCP server example that starts with from mcp.server.fastmcp import FastMCP, and it fails on import with ModuleNotFoundError. Once it runs, a tool that calls your API with a blocking HTTP client holds up every other call the server receives until that API answers.

What you get

You will end up with a stdio MCP server whose schemas come from type hints, and an async API client that keeps other calls moving. This is for you if you have an HTTP API and want agent hosts to reach it through a server written in Python.

Short answer

Install the official mcp package and create an MCPServer. Write each tool as an async function with type hints and a return type such as a TypedDict, so the SDK derives the input and output schemas and returns structured content. Open one httpx.AsyncClient in the server’s lifespan, call mcp.run() for stdio, and check it with a scripted Client that lists the tools and calls one. Never call a blocking client inside an async tool.

You will need

Python 3.11 or later, the mcp package, and an HTTP client for your API, here httpx. Verified 2026-11-30 against Python 3.12.3, mcp 2.3.0 and httpx 0.29.0. The sample’s npm ci installs the pinned Python packages into pydeps/, and every command runs with PYTHONPATH=pydeps. A stand-in shipments API runs on 127.0.0.1, so nothing leaves the machine. Version 2 of mcp renamed the FastMCP class to MCPServer, as the migration guide records, so examples written for version 1 need the import changed.1 The standalone package’s installation page offers the other route, “a single import change” to fastmcp for most servers that import FastMCP from mcp.server.fastmcp.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
Low-level Server APIAn exact schema from a file or a database, or full control of every resultYou write each schema, check each argument, and build each result by handYour tools are ordinary typed functions
MCPServer in the official SDKMost servers: typed functions, derived schemas, and the SDK the protocol’s own project maintainsFeatures arrive with SDK releases, and version 2 renamed the class and moved importsYou need a feature only the standalone package has
Standalone fastmcp packageYou want its extras, such as server composition, proxying, and tool transforms, or its release pace32 more pinned packages here, and breaking changes allowed in minor releasesYou want the smallest dependency set

MCPServer and fastmcp derived the same fields, types, and required list from the same function in the runs below, so the choice between them is about features, dependencies, and release pace. fastmcp adds server composition, which neither the official SDK’s documentation index nor its MCPServer source offers. Its installation page says breaking changes may occur in minor versions to stay current with the protocol. The low-level Server trades every derived schema for exact control, which earns its keep when the schema already exists elsewhere.

Write the tool as a typed async function

The return type is a TypedDict, so the SDK publishes it as the tool’s output schema. The Context argument hands the tool the client opened in the lifespan, and stays out of the input schema.

class Shipment(TypedDict):
    id: str
    status: Literal["in_transit", "delivered", "delayed"]
    carrier: str
    eta: str | None
    last_event: str


@dataclass
class Deps:
    api: httpx.AsyncClient


@asynccontextmanager
async def lifespan(server: MCPServer) -> AsyncIterator[Deps]:
    # One async client for the life of the server. trust_env=False keeps proxy
    # variables from the environment off the API calls.
    async with httpx.AsyncClient(base_url=API_BASE, timeout=10.0, trust_env=False) as api:
        yield Deps(api)


mcp = MCPServer("shipments", lifespan=lifespan)


def segment(value: str) -> str:
    """Escape a caller's id as one URL path segment."""
    if value in ("", ".", ".."):
        raise ToolError(f"{value!r} is not a shipment id. Ids look like shp_1001.")
    return quote(value, safe="")


@mcp.tool()
async def get_shipment(shipment_id: str, ctx: Context) -> Shipment:
    """Read one shipment by id, such as shp_1001: its status, carrier, ETA and last scan."""
    api = ctx.request_context.lifespan_context.api
    res = await api.get(f"/shipments/{segment(shipment_id)}")
    if res.status_code == 404:
        raise ToolError(f"No shipment {shipment_id}. Ids look like shp_1001.")
    res.raise_for_status()
    body = res.json()
    last = body["events"][-1]
    return {
        "id": body["id"],
        "status": body["status"],
        "carrier": body["carrier"],
        "eta": body["eta"],
        "last_event": f"{last['what']} at {last['where']}, {last['at']}",
    }


if __name__ == "__main__":
    mcp.run()

The tool returns five fields and drops the API’s internal_ref and _links. A ToolError reaches the model as a tool result with is_error set, which the handling errors guide separates from a protocol error. segment escapes the id, so ../admin cannot reach another path on your API.

Call it from a scripted client

The client starts the stand-in API, launches server.py over stdio with the API’s address as an argument, lists the tools, and calls one twice.

PYTHONPATH=pydeps python3 client.py
protocol revision: 2026-07-28
tool get_shipment: Read one shipment by id, such as shp_1001: its status, carrier, ETA and last scan.
  input  {"properties": {"shipment_id": {"title": "Shipment Id", "type": "string"}}, "required": ["shipment_id"], "title": "get_shipmentArguments", "type": "object"}
  output {"properties": {"carrier": {"title": "Carrier", "type": "string"}, "eta": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Eta"}, "id": {"title": "Id", "type": "string"}, "last_event": {"title": "Last Event", "type": "string"}, "status": {"enum": ["in_transit", "delivered", "delayed"], "title": "Status", "type": "string"}}, "required": ["id", "status", "carrier", "eta", "last_event"], "title": "Shipment", "type": "object"}
call shp_1001: is_error=False {"id": "shp_1001", "status": "in_transit", "carrier": "Northwind Freight", "eta": "2026-12-02", "last_event": "departed at Rotterdam hub, 2026-11-28T09:14:00Z"}
call ../admin: is_error=True Error executing tool get_shipment: No shipment ../admin. Ids look like shp_1001.
paths the API received: ['/shipments/shp_1001', '/shipments/..%2Fadmin']

Both schemas came from the function signature. The Literal became an enum, and str | None became a nullable eta that is still required. The client and server agreed on revision 2026-07-28 of the protocol. The SDK’s stdio transport starts the server in a process group of its own. On exit it closes the server’s stdin, waits two seconds, then sends the group SIGTERM, and SIGKILL two seconds later if anything in it still runs.

The same tool on the other two

The standalone package needs a different import and a bare @mcp.tool decorator. record.sh installed fastmcp 4.2.6 into a scratch directory, checked each wheel’s SHA-256, ran the same client, and kept what it printed.

cat evidence/fastmcp.txt
fastmcp 4.2.6, mcp 2.3.0
protocol revision: 2026-07-28
tool get_shipment: Read one shipment by id, such as shp_1001: its status, carrier, ETA and last scan.
  input  {"additionalProperties": false, "properties": {"shipment_id": {"type": "string"}}, "required": ["shipment_id"], "type": "object"}
  output {"properties": {"carrier": {"type": "string"}, "eta": {"anyOf": [{"type": "string"}, {"type": "null"}]}, "id": {"type": "string"}, "last_event": {"type": "string"}, "status": {"enum": ["in_transit", "delivered", "delayed"], "type": "string"}}, "required": ["id", "status", "carrier", "eta", "last_event"], "type": "object"}
call shp_1001: is_error=False {"id": "shp_1001", "status": "in_transit", "carrier": "Northwind Freight", "eta": "2026-12-02", "last_event": "departed at Rotterdam hub, 2026-11-28T09:14:00Z"}
call ../admin: is_error=True No shipment ../admin. Ids look like shp_1001.
paths the API received: ['/shipments/shp_1001', '/shipments/..%2Fadmin']

fastmcp 4.2.6 installs mcp 2.3.0 underneath it. Its schemas drop the title keys and add "additionalProperties": false, and its error text has no prefix. It also pins twice as many packages as the worked path.

grep -c "==" requirements.txt fastmcp-requirements.txt
requirements.txt:31
fastmcp-requirements.txt:63

The first file holds mcp, httpx and their dependencies. The second holds all 31 of those plus 32 more, fastmcp and fastmcp-slim among them. The low-level Server in lowlevel.py returns the schemas it was given, keyword for keyword.

PYTHONPATH=pydeps python3 client.py lowlevel.py
  input  {"properties": {"shipment_id": {"type": "string"}}, "required": ["shipment_id"], "type": "object"}
  output {"properties": {"carrier": {"type": "string"}, "eta": {"type": ["string", "null"]}, "id": {"type": "string"}, "last_event": {"type": "string"}, "status": {"enum": ["in_transit", "delivered", "delayed"]}}, "required": ["id", "status", "carrier", "eta", "last_event"], "type": "object"}

Check it worked

Eleven tests run over the real stdio transport. They cover the derived schemas, structured content and its JSON text twin, an unknown id, and path escaping. Others check that a wrong type never reaches the API, test the low-level server, and run the blocking race below. The last starts a server that ignores SIGTERM and checks that the client still ends it and its child.

PYTHONPATH=pydeps python3 test_server.py
test_a_blocking_call_makes_ping_wait (__main__.BlockingTests.test_a_blocking_call_makes_ping_wait) ... ok
test_a_worker_thread_lets_ping_answer_first (__main__.BlockingTests.test_a_worker_thread_lets_ping_answer_first) ... ok
test_an_async_client_lets_ping_answer_first (__main__.BlockingTests.test_an_async_client_lets_ping_answer_first) ... ok
test_a_missing_argument_is_checked_by_hand (__main__.LowLevelTests.test_a_missing_argument_is_checked_by_hand) ... ok
test_the_hand_built_result_matches_the_mcpserver_one (__main__.LowLevelTests.test_the_hand_built_result_matches_the_mcpserver_one) ... ok
test_a_call_returns_structured_content_and_the_same_json_as_text (__main__.MCPServerTests.test_a_call_returns_structured_content_and_the_same_json_as_text) ... ok
test_a_wrong_type_is_refused_before_the_api_is_called (__main__.MCPServerTests.test_a_wrong_type_is_refused_before_the_api_is_called) ... ok
test_an_id_is_escaped_as_one_path_segment (__main__.MCPServerTests.test_an_id_is_escaped_as_one_path_segment) ... ok
test_an_unknown_id_is_a_tool_error_the_model_can_read (__main__.MCPServerTests.test_an_unknown_id_is_a_tool_error_the_model_can_read) ... ok
test_schemas_come_from_the_type_hints (__main__.MCPServerTests.test_schemas_come_from_the_type_hints) ... ok
test_a_server_that_ignores_sigterm_is_killed_with_its_child (__main__.StopTests.test_a_server_that_ignores_sigterm_is_killed_with_its_child) ... ok

Every line ends in ok, and the script exits 1 if one does not. The page leaves out the line after them, which prints a time.

When it goes wrong

An async tool that calls a blocking client stops the event loop until the API answers, so the server reads no other request in the meantime. Python’s asyncio guide says blocking code delays all concurrent tasks. The pitfall server has three versions of the tool.

@mcp.tool()
async def get_shipment_blocking(shipment_id: str) -> dict:
    """Blocks the event loop for as long as the API takes."""
    return fetch_blocking(shipment_id)


@mcp.tool()
async def get_shipment_in_thread(shipment_id: str) -> dict:
    """Runs the same blocking client on a worker thread."""
    return await anyio.to_thread.run_sync(fetch_blocking, shipment_id)

The stand-in answers the slow id after one second. The script starts that call, sends a ping tool call once the stand-in has received it, and prints which answer came back first.2

PYTHONPATH=pydeps python3 pitfall.py
get_shipment_blocking    answers came back: get_shipment_blocking then ping  (ping waited)
get_shipment_in_thread   answers came back: ping then get_shipment_in_thread  (ping answered first)
get_shipment_async       answers came back: ping then get_shipment_async  (ping answered first)

Use an async client, or move the blocking call to a thread with anyio.to_thread.run_sync. Both kept the ping moving.

An import of httpx that worked under version 1 can fail under version 2. The migration guide says the SDK replaced httpx with httpx2, so pin your own HTTP client in your requirements as this sample does.

When not to do this

Do not write the low-level Server for ordinary tools. Its guide says it advertises your schema and never applies it, so every argument check is yours, and one of the tests on this page checks a hand-written one.

Do not add fastmcp for one server you could write on MCPServer. It brought 32 packages that mcp alone did not, and its own documentation allows breaking changes in minor releases. Pin an exact version if you take it.

Do not put a blocking call in an async def tool, even one that is fast in testing. A slow upstream turns it into a stall for every other call on the server.

Do not choose stdio for a server several hosts share over a network. Stdio gives each host its own server process, and a remote deployment needs Streamable HTTP and its own security checks.

Last verified

Verified 2026-11-30 against Python 3.12.3, mcp 2.3.0, httpx 0.29.0 and fastmcp 4.2.6. Every output block is what the command preceding it printed. The fastmcp block was written by record.sh on the same day and is replayed from evidence/fastmcp.txt.

Footnotes

  1. “FastMCP created the high-level Python API incorporated into the official MCP Python SDK in 2024,” says the standalone project’s welcome page. Version 2 of the official SDK renamed its FastMCP class MCPServer, and still ships a module called fastmcp.py whose docstring states that it has no API. It exists to raise the import error with a pointer to the migration guide. ↩︎ Back to text

  2. Revision 2025-11-25 has a ping of its own, a request either side can send to see whether the other is still there. The changelog for revision 2026-07-28 lists ping among the methods it removed, which is why the race here sends a tool that happens to be called ping. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.