Building an MCP Client in Python from Scratch
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. 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. You must also use the Python MCP SDK 2.0.0 or higher, as the official client guide requires.
That version note matters. The SDK reached 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 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:
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
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.
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")
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 notes, so there is nothing extra to install. The weather data comes from the free, keyless Open-Meteo API.
The comment about stderr is not decoration. In the stdio transport, 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:
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())
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, 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():
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, 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"
}
}
}
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
}
}
These shapes follow the tools section of the 2026-07-28 spec. Four details are worth knowing.
- First, there is no handshake anymore. The 2026-07-28 revision 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. - Second, servers must implement a new
server/discovercall 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'sClientnegotiates the version automatically and still works with 2025-era servers. - Third, every result carries a
resultType, and "complete" means an ordinary result. - 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 does the same mapping. This is the first piece of client.py:
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)
)
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.
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:
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 !
Comments
No comments yet. Start the discussion.