Building an MCP Client in Python from Scratch A tutorial demonstrates building a working Model Context Protocol (MCP) client in Python using the official MCP Python SDK 2.0.0 or higher, connecting to a local server over stdio and routing Claude's tool calls through a loop that handles chained calls and tool errors. The guide targets the stateless 2026-07-28 spec revision and warns that many existing tutorials still show the v1 API (ClientSession, session.initialize()), which no longer matches what `pip install mcp` installs. It requires Python 3.10 or higher, the uv package manager, and an Anthropic API key. In this article, you will learn how to build a working MCP client in Python with the official MCP Python SDK 2.0, connect it to a local server over stdio, and let Claude call that server’s tools. Topics we will cover include: - How an MCP client connects to a server over stdio, lists its tools, and calls them directly. - What the JSON-RPC messages behind a tool call look like under the stateless 2026-07-28 spec revision. - How to convert MCP tools into Claude’s tool format and route Claude’s tool calls in a loop that handles chained calls and tool errors. What an MCP Client Does Three roles show up in the MCP architecture https://modelcontextprotocol.io/docs/2026-07-28/learn/architecture . The host is the AI application. The server exposes tools, resources, or prompts. The client sits inside the host and keeps one connection to one server. Its job is simple. It connects, asks the server what tools exist, and calls a tool when the model asks for one. The model never talks to the server directly. Your client translates in both directions, and that translation is the code you are about to write. Prerequisites You need Python 3.10 or higher, the uv package manager, and an Anthropic API key https://console.anthropic.com/settings/keys . You must also use the Python MCP SDK 2.0.0 or higher, as the official client guide https://modelcontextprotocol.io/docs/2026-07-28/develop/build-client requires. That version note matters. The SDK reached v2.0.0 https://github.com/modelcontextprotocol/python-sdk/releases/tag/v2.0.0 to support the 2026-07-28 spec revision, and pip install mcp now installs 2.x. Many tutorials still show the v1 API ClientSession, session.initialize , which does not match what you will install today. The migration guide https://py.sdk.modelcontextprotocol.io/migration/ covers every change if you have older code. Project Setup If you do not have uv yet, install it with the command from the official server guide https://modelcontextprotocol.io/docs/2026-07-28/develop/build-server : curl -LsSf https://astral.sh/uv/install.sh | sh 1 curl -LsSf https://astral.sh/uv/install.sh | sh Then create the project: Create the project and a virtual environment uv init mcp-client cd mcp-client uv venv source .venv/bin/activate Windows: .venv\Scripts\activate Install the MCP SDK with CLI extras , the Anthropic SDK, and dotenv uv add "mcp cli " anthropic python-dotenv Remove the boilerplate file and create the files we will fill in rm main.py Windows: del main.py touch server.py explore.py client.py Store the API key outside your code, and keep it out of git echo "ANTHROPIC API KEY=your-api-key-goes-here" .env echo ".env" .gitignore 12345678910111213141516 Create the project and a virtual environmentuv init mcp-clientcd mcp-clientuv venvsource .venv/bin/activate Windows: .venv\Scripts\activate Install the MCP SDK with CLI extras , the Anthropic SDK, and dotenvuv add "mcp cli " anthropic python-dotenv Remove the boilerplate file and create the files we will fill inrm main.py Windows: del main.pytouch server.py explore.py client.py Store the API key outside your code, and keep it out of gitecho "ANTHROPIC API KEY=your-api-key-goes-here" .envecho ".env" .gitignore This gives you one project that holds both sides of the connection. mcp cli brings in the server and client classes. python-dotenv loads your key from .env so it never lands in source control. The Test Server A client needs something to talk to. Put this in server.py . It exposes two tools, so you can later watch Claude chain them. python import logging from typing import Any from urllib.parse import urlencode import httpx2 from mcp.server import MCPServer In a stdio server, stdout carries the protocol. Logs must go to stderr. logging.basicConfig level=logging.INFO logging writes to stderr by default logger = logging.getLogger name mcp = MCPServer "weather-tools" GEOCODE URL = "https://geocoding-api.open-meteo.com/v1/search" FORECAST URL = "https://api.open-meteo.com/v1/forecast" async def fetch json url: str - dict str, Any | None: """GET a URL and return parsed JSON, or None if anything goes wrong.""" async with httpx2.AsyncClient as http: try: response = await http.get url, timeout=15.0 response.raise for status return response.json except Exception: logger.exception "Request to %s failed", url return None @mcp.tool async def get weather city: str - str: """Get the current temperature and wind speed for a city. Args: city: City name, for example Lagos or Tokyo """ geo = await fetch json f"{GEOCODE URL}?{urlencode {'name': city, 'count': 1} }" if not geo or not geo.get "results" : return f"Could not find a city called '{city}'." place = geo "results" 0 query = urlencode { "latitude": place "latitude" , "longitude": place "longitude" , "current": "temperature 2m,wind speed 10m", } forecast = await fetch json f"{FORECAST URL}?{query}" if not forecast or "current" not in forecast: return "Weather data is unavailable right now." current = forecast "current" return f"{place 'name' }, {place.get 'country', 'unknown country' }: " f"{current 'temperature 2m' } °C, wind {current 'wind speed 10m' } km/h" @mcp.tool def convert temperature value: float, from unit: str, to unit: str - str: """Convert a temperature between celsius, fahrenheit and kelvin. Args: value: The temperature to convert from unit: celsius, fahrenheit or kelvin to unit: celsius, fahrenheit or kelvin """ units = {"celsius", "fahrenheit", "kelvin"} source, target = from unit.lower , to unit.lower if source not in units or target not in units: Raised errors come back to the client as a tool error the model can read raise ValueError "Units must be celsius, fahrenheit or kelvin." Normalise to celsius first, then convert out if source == "fahrenheit": celsius = value - 32 5 / 9 elif source == "kelvin": celsius = value - 273.15 else: celsius = value if target == "fahrenheit": result = celsius 9 / 5 + 32 elif target == "kelvin": result = celsius + 273.15 else: result = celsius return f"{value} {source} is {result:.1f} {target}" if name == " main ": mcp.run transport="stdio" 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 import loggingfrom typing import Anyfrom urllib.parse import urlencode import httpx2from mcp.server import MCPServer In a stdio server, stdout carries the protocol. Logs must go to stderr.logging.basicConfig level=logging.INFO logging writes to stderr by defaultlogger = logging.getLogger name mcp = MCPServer "weather-tools" GEOCODE URL = "https://geocoding-api.open-meteo.com/v1/search"FORECAST URL = "https://api.open-meteo.com/v1/forecast" async def fetch json url: str - dict str, Any | None: """GET a URL and return parsed JSON, or None if anything goes wrong.""" async with httpx2.AsyncClient as http: try: response = await http.get url, timeout=15.0 response.raise for status return response.json except Exception: logger.exception "Request to %s failed", url return None @mcp.tool async def get weather city: str - str: """Get the current temperature and wind speed for a city. Args: city: City name, for example Lagos or Tokyo """ geo = await fetch json f"{GEOCODE URL}?{urlencode {'name': city, 'count': 1} }" if not geo or not geo.get "results" : return f"Could not find a city called '{city}'." place = geo "results" 0 query = urlencode { "latitude": place "latitude" , "longitude": place "longitude" , "current": "temperature 2m,wind speed 10m", } forecast = await fetch json f"{FORECAST URL}?{query}" if not forecast or "current" not in forecast: return "Weather data is unavailable right now." current = forecast "current" return f"{place 'name' }, {place.get 'country', 'unknown country' }: " f"{current 'temperature 2m' } °C, wind {current 'wind speed 10m' } km/h" @mcp.tool def convert temperature value: float, from unit: str, to unit: str - str: """Convert a temperature between celsius, fahrenheit and kelvin. Args: value: The temperature to convert from unit: celsius, fahrenheit or kelvin to unit: celsius, fahrenheit or kelvin """ units = {"celsius", "fahrenheit", "kelvin"} source, target = from unit.lower , to unit.lower if source not in units or target not in units: Raised errors come back to the client as a tool error the model can read raise ValueError "Units must be celsius, fahrenheit or kelvin." Normalise to celsius first, then convert out if source == "fahrenheit": celsius = value - 32 5 / 9 elif source == "kelvin": celsius = value - 273.15 else: celsius = value if target == "fahrenheit": result = celsius 9 / 5 + 32 elif target == "kelvin": result = celsius + 273.15 else: result = celsius return f"{value} {source} is {result:.1f} {target}" if name == " main ": mcp.run transport="stdio" MCPServer is the SDK 2.0 name for what v1 called FastMCP . The @mcp.tool decorator turns each function’s type hints and docstring into the tool’s name, description, and input schema, which is exactly what the client will read later. httpx2 is the HTTP client the SDK itself depends on, as the official server guide https://modelcontextprotocol.io/docs/2026-07-28/develop/build-server notes, so there is nothing extra to install. The weather data comes from the free, keyless Open-Meteo API https://open-meteo.com/ . The comment about stderr is not decoration. In the stdio transport https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/stdio , the server reads from stdin and writes JSON-RPC to stdout, and anything else written there corrupts the stream. A single stray print is enough to break the server. Step 1: Connect and List Tools Before any model gets involved, prove the connection works. Put this in explore.py : python import asyncio import json import sys from mcp import Client, StdioServerParameters from mcp.client.stdio import stdio client Launch server.py with the same Python interpreter that runs this script params = StdioServerParameters command=sys.executable, args= "server.py" async def main - None: Entering the block starts the server and connects. Leaving it shuts both down. async with Client stdio client params as client: tool list = await client.list tools for tool in tool list.tools: print f"\n{tool.name}: {tool.description}" print json.dumps tool.input schema, indent=2 if name == " main ": asyncio.run main 12345678910111213141516171819202122 import asyncioimport jsonimport sys from mcp import Client, StdioServerParametersfrom mcp.client.stdio import stdio client Launch server.py with the same Python interpreter that runs this scriptparams = StdioServerParameters command=sys.executable, args= "server.py" async def main - None: Entering the block starts the server and connects. Leaving it shuts both down. async with Client stdio client params as client: tool list = await client.list tools for tool in tool list.tools: print f"\n{tool.name}: {tool.description}" print json.dumps tool.input schema, indent=2 if name == " main ": asyncio.run main Run it with uv run explore.py from the project folder. StdioServerParameters only describes the subprocess to launch. stdio client turns that description into a transport, and Client opens the transport when you enter its async with block. According to the official guide https://modelcontextprotocol.io/docs/2026-07-28/develop/build-client , that block is the entire connection lifecycle, so there is nothing to close by hand. Using sys.executable instead of the string “python” guarantees the server runs in the same virtual environment as the client. You should see both tools printed with their JSON Schema. That schema is what the model will use to decide how to call them. Step 2: Call a Tool Directly Now call a tool yourself, with no model involved. Replace main in explore.py with the code below. Put the new import with the others at the top of the file, and the helper function just above main : php from mcp types import TextContent def result text result - str: """Join the text blocks of a tool result into one string.""" return "\n".join block.text for block in result.content if isinstance block, TextContent async def main - None: async with Client stdio client params as client: ok = await client.call tool "convert temperature", {"value": 30, "from unit": "celsius", "to unit": "fahrenheit"}, print result text ok , "| is error:", ok.is error An invalid unit makes the tool raise on the server side bad = await client.call tool "convert temperature", {"value": 1, "from unit": "celsius", "to unit": "rankine"}, print result text bad , "| is error:", bad.is error 123456789101112131415161718192021222324 from mcp types import TextContent def result text result - str: """Join the text blocks of a tool result into one string.""" return "\n".join block.text for block in result.content if isinstance block, TextContent async def main - None: async with Client stdio client params as client: ok = await client.call tool "convert temperature", {"value": 30, "from unit": "celsius", "to unit": "fahrenheit"}, print result text ok , "| is error:", ok.is error An invalid unit makes the tool raise on the server side bad = await client.call tool "convert temperature", {"value": 1, "from unit": "celsius", "to unit": "rankine"}, print result text bad , "| is error:", bad.is error call tool returns a CallToolResult . Its content is a list of blocks, which is why result text narrows to TextContent before reading .text . The second call shows the part people miss: a failing tool does not raise an exception in your client. It answers with is error set to True, and the message tells the model what went wrong so it can try again. Remember this flag, because the next steps depend on it. What Just Happened on the Wire The SDK hid the messages. Here is what crossed the connection, simplified. Under the stdio transport https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/stdio , each JSON-RPC message is sent on a single line. The examples below are pretty-printed for readability. Your call tool call produced a request like this: { "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "convert temperature", "arguments": { "value": 30, "from unit": "celsius", "to unit": "fahrenheit" } } } 123456789 { "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "convert temperature", "arguments": { "value": 30, "from unit": "celsius", "to unit": "fahrenheit" } }} And the server answered: { "jsonrpc": "2.0", "id": 2, "result": { "resultType": "complete", "content": { "type": "text", "text": "30.0 celsius is 86.0 fahrenheit" } , "isError": false } } 123456789 { "jsonrpc": "2.0", "id": 2, "result": { "resultType": "complete", "content": { "type": "text", "text": "30.0 celsius is 86.0 fahrenheit" } , "isError": false }} These shapes follow the tools section of the 2026-07-28 spec https://modelcontextprotocol.io/specification/2026-07-28/server/tools.md . Four details are worth knowing. 1. First, there is no handshake anymore. The 2026-07-28 revision https://modelcontextprotocol.io/specification/2026-07-28/changelog.md removed initialize and made MCP stateless. Every request carries its protocol version and client capabilities in meta , which the examples above leave out for brevity, as the spec’s own examples do. 2. Second, servers must implement a new server/discover call that advertises their supported versions, capabilities, and identity. Clients can use it to pick a version up front or to probe older servers. You never call it yourself, because the SDK’s Client negotiates the version automatically https://github.com/modelcontextprotocol/python-sdk/releases/tag/v2.0.0 and still works with 2025-era servers. 3. Third, every result carries a resultType , and “complete” means an ordinary result. 4. Fourth, errors come in two kinds. A malformed request or unknown tool is a protocol-level JSON-RPC error. A tool that ran and failed returns a normal result with isError: true . Your client should pass the second kind to the model, because the spec says tool execution errors are what let a model correct itself. Step 3: Turn MCP Tools into Claude Tools Claude needs each tool described in its own format. The two formats line up almost one to one: | MCP tool field | Claude tool field | |---|---| | name | name | | description | description | | input schema | input schema | The official guide https://modelcontextprotocol.io/docs/2026-07-28/develop/build-client does the same mapping. This is the first piece of client.py : python import asyncio import sys from anthropic import AsyncAnthropic from dotenv import load dotenv from mcp import Client, StdioServerParameters from mcp.client.stdio import stdio client from mcp types import TextContent load dotenv loads ANTHROPIC API KEY from .env MODEL = "claude-opus-5-5" any tool-capable Claude model works here MAX TURNS = 8 hard stop so a confused model cannot loop forever anthropic = AsyncAnthropic def server params server script path: str - StdioServerParameters: """Describe the subprocess that runs the server script.""" if server script path.endswith ".py" : command = sys.executable elif server script path.endswith ".js" : command = "node" else: raise ValueError "Server script must be a .py or .js file" return StdioServerParameters command=command, args= server script path def to claude tools tool list - list dict : """Convert MCP tool definitions into Claude's tool format.""" return { "name": tool.name, "description": tool.description or "", "input schema": tool.input schema, } for tool in tool list.tools def result text result - str: """Join the text blocks of a tool result into one string.""" return "\n".join block.text for block in result.content if isinstance block, TextContent 1234567891011121314151617181920212223242526272829303132333435363738394041424344 import asyncioimport sys from anthropic import AsyncAnthropicfrom dotenv import load dotenvfrom mcp import Client, StdioServerParametersfrom mcp.client.stdio import stdio clientfrom mcp types import TextContent load dotenv loads ANTHROPIC API KEY from .env MODEL = "claude-opus-5-5" any tool-capable Claude model works hereMAX TURNS = 8 hard stop so a confused model cannot loop foreveranthropic = AsyncAnthropic def server params server script path: str - StdioServerParameters: """Describe the subprocess that runs the server script.""" if server script path.endswith ".py" : command = sys.executable elif server script path.endswith ".js" : command = "node" else: raise ValueError "Server script must be a .py or .js file" return StdioServerParameters command=command, args= server script path def to claude tools tool list - list dict : """Convert MCP tool definitions into Claude's tool format.""" return { "name": tool.name, "description": tool.description or "", "input schema": tool.input schema, } for tool in tool list.tools def result text result - str: """Join the text blocks of a tool result into one string.""" return "\n".join block.text for block in result.content if isinstance block, TextContent server params accepts a Python or Node server, so the client works with servers written in either language. AsyncAnthropic is used instead of the sync client so model calls do not block the event loop that is serving the MCP connection. Swap MODEL for any tool-capable model from Anthropic’s model list https://platform.claude.com/docs/en/models/opus-5-5/overview . Step 4: Route the Model’s Tool Calls This is the core of the client. When Claude wants a tool, your code runs it through the server and returns the result. That can happen several times in a row, so it needs a loop. Add this to client.py : php async def process query client: Client, tools: list dict , query: str - str: """Answer a query, letting Claude call MCP tools until it is done.""" messages = {"role": "user", "content": query} for in range MAX TURNS : response = await anthropic.messages.create model=MODEL, max tokens=2048, messages=messages, tools=tools, No tool request means Claude has given its final answer if response.stop reason = "tool use": return "\n".join b.text for b in response.content if b.type == "text" Keep Claude's full turn in the history, exactly as returned messages.append {"role": "assistant", "content": response.content} tool results = for block in response.content: if block.type = "tool use": continue print f" Calling tool {block.name} with args {block.input} " result = await client.call tool block.name, block.input tool results.append { "type": "tool result", "tool use id": block.id, "content": result text result , "is error": result.is error, } Tool results go back as a user message, then the loop asks Claude again messages.append {"role": "user", "content": tool results} return "Stopped after reaching the turn limit." 1234567891011121314151617181920212223242526272829303132333435363738 async def process query client: Client, tools: list dict , query: str - str: """Answer a query, letting Claude call MCP tools until it is done.""" messages = {"role": "user", "content": query} for in range MAX TURNS : response = await anthropic.messages.create model=MODEL, max tokens=2048, messages=messages, tools=tools, No tool request means Claude has given its final answer if response.stop reason = "tool use": return "\n".join b.text for b in response.content if b.type == "text" Keep Claude's full turn in the history, exactly as returned messages.append {"role": "assistant", "content": response.content} tool results = for block in response.content: if block.type = "tool use": continue print f" Calling tool {block.name} with args {block.input} " result = await client.call tool block.name, block.input tool results.append { "type": "tool result", "tool use id": block.id, "content": result text result , "is error": result.is error, } Tool results go back as a user message, then the loop asks Claude again messages.append {"role": "user", "content": tool results} return "Stopped after reaching the turn limit." Here is the flow. Claude replies either with text or with one or more tool use blocks, and stop reason tells you which. For each tool use block, client.call tool sends a tools/call request to the server, and the result goes back to Claude as a tool result tied to the block’s id. Passing is error along lets Claude read a failure and recover, which is the behavior you saw in Step 2. Two details are easy to get wrong. Append response.content untouched instead of rebuilding it, because the model’s thinking blocks must stay with the conversation that produced them, as the Opus 5.5 docs https://platform.claude.com/docs/en/models/opus-5-5/overview describe. And keep MAX TURNS . The official quickstart makes a single round of tool calls, which breaks on any question that needs two tools in sequence. Step 5: Chat Loop and Entry Point Finish client.py with the chat loop and main : php async def chat loop client: Client, tools: list dict - None: print "\nType a question, or 'quit' to exit." while True: try: input blocks, so run it on a worker thread query = await asyncio.to thread input, "\nQuery: " .strip except EOFError: break if query.lower == "quit": break if not query: continue try: print "\n" + await process query client, tools, query except Exception as e: print f"\nError: {e}" report it, keep the session alive async def main - None: if len sys.argv < 2: print "Usage: python client.py