Version scope: 2024-11-05. This notebook teaches historical HTTP+SSE examples. For new implementations, consult the current stdio and Streamable HTTP specification. The examples below are not a current SDK compatibility guarantee.
Protocol Specifications & Lifecycle
Why This Matters
Every Model Context Protocol (MCP) server relies on strict message framing and state management to safely bridge AI models with external data and tools, preventing malformed payloads, race conditions, and security vulnerabilities when building custom integrations.
Client-Host-Server Architecture
MCP decouples the AI application from external integrations using a stateful, three-part architecture connected over a transport layer (such as stdio or Streamable HTTP / SSE).
Diagram as text and editable source
- Host applicationCoordinates client connections → Client A: Creates client
- Host applicationCoordinates client connections → Client B: Creates client
- Client A → Local serverTools · resources · prompts: stdio session
- Client B → Remote serverTools · resources · prompts: Legacy HTTP+SSE
Host
The user-facing LLM application (e.g., an IDE or desktop chat app) that manages security policies, user consent, and overall LLM orchestration.
Client
A protocol connector instantiated by the Host that maintains a dedicated 1:1 stateful session with a single MCP Server.
Server
A lightweight program exposing specific capabilities—Tools (executable functions), Resources (contextual data), and Prompts (templated workflows)—to the Client.
JSON-RPC 2.0 Message Types
All communication between the Client and Server uses JSON-RPC 2.0, which defines three distinct message types:
| Message Type | Required Fields | Purpose |
|---|---|---|
| Request | jsonrpc ("2.0"), id, method | Initiates an operation and expects a matched response. |
| Response | jsonrpc ("2.0"), id, result OR error |
Returns the outcome of a Request using the exact same id.
|
| Notification | jsonrpc ("2.0"), method |
Sends a one-way event without an id; must never receive a response.
|
The Three-Phase Connection Lifecycle
Because MCP connections are stateful, both peers must strictly enforce a three-phase lifecycle. Select a phase below to inspect its rules and protocol invariants:
1. Initialization Handshake
Mandatory First Step
The Client sends an initialize request declaring its protocol version and supported capabilities (e.g., roots, sampling). The Server replies with its own protocol version and capabilities (e.g., tools, resources), and the Client confirms readiness by sending a notifications/initialized notification.
tools/call) before initialization completes is a strict protocol violation.
Worked Examples: JSON-RPC 2.0 Wire Payloads
Executing the MCP Initialization Handshake
Trace the exact sequence of JSON-RPC 2.0 messages required to establish a valid MCP session before any tools can be listed or invoked:
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {
"roots": { "listChanged": true },
"sampling": {}
},
"clientInfo": {
"name": "mcp-security-inspector",
"version": "1.0.0"
}
}
}
// Step 2: Server Response (matches id: 1)
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2024-11-05",
"capabilities": {
"tools": { "listChanged": true },
"resources": { "subscribe": false, "listChanged": true }
},
"serverInfo": {
"name": "local-files-server",
"version": "1.0.0"
}
}
}
// Step 3: Client Notification (no "id" field; expects no response)
{
"jsonrpc": "2.0",
"method": "notifications/initialized"
}
Handling a Tool Call & JSON-RPC Error Response
Once in the Operation phase, observe how a Client invokes a tool via tools/call and how a Server must format a protocol-level JSON-RPC error object if the requested tool does not exist:
// Client invokes a non-existent tool during Operation phase
{
"jsonrpc": "2.0",
"id": 42,
"method": "tools/call",
"params": {
"name": "delete_production_db",
"arguments": { "force": true }
}
}
// Server returns a JSON-RPC 2.0 Error Response matching id: 42
{
"jsonrpc": "2.0",
"id": 42,
"error": {
"code": -32602,
"message": "Unknown tool: delete_production_db"
}
}
Transports & Communication Channels
While JSON-RPC 2.0 defines message semantics, transports determine how bytes move between client and server—shaping latency, concurrency, and network attack surfaces.
Local Process Communication with Stdio
Designed for local integrations where the MCP host (such as an IDE or desktop AI client) launches the MCP server as a child subprocess on the same machine.
-
Bidirectional OS Pipes: The client writes UTF-8, newline-delimited JSON-RPC 2.0 messages to the server's
stdinstream, and the server writes responses/notifications back tostdout. -
Strict Stream Hygiene: Because
stdoutcarries raw protocol frames, any human-readable logs printed tostdoutcorrupt the JSON-RPC stream and break the connection. All diagnostic logging must go tostderror a file. - Operational Trade-offs: Delivers near-zero latency, opens no network ports, and inherits the host user's OS permissions directly, but binds one process to a single client session (1:1 lifecycle).
Remote Network Communication with SSE
The SSE (Server-Sent Events) transport—formally HTTP+SSE—enables MCP servers to run remotely over HTTP/HTTPS and serve multiple concurrent clients.
-
Dual-Channel HTTP Pattern: Client opens a persistent
GET /ssestream (Accept: text/event-stream). The server emits an initialendpointevent containing a session-specific URI (e.g.,/messages?sessionId=9f8a2) where the client sendsPOSTJSON-RPC payloads. -
Network & Security Boundaries: Remote deployments must enforce TLS encryption, token authentication (OAuth 2.1 bearer tokens), and strict
OriginandHostheader validation to block DNS rebinding and cross-site request attacks. -
Protocol Evolution (Streamable HTTP): Newer MCP specification revisions introduced Streamable HTTP to unify
GETandPOSTchannels into a single endpoint and support stateless serverless scaling.
Diagram as text and editable source
- Local client → Server subprocess: stdin: protocol messages
- Server subprocess → Local client: stdout: protocol messages
- Server subprocess → Diagnostic logsstderr (not protocol stdout): stderr
- Remote client → HTTP+SSE server2024-11-05 binding: POST: client messages
- HTTP+SSE server2024-11-05 binding → Remote client: SSE: endpoint + messages
Stdio vs. SSE (HTTP+SSE) Transport Comparison
| Dimension | Stdio Transport | SSE (HTTP+SSE) Transport |
|---|---|---|
| Deployment Scope | Local machine (child subprocess) | Local or remote network (HTTP server) |
| Communication Channels | stdin (client → server) and stdout (server → client) |
POST endpoint (client → server) and GET SSE stream (server → client) |
| Message Framing | Newline-delimited JSON-RPC 2.0 | SSE data: events and HTTP POST JSON bodies |
| Client Concurrency | Single client per spawned process | Multiple concurrent clients via session IDs |
| Primary Security Control | OS user permissions and process sandboxing | TLS, bearer/OAuth authentication, and Origin/Host validation |
Worked Examples: TypeScript SDK & Host Setup
Configuring a Local Stdio Server & Host
Route all diagnostic logs to stderr via console.error() so stdout stays strictly reserved for JSON-RPC frames, then register the binary in your host config:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
// IMPORTANT: Never use console.log() in stdio servers—it writes to stdout!
console.error("[local-files] Booting MCP server on stdio...");
const server = new McpServer({
name: "local-files",
version: "1.0.0"
});
// Register tools and resources here
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("[local-files] Connected and awaiting initialize handshake.");
{
"mcpServers": {
"local-files": {
"command": "node",
"args": ["/abs/path/to/dist/server.js"],
"env": {
"ALLOWED_DIR": "/Users/dev/workspace"
}
}
}
}
Configuring a Remote SSE Server & Client Connection
Expose paired GET /sse and POST /messages endpoints keyed by transport.sessionId, enforcing bearer token authentication and Origin / Host allowlisting before accepting traffic:
import express from "express";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
const app = express();
const sessions = new Map<string, SSEServerTransport>();
const ALLOWED_ORIGINS = new Set(["https:">//app.example.com"]);
// Security middleware: block DNS rebinding & unauthorized callers
function validateSecurityBoundary(req: express.Request, res: express.Response, next: express.NextFunction) {
const origin = req.headers.origin;
if (origin && !ALLOWED_ORIGINS.has(origin)) {
return res.status(403).json({ error: "Untrusted Origin header" });
}
const auth = req.headers.authorization;
if (!auth || auth !== `Bearer ${process.env.MCP_SERVER_TOKEN}`) {
return res.status(401).json({ error: "Invalid or missing Bearer token" });
}
next();
}
app.get("/sse", validateSecurityBoundary, async (req, res) => {
const server = new McpServer({ name: "remote-mcp", version: "1.0.0" });
const transport = new SSEServerTransport("/messages", res);
sessions.set(transport.sessionId, transport);
res.on("close", () => sessions.delete(transport.sessionId));
await server.connect(transport);
});
app.post("/messages", validateSecurityBoundary, async (req, res) => {
const sessionId = String(req.query.sessionId || "");
const transport = sessions.get(sessionId);
if (!transport) {
return res.status(404).json({ error: "Unknown or expired sessionId" });
}
await transport.handlePostMessage(req, res);
});
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
const transport = new SSEClientTransport(new URL("https:">//mcp.example.com/sse"), {
requestInit: {
headers: {
Authorization: `Bearer ${process.env.MCP_TOKEN}`
}
}
});
const client = new Client({ name: "remote-agent", version: "1.0.0" });
await client.connect(transport);
Interactive Knowledge Check
Test your mastery of MCP transports, stream hygiene, HTTP+SSE routing, and security boundaries.
Which architectural constraint differentiates the local stdio transport from the remote HTTP+SSE transport in MCP?
Why must an MCP server using the stdio transport never call console.log() for diagnostic debugging?
In the dual-channel HTTP+SSE transport pattern, how does the MCP client discover where to send its JSON-RPC POST requests?
Which attack vector is specifically mitigated when a remote HTTP+SSE MCP server strictly validates incoming HTTP Origin and Host headers against an allowlist?
When deploying a remote HTTP+SSE MCP server that stores active SSEServerTransport instances in an in-memory Map keyed by sessionId behind a load balancer, what routing requirement applies?
References and source links
- Model Context Protocol maintainers (2024-11-05). Architecture: historical specification used by this notebook.https://modelcontextprotocol.io/specification/2024-11-05/architecture
- Model Context Protocol maintainers (2024-11-05). Transports: stdio and legacy HTTP+SSE.https://modelcontextprotocol.io/specification/2024-11-05/basic/transports
- Model Context Protocol maintainers (2026-07-28). Current transport documentation: consult this before building a new server.https://modelcontextprotocol.io/specification/2026-07-28/basic/transports
Reference list added during the visual refresh on 14 Nov 2026. It is a reading path, not a completed claim-by-claim audit of this imported notebook.