Connect a Python Agent to MCP Servers With the Official MCP SDK
The problem: every agent rewrites the same tool integrations
So far the trip helper's tools live in trip_tools.py, inside the agent's own code. That is fine for one agent. But imagine you build three agents that all need the weather tool, and a colleague has already written tools for your company's booking system, and a code editor you use can also talk to tools. Without a shared format, each agent wraps each tool again, with its own schema and its own error handling.
The Model Context Protocol (MCP) is an open protocol for exactly this. A server exposes tools (and other things, such as resources and prompts) in a standard way. A client, inside your agent, connects to the server, asks what tools it has, and calls them. Any MCP client can use any MCP server. The LLM Fundamentals course explains what MCP is; this lesson connects the trip helper to a real MCP server using the official Python SDK.
You will:
- write a tiny MCP server with the trip tools
- connect to it from Python, list its tools and call one
- plug its tools into the agent loop, so the model can use them like local tools
Install and version note
The mcp package installed at the start of the course is the official Python SDK. This lesson was tested with version 2.3.0 of the SDK, whose documentation is at py.sdk.modelcontextprotocol.io.
The SDK changed names between major versions. In version 1, the high level server class was called FastMCP and lived in mcp.server.fastmcp. In version 2 it is MCPServer in mcp.server, and the client side has a Client class. Many tutorials online still show the version 1 names; if an import fails, check which version you have with pip show mcp.
Step 1: a tiny MCP server
Save this as trip_server.py. Its data is made up, like the rest of the course:
python# file: trip_server.py """A tiny MCP server with the trip helper tools. All data is made up.""" from mcp.server import MCPServer from mcp.server.mcpserver.exceptions import ToolError mcp = MCPServer("trip-helper") FAKE_WEATHER = { "lisbon": {"forecast": "sunny", "high_c": 22, "low_c": 14}, "kyoto": {"forecast": "light rain", "high_c": 17, "low_c": 9}, "oslo": {"forecast": "cloudy", "high_c": 6, "low_c": -1}, } FAKE_RATES_TO_EUR = {"EUR": 1.0, "USD": 0.92, "JPY": 0.0061, "INR": 0.011, "NOK": 0.085} @mcp.tool() def get_weather(city: str) -> dict: """Get the 3 day forecast for one city (high and low in Celsius).""" data = FAKE_WEATHER.get(city.strip().lower()) if data is None: raise ToolError(f"Unknown city '{city}'. Try Lisbon, Kyoto or Oslo.") return {"city": city.title(), **data} @mcp.tool() def convert_currency(amount: float, from_currency: str, to_currency: str) -> dict: """Convert money between currencies using ISO codes like USD, EUR, JPY.""" src, dst = from_currency.upper(), to_currency.upper() if src not in FAKE_RATES_TO_EUR or dst not in FAKE_RATES_TO_EUR: raise ToolError(f"Supported currencies: {sorted(FAKE_RATES_TO_EUR)}") return {"amount": round(amount * FAKE_RATES_TO_EUR[src] / FAKE_RATES_TO_EUR[dst], 2), "currency": dst} if __name__ == "__main__": mcp.run() # stdio transport: the client starts this file as a subprocess
This is the whole server:
MCPServer("trip-helper")creates a server with a name clients can see.@mcp.tool()turns a normal Python function into an MCP tool. The SDK reads the function name, the type hints and the docstring and builds the tool's name, JSON Schema and description from them, much like the helper you wrote in lesson 3.- Raising
ToolErrorreports an expected problem. The SDK sends it back to the client as a result marked as an error, not as a crash. That is the same "errors are tool results" idea from lesson 4, built into the protocol. mcp.run()uses the stdio transport by default: the server reads requests from standard input and writes responses to standard output.
You do not start this server yourself. With stdio, the client launches it as a subprocess and talks to it through pipes. MCP also defines an HTTP based transport for servers that run remotely; the client code differs only in how you connect.
Step 2: connect, list tools, call one
Save this as list_mcp_tools.py in the same folder:
python# file: list_mcp_tools.py import asyncio import sys from mcp import Client, StdioServerParameters SERVER = StdioServerParameters(command=sys.executable, args=["trip_server.py"]) async def main() -> None: async with Client(SERVER) as client: print("connected to:", client.server_info.name) result = await client.list_tools() for tool in result.tools: print("-", tool.name, ":", tool.description) print(" schema:", tool.input_schema) call = await client.call_tool("get_weather", {"city": "Atlantis"}) print("is_error:", call.is_error, "| text:", call.content[0].text) asyncio.run(main())
What happens:
StdioServerParameters(command=sys.executable, args=["trip_server.py"])says how to start the server.sys.executableis the Python running this script, so the server uses the same virtual environment.async with Client(SERVER) as client:starts the subprocess, performs the MCP handshake, and closes everything when the block ends.client.server_info.nameis the name the server announced.await client.list_tools()returns a result whose.toolslist holds each tool'sname,descriptionandinput_schema.await client.call_tool(name, arguments)runs a tool. The result has.content(a list of content blocks; text results come as blocks with a.textfield) and.is_error.
The MCP SDK is asynchronous, so the code uses async/await and starts with asyncio.run(main()). The SDK's own examples use anyio, which works the same way here.
The tested output, trimmed:
textconnected to: trip-helper - get_weather : Get the 3 day forecast for one city (high and low in Celsius). schema: {'type': 'object', 'properties': {'city': {'title': 'City', 'type': 'string'}}, 'required': ['city'], ...} - convert_currency : Convert money between currencies using ISO codes like USD, EUR, JPY. ... is_error: True | text: Error executing tool get_weather: Unknown city 'Atlantis'. Try Lisbon, Kyoto or Oslo.
Two things to notice. The schema was generated from the type hints, including required. And the call for "Atlantis" did not raise an exception in the client: it came back as a normal result with is_error set to True and the error message as text. The SDK also printed a log line about the failed tool to the terminal, which you can ignore or silence with Python's logging settings.
sequenceDiagram autonumber participant C as Client (your agent) participant S as trip_server.py C->>S: async with Client(SERVER): start subprocess C->>S: MCP handshake (initialize) S-->>C: server_info.name: trip-helper C->>S: list_tools() S-->>C: get_weather, convert_currency + input_schema C->>S: call_tool get_weather, city Atlantis S->>S: ToolError: Unknown city S-->>C: result: is_error True, text content Note over C,S: The error comes back as a result, not a crash
Diagram: Client and server over stdio: handshake, list the tools, call one, and an error comes back as a result.
Animation: The client starts the server as a subprocess, lists its tools and calls one. The Atlantis call comes back as a result with is_error True.
Step 3: give MCP tools to the model
An MCP tool already carries a name, a description and a JSON Schema. Those are exactly the three things the chat completions tools format needs, so the translation is direct. Save this as mcp_agent.py:
python# file: mcp_agent.py import asyncio import json import sys from mcp import Client, StdioServerParameters from mcp.types import TextContent from llm import client as llm, MODEL SERVER = StdioServerParameters(command=sys.executable, args=["trip_server.py"]) def to_openai_tool(tool) -> dict: """An MCP tool already carries a JSON Schema, so the translation is direct.""" return {"type": "function", "function": { "name": tool.name, "description": tool.description or "", "parameters": tool.input_schema}} def result_text(result) -> str: text = "\n".join(block.text for block in result.content if isinstance(block, TextContent)) return json.dumps({"error": text}) if result.is_error else text async def run_agent(question: str, max_steps: int = 5) -> str: async with Client(SERVER) as mcp: tools = [to_openai_tool(t) for t in (await mcp.list_tools()).tools] messages = [{"role": "system", "content": "You are a trip helper. Use tools for facts. Be brief. " "If a tool returns an error, fix the arguments and call it again. Never guess a number."}, {"role": "user", "content": question}] failed = None # name of a tool whose latest call returned an error corrected = False for _ in range(max_steps): msg = llm.chat.completions.create(model=MODEL, messages=messages, tools=tools, temperature=0).choices[0].message messages.append(msg) if not msg.tool_calls: if failed and not corrected: # the model is answering over a failed call corrected = True print(f" correction: {failed} failed, asking for a retry") messages.append({"role": "user", "content": f"The {failed} call failed. Read the error, " "then call it again with exactly the parameter names in its schema."}) continue return msg.content for call in msg.tool_calls: try: args = json.loads(call.function.arguments or "{}") output = result_text(await mcp.call_tool(call.function.name, args)) except json.JSONDecodeError: output = json.dumps({"error": "Arguments were not valid JSON."}) if output.startswith('{"error"'): failed = call.function.name elif failed == call.function.name: failed = None print(f" MCP {call.function.name}({call.function.arguments}) -> {output[:120]}") messages.append({"role": "tool", "tool_call_id": call.id, "content": output}) return "Stopped at the step limit." if __name__ == "__main__": print(asyncio.run(run_agent("How many EUR is 5000 JPY, and how warm does Lisbon get?")))
The pieces:
to_openai_toolmaps an MCP tool to the{"type": "function", "function": {...}}format from lesson 2, usinginput_schemaasparameters.result_textjoins the text blocks of a result. Ifis_erroris set, it wraps the text as{"error": ...}, the same shape your local tools use, so the model sees errors consistently.- The loop is the agent loop from lesson 2. The only change is where tools run:
await mcp.call_tool(...)instead of a local function. The MCP connection stays open for the whole run.
The agent does not know or care that the tools live in another process. You could point SERVER at a different MCP server, one you did not write, and the same loop would use its tools.
What happened in the test run
The first run of mcp_agent.py with qwen2.5:1.5b on Ollama asked "How many EUR is 5000 JPY, and how warm does Lisbon get?" and showed a small model failure clearly:
- The model called
convert_currencywith a broken argument name: it merged two keys into one,"amount from_currency": "JPY". The MCP server validated the arguments against the schema, rejected the call, and the error came back throughis_errorwith a message sayingfrom_currencywas missing. - The
get_weathercall for Lisbon worked. - The model then did not retry the conversion. It answered with a made-up figure for the yen conversion, while the made-up rates in the server would give about 30.5 EUR.
The protocol did its job: bad arguments were caught and reported. The model did not use the report. A stronger system prompt ("If a tool returns an error, fix the arguments and call it again. Never guess a number.") did not change that in two more runs: the same merged key, the same guessed number.
What fixed it was code. The final mcp_agent.py above tracks the name of any tool whose latest call failed. If the model tries to answer while a call is still failed, the loop adds one correction message and continues. In the tested run with the correction in place:
textMCP convert_currency({"amount from_currency":"JPY","to_currency":"EUR","amount":5000}) -> {"error": ...} MCP get_weather({"city":"Lisbon"}) -> {"city": "Lisbon", "forecast": "sunny", ...} correction: convert_currency failed, asking for a retry MCP convert_currency({"amount":5000,"from_currency":"JPY","to_currency":"EUR"}) -> {"amount": 30.5, ...} 5000 JPY is approximately 30.50 EUR, and Lisbon is expected to be warm with a high of 22°C and a low of 14°C.
The model made the same mistake again, but this time the second call had correct argument names, and the final answer used the real tool result.
sequenceDiagram autonumber participant M as Model participant A as mcp_agent loop participant S as MCP server A->>S: list_tools(), map to OpenAI tool format A->>M: question + tools M-->>A: convert_currency (merged key) + get_weather A->>S: call_tool convert_currency S-->>A: is_error: from_currency missing A->>S: call_tool get_weather Lisbon S-->>A: sunny, high 22, low 14 A->>M: both tool results M-->>A: Tries to answer over the failed call A->>M: Correction: call it again with the schema names M-->>A: convert_currency amount 5000, JPY to EUR A->>S: call_tool convert_currency S-->>A: amount 30.5 A->>M: tool result M-->>A: 5000 JPY is about 30.50 EUR
Diagram: The server rejects the merged key, the loop adds one correction, and the retry gets 30.5 EUR.
More ways to handle ignored tool errors
The correction turn is one option. Others, in the spirit of lessons 4 and 11:
- Return a failure status. If the run must end while a call is still failed, return a status that says so instead of an answer, as the budgeted agent in lesson 11 does.
- Limit corrections. The code corrects once. A model that fails twice in a row on the same call is unlikely to succeed on the tenth try.
- Use a larger model through
AGENT_MODEL. Argument formatting errors like a merged key are less common in larger models, but keep the check anyway.
Trust and MCP servers
An MCP server is code that runs on your machine (with stdio) or a service you send data to (with HTTP). Treat servers you did not write like any dependency:
- Read what a server's tools do before connecting it. A server can expose tools that write files, send messages or spend money.
- Apply the allowlist and approval rules from lesson 6. Map MCP tools through your own
POLICYbefore giving them to the model. Nothing about MCP makes a risky tool safe. - Tool results are untrusted input. A server that fetches web pages or emails can return text containing prompt injection, exactly as in lesson 6.
- Tool descriptions are also input. They go into the model's prompt, so a malicious server can try to steer the model through its descriptions. Only connect servers you trust.
Common mistakes
- Copying version 1 tutorials (
FastMCP,mcp.server.fastmcp) into a version 2 install, or the other way round. - Printing to standard output in a stdio server. Standard output carries the protocol. Debug output from
printin the server can break the connection; log to standard error instead. - Opening a new connection for every tool call. Keep one
Clientopen for the whole agent run. - Ignoring
is_error. Treat error results as errors and show them to the model clearly. - Connecting servers without reviewing their tools. Every tool a server exposes becomes an action your agent can take.
What to try next
- Add a
search_hotelstool totrip_server.pyand confirm the agent picks it up with no change tomcp_agent.py. - Run
list_mcp_tools.pywith a different MCP server from the SDK's examples, changing onlySERVER. - Remove the correction turn and rerun the 5000 JPY question a few times to see how often your model guesses.
- Wrap the MCP tools with the
POLICYcheck from lesson 6, so any tool not on your list is refused.
Next: the trip helper has many moving parts now. Before you change anything else, you need a way to know whether a change made it better or worse. That is the eval harness.
Sources
Convert MCP tools into the model's tool format
An MCP server lists its tools with a name, a description and an input schema. The chat completions API wants a different wrapper around the same information.
Write mcp_to_tools(mcp_tools) where mcp_tools is a list of dicts like {"name": "get_weather", "description": "...", "inputSchema": {...}}.
Return a list of {"type": "function", "function": {"name": ..., "description": ..., "parameters": ...}}.
- A missing or None description becomes "".
- A missing inputSchema becomes {"type": "object", "properties": {}}.
- Skip any tool whose name is already taken by an earlier tool in the list: two tools with one name would confuse the model.
The worked solution unlocks after your first attempt.
Check what you learned
Answer all 3 questions. You need at least 2 right to pass.
1. How does the stdio MCP server get started in this lesson?
2. What did the client receive when get_weather was called for Atlantis?
3. What finally made the agent retry the failed convert_currency call?