Sub topic 4
Starting a Session: Initialization and Capability Negotiation
This chapter assumes you can read JSON, know the host, client, and server roles from the earlier chapters, and understand the JSON-RPC request, response, and notification shapes. Here you will learn the three-message handshake that begins every Model Context Protocol (MCP) session. You will also learn how the two sides agree on features, and which mistakes cause the most failures.
Why a handshake is needed
An MCP client and server are written by different people and released on different schedules. Before they exchange real work, they must settle two questions:
- Which version of the protocol will both sides speak?
- Which optional features does each side support?
The initialization phase answers both. Nothing else may happen first. The client sends one request, the server answers it, and the client sends one notification to say it is ready. After that, normal traffic begins.
The lifecycle at a glance
A session moves through three phases: initialization, operation, and shutdown. This chapter covers the first phase in detail and touches on the last.
Step 1: the initialize request
The client always speaks first. It sends an initialize request that carries three things: the protocol version it wants, the capabilities it offers, and information about itself.
{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18", "capabilities": {"sampling": {}}, "clientInfo": {"name": "example-client", "version": "1.0.0"}}}Each field has a job:
| Field | Meaning |
|---|---|
| `protocolVersion` | The version string the client prefers. It should be the latest version the client supports. |
| `capabilities` | The optional client features available to the server, such as `sampling`, `roots`, and `elicitation`. |
| `clientInfo` | The client's `name` and `version`, useful for logs and debugging. |
In the example, "sampling": {} means the client lets the server ask it for model completions. The empty object is deliberate. A capability is present when its key exists, even if it has no settings.
Step 2: the server's response
The server replies with a normal JSON-RPC result that uses the same id. It states its own version, capabilities, and identity. A typical reply looks like this:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2025-06-18",
"capabilities": {
"tools": {"listChanged": true},
"resources": {"subscribe": true, "listChanged": true},
"prompts": {},
"logging": {}
},
"serverInfo": {"name": "demo", "version": "0.1.0"}
}
}This server announces that it provides tools, resources, and prompts, and that it can send log messages. The sub-keys such as listChanged and subscribe are flags for finer features. They are covered below.
Step 3: the initialized notification
The client finishes the handshake with a notification, which has no id and expects no reply:
{"jsonrpc": "2.0", "method": "notifications/initialized"}This message tells the server that the client has processed the response and is ready. Until it is sent, the server should not send requests of its own. The only messages allowed earlier are pings and logging messages. The client, likewise, should not send other requests before the server has answered initialize, apart from pings.
Version negotiation
The version string is a date, such as 2025-06-18, that names a revision of the specification. The rules are simple:
- The client sends the latest version it supports.
- If the server supports that version, it answers with the same string.
- If it does not, it answers with another version it does support, normally its latest.
- If the client cannot work with the version the server chose, it should disconnect.
The server never fails the request just because the versions differ. It proposes a version and the client decides whether to accept. This keeps the decision on the side that can see both the request and the reply.
When using Streamable HTTP, the client must also send the negotiated version in an MCP-Protocol-Version header on every later request. Chapter on transports covers this in detail.
Capability negotiation
Capabilities are the core of the handshake. Each side lists what it can do, and a feature is usable only if the side that must implement it declared it.
What servers declare
| Capability | Meaning | Sub-flags |
|---|---|---|
| `tools` | The server exposes callable tools. | `listChanged` |
| `resources` | The server exposes readable data. | `subscribe`, `listChanged` |
| `prompts` | The server exposes prompt templates. | `listChanged` |
| `logging` | The server can emit log messages. | none |
| `completions` | The server can suggest argument values. | none |
What clients declare
| Capability | Meaning | Sub-flags |
|---|---|---|
| `sampling` | The server may request model completions through the client. | none |
| `roots` | The server may ask which filesystem roots the client exposes. | `listChanged` |
| `elicitation` | The server may ask the user for input through the client. | none |
Sub-flags
A sub-flag refines a capability. listChanged promises that the side will send a notification when its list of tools, prompts, resources, or roots changes, so the other side can refetch. subscribe on resources means a client may ask to be told when one particular resource changes.
A missing flag means "no". A server that declares "tools": {} offers tools but promises no change notifications. The client must then refetch the list itself if it wants fresh data.
Respecting the negotiated result
After the handshake, each side keeps the other's capabilities in memory and treats them as a contract.
- A client should call
tools/listonly if the server declaredtools. - A server should send
sampling/createMessageonly if the client declaredsampling. - A side should not rely on a flag the peer did not declare.
The following Python sketch shows a client-side guard that applies this rule. It works on the parsed result object from the initialize response.
def server_supports(result: dict, feature: str, flag: str | None = None) -> bool:
"""Return True if the server declared a capability (and optional sub-flag)."""
capabilities = result.get("capabilities", {})
if feature not in capabilities:
return False
if flag is None:
return True
return bool(capabilities[feature].get(flag, False))
init_result = {
"protocolVersion": "2025-06-18",
"capabilities": {"tools": {"listChanged": True}, "prompts": {}},
"serverInfo": {"name": "demo", "version": "0.1.0"},
}
print(server_supports(init_result, "tools")) # True
print(server_supports(init_result, "tools", "listChanged")) # True
print(server_supports(init_result, "resources")) # False
print(server_supports(init_result, "prompts", "listChanged")) # FalseNote the difference between the last two checks. resources is absent, so the feature is unavailable. prompts is present but has no listChanged flag, so the feature exists without change notifications.
What the official SDK does for you
You rarely write the handshake by hand. The Python SDK performs it inside session.initialize():
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def main():
params = StdioServerParameters(command="python", args=["server.py"])
async with stdio_client(params) as (read, write):
async with ClientSession(read, write) as session:
result = await session.initialize()
print(result.protocolVersion)
print(result.serverInfo.name)
print(result.capabilities.tools is not None)
asyncio.run(main())The call sends initialize, waits for the reply, sends notifications/initialized, and returns the server's result. The returned object lets you inspect what the server declared before you make further calls. This code assumes a server.py that uses the SDK's FastMCP class, which fills in the tools, resources, and prompts capabilities automatically from the functions you register.
Timeouts and failure handling
Initialization is a request like any other, so it can fail or hang.
- Set a timeout. If the server never answers, the client should give up and close the connection rather than wait forever.
- A server may reply with a JSON-RPC error object, for example when the request is malformed. The client should treat that as a failed start.
- A client may cancel its own
initializerequest. The specification says this request should not be cancelled, since the session has not yet begun. Prefer a timeout and a clean disconnect.
Shutdown
No special MCP message ends a session. The transport does it:
- With stdio, the client closes the server's input stream, waits for it to exit, and if needed sends termination signals.
- With Streamable HTTP, the client closes its HTTP connections. It may also send an HTTP DELETE with its session ID.
Common errors
- Skipping
notifications/initialized. The server may reject or ignore requests. Always send it after a successful reply. - Calling features that were not declared. Calling
resources/listagainst a server with noresourcescapability usually returns a "method not found" error. - Assuming
listChangedis always on. Check the flag before you rely on notifications, or you will show stale lists. - Hard-coding the version. Read the version in the server's reply and compare it with what your client supports.
- Writing logs to standard output on a stdio server. Stdout carries the protocol messages. Stray
printcalls corrupt the stream and the handshake fails. Log to standard error instead. - Treating
serverInfoas trusted. The name and version are self-reported. Use them for display and diagnostics, not for security decisions.
Exercises
Exercise
A server's initialize result contains "capabilities": {"tools": {}, "resources": {"subscribe": true}}. Which of these can the client rely on: calling tools/list, calling prompts/list, receiving a notification when the tool list changes, subscribing to a specific resource?
Show answer
The client can call tools/list because tools is declared, and it can subscribe to a specific resource because resources declares subscribe. It cannot rely on prompts/list because prompts is absent. It cannot rely on tool list change notifications because tools has no listChanged flag.
Exercise
A client sends protocolVersion "2025-06-18", but the server only supports an older version. What should each side do?
Show answer
The server should not fail the request. It replies with an older version it supports, normally its latest. The client then compares that version with the ones it supports. If it can work with it, it sends notifications/initialized and continues. Otherwise it disconnects.
Exercise
A stdio server works when run alone but the client hangs during initialize. The server code contains print("starting up") at the top. What is the likely cause and the fix?
Show answer
The print writes a non-JSON line to standard output, which the client reads as protocol data. This corrupts the stream, so the handshake does not complete. Remove the call or write to standard error, for example with print("starting up", file=sys.stderr).