Building MCP tools with Python SDK 2.3: typed tools, safe errors and the 2026-07-28 protocol
The MCP Python SDK 2.x treats the 2026-07-28 specification as its latest protocol and adds discovery, a new client and an Apps extension. This guide builds a small orders server, connects to it in-process and explains what the model sees when a tool fails.
- Reading time
- 13 min
- Sections
- 9
- Code examples
- 6
- Tables
- 1
- Sources
- 6
- Published
- 23 Nov 2026
- What changed
- MCP Python SDK 2.3.0 released
- Why it matters
- For tool authors, the 2.x SDK makes good habits cheap.
- What to do
- Pin the SDK
The Model Context Protocol (MCP) is a standard way for an AI application to discover and call tools, read data and fetch prompt templates from a separate server. Before MCP, every agent framework had its own tool format, and every integration was written several times. With MCP, you write a server once and any MCP-capable host can use it, much like a USB device that works in any computer with a USB port.
The official Python SDK has a 2.x line, and its current release is 2.3.0, published on 2 October 2026. Its version registry lists five known protocol versions, from 2024-11-05 to 2026-07-28, and splits them into "handshake" versions, which use the older initialize exchange, and one "modern" version, 2026-07-28. The SDK's client now probes a server/discover method first and falls back to the handshake for older servers.
This tutorial builds a two-tool orders server with the 2.3.0 SDK, connects to it from a client in the same process (no network, no subprocess), and walks through the outputs. All code was run with mcp==2.3.0 on Python 3.13.
What happened
MCP Python SDK 2.3.0 released (2 October 2026)
The mcp package reached 2.3.0 on PyPI, after 2.1.0 (24 August) and 2.2.0 (7 September). A 1.30.0 release on 7 September shows the 1.x line still receives updates for projects that have not migrated. The README points to a "What's new in v2" page and a migration guide, and its examples use the new MCPServer class and a high-level Client.
Protocol version 2026-07-28 is the SDK's latest (28 July 2026)
In 2.3.0, LATEST_PROTOCOL_VERSION is 2026-07-28 and OLDEST_SUPPORTED_VERSION is 2024-11-05. The registry marks 2026-07-28 as the only modern version and 2025-11-25 as the latest handshake version. When we connected our in-process client to our server, the client reported protocol 2026-07-28.
A2A Python SDK 1.3.1 (17 November 2026)
For agent-to-agent communication, the separate a2a-sdk package for the A2A protocol published 1.3.1 on 17 November. MCP connects an agent to tools and data; A2A connects agents to other agents. The two are complementary, as the A2A page explains.
How MCP fits into an agent
An agent is a loop: the model reads the conversation, decides to call a tool, the host runs the tool, and the result goes back into the conversation. MCP standardises the middle part, between the host and the tool provider.
There are three roles:
- Host: the AI application, such as a chat app, an IDE or your agent service.
- Client: a connector inside the host, one per server.
- Server: a program that exposes tools (actions the model can call), resources (data the host can read, addressed by URI) and prompts (reusable templates).
The model never talks to the server directly. It sees tool names, descriptions and JSON Schemas, chooses a call, and the host sends that call through the client. This is the same function calling mechanism models already use, with the tool definitions coming from a server instead of your own code. The ReAct tool-calling simulation animates that loop.
Building a server step by step
pip install "mcp==2.3.0"
import asyncio
from pydantic import BaseModel
from mcp import Client
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
server = MCPServer("orders")
ORDERS = {"A-42": {"status": "delivered", "amount": 120.0}}
class OrderStatus(BaseModel):
order_id: str
status: str
amount: float
@server.tool()
def get_order(order_id: str) -> OrderStatus:
"""Return the status and amount of an order."""
if order_id not in ORDERS:
raise ToolError(f"unknown order {order_id}; IDs look like A-42")
return OrderStatus(order_id=order_id, **ORDERS[order_id])
@server.resource("policy://refunds")
def refund_policy() -> str:
"""The current refund policy text."""
return "Refunds within 30 days of delivery. Shipping is not refunded."
Three things happen without extra code:
- The input schema comes from the type hints.
order_id: strbecomes a JSON Schema property of type string. The docstring becomes the tool description the model reads. - The output schema comes from the return type. Because
get_orderreturns a Pydantic model, the tool advertises an output schema withorder_id,statusandamount, and results carrystructured_contentthat a host can validate. - Resources are addressed by URI.
policy://refundsis something the host can read and place into context, without the model needing to call a tool.
Connecting a client in-process
The 2.x Client accepts a URL (Streamable HTTP), stdio launch parameters, any transport, or, for tests, the server object itself. Passing the object "dispatches directly without JSON-RPC framing", which makes it ideal for unit tests:
async def main():
async with Client(server) as client:
print("protocol:", client.protocol_version)
for t in (await client.list_tools()).tools:
print("tool:", t.name, "| input schema:", t.input_schema["properties"])
print(" output schema keys:", list((t.output_schema or {}).get("properties", {})))
ok = await client.call_tool("get_order", {"order_id": "A-42"})
print("structured:", ok.structured_content, "| is_error:", ok.is_error)
bad = await client.call_tool("get_order", {"order_id": "Z-1"})
print("bad call is_error:", bad.is_error, "|", bad.content[0].text)
res = await client.read_resource("policy://refunds")
print("resource:", res.contents[0].text)
asyncio.run(main())
protocol: 2026-07-28
tool: get_order | input schema: {'order_id': {'title': 'Order Id', 'type': 'string'}}
output schema keys: ['order_id', 'status', 'amount']
structured: {'order_id': 'A-42', 'status': 'delivered', 'amount': 120.0} | is_error: False
bad call is_error: True | Error executing tool get_order: unknown order Z-1; IDs look like A-42
resource: Refunds within 30 days of delivery. Shipping is not refunded.
What the model sees when a tool fails
Tool errors are where many agents go wrong. If the model sees nothing useful, it guesses. If it sees a raw stack trace, you may leak file paths, SQL or secrets into the conversation and your logs.
The 2.3.0 SDK draws a clear line, documented on the ToolError class:
| What the tool does | What the model sees | What the server logs |
|---|---|---|
Raises ToolError("message") |
is_error=True with "Error executing tool name: message" |
INFO, no traceback |
| Raises any other exception | is_error=True with only "Error executing tool name" |
ERROR with full traceback |
| Receives arguments that fail the input schema | An anticipated error, treated like ToolError |
INFO |
Raises MCPError |
A JSON-RPC protocol error, not a tool result | Protocol error |
We tested both paths. Before adding the ToolError, our first version simply did ORDERS[order_id], which raised KeyError: 'Z-1'. The server printed the full traceback, and the client received only Error executing tool get_order. After switching to ToolError, the client received the helpful text "unknown order Z-1; IDs look like A-42", which a model can act on by asking the user for a correct ID.
The rule of thumb: raise ToolError with a short, safe, actionable message for problems the caller can fix. Let everything else crash, so it stays on the server. This mirrors the opt-in error handling in agent frameworks such as LangChain's ToolErrorMiddleware.
From MCP tools to model tool definitions
A host has to translate what the server lists into the tool format its model expects. With the 2.x client, that is a few lines. Here we turn the server's tools into the common "function" format used by many chat APIs:
async def tool_definitions():
async with Client(server) as client:
listed = await client.list_tools()
return [{"type": "function",
"function": {"name": t.name, "description": t.description,
"parameters": t.input_schema}} for t in listed.tools]
For get_order, the generated parameters object is {"type": "object", "properties": {"order_id": {"title": "Order Id", "type": "string"}}, "required": ["order_id"], "title": "get_orderArguments"}, and the whole definition serialises to 277 characters.
That number is worth a moment. Tool definitions are sent to the model on every turn of the loop, because the model must see them to choose a call. One small tool costs little. A host that connects five servers with 15 tools each, with longer descriptions of around 1,000 characters per tool, sends roughly 75,000 characters of tool definitions per model call, which is on the order of 19,000 tokens at a rough four characters per token, before the user has said anything. Over a 10-turn agent run that is close to 190,000 input tokens spent only on tool lists, unless your provider's prompt caching absorbs it. This is why hosts filter tools per task, why descriptions should be short and precise, and why "connect every server" is rarely a good default. The agent loop token cost simulation shows how this repeated overhead adds up.
Continue learning
How this article connects
6 pages link to or from it. Drag to turn, click a dot to open it.
What changed in the 2.x protocol handling
Discovery instead of a handshake
Older MCP sessions start with an initialize request where client and server agree on a version and capabilities. The 2.x client's default mode="auto" "probes server/discover and falls back to the initialize handshake on legacy servers". You can force mode="legacy" for "byte-identical pre-2026 behavior", or pin a modern version string such as "2026-07-28" and reuse a known discovery result to skip the probe.
Why might this matter? A handshake creates per-connection state. A discovery call that can be cached makes it easier to put MCP servers behind ordinary load balancers, where any replica can answer any request. Treat the details as specification territory and check them against the spec for your version.
Multi-round input and elicitation
The 2.x client has an elicitation_callback and an input_required_max_rounds setting (default 10). Comments in the tool runner say that for protocol versions from 2026-07-28 a tool's parameters can be resolved with client input over several rounds, surfacing "batched questions" before the tool body runs. In practice this is how a server can ask the user for a missing value, such as a confirmation, without the model inventing it.
MCP Apps as an extension
The SDK includes mcp.server.apps, an implementation of the MCP Apps extension (io.modelcontextprotocol/ui). A tool can point to a ui:// HTML resource that the host renders "in a sandboxed iframe". The docstring stresses graceful degradation: a UI-enabled tool "should still return meaningful text for clients that did not negotiate Apps". The generative UI page covers why tools are starting to return interfaces, not only text.
What it means in practice
For tool authors, the 2.x SDK makes good habits cheap. Typed signatures give you schemas, Pydantic return types give hosts structured results, and ToolError gives the model useful errors without leaking internals. The in-process client means every tool can have a fast unit test.
For platform teams, the move toward discovery and version pinning matters more. Mixed fleets will exist for a while: hosts that speak only handshake versions, servers that speak only modern ones, and SDKs that support both. Test each pair you depend on.
Security does not come from the protocol alone. An MCP server is code with access to your systems, and its tool descriptions are text the model reads and may obey. Use scoped credentials (OAuth for tool access), run untrusted servers in a sandbox, and treat tool outputs as untrusted input. The MCP tool page collects more background.
What to do now
- Pin the SDK. Use
mcp==2.3.0for new servers and record the protocol versions your hosts support. - Type every tool. Add precise type hints and a clear docstring; they become the schema and the description the model reads.
- Return Pydantic models where structure helps. Hosts get an output schema and
structured_contentto validate. - Use ToolError for expected failures. Write messages that tell the model what to do next, and never include secrets or stack traces.
- Unit test in-process. Use
Client(server)in tests so every tool runs without network or subprocess setup. - Test the legacy path. If old hosts connect to your server, run a test with
mode="legacy"as well as the default. - Keep side effects behind confirmation. For destructive tools, require explicit confirmation via elicitation or a human approval step in the host.
- Review third-party servers like dependencies. Read their tool descriptions and permissions before installing them.
Risks and open questions
Version skew. With handshake and modern versions side by side, a host and server can each be "MCP compatible" and still fail to talk. Pin and test pairs.
Migration cost from 1.x. The 1.x line still receives releases, which suggests many projects have not moved. Adapters in other frameworks may lag the 2.x API; check their release dates before upgrading.
Tool descriptions are an attack surface. A malicious server can put instructions in a description. Hosts should show users what tools do and limit what they can reach.
Error messages can still leak. ToolError text goes to the model verbatim. Code review should check every message for internal details.
Watch next: adoption of server/discover by major hosts, how frameworks such as LangChain's MCP adapters support SDK 2.x, and whether MCP Apps moves from draft to stable.
Frequently asked questions
What is the difference between a tool and a resource in MCP?
A tool is an action the model chooses to call with arguments, such as looking up an order. A resource is data addressed by a URI that the host can read and add to context, such as a policy document. Resources do not need the model to decide to call them.
Do I need a network to test an MCP server?
No. In SDK 2.3.0 you can pass the MCPServer object to Client and call tools in-process. Our example ran this way with no network and no subprocess.
Why does my tool error only say "Error executing tool"?
Any exception other than ToolError (or ResourceError) is treated as a crash. The model sees only the generic message and the server logs the traceback. Raise ToolError with a safe message for errors the model should see.
Which protocol versions does SDK 2.3.0 support?
Its registry lists 2024-11-05, 2025-03-26, 2025-06-18, 2025-11-25 and 2026-07-28. The first four use the initialize handshake; 2026-07-28 is the modern version reached through discovery.
Is MCP the same as A2A?
No. MCP connects an AI application to tools, data and prompts. A2A is a protocol for agents to talk to other agents. Many systems use both.
Summary
The MCP Python SDK 2.3.0 makes 2026-07-28 its latest protocol, probes server/discover before falling back to the older handshake, and ships an Apps extension for tools with interactive interfaces. Building a small orders server shows the practical gains: type hints become input schemas, Pydantic return types become output schemas with structured results, and ToolError gives the model actionable errors while other exceptions stay on the server. Test tools in-process, pin versions across hosts and servers, and treat every server and its descriptions as code with access to your systems.
Sources
- Code PyPI: mcp 2.3.0
- Code PyPI: mcp 2.2.0
- Code PyPI: mcp 1.30.0
- Code PyPI: mcp-types
- Code PyPI: a2a-sdk 1.3.1
- Code PyPI: mcp 2.1.0
Cite this article
Kelahmet, Ö. C. (2026, November 23). Building MCP tools with Python SDK 2.3: typed tools, safe errors and the 2026-07-28 protocol. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/mcp-python-sdk-v2-server-tutorial
BibTeX
@online{kelahmet2026python,
author = {Kelahmet, {\"O}zer Cem},
title = {{Building MCP tools with Python SDK 2.3: typed tools, safe errors and the 2026-07-28 protocol}},
year = {2026},
month = {nov},
url = {https://www.ozercemkelahmet.com/articles/mcp-python-sdk-v2-server-tutorial}
}Version historyfirst version
- Published
Factual corrections are listed here with what changed. Wording and formatting edits are not listed.