Sub topic 3
How a session starts: messages and capability negotiation
This chapter covers what happens on the wire between an MCP client and your server before any tool is called. It assumes you can read JSON, know the basic host, client, and server roles from the previous chapter, and have a rough idea of how LLM tool calling works. You do not need to write any protocol code yourself. The SDK handles it. Knowing the sequence still helps when a server connects but shows no tools, or when a host refuses to start it.
Why the lifecycle matters
An MCP session is not a single request. The client and server first agree on a protocol version and on which features each side supports. Only then can they exchange tool calls. If you skip or misread this step, you get symptoms such as:
- A host that lists your server as "connected" but shows zero tools.
- A client that disconnects immediately with a version error.
- A server that receives a request it never advertised support for.
Messages are JSON-RPC 2.0
MCP uses JSON-RPC 2.0 as its message format. JSON-RPC is a small standard for calling named methods with JSON. Every MCP message is one of three kinds.
| Kind | Has `id` | Expects a reply | Example |
|---|---|---|---|
| Request | Yes | Yes | `initialize`, `tools/list`, `tools/call` |
| Response | Yes (matches the request) | No | A `result` or an `error` |
| Notification | No | No | `notifications/initialized` |
Either side can send requests. In practice the client sends most of them, and the server answers. Servers can also send requests to the client for optional features such as sampling (asking the host's model to generate text) and roots (listing the directories the client is working in). Those only work if the client declared support during setup.
A request looks like this:
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list"
}A successful response carries the same id and a result:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"tools": []
}
}A failed request gets an error object instead of result. It has an integer code and a message:
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32601,
"message": "Method not found"
}
}The id is how the client matches a response to the request that caused it. Several requests can be in flight at once, so responses may arrive in a different order.
The three phases of a session
A session has three phases: initialization, normal operation, and shutdown.
Phase 1: initialization
The client always speaks first. It sends an initialize request with three things:
protocolVersion: the newest MCP version the client supports.capabilities: the optional features the client offers.clientInfo: the client's name and version.
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-06-18",
"capabilities": {
"roots": { "listChanged": true },
"sampling": {}
},
"clientInfo": { "name": "example-host", "version": "1.0.0" }
}
}The server replies with the same three kinds of information from its side. It may also include an instructions string, which some hosts show to the model as general guidance about the server.
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2025-06-18",
"capabilities": {
"tools": { "listChanged": false },
"resources": {},
"prompts": {}
},
"serverInfo": { "name": "team-tools", "version": "0.1.0" }
}
}Finally the client sends a notifications/initialized notification. This tells the server the client is ready. Until the server has seen it, the server should not send requests of its own, apart from pings and logging. Likewise, before the server has answered initialize, the client should send nothing except pings.
Phase 2: normal operation
Now both sides may use only the features they negotiated. Typical traffic is tools/list, tools/call, resources/read, prompts/get, and periodic ping requests to check the connection is alive.
Phase 3: shutdown
MCP defines no special shutdown message. The transport ends the session. With stdio, the client closes the server's input stream, waits for it to exit, and then terminates the process if needed. With Streamable HTTP, the client closes the connection or ends the session. Your server should treat the end of input as a normal signal to exit.
Version negotiation
Protocol versions are date strings such as 2025-06-18. The rule is simple:
- The client sends the latest version it supports.
- If the server supports that version, it answers with the same one.
- If not, it answers with another version it does support, normally its latest.
- If the client cannot work with the version the server chose, it disconnects.
A version error therefore usually means a very old SDK on one side. Upgrading the SDK (pip install -U "mcp[cli]") is the usual fix. The SDK sends and checks the version for you, so you almost never write this by hand.
Capability negotiation
Capabilities are the core of the handshake. Each side lists the optional features it supports, and after that each side may only use features the other side declared.
What a server can declare
| Server capability | Meaning | Requests it enables |
|---|---|---|
| `tools` | The server offers tools. | `tools/list`, `tools/call` |
| `resources` | The server offers resources. | `resources/list`, `resources/read` |
| `prompts` | The server offers prompts. | `prompts/list`, `prompts/get` |
| `logging` | The server can send log messages to the client. | `notifications/message` |
| `completions` | The server can suggest argument values. | `completion/complete` |
Tools, resources, and prompts accept sub-flags:
listChanged: the server will send a notification when its list changes, so the client should re-fetch it.subscribe(resources only): the client can subscribe to updates for a single resource.
What a client can declare
| Client capability | Meaning |
|---|---|
| `roots` | The client can tell the server which directories or locations it may work in. |
| `sampling` | The client can ask its model to generate text on the server's behalf. |
| `elicitation` | The client can ask the user for extra input on the server's behalf. |
Newer protocol versions add more capabilities, so check the specification for the version your host supports.
How the SDK fills in capabilities
You do not write the capabilities object. The Python SDK builds it from what you registered. The server below registers one tool and nothing else:
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("team-tools")
@mcp.tool()
def ping_team() -> str:
"""Return a fixed string, to confirm the server is reachable."""
return "pong"
if __name__ == "__main__":
mcp.run()Because a tool is registered, the server advertises the tools capability. If you later add @mcp.resource(...) or @mcp.prompt() handlers, the matching capabilities appear in the next initialize response without further work.
Watching the handshake yourself
The quickest way to see these messages is to talk to a stdio server directly. This script launches the server above as a subprocess and sends the handshake as raw lines of JSON. Each message must be on a single line. Save the server as server.py first.
import json
import subprocess
import sys
proc = subprocess.Popen(
[sys.executable, "server.py"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
)
def send(message: dict) -> None:
proc.stdin.write(json.dumps(message) + "\n")
proc.stdin.flush()
def receive() -> dict:
return json.loads(proc.stdout.readline())
send({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-06-18",
"capabilities": {},
"clientInfo": {"name": "manual-client", "version": "0.0.1"},
},
})
init = receive()
print("Server capabilities:", init["result"]["capabilities"])
send({"jsonrpc": "2.0", "method": "notifications/initialized"})
send({"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
tools = receive()
print("Tools:", [t["name"] for t in tools["result"]["tools"]])
proc.stdin.close()
proc.wait(timeout=5)Running it prints the capability object the SDK built, followed by ['ping_team']. The exact capability contents depend on your SDK version. The point to check is that tools is present.
Two details are worth noticing. First, the client declared empty capabilities, so the server must not send it sampling or roots requests. Second, closing standard input is how this script ends the session, which matches the shutdown behavior described earlier.
Common errors and how to read them
| Symptom | Likely cause | What to check |
|---|---|---|
| Host reports a timeout during startup | The server never answered `initialize`. The process may have crashed, or the command or path is wrong. | Run the same command in a terminal. Look at stderr. |
| Parse error or "invalid JSON" at startup | Something other than JSON-RPC went to stdout. | Remove `print()` calls. Send logs to stderr. |
| Connected, but no tools appear | No tool was registered, or the host cached an earlier list. | Call `tools/list` in the Inspector. Restart the host. |
| `-32601 Method not found` | The client called a method the server did not advertise. | Compare the request with the server's capabilities. |
| `-32602 Invalid params` | The request had wrong or missing parameters. | Compare the request body with the method's schema. |
| Version mismatch error | The client and server share no protocol version. | Upgrade the older SDK. |
The standard JSON-RPC error codes you will see most are -32700 (parse error), -32600 (invalid request), -32601 (method not found), -32602 (invalid params), and -32603 (internal error). These describe failures of the protocol itself. Failures inside a tool are reported differently, and a later chapter on error handling covers that.
Dynamic lists and `listChanged`
If your tool set changes while the server runs, for example when tools appear depending on the user's permissions, set listChanged to true and send notifications/tools/list_changed when the list changes. A client that sees the flag re-fetches tools/list after the notification. A client that did not see the flag has no reason to expect the notification, and may ignore it. Most team servers register a fixed set of tools at startup, so you can leave this alone.
Exercise
A teammate's host connects to your stdio server and then fails with a JSON parse error before listing any tools. The server code contains print("Server starting...") at the top of main. Explain what is going wrong and how you would fix it.
Show answer
With stdio, the server's stdout is the protocol channel and must contain only JSON-RPC messages. The print call writes the plain text "Server starting..." into that stream, and the client fails when it tries to parse that line as JSON. Remove the call or send it to stderr, for example with print("Server starting...", file=sys.stderr) or a logging handler configured with stream=sys.stderr.
Exercise
During initialize, your server's response has "capabilities": {"tools": {}}. A client then sends resources/list. What should happen, and why?
Show answer
The server did not declare the resources capability, so the client should not send that request. If it does, the server should answer with a JSON-RPC error such as -32601 (method not found). Each side may use only the features the other declared during negotiation.
Exercise
In the handshake, which message does the client send after receiving the server's initialize response, and why is it a notification instead of a request?
Show answer
It sends notifications/initialized. It is a notification because it needs no reply. It only tells the server that the client has finished setup and that normal operation can begin, so it carries no id.