Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

19.5 Practice: Discover and Call an MCP Tool

MCP tool integration

Use the official Python SDK v2 to connect to an in-process server. The example probes the protocol version with server/discover, lists the tools, and calls add. The in-process transport lets CI exercise the full call without a network listener or model credentials.

python -m pip install "mcp>=2,<3"
python examples/chapter19/mcp_demo.py
"""Discover and call an MCP 2026-07-28 tool through the official Python SDK."""

import asyncio

from mcp import Client
from mcp.server import MCPServer
from mcp.types import TextContent

server = MCPServer("arithmetic")


@server.tool()
def add(a: int, b: int) -> str:
    """Add two integers."""
    return str(a + b)


async def main() -> None:
    async with Client(server) as client:
        if client.protocol_version != "2026-07-28":
            raise RuntimeError(f"Unexpected MCP version: {client.protocol_version}")
        tools = await client.list_tools()
        print(f"{client.protocol_version}: {', '.join(tool.name for tool in tools.tools)}")

        result = await client.call_tool("add", {"a": 12, "b": 8})
        if result.is_error:
            raise RuntimeError(f"Tool failed: {result.content}")
        for block in result.content:
            if isinstance(block, TextContent):
                print(block.text)


if __name__ == "__main__":
    asyncio.run(main())

Expected output is 2026-07-28: add followed by 20. The SDK handles discovery and request metadata. To connect to a separate tool process or a remote service, use the corresponding client transport settings. Load and invoke tools inside the client context. A tool wrapper that captures a client can only be used while that context is open.

When wiring tools into an agent, the host decides which tools the model can see. Tool code validates arguments and access rights. Tools that write state should enforce server-side permissions, any required approval, and idempotency. Treat third-party content in tool results as data when passing it to the model.

The repository command python -m reference_agent.mcp_server is a minimal MCP 2024-11-05 example for inspecting raw stdio messages. See the SDK's protocol versions guide for modern and handshake-era clients.