Sub topic 8
Connecting to a server with the Python SDK
This chapter assumes you can read async Python, know what JSON and JSON Schema are, and have called an LLM API with tools before. You will launch an MCP server from your own code, complete the handshake, and make one tool call. The chapter uses the server.py from the previous chapter.
What the client session does
In the official mcp package, a ClientSession is your application's client. It speaks JSON-RPC over a pair of streams. It does not know how those streams are created. A transport helper creates them, and for a local server that helper is stdio_client.
For stdio, your application starts the server as a subprocess. It writes requests to the subprocess's standard input and reads responses from its standard output.
Connecting and calling a tool
Install the SDK with pip install mcp. Save this next to server.py:
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())Run it with python client.py. You should see the add tool, its schema, and a result of False ['5'].
What each step does
StdioServerParametersdescribes how to start the server: the command and its arguments. It starts the process but does not run it yet.stdio_clientis an async context manager. On entry it starts the subprocess and yields a read stream and a write stream. On exit it shuts the subprocess down.ClientSessionwraps those streams and turns method calls into JSON-RPC requests.initialize()performs the handshake. The client and server agree on a protocol version and exchange capabilities. No other request is valid before it completes.list_tools()andcall_tool()sendtools/listandtools/callrequests.
Reading the result
call_tool returns a result object, not a bare value. Two fields matter now:
contentis a list of content blocks. Text blocks havetype == "text"and atextfield. Servers can also return images and other types, so filter bytypebefore reading.text.isErrorisTruewhen the tool itself failed. This is different from a protocol error. A tool failure comes back as a normal result withisErrorset, so check it before using the content.
Common errors
- Starting the subprocess with the wrong interpreter.
command="python"uses whicheverpythonis on thePATH. If the server's dependencies live in a virtual environment, usesys.executableor the full path. - Printing to stdout in the server. With stdio, standard output carries the protocol messages. A stray
print()in the server corrupts the stream. Log to standard error instead. - Calling methods before
initialize(). The session is not ready until the handshake finishes. - Using the session outside its
async withblock. Once the block exits, the subprocess is gone and later calls fail.
Exercise
Your client prints nothing and then fails with a parsing error shortly after initialize(). The server has a print("starting") line at the top of server.py. What is wrong, and how do you fix it?
Show answer
With the stdio transport, the server's standard output carries the JSON-RPC messages, so the extra print text is read as a malformed message. Remove the print or send it to standard error, for example with print("starting", file=sys.stderr), or use the logging module, which writes to standard error by default.