Sub topic 6
Initialization and the connection lifecycle
This chapter assumes you can read async Python and have seen the JSON-RPC message shapes from the previous chapters. You should also have the server.py calculator from the earlier chapter. Here you will learn what happens between launching a server and making your first tool call, and where that stage tends to fail.
The three phases
Every MCP connection moves through three phases:
- Initialization. Client and server agree on a protocol version and exchange capabilities.
- Operation. Both sides send requests, responses and notifications within the agreed capabilities.
- Shutdown. The connection closes, and the transport defines how.
The phases are strict. A client that calls tools/list before initialization finishes is breaking the protocol, and a server may reject the call.
The initialize request
The client always speaks first. Its initialize request carries three things:
protocolVersion: the newest protocol version the client supports. Versions are date strings such as2025-06-18.capabilities: the optional features the client offers, such as sampling or roots.clientInfo: a name and version, useful in server logs.
The server replies with its own protocolVersion, capabilities and serverInfo. It may also include instructions, a text hint about how to use the server. A host can pass those instructions to the model, but they come from a third party, so treat them as untrusted text.
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-06-18",
"capabilities": {},
"clientInfo": {"name": "my-host", "version": "0.1.0"}
}
}After the response arrives, the client sends notifications/initialized. A notification has no id and gets no reply. It tells the server that the client is ready, and the operation phase begins after it.
Version negotiation
If the server supports the client's requested version, it answers with the same version. If it does not, it answers with another version it does support, normally its newest. The client then decides what to do. If it can't work with the server's version, it should disconnect.
Your host should treat a version mismatch as a connection failure with a clear message. Don't try to carry on with a version you haven't tested against.
Capabilities decide what you may call
Capabilities are the contract for the operation phase. A server that does not declare tools should not receive tools/list. The server capabilities you will meet most often are:
| Capability | Meaning | Sub-flags |
|---|---|---|
| `tools` | Server exposes callable tools | `listChanged` |
| `resources` | Server exposes readable data | `subscribe`, `listChanged` |
| `prompts` | Server exposes prompt templates | `listChanged` |
| `logging` | Server can send log messages to the client | none |
The listChanged flag means the server may send a notification when its list changes. A host that caches tool definitions should watch for it and refresh the cache. A host that rebuilds the tool list on every turn, as the agent loop in this tutorial does, doesn't need to.
Inspecting the handshake with the SDK
ClientSession.initialize() sends the request, reads the response and sends the initialized notification. It returns the server's answer, so you can inspect what was negotiated.
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:
init = await asyncio.wait_for(session.initialize(), timeout=10)
print("protocol:", init.protocolVersion)
print("server:", init.serverInfo.name, init.serverInfo.version)
if init.instructions:
print("instructions:", init.instructions)
caps = init.capabilities
print("tools:", caps.tools is not None)
print("resources:", caps.resources is not None)
print("prompts:", caps.prompts is not None)
if caps.tools is not None:
listed = await session.list_tools()
print([t.name for t in listed.tools])
asyncio.run(main())Against the calculator server, this prints tools: True, resources: False and prompts: False. FastMCP declares only the capabilities for which you registered something.
The asyncio.wait_for call matters. A server that starts but never answers initialize would otherwise hang your host forever.
What the SDK does for you, and what it doesn't
The two nested async with blocks are the lifecycle in code:
stdio_clientstarts the server as a subprocess and manages its pipes. Leaving the block closes them and stops the process.ClientSessionruns a background task that reads incoming messages and matches responses to request ids. Leaving the block stops that task.
The SDK does not call initialize() for you. Forgetting it is the most common lifecycle bug, and it shows up as a confusing error on the first real call rather than at the point of the mistake.
Shutdown
Shutdown has no protocol message of its own. The transport does the closing.
- stdio. The client closes the server's standard input and waits for the process to exit. If it doesn't exit, the client sends SIGTERM, and then SIGKILL if that fails. The SDK follows this sequence when the
stdio_clientblock exits. - Streamable HTTP. The client closes its HTTP connections. If the server assigned a session id in an
Mcp-Session-Idheader, the client can end the session with an HTTP DELETE request.
For servers that hold state, close the connection deliberately. A host that exits without leaving the async with blocks can leave orphaned server processes behind.
Failure modes
| Symptom | Likely cause |
|---|---|
| `initialize()` hangs | Server crashed on startup, wrong command, or the server wrote nothing to stdout |
| Parse errors immediately after launch | The server printed non-protocol text to stdout, for example a `print()` call |
| Connection closed during initialize | Import error or missing dependency in the server process |
| Error on the first `list_tools` | `initialize()` was never called |
| Method not found for `resources/list` | The server never declared `resources` and you didn't check |
| Works alone, fails in the host | The subprocess runs with a different working directory, interpreter or environment |
Lifetime in a real application
A session represents one live connection, so decide how long it should live:
- One session per host process. Open each server at startup, keep the sessions for the life of the process, and close them on exit. This avoids paying the startup and handshake cost on every user turn.
- One session per request. Simple and isolated, but slow for subprocess servers that need seconds to start.
Most hosts use the first approach. It means you need to handle a server dying mid-session. A call on a dead session raises an error, and the host must either reconnect, which includes a fresh initialize, or report the tool as unavailable to the model.
Exercise
Your host launches a stdio server and gets a McpError on the first list_tools() call. The server process is running and healthy. Name the first thing to check, and one more check that should come before any tool listing.
Show answer
Check that await session.initialize() was called and completed before list_tools(). The SDK does not do it automatically, and the operation phase starts only after the handshake. The second check is the server's declared capabilities in the initialize result: only call list_tools() if capabilities.tools is not None.
Exercise
A stdio server works when run by hand but your host fails with a JSON parse error right after launch. What is the most likely cause in the server code, and where should the server write its debug messages instead?
Show answer
The server probably writes debug text to standard output with print(), which mixes it into the JSON-RPC stream. It should write debug messages to standard error, or use the logging facility of the SDK.