Sub topic 6
Initialization and capability negotiation
Every MCP connection starts with a handshake. The client and server agree on a protocol version and declare which optional features they support. Only after that do they exchange tool calls. This chapter covers the handshake, the lifecycle around it, and the errors it produces.
This chapter assumes you know the host, client and server roles, the message shapes of JSON-RPC 2.0 (requests, responses, notifications), and the two transports, stdio and Streamable HTTP. You should also be able to run a short Python script.
Why a handshake is needed
MCP has several revisions, and each adds features. A server written for an older revision may not know about newer messages. A client may not implement features such as sampling, where the server asks the client's model to generate text. If both sides assumed the same feature set, one of them would eventually send a message the other could not handle.
The handshake solves this in two steps:
- Version negotiation. Both sides settle on one protocol revision.
- Capability negotiation. Each side states which optional features it supports. After that, each side sends only messages the other side declared.
The three phases of a connection
A connection moves through three phases.
| Phase | What happens | Messages allowed |
|---|---|---|
| Initialization | Version and capabilities are agreed | `initialize`, its response, `notifications/initialized`, and `ping` |
| Operation | Normal use: listing and calling tools, reading resources | Anything both sides declared |
| Shutdown | The connection is closed | None (the transport is closed) |
The initialize message must be the first one the client sends. Before the server has answered it, the client should send nothing except pings. Before it receives notifications/initialized, the server should send nothing except pings and log messages. A client that skips the handshake and calls tools/list directly is out of spec. Many servers reject such a request.
The initialize request
The client sends its newest supported protocol version, its capabilities and some identifying information.
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-06-18",
"capabilities": {
"roots": { "listChanged": true },
"sampling": {}
},
"clientInfo": {
"name": "example-assistant",
"version": "1.4.0"
}
}
}Each field has a purpose:
protocolVersionis a date string that names a revision of the specification. It is not a semantic version number.capabilitieslists optional client features.rootslets the server ask which directories the client works in, andlistChangedmeans the client will notify the server when that list changes.samplinglets the server request model completions through the client. An empty object, as in"sampling": {}, means the feature is supported with no sub-options. A key that is absent means the feature is not supported.clientInfogives a name and version. It is useful in logs and bug reports. Do not use it to decide security questions, because any process can claim any name.
The initialize response
The server answers with the version it will use, its own capabilities and its own identity.
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2025-06-18",
"capabilities": {
"tools": { "listChanged": false },
"resources": { "subscribe": true, "listChanged": true },
"logging": {}
},
"serverInfo": {
"name": "calculator",
"version": "0.1.0"
},
"instructions": "Use add for integer addition."
}
}The server capability keys map to the primitives you met earlier:
tools: the server offers tools.listChangedmeans it will sendnotifications/tools/list_changedwhen the set of tools changes.resources: the server offers resources.subscribemeans the client can subscribe to changes in a single resource.prompts: the server offers prompts.logging: the server can send structured log messages to the client.completions: the server supports argument autocompletion for prompts and resource templates.
The optional instructions string is a hint from the server to the client about how to use it. Some hosts add it to the model's context, which costs tokens, so keep it short.
Version negotiation rules
The rules are short:
- The client sends the latest version it supports.
- If the server supports that version, it replies with the same version.
- Otherwise, the server replies with a different version it does support. This is normally its own latest version.
- If the client does not support the version in the response, it should disconnect.
A server may also reject the request with a JSON-RPC error. The error data field then lists the versions it supports:
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32602,
"message": "Unsupported protocol version",
"data": { "supported": ["2024-11-05"], "requested": "2025-06-18" }
}
}In practice the SDKs do this for you. The common failure is an old server paired with a new client, or the reverse. The symptom is a connection that closes immediately after initialize. The fix is usually to update the SDK in the server.
For Streamable HTTP, once the version is agreed, the client sends it on every later request in an MCP-Protocol-Version header. If the server issued a session ID in the initialize response, the client also sends it in an Mcp-Session-Id header.
The initialized notification
After it receives the response, the client sends a notification. It has no id and gets no reply:
{"jsonrpc": "2.0", "method": "notifications/initialized"}This message marks the point where the client is ready. Until the server receives it, the server should not send requests of its own. If you write a client and forget this notification, some servers will never answer your later requests. Others will work anyway, so the bug is easy to miss.
Running the handshake by hand
The script below acts as a minimal client. It launches the server.py calculator from the server-writing chapter, performs the handshake over stdio and lists the tools. The stdio transport uses one JSON message per line.
import json
import subprocess
import sys
proc = subprocess.Popen(
[sys.executable, "server.py"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True,
)
def send(message: dict) -> None:
proc.stdin.write(json.dumps(message) + "\n")
proc.stdin.flush()
def request(request_id: int, method: str, params: dict | None = None) -> dict:
message = {"jsonrpc": "2.0", "id": request_id, "method": method}
if params is not None:
message["params"] = params
send(message)
while True:
line = proc.stdout.readline()
if not line:
raise RuntimeError("server closed the connection")
reply = json.loads(line)
if reply.get("id") == request_id: # skip notifications
return reply
init = request(1, "initialize", {
"protocolVersion": "2025-06-18",
"capabilities": {},
"clientInfo": {"name": "handshake-demo", "version": "0.1"},
})
print("version:", init["result"]["protocolVersion"])
print("server capabilities:", init["result"]["capabilities"])
send({"jsonrpc": "2.0", "method": "notifications/initialized"})
tools = request(2, "tools/list")
print("tools:", [t["name"] for t in tools["result"]["tools"]])
proc.stdin.close() # shutdown: closing stdin ends a stdio server
proc.wait(timeout=5)Because the client sends "capabilities": {}, it declares no optional features. The server must then not send sampling or roots requests. Try changing the protocolVersion to "1999-01-01" and see how your server responds. The SDK usually replies with its own latest version rather than an error.
How capabilities change behavior
Capabilities are a contract. They have practical effects on both sides:
- A client should call
tools/listonly if the server declaredtools. Callingresources/liston a server withoutresourcesusually returns a "method not found" error (-32601). - If the server declared
tools.listChanged, the client should re-fetch the list when it receivesnotifications/tools/list_changed. Without that capability, the client can cache the list for the whole session. - A server may call
sampling/createMessageonly if the client declaredsampling. Most hosts also ask the user before honoring such a request. - Capabilities are fixed for the connection. To change them, disconnect and run the handshake again.
This is also why a tool can appear in a server's code but not in the assistant. Either the server never declared tools, or the host chose not to expose them.
Timeouts, cancellation and failures
Initialization is where most startup failures show up, so each side should plan for them:
- Slow startup. A server launched with
npx -ymay download packages on first run. The host's startup timeout can expire beforeinitializecompletes. Run the command once manually to warm the cache. - Output on stdout. On stdio, stdout carries only protocol messages. A stray
print()or a banner line from a package manager corrupts the stream. The client then fails to parse the first line, and the handshake fails. Write diagnostics to stderr. - Cancellation. Either side can abandon an in-flight request by sending
notifications/cancelledwith therequestIdand an optional reason. Theinitializerequest itself must not be cancelled by the client. - Pings. Either side can send a
pingrequest at any time, including during initialization. The receiver must answer promptly with an empty result. It is a cheap liveness check.
Shutdown
The protocol defines no shutdown message. The transport ends the session:
- stdio: the client closes the server's stdin, waits for the process to exit, and sends
SIGTERMif it does not. If the process still does not exit, it sendsSIGKILL. A server can also exit on its own. - Streamable HTTP: the client closes its connections. If a session ID was used, it can send an HTTP
DELETEto the endpoint with that ID to end the session explicitly. Servers may answer405 Method Not Allowed.
Common errors at a glance
| Symptom | Likely cause | Check |
|---|---|---|
| Connection closes right after `initialize` | Version mismatch | Compare `protocolVersion` in both messages |
| "Invalid JSON" on the first message | Extra text on stdout | Move prints to stderr |
| Server connects but no tools appear | `tools` capability missing, or host filtering | Read the `capabilities` in the response |
| Client hangs on start | Slow package download or no `initialized` sent | Run the command manually and watch the timing |
| List never refreshes | `listChanged` not declared or not handled | Look for `list_changed` notifications in the logs |
Exercise
A server's initialize response contains "capabilities": {"tools": {}}. A client wants to read a file through a resource. What should it do, and why?
Show answer
It should not send resources/list or resources/read, because the server did not declare the resources capability. The server only promised tools, and the request would likely fail with a "method not found" error. The client should use a tool the server offers, or connect to a server that declares resources.
Exercise
In the handshake script, what would go wrong if you removed the line that sends notifications/initialized, and why might you not notice right away?
Show answer
The client would skip the signal that tells the server initialization is complete. A strict server might ignore or reject later requests such as tools/list. Lenient servers answer anyway, so the script could appear to work. The bug would then surface only against stricter servers.
Exercise
A new server you wrote works in the MCP Inspector but fails in your assistant right after startup, with a JSON parse error. Name two likely causes related to this chapter.
Show answer
First, something writes non-protocol text to stdout, such as a debug print() or a package-manager banner, which corrupts the line-delimited message stream. Second, the host and server may disagree on the protocol version, so the connection closes after initialize. Check stderr and the logged initialize messages to tell the two apart.