Python SDK: MCPServer, Context and Client
The Python SDK 2.x (`mcp` 2.3) builds servers with `MCPServer` (renamed from FastMCP): decorators turn plain functions into tools, resources and prompts, type hints become JSON Schemas, and return annotations become output schemas. Know the two error channels, the per-request `Context`, lifespan state, how 2026-07-28 changes elicitation (resolvers and multi-round-trip instead of server push), and what multi-worker HTTP deployment needs.
Key points
- 1
Imports:
from mcp.server import MCPServerfor servers andfrom mcp import Clientfor clients; there is nofrom mcp import MCPServer.mcp.server.fastmcpnow raisesModuleNotFoundErrorpointing at the migration guide, and an unnamed server reportsmcp-server. - 2
@mcp.tool()derives the name from the function, the description from the docstring and the input schema from type hints. Parameters without defaults are required;Annotated[int, Field(ge=1, le=50)]addsminimum/maximum;Literal[...]becomes an enum. Arguments are validated by Pydantic (lax mode, so "5" becomes 5 but 2.5 fails forint) before the function runs, and failures returnis_error=Truetext the model can act on. - 3
The return annotation is the output schema. Scalars, lists, tuples and unions are wrapped as
{"result": ...}; models,TypedDicts, dataclasses anddict[str, ...]are not. Lists become one text block per item. Return values are validated, a class with no body annotations silently becomes text-only, andstructured_output=Falseopts out. - 4
Errors:
ToolErrorgivesis_error=TruewithError executing tool <name>: <message>; any other exception gives onlyError executing tool <name>plus an ERROR traceback in the log;MCPErrorpropagates as a JSON-RPC error thatClient.call_toolraises (a v2 change).ResourceNotFoundErrormaps to-32602with the URI indata. Unknown tool names returnis_error=TruewithUnknown tool: <name>. - 5
Contextis injected by annotation under any parameter name and never appears in the schema. It exposesrequest_id,read_resource,report_progress(a no-op unless the caller passedprogress_callback=),session,headersandrequest_context.lifespan_context.mcp.get_context()was removed; passctxto helpers explicitly. - 6
Lifespan: an
@asynccontextmanagerpassed asMCPServer(..., lifespan=...)runs once around the server; its yielded object isctx.request_context.lifespan_context, typed withContext[AppCtx]. Without one it is{}, neverNone. - 7
Sync
defhandlers run on a worker thread in v2 (asyncio.get_running_loop()raises inside them);async defhandlers stay on the event loop. A plaindeftool must callanyio.from_thread.check_cancelled()to stop early; async cleanup after cancellation needsanyio.move_on_after(..., shield=True)in afinally. - 8
Elicitation:
Annotated[T, Resolve(fn)]resolvers returningElicit(...)work on every era (pushed on 2025-11-25 sessions, returned asInputRequiredResulton 2026-07-28).ctx.elicit()/ctx.elicit_url()need a legacy back-channel and fail on 2026-07-28. Asking a client that did not declare the capability fails with-32021. Tools cannot combineResolve(...)with their ownInputRequiredResultreturn (InvalidSignature). - 9
requestStateis sealed and verified by default under a per-process random key, and bound to a TTL (600 s), the authenticated principal and the originating request. Multi-worker or restart-surviving deployments needRequestStateSecurity(keys=[...])and the same server name (the audience claim) on every instance; rotate with[OLD, NEW], then[NEW, OLD], then[NEW]after one TTL. - 10
Running:
mcp.run()is stdio and blocks;run(transport="streamable-http", port=...)serves/mcp. Transport options go torun()orstreamable_http_app(), never the constructor. Mounted apps need the host lifespan to entermcp.session_manager.run(), and real hostnames needtransport_security=TransportSecuritySettings(allowed_hosts=[...])or every request gets 421. - 11
Client:
Client(x)picks Streamable HTTP for a URL, a subprocess forStdioServerParameters(with an allow-listed environment, so passenv=), in-memory for a server object, and treats anything else as a transport.mode="auto"probesserver/discoverand falls back toinitialize;mode="legacy"forces the handshake; a version pin sends nothing (pair it withprior_discover=).Client(mcp, raise_exceptions=True)is the test harness. - 12
On 2026-07-28 change notifications travel only on
subscriptions/listen: publish withctx.notify_tools_changed()and friends, and share oneSubscriptionBusacross replicas. The protocol logging capability is deprecated; log with the standardloggingmodule to stderr.
Common traps
Writing
@mcp.toolwithout parentheses: it raisesTypeErrorat import.Returning an error string from a tool:
is_errorstays false, so the model treats it as a successful answer. RaiseToolErrorinstead.Expecting
MCPErrorraised in a tool to come back as anis_errorresult, as in v1; in v2 it is a JSON-RPC error and the model sees nothing.Using
print()in a stdio server; stdout is the protocol channel. Uselogging.Passing
port=orstateless_http=toMCPServer(...): transport options moved torun()andstreamable_http_app(), and passinginstructionspositionally now lands intitle.Assuming
stateless_http=Trueis needed to scale 2026-07-28 traffic; modern requests are sessionless anyway, and multi-round-trip retries still fail across workers without sharedrequestStatekeys.Mounting
streamable_http_app()in Starlette or FastAPI without enteringmcp.session_manager.run()in the host lifespan, which fails withTask group is not initialized.On the low-level
Server, assuming the advertisedinput_schemais enforced or that exceptions becomeis_errorresults; neither happens.
Read the source
Further reading
Suggest a resourceNo extra reading for Python SDK: MCPServer, Context and Client yet. Found a guide, video or cheat sheet that made it click? Share it and help the next learner.
Test yourself on Python SDK: MCPServer, Context and Client
Ten questions, with the answer and explanation after each one.