Building an MCP Client
- Connect a Python MCP client to a stdio server using StdioServerParameters and stdio_client
- Implement the agentic tool-call loop following the three rules for Anthropic Messages API tool use
- Explain why asyncio.to_thread is needed for blocking I/O inside an async chat loop
What a Client Does
So far in this track we have focused on building servers. But MCP is a two-sided protocol: servers expose capabilities, clients consume them. If you are building an AI application that needs to access MCP servers — rather than authoring servers for others to use — you are building a client.
In the architecture from Lesson 2, the client is the component the host creates to maintain a connection to one server. In this lesson, you will build a minimal host application that is also the client: a command-line chatbot that connects to a server over stdio, queries its tools, passes them to Claude, and runs a conversational loop where Claude can call those tools on demand.
This is exactly how Claude Desktop works under the hood, stripped down to its essentials. Building it yourself gives you a complete mental model of the protocol flow and the foundation for building any custom AI application that uses MCP.
Prerequisites
- Python 3.10 or higher, with
uv - An Anthropic API key (get one at console.anthropic.com)
- The weather server from Lesson 7 (or any MCP server you built)
Project Setup
uv init mcp-client
cd mcp-client
uv add mcp anthropic python-dotenv
touch client.py .env .gitignore
Add your API key to .env:
ANTHROPIC_API_KEY=your_key_here
Add .env to .gitignore so you do not accidentally commit it:
.env
.venv
Connecting to a Server
The MCP Python SDK provides two key abstractions for the client side: StdioServerParameters (a configuration object describing how to launch the server) and stdio_client (a context manager that launches the server and returns a transport).
import asyncio
import sys
from pathlib import Path
from anthropic import Anthropic
from dotenv import load_dotenv
from mcp import Client, StdioServerParameters
from mcp.client.stdio import stdio_client
from mcp.types import TextContent
load_dotenv()
MODEL = "claude-sonnet-4-5"
MAX_TOKENS = 8096
MAX_TOOL_TURNS = 10
anthropic = Anthropic()
def server_params(server_script: str) -> StdioServerParameters:
path = Path(server_script)
if path.suffix == ".py":
command, args = "python", [str(path)]
elif path.suffix == ".js":
command, args = "node", [str(path)]
else:
raise ValueError(f"Unsupported server script type: {path.suffix}")
return StdioServerParameters(command=command, args=args)
async def main() -> None:
if len(sys.argv) < 2:
print("Usage: uv run client.py ")
sys.exit(1)
async with Client(stdio_client(server_params(sys.argv[1]))) as client:
tools = await client.list_tools()
print(f"Connected. Tools: {[t.name for t in tools.tools]}")
await chat_loop(client)
The async with Client(...) as client: block is the connection lifetime. When Python enters the block, the SDK launches the server subprocess and performs discovery. When Python exits the block — whether normally or due to an exception — the SDK shuts down the server subprocess cleanly. You never need to manually close the connection.
Listing Tools and Formatting Them for Claude
Claude's Messages API accepts tools in a specific format. After listing the server's tools, you need to convert MCP's tool definitions to Anthropic's format:
async def process_query(client: Client, query: str) -> str:
tool_list = await client.list_tools()
available_tools = [
{
"name": t.name,
"description": t.description or "",
"input_schema": t.input_schema,
}
for t in tool_list.tools
]
messages = [{"role": "user", "content": query}]
# ... (agentic loop below)
The input_schema field from MCP is already a JSON Schema dict — exactly what Anthropic's API expects. This is not a coincidence; MCP's tool schema format was designed to be compatible with the major model providers' tool formats.
The Agentic Tool-Call Loop
The core of any MCP client is the loop that runs while the model keeps calling tools. The pattern is:
- Call Claude with the current messages and tool list
- If the response is
end_turn, return the final text to the user - If the response contains
tool_useblocks, execute each tool call via the MCP client - Append the assistant's response and all tool results to messages
- Go to step 1
for _ in range(MAX_TOOL_TURNS):
response = anthropic.messages.create(
model=MODEL,
max_tokens=MAX_TOKENS,
tools=available_tools,
messages=messages,
)
if response.stop_reason == "end_turn":
text_blocks = [b.text for b in response.content if hasattr(b, "text")]
return " ".join(text_blocks)
# Append the full assistant turn (including any thinking blocks)
messages.append({"role": "assistant", "content": response.content})
# Collect tool calls and execute them
tool_results = []
for block in response.content:
if block.type != "tool_use":
continue
result = await client.call_tool(block.name, block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": [
{"type": "text", "text": c.text}
for c in result.content
if isinstance(c, TextContent)
],
"is_error": result.is_error,
})
# All tool results go in a single user message
messages.append({"role": "user", "content": tool_results})
return "Reached the maximum number of tool turns."
Three Critical Rules for the Tool-Call Loop
The Anthropic Messages API enforces strict rules about how tool calls and results must be ordered in a conversation. Violating them produces an API error.
Rule 1: Replay the assistant turn exactly. When you append the assistant's response to messages, append the entire response.content list as-is — do not filter or modify it. The API needs to see exactly what the model produced, including thinking blocks.
Rule 2: Answer every tool use in one user message. If the model calls three tools, your next user message must contain exactly three tool_result blocks — one for each tool_use, matched by tool_use_id. Do not spread results across multiple messages. Do not include non-result content in the same message.
Rule 3: Pass is_error through. If result.is_error is true, set "is_error": True in the tool result. This tells the model that the tool execution failed and gives it the error message to work with. Do not suppress errors — a model that knows a tool failed can recover; a model given a silent failure cannot.
The Chat Loop
async def chat_loop(client: Client) -> None:
print("Type your message (Ctrl+C to exit):
")
while True:
try:
query = await asyncio.to_thread(input, "You: ")
except (KeyboardInterrupt, EOFError):
print("
Goodbye.")
break
if not query.strip():
continue
response = await process_query(client, query)
print(f"
Assistant: {response}
")
if __name__ == "__main__":
asyncio.run(main())
Note the use of asyncio.to_thread(input, ...). The built-in input() is a blocking call. If you call it directly in an async function, it blocks the entire event loop, preventing any network I/O from completing. Wrapping it with asyncio.to_thread runs it in a thread pool, keeping the event loop free.
Running the Client
# Connect to the Python weather server from Lesson 7
uv run client.py path/to/weather/weather.py
# Or connect to the TypeScript weather server from Lesson 8
uv run client.py path/to/weather/build/index.js
Try asking: "What weather alerts are active in Texas?" or "What is the forecast for San Francisco?" and watch Claude discover the tools, call them, and incorporate the results into its response.
TypeScript Version (Sketch)
The TypeScript client follows the same pattern but uses the Node.js SDK:
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
const mcp = new Client(
{ name: "mcp-client-cli", version: "1.0.0" },
{ versionNegotiation: { mode: "auto" } } // handles both 2026 and 2025 servers
);
const transport = new StdioClientTransport({ command, args: [serverPath] });
await mcp.connect(transport);
const { tools } = await mcp.listTools();
// ... (same loop logic using the Anthropic TypeScript SDK)
await mcp.close(); // cleanup in a finally block
The key difference: Python's async with Client(...) manages the connection lifetime automatically. TypeScript requires an explicit await mcp.close() in a finally block to ensure the server subprocess is terminated even if an error occurs.
- The Client context manager handles server lifecycle automatically — connect on enter, clean shutdown on exit
- Every tool_use block in an assistant turn must be answered in a single user message with matching tool_result blocks by id
- Passing is_error through to the model lets it recover from tool failures rather than silently treating them as successes
Progress is saved in this browser only — clear your cache or switch device and it's gone. Create a free account and it follows you everywhere.