Claude Desktop, Cursor, or agent runtime.
- Manages LLM inference session
- Human-in-the-loop approval UI
- 1:1 Client connection orchestrator
JSON-RPC 2.0 message framing.
- Stdio: Local subprocess stdin/stdout
- SSE: HTTP/2 Server-Sent Events
- Strict initialization handshake
Isolated domain process.
- Tools: Executable actions (APIs, DBs)
- Resources: Passive contextual data
- Prompts: Templated workflow guides
Source: Madhurjo AI Systems Engineering • Anthropic MCP Architecture Blueprint
The rapid maturation of Large Language Models (LLMs) from interactive conversational chatbots into autonomous software agents exposed a fundamental architectural flaw in modern AI engineering: the integration fragmentation crisis.
Before late 2024, connecting a foundation model to an external database, enterprise CRM, local file system, or developer CLI required bespoke integration code. Every developer platform implemented proprietary tool-calling specifications. Developers faced an unsustainable M × N engineering matrix, where M foundation models had to build custom connectors for N enterprise data stores.
The Model Context Protocol (MCP), open-sourced by Anthropic under the permissive MIT license, solves this fragmentation by establishing an open, standardized protocol for AI applications. Conceptually analogous to the Language Server Protocol (LSP) in developer IDEs or a universal USB-C standard for AI software, MCP decouples foundation model reasoning from tool execution and data access.
This technical guide provides an exhaustive architectural walkthrough of MCP: its three-tier topology, JSON-RPC 2.0 protocol mechanics, transport implementations (Stdio vs. SSE), enterprise security guardrails, and a production-grade Python MCP server implementation.
1. System Architecture: The Three-Tier Topology
The Model Context Protocol is structured around a strict client-host-server hierarchy designed to keep foundational models isolated from direct environment execution:
| Tier | Component | Primary Responsibility |
|---|---|---|
| 1. Host | Claude Desktop, Cursor, Agent Runtimes | Runs the LLM, manages UX context, and enforces human-in-the-loop security prompts. |
| 2. Client | Internal MCP Client Engine | Maintains isolated 1:1 sessions with servers, message serialization, and error handling. |
| 3. Server | Standalone Python / TypeScript Process | Exposes domain tools, read-only data resources, and versioned prompts. |
The Host Layer
The Host is the user-facing application orchestrating the AI interaction. Examples include desktop interfaces (such as Claude Desktop), development environments (such as Cursor or Zed), terminal agents (such as Claude Code), or proprietary enterprise backend services. The Host controls user approvals, manages authentication tokens, and coordinates conversations.
The Client Layer
Within the Host resides one or more MCP Clients. A Client maintains a dedicated 1:1 connection with a single MCP Server. Clients handle protocol handshakes, negotiate capabilities, serialize outgoing JSON-RPC requests, and deserialize incoming responses.
The Server Layer
The MCP Server is a lightweight, decoupled process exposing domain-specific capabilities. Crucially, an MCP server does not need to know which LLM is querying it, nor does it require direct access to model weights. It acts purely as a capability provider conforming to the protocol specification.
2. Protocol Framing: JSON-RPC 2.0 & Transports
MCP standardizes message interchange using the lightweight JSON-RPC 2.0 specification. Every interaction is categorized as a Request, a Response, or a Notification.
Transport Mechanisms: Stdio vs. SSE
The protocol defines two foundational transport mechanisms:
- Standard Input/Output (Stdio): The Client launches the Server as a local child process. Communication flows across standard input (stdin) and standard output (stdout). Stdio is ideal for local desktop tools, developer utilities, and command-line automation due to its zero-configuration security boundary.
- Server-Sent Events (SSE) over HTTP: The Client connects to a remote MCP Server over HTTP/2 or HTTPS. The Server streams asynchronous JSON-RPC notifications and responses to the Client via an open SSE stream, while the Client emits requests via HTTP POST endpoints. SSE enables cloud-hosted enterprise tool servers and team-shared microservices.
3. The Three Core Primitives: Tools, Resources & Prompts
The MCP specification categorizes all server-side capabilities into three distinct primitives:
- Tools (Executable Actions): Callable functions that allow an LLM to take actions in the external world. Each tool declares a name, semantic description, and JSON Schema input parameters. Examples include executing SQL queries, managing Git branches, or calling APIs.
- Resources (Contextual Data): Passive, read-only data sources identified by standardized URIs (e.g.
postgres://db/schema,file:///logs/app.log). Unlike tools, resources are read without side effects. - Prompts (Templated Workflows): Pre-packaged prompt templates and slash commands embedded in the server to guide users through complex operational workflows.
4. Production Python MCP Server Implementation
Below is a production-grade, tested Python implementation conforming to the official Model Context Protocol JSON-RPC 2.0 specification:
import json
import typing
class MCPServer:
def __init__(self, name: str, version: str):
self.name = name
self.version = version
self.tools = {}
def register_tool(self, name: str, description: str, input_schema: dict, handler: typing.Callable):
self.tools[name] = {
"name": name,
"description": description,
"inputSchema": input_schema,
"handler": handler
}
def handle_request(self, message: dict) -> dict:
msg_id = message.get("id")
method = message.get("method")
params = message.get("params", {})
# 1. MCP Initialization Handshake
if method == "initialize":
return {
"jsonrpc": "2.0",
"id": msg_id,
"result": {
"protocolVersion": "2024-11-05",
"serverInfo": {"name": self.name, "version": self.version},
"capabilities": {
"tools": {"listChanged": False},
"resources": {"subscribe": False, "listChanged": False},
"prompts": {"listChanged": False}
}
}
}
# 2. Tools Discovery Primitive
elif method == "tools/list":
tool_definitions = [
{"name": t["name"], "description": t["description"], "inputSchema": t["inputSchema"]}
for t in self.tools.values()
]
return {"jsonrpc": "2.0", "id": msg_id, "result": {"tools": tool_definitions}}
# 3. Tool Execution Primitive
elif method == "tools/call":
tool_name = params.get("name")
tool_args = params.get("arguments", {})
if tool_name not in self.tools:
return {"jsonrpc": "2.0", "id": msg_id, "error": {"code": -32601, "message": f"Tool '{tool_name}' not found."}}
try:
result_content = self.tools[tool_name]["handler"](tool_args)
return {"jsonrpc": "2.0", "id": msg_id, "result": {"content": [{"type": "text", "text": str(result_content)}], "isError": False}}
except Exception as e:
return {"jsonrpc": "2.0", "id": msg_id, "result": {"content": [{"type": "text", "text": f"Execution error: {str(e)}"}], "isError": True}}
return {"jsonrpc": "2.0", "id": msg_id, "error": {"code": -32601, "message": f"Unknown method: {method}"}}
5. Security Architecture & Enterprise Guardrails
Because MCP servers execute real system commands, read proprietary databases, and mutate production state, robust security boundaries are mandatory:
- Principle of Least Privilege: Run MCP server processes under unprivileged daemon users with strict file system sandboxing. Never run server processes as root or administrator.
- Human-in-the-Loop Confirmation: Host applications must require explicit user approval before invoking tools that perform mutations (e.g.,
DROP TABLE,git push --force, orDELETE /api/users). - Adversarial Prompt Injection Defense: Untrusted external data retrieved via resources or tool outputs can contain embedded prompt injection payloads attempting to hijack agent control flow. For comprehensive architectural defenses, consult our technical guide on Prompt Injection Defense in Production.
6. Summary & Cross-Pillar Integration
The Model Context Protocol standardizes the bridge between AI reasoning and real-world system capability. By replacing fragile, bespoke connectors with a clean client-host-server specification, MCP establishes the foundation for durable multi-agent architectures.
To explore how MCP connects to autonomous agent workflows in developer environments, continue to our comparative analysis of Claude Code vs. Cursor.
Comments
Post a Comment