Model Context Protocol: The MCP Lifecycle
The Model Context Protocol (MCP) defines a standardized communication protocol that connects AI host applications (such as Claude Desktop or Cursor IDE) to local and remote external servers (tools, resources, and context providers). While the MCP architecture establishes who the participants are, the MCP Lifecycle dictates how these participants establish, negotiate, utilize, and terminate their continuous connections over time. Understanding the exact message sequencing, protocol negotiation, and state transitions during this lifecycle is essential for building custom, resilient MCP clients and servers.
1. Core Definition & Mental Model
What is the MCP Lifecycle?
The MCP Lifecycle is the formal sequence of operational phases and rules that govern how a client (acting on behalf of an LLM host) and an MCP server establish a connection, negotiate communication contracts, execute tasks, and gracefully end the session.
A session represents a single, continuous, stateful communication channel between the client and server. For instance, when a user launches Claude Desktop configured with a local File System server or remote GitHub server, a background session begins immediately and persists until either Claude Desktop terminates or the connection drops.
The Real-World Analogy: The Formal Diplomatic Handshake
Analogy: Imagine two foreign ambassadors meeting for a bilateral negotiation.
- Handshake & Protocol Verification (Initialization): They do not immediately talk policy. First, they greet each other, establish a shared language dialect (Protocol Version), and hand over credentials showing what authority they possess (Capabilities). Neither diplomat issues binding policy commands until the official credentials are mutually acknowledged.
- Working Sessions (Normal Operation): Once the diplomatic framework is certified, they consult lists of agreed-upon topics (Capability Discovery) and negotiate specific treaties or issue commands (Tool Calling & Resource Fetching).
- Departure (Shutdown): When the summit concludes, they do not create a new protocol treaty to leave; they simply close the conference room door and sever physical communication (Transport-layer teardown).
The MCP Lifecycle consists of three primary, non-overlapping phases:
2. Phase 1: Initialization & The Handshake
The initialization phase must be the absolute first interaction between a client and an MCP server. Before any actual tooling or file operations occur, the client and server must verify protocol compatibility and declare their respective operational boundaries.
Step 1: The Client initialize Request
The client sends a JSON-RPC 2.0 request invoking the initialize method on the server. This payload contains three mandatory structures:
protocolVersion: The string/date representation of the MCP protocol specification the client understands.capabilities: The features the client provides to the server (e.g., file directoryroots, AIsampling).clientInfo: The identifying metadata of the client host (name, version).
{
"jsonrpc": "2.0",
"id": 0,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {
"roots": {
"listChanged": true
},
"sampling": {}
},
"clientInfo": {
"name": "Claude-Desktop",
"version": "1.0.0"
}
}
}
Step 2: The Server initialize Response
The server processes the parameters, matches the request ID, and responds with its own implementation parameters:
protocolVersion: The MCP protocol version the server intends to operate on.capabilities: The primitives exposed by the server (e.g.,tools,resources,prompts,logging).serverInfo: Identifying name and version of the server package.
{
"jsonrpc": "2.0",
"id": 0,
"result": {
"protocolVersion": "2024-11-05",
"capabilities": {
"tools": {
"listChanged": true
},
"resources": {
"subscribe": true,
"listChanged": true
}
},
"serverInfo": {
"name": "secure-filesystem-server",
"version": "2.0.1"
}
}
}
Step 3: The initialized Notification
Upon verifying the server's response and confirming that the negotiated parameters are acceptable, the client fires a one-way JSON-RPC notification (notifications/initialized).
- Notifications do not contain an
idfield. - The server must not send a JSON-RPC response back to this notification.
{
"jsonrpc": "2.0",
"method": "notifications/initialized"
}
The Two Golden Protocol Rules of Initialization
Rule 1 (Client Constraint): The client must not send any JSON-RPC requests other than
pingprior to receiving the server's response to theinitializerequest. Requestingtools/listbefore this response arrives violates the protocol.Rule 2 (Server Constraint): The server must not send any JSON-RPC requests or notifications other than
pingandlogging/messageprior to receiving thenotifications/initializedsignal.
3. Version & Capability Negotiation
Version Negotiation
Because MCP is an evolving protocol, clients and servers deployed at different times may specify divergent protocol strings (typically formatted as dates like 2024-11-05).
If the server's protocol version is supported by the client runtime, the client adjusts to the server's conventions and issues the initialization confirmation. If incompatible, the client terminates transport without entering the operation phase.
Capability Breakdown: Client vs. Server
Capability negotiation establishes expectations. Neither party can invoke an endpoint or feature that was not explicitly advertised during the handshake.
Sub-Capabilities
Capabilities may contain sub-capabilities that define dynamic behavioral extensions:
listChanged: Indicates that the server (or client) will fire notifications whenever the available list of tools, resources, or roots is mutated during runtime (e.g.,notifications/tools/list_changed).subscribe: Exclusively used in resources. Allows a client to subscribe to a specific URI so the server can push updates whenever that exact resource modifies.
4. Phase 2: Normal Operation
Once the session is fully initialized, normal operation begins. This phase breaks down into two distinct sub-stages: Capability Discovery and Execution (Tool Calling & Context Ingestion).
Stage 2A: Capability Discovery
Immediately after the notifications/initialized event, clients automatically execute capability discovery. The client sends requests to catalog everything the server provides:
tools/listprompts/listresources/list
If a server advertises that it only supports tools (and omits prompts or resources in its initialization capabilities), any discovery requests directed to unsupported categories will result in standard JSON-RPC error objects (e.g., -32601 Method not found), which the client handles gracefully without breaking the session.
Example Discovery Response: tools/list
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"tools": [
{
"name": "read_file",
"description": "Read the complete contents of a file from the file system.",
"inputSchema": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Absolute or relative system path to the target file."
}
},
"required": ["path"]
}
}
]
}
}
Stage 2B: Tool Calling & Interaction
When a user asks the LLM a question requiring tool interaction, the host matches the prompt against the cached tool schemas, constructs the input arguments, and delegates the call through the client via tools/call.
Example Request: tools/call
{
"jsonrpc": "2.0",
"id": 4,
"method": "tools/call",
"params": {
"name": "read_file",
"arguments": {
"path": "/Users/nitish/Desktop/hello.py"
}
}
}
Example Response: tools/call
{
"jsonrpc": "2.0",
"id": 4,
"result": {
"content": [
{
"type": "text",
"text": "print('Hello World from MCP!')\n"
}
],
"isError": false
}
}
5. Phase 3: Session Shutdown & Transport Teardown
An essential architectural detail of the MCP shutdown phase is that no JSON-RPC messages are exchanged to terminate the connection. There is no shutdown or exit method in the JSON-RPC layer. Instead, shutdown is entirely managed by the Transport Layer.
STDIO Transport (Local Servers)
Local MCP servers are spawned by the client as OS child processes. Communication flows through standard I/O pipes:
-
Client-Initiated Shutdown (Standard Flow):
- The client closes the server's standard input pipe (
stdin). - The server encounters an End-Of-File (
EOF) condition on its input reader, performs local resource cleanup, and terminates voluntarily. - If the server does not terminate, the client escalates by issuing an operating system signal:
SIGTERM: A polite request asking the process to clean up resources, close file descriptors, and exit.SIGKILL: If the server continues hanging past a given grace period, the client invokesSIGKILL, instructing the kernel to immediately drop the process from memory.
- The client closes the server's standard input pipe (
-
Server-Initiated Shutdown (Uncommon/Abrupt):
- The server terminates unexpectedly or closes its
stdoutpipe. - The client catches the broken pipe event and cleans up local session handlers.
- The server terminates unexpectedly or closes its
HTTP with SSE Transport (Remote Servers)
Remote servers operate over standard web channels (e.g., HTTP POST with Server-Sent Events):
- Client-Initiated: The client drops the active HTTP POST/SSE long-poll connection.
- Server-Initiated: The remote server closes the connection abruptly (due to internal crashes, restarts, or timeouts). The client must implement reconnection heuristics or gracefully inform the host UI that context providers went offline.
6. Edge Cases & Protocol Exceptions
1. The ping Request
When long-running computations happen without active messaging, network intermediaries, OS proxies, or stateful firewalls can drop connections silently. The ping method acts as a lightweight heartbeat.
- Can be sent in both directions (Client Server or Server Client).
- Permitted even during the initial handshake before full initialization completes.
Ping Payload:
{
"jsonrpc": "2.0",
"id": 101,
"method": "ping"
}
Ping Response:
{
"jsonrpc": "2.0",
"id": 101,
"result": {}
}
2. Standardized JSON-RPC Error Handling
MCP inherits its complete error schema directly from the JSON-RPC 2.0 specification:
{
"jsonrpc": "2.0",
"id": 2,
"error": {
"code": -32601,
"message": "Method not found",
"data": "The server does not support prompts capability."
}
}
3. Request Timeouts & Explicit Cancellation
To prevent an unresponsive, frozen, or overloaded server from permanently stalling the host AI process and consuming system resources, the client utilizes request timeouts.
- The client sets an internal threshold via its MCP SDK (e.g., ).
- If the response does not return within the allotted duration, the client dispatches a
notifications/cancellednotification targeting the specific request ID. - The server receives the cancellation, ceases processing immediately, and does not return a response payload for that ID.
Cancellation Notification Payload:
{
"jsonrpc": "2.0",
"method": "notifications/cancelled",
"params": {
"requestId": 7,
"reason": "Request timed out after 30000ms"
}
}
4. Progress Notifications
For heavy operations (e.g., indexing a repository containing thousands of source files), servers can transmit intermediate progress states to the client using a pre-assigned token.
- The client includes a
progressTokeninside the request's_metaparameter field. - The server dispatches out-of-band
notifications/progressmessages referencing that token. - The client receives these events, updating the host UI with visual progress bars or task metrics.
Client Request with Progress Token:
{
"jsonrpc": "2.0",
"id": 8,
"method": "tools/call",
"params": {
"name": "scan_repository",
"arguments": { "repo": "octocat/Hello-World" },
"_meta": {
"progressToken": 7
}
}
}
Server Progress Notification:
{
"jsonrpc": "2.0",
"method": "notifications/progress",
"params": {
"progressToken": 7,
"progress": 60,
"total": 100,
"message": "Scanned 600 out of 1000 files"
}
}
7. Complete End-to-End Session Trace
The following diagram tracks the lifecycle of an MCP session from the moment the user launches Claude Desktop to the time the application process is closed:
8. Summary and Key Takeaways
- Three Discrete Lifecycle Phases: Every MCP session strictly advances through Initialization, Normal Operation, and Shutdown.
- The Mandatory Handshake Sequence: Initialization strictly follows a three-step protocol sequence: Client
initializerequest Serverinitializeresponse Clientnotifications/initialized. - Strict Isolation Rules During Initialization: The client cannot send operational requests (tools, resources) before the server's initialization response arrives. The server cannot send operational requests/notifications before receiving the
notifications/initializedevent. Onlyping(and server logging) is permitted during the handshake. - Contractual Capability Negotiation: Features like
roots,sampling,tools,prompts, andresourcesare negotiated during the handshake. A client or server cannot invoke methods that were not declared upfront. - Automatic Capability Discovery: Immediately upon receiving the
notifications/initializedconfirmation, the client automatically triggers batch discovery requests (tools/list,prompts/list,resources/list) to catalog endpoints for the host LLM. - Transport-Driven Teardown: The shutdown phase does not use JSON-RPC messaging. In local setups (
stdio), termination is executed by closing input pipes followed by OS signals (SIGTERMandSIGKILL). In remote setups (HTTP), it is executed by severing the network connection. - Robust Exception Primitives: MCP implements standard JSON-RPC 2.0 error codes (
-32601Method Not Found,-32602Invalid Params), out-of-bandpingheartbeats, client-side timeout cancellations vianotifications/cancelled, and stateful progress tracking usingprogressToken.