Sub topic 8
Connecting to a server with the Python SDK
This chapter assumes you can read async Python, know what an MCP host, client and server are, and have the server.py from the previous chapter (the calc server with one add tool). You will write the client half: launch the server, open a session, and call a tool.
What the SDK gives you
The official mcp package splits the client into two layers:
- A transport moves bytes. For a local server,
stdio_clientstarts the server as a subprocess and connects to its standard input and output. - A session,
ClientSession, speaks the protocol over those streams. It builds JSON-RPC requests, matches responses to them, and exposes methods such asinitialize(),list_tools()andcall_tool().
You nest them. The transport yields a pair of streams, and the session wraps that pair.
A first connection
Save this next to server.py and run it. It starts the server, lists its tools and calls one.
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
server_params = StdioServerParameters(command="python", args=["server.py"])
async def main():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
listed = await session.list_tools()
for tool in listed.tools:
print(tool.name, "-", tool.description)
print(tool.inputSchema)
result = await session.call_tool("add", {"a": 2, "b": 3})
print(result.isError, [c.text for c in result.content if c.type == "text"])
asyncio.run(main())You should see the add tool with its schema, then False ['5']. The next chapter covers schemas in detail, so this chapter looks at the connection itself.
The server parameters
StdioServerParameters describes how to start the process:
| Field | Meaning |
|---|---|
| `command` | The executable to run, such as `python` or `npx`. |
| `args` | Command-line arguments as a list. |
| `env` | Environment variables for the child. Optional. |
| `cwd` | Working directory for the child. Optional. |
Two details cause trouble in practice.
pythonmay not be the interpreter you want. If the server needs packages from your virtual environment, usesys.executableas the command so the child runs the same interpreter as the host.envis not merged with your full environment. The SDK passes a small safe set of variables (such asPATHandHOME) plus whatever you add. Secrets such as an API key must be passed explicitly, and this is useful: the server gets only what you give it.
import sys
from mcp import StdioServerParameters
server_params = StdioServerParameters(
command=sys.executable,
args=["server.py"],
env={"CALC_PRECISION": "6"},
)What `initialize()` does
initialize() performs the handshake from the lifecycle chapter. The client sends its protocol version and capabilities, the server replies with its own, and the client sends an initialized notification. The SDK handles all three steps. The return value is useful:
init = await session.initialize()
print(init.serverInfo.name, init.protocolVersion)
print("tools supported:", init.capabilities.tools is not None)Check capabilities before calling optional features. A server that declares no tools capability may reject list_tools().
You must call initialize() before anything else. Requests sent earlier fail or hang, depending on the server.
Making the connection reusable
The nested async with blocks work for a script. An application usually needs the session to stay open across many user turns and to be passed to other functions. AsyncExitStack lets you enter both context managers and close them together later.
from contextlib import AsyncExitStack
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
class McpConnection:
def __init__(self, params: StdioServerParameters):
self.params = params
self._stack = AsyncExitStack()
self.session: ClientSession | None = None
async def __aenter__(self) -> ClientSession:
try:
read, write = await self._stack.enter_async_context(
stdio_client(self.params)
)
self.session = await self._stack.enter_async_context(
ClientSession(read, write)
)
await self.session.initialize()
except BaseException:
await self._stack.aclose()
raise
return self.session
async def __aexit__(self, *exc_info):
await self._stack.aclose()Use it like this:
async def main():
async with McpConnection(server_params) as session:
result = await session.call_tool("add", {"a": 10, "b": 5})
print(result.content[0].text)The try/except matters. If initialize() raises, __aexit__ never runs because __aenter__ did not complete. Without the cleanup, the subprocess stays alive.
The channel belongs to the protocol
With stdio, the server's standard output is the protocol channel. Anything else written there corrupts the JSON-RPC stream. If your server has a stray print("debug"), the client sees invalid JSON and the session fails or logs parse errors.
- In servers, log to standard error or use the
loggingmodule, which writes to stderr by default. - On the client side, the SDK forwards the child's stderr to your terminal. That is where server logs and tracebacks appear.
Errors at two levels
A tool call can fail in two different ways, and your code must tell them apart.
- A protocol error raises an exception in your client. Examples are an unknown method, a malformed request, or a dead server. The SDK raises
McpErrorfor errors the server reports, and other exceptions for broken transports. - A tool error is a normal response with
isError=True. The tool ran, or tried to, and reports failure in its content, so the model can read it.
from mcp import McpError
async def safe_call(session, name, args):
try:
result = await session.call_tool(name, args)
except McpError as exc:
return f"Protocol error: {exc}", True
text = "\n".join(c.text for c in result.content if c.type == "text")
return text, bool(result.isError)The next chapters build on this split. Tool errors go back to the model so it can retry, and protocol errors usually mean your application has a bug or the server is gone.
Timeouts
Without a timeout, a hung server blocks your application. ClientSession accepts read_timeout_seconds as a timedelta, which applies to every request:
from datetime import timedelta
async with ClientSession(
read, write, read_timeout_seconds=timedelta(seconds=30)
) as session:
...A request that exceeds the limit raises an exception instead of waiting forever. call_tool also accepts its own read_timeout_seconds, so you can allow a slow tool more time than a fast one.
Common mistakes
- Calling
list_tools()beforeinitialize(). - Using a relative path such as
server.pywhen the host runs from a different directory. Use an absolute path, or setcwd. - Forgetting that the child does not inherit your secrets.
- Letting the session outlive its
async withblock, then calling it after the subprocess has exited. - Printing to stdout inside a stdio server.
Exercise
Your client prints "connection closed" right after you start it, and server.py works when you test it in isolation with another tool. Name two causes specific to how the SDK launches the server, and how you would check each.
Show answer
First, command="python" may resolve to a different interpreter than your virtual environment's, so the server fails to import its packages. Check by running the same command in the client's environment, or switch to sys.executable. Second, a relative server.py path may not exist in the host's working directory, or the server may need an environment variable that the SDK did not pass to the child. Check by using an absolute path or setting cwd, and by adding the variable to env. The server's traceback appears on stderr in both cases.
Exercise
A tool call returns a result with isError=True. Does call_tool raise an exception? What should the host do with the result?
Show answer
No. A tool error is a normal response, so no exception is raised. The host should check isError and pass the error text back to the model so it can correct its arguments or choose another approach. Exceptions such as McpError are for protocol-level failures.