# MCP Specification Deep Dive

## What Is It?

The **Model Context Protocol (MCP) Specification** is the official protocol definition for standardized communication between AI assistants and external systems. With **6.8k+ stars**, it defines the architecture, primitives, and transport mechanisms that enable interoperable AI integrations.

**Repository:** [modelcontextprotocol/modelcontextprotocol](https://github.com/modelcontextprotocol/modelcontextprotocol)

---

## The Problem It Solves

AI integration traditionally requires:
- Custom protocols for each AI platform
- Proprietary tool implementations
- No standardized communication
- Siloed development efforts

MCP provides:
- **Standardized protocol** for all AI systems
- **Clear architecture** with defined roles
- **Extensible primitives** for common patterns
- **Transport flexibility** for different deployments

---

## Key Statistics

| Metric | Value |
|--------|-------|
| **Stars** | 6,800 |
| **Forks** | 900 |
| **Protocol Version** | 2025-11-25 |
| **Base Protocol** | JSON-RPC 2.0 |
| **License** | MIT |
| **Organization** | Anthropic |

---

## Architecture Overview

### Three Components

```
┌─────────────────────────────────────────────────────────────────┐
│                          HOST                                    │
│    (Claude Desktop, IDE, AI Application)                        │
│                                                                  │
│    ┌─────────────────────────────────────────────────────────┐  │
│    │                     MCP CLIENT                          │  │
│    │      (Protocol handler, manages connections)            │  │
│    └───────────────────────┬─────────────────────────────────┘  │
└────────────────────────────┼────────────────────────────────────┘
                             │
                   JSON-RPC 2.0 Messages
                             │
┌────────────────────────────▼────────────────────────────────────┐
│                       MCP SERVER                                 │
│    (External service, tool provider, data source)               │
│                                                                  │
│    • Tools      • Resources      • Prompts                      │
│    • Sampling   • Elicitation    • Roots                        │
└─────────────────────────────────────────────────────────────────┘
```

### Component Roles

| Component | Role | Examples |
|-----------|------|----------|
| **Host** | Container application | Claude Desktop, VS Code, IDE |
| **Client** | Protocol handler | SDK implementation |
| **Server** | Capability provider | Database, API, filesystem |

---

## Protocol Layer

### Base: JSON-RPC 2.0

All MCP communication uses JSON-RPC 2.0:

```json
// Request
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_weather",
    "arguments": { "location": "Seattle" }
  }
}

// Response
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "content": [
      { "type": "text", "text": "72°F, partly cloudy" }
    ]
  }
}

// Notification (no id)
{
  "jsonrpc": "2.0",
  "method": "notifications/progress",
  "params": { "progress": 50, "total": 100 }
}
```

### Message Types

| Type | Has ID | Expects Response |
|------|--------|------------------|
| **Request** | Yes | Yes |
| **Response** | Yes (matches request) | No |
| **Notification** | No | No |

---

## The 6 Primitives

### 1. Tools

Actions the AI can invoke:

```json
{
  "name": "send_email",
  "description": "Send an email to a recipient",
  "inputSchema": {
    "type": "object",
    "properties": {
      "to": { "type": "string", "format": "email" },
      "subject": { "type": "string" },
      "body": { "type": "string" }
    },
    "required": ["to", "subject", "body"]
  }
}
```

**Flow:**
```
AI decides to use tool → Client sends tools/call → Server executes → Result returned
```

### 2. Resources

Data the AI can read:

```json
{
  "uri": "file:///project/src/main.py",
  "name": "main.py",
  "description": "Main application entry point",
  "mimeType": "text/x-python"
}
```

**URI Schemes:**
- `file://` - Local files
- `http://` / `https://` - Web resources
- Custom schemes (e.g., `db://`, `config://`)

### 3. Prompts

Reusable prompt templates:

```json
{
  "name": "code_review",
  "description": "Review code for best practices",
  "arguments": [
    {
      "name": "language",
      "description": "Programming language",
      "required": true
    },
    {
      "name": "focus",
      "description": "Review focus area",
      "required": false
    }
  ]
}
```

### 4. Sampling

Server requests LLM completion from host:

```json
{
  "method": "sampling/createMessage",
  "params": {
    "messages": [
      { "role": "user", "content": { "type": "text", "text": "Summarize this" } }
    ],
    "modelPreferences": {
      "hints": [{ "name": "claude-3-opus" }],
      "costPriority": 0.5,
      "speedPriority": 0.5
    },
    "maxTokens": 1000
  }
}
```

### 5. Elicitation

Server requests information from user:

```json
{
  "method": "elicitation/request",
  "params": {
    "message": "Please provide your API key",
    "requestedSchema": {
      "type": "object",
      "properties": {
        "apiKey": { "type": "string" }
      }
    }
  }
}
```

### 6. Roots

Define accessible file system areas:

```json
{
  "method": "roots/list",
  "result": {
    "roots": [
      { "uri": "file:///home/user/project", "name": "Project Root" },
      { "uri": "file:///home/user/.config", "name": "Config" }
    ]
  }
}
```

---

## Lifecycle

### Connection Phases

```
1. Initialize
   Client → Server: initialize request
   Server → Client: capabilities response
   Client → Server: initialized notification

2. Operation
   Bidirectional message exchange
   Tool calls, resource reads, etc.

3. Shutdown
   Either party can disconnect
   Clean resource cleanup
```

### Initialize Handshake

```json
// Client → Server
{
  "method": "initialize",
  "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "roots": { "listChanged": true },
      "sampling": {}
    },
    "clientInfo": {
      "name": "Claude Desktop",
      "version": "1.0.0"
    }
  }
}

// Server → Client
{
  "result": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "tools": { "listChanged": true },
      "resources": { "subscribe": true }
    },
    "serverInfo": {
      "name": "Database Server",
      "version": "2.0.0"
    }
  }
}
```

---

## Capabilities

### Server Capabilities

| Capability | Description |
|------------|-------------|
| `tools` | Exposes callable functions |
| `resources` | Provides readable data |
| `prompts` | Offers prompt templates |
| `logging` | Sends log messages |

### Client Capabilities

| Capability | Description |
|------------|-------------|
| `roots` | Provides filesystem roots |
| `sampling` | Allows LLM completions |
| `elicitation` | Supports user prompts |

### Dynamic Notifications

```json
// Server notifies tools changed
{
  "method": "notifications/tools/list_changed"
}

// Client notifies roots changed
{
  "method": "notifications/roots/list_changed"
}
```

---

## Transport Mechanisms

### STDIO

Standard input/output for local processes:

```
Host spawns server process
  ↓
Communication via stdin/stdout
  ↓
JSON-RPC messages on each line
```

**Best for:** Local tools, Claude Desktop, development

### Streamable HTTP

HTTP with streaming support:

```
POST /mcp/messages
Content-Type: application/json

{"jsonrpc":"2.0","method":"tools/call"...}
```

**Best for:** Remote servers, web deployments

### SSE (Server-Sent Events)

For real-time streaming:

```
GET /mcp/events
Accept: text/event-stream

data: {"jsonrpc":"2.0","method":"progress"...}
data: {"jsonrpc":"2.0","method":"complete"...}
```

**Best for:** Long-running operations, progress updates

---

## Security Model

### OAuth 2.1 Support

For authenticated servers:

```json
{
  "capabilities": {
    "oauth": {
      "authorizationUrl": "https://auth.example.com/authorize",
      "tokenUrl": "https://auth.example.com/token",
      "scopes": ["read", "write"]
    }
  }
}
```

### Security Best Practices

1. **Validate all inputs** - Don't trust client data
2. **Sandbox execution** - Limit server capabilities
3. **Authenticate connections** - Use OAuth for sensitive operations
4. **Log operations** - Audit trail for actions
5. **Limit scope** - Minimal necessary permissions

---

## Protocol Versioning

### Current Version: 2024-11-05

The protocol version is exchanged during initialization:

```json
{
  "method": "initialize",
  "params": {
    "protocolVersion": "2024-11-05"
  }
}
```

### Version Negotiation

1. Client sends preferred version
2. Server responds with supported version
3. Both use agreed version
4. Fail if incompatible

---

## Complete Tool Flow

```
1. Host receives user request
   "What's the weather in Seattle?"

2. Client lists available tools
   → GET tools/list
   ← [{ name: "get_weather", ... }]

3. AI decides to use tool
   Reasoning: Need weather data, have get_weather tool

4. Client calls tool
   → POST tools/call
   {
     "name": "get_weather",
     "arguments": { "location": "Seattle" }
   }

5. Server executes and responds
   ← {
     "content": [
       { "type": "text", "text": "72°F, partly cloudy" }
     ]
   }

6. AI incorporates result
   "The weather in Seattle is 72°F and partly cloudy."
```

---

## Complete Resource Flow

```
1. Client lists resources
   → GET resources/list
   ← [{ uri: "file:///project/README.md", ... }]

2. Client requests specific resource
   → POST resources/read
   { "uri": "file:///project/README.md" }

3. Server returns content
   ← {
     "contents": [{
       "uri": "file:///project/README.md",
       "mimeType": "text/markdown",
       "text": "# Project\n\nDocumentation..."
     }]
   }

4. AI uses content in response
```

---

## Error Handling

### Error Response

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32602,
    "message": "Invalid params",
    "data": {
      "details": "Missing required field: location"
    }
  }
}
```

### Standard Error Codes

| Code | Meaning |
|------|---------|
| -32700 | Parse error |
| -32600 | Invalid request |
| -32601 | Method not found |
| -32602 | Invalid params |
| -32603 | Internal error |

---

## Implementations

### Official SDKs

| SDK | Language | Repository |
|-----|----------|------------|
| **TypeScript** | TS/JS | modelcontextprotocol/typescript-sdk |
| **Python** | Python | modelcontextprotocol/python-sdk |
| **Kotlin** | Kotlin | modelcontextprotocol/kotlin-sdk |

### Official Servers

| Server | Purpose |
|--------|---------|
| **filesystem** | File operations |
| **github** | GitHub API |
| **postgres** | Database queries |
| **sqlite** | SQLite access |
| **fetch** | HTTP requests |

---

## Extension Points

### Custom Transport

Implement any transport meeting requirements:
- Reliable message delivery
- Bidirectional communication
- Connection lifecycle management

### Custom Primitives

Extend beyond standard primitives:
- Domain-specific tools
- Specialized resources
- Custom prompt patterns

---

## Comparison to Alternatives

| Protocol | Focus | Adoption |
|----------|-------|----------|
| **MCP** | AI integration | Growing |
| **LSP** | IDE features | Mature |
| **REST** | Web APIs | Universal |
| **GraphQL** | Flexible queries | Wide |

### MCP Advantages

1. **AI-native** - Designed for LLM workflows
2. **Bidirectional** - Server can request from client
3. **Standardized** - One protocol for all tools
4. **Capability-based** - Negotiate features
5. **Transport-agnostic** - Multiple options

---

## Best Practices

### Tool Design

```json
{
  "name": "search_documents",
  "description": "Search indexed documents. Returns top matches with relevance scores. Use for finding specific information.",
  "inputSchema": {
    "type": "object",
    "properties": {
      "query": {
        "type": "string",
        "description": "Natural language search query"
      },
      "limit": {
        "type": "number",
        "description": "Maximum results (1-100)",
        "default": 10
      }
    },
    "required": ["query"]
  }
}
```

### Resource Design

```json
{
  "uri": "db://users/{userId}/profile",
  "name": "User Profile",
  "description": "Complete user profile including preferences and history",
  "mimeType": "application/json"
}
```

---

## Resources

- **Specification:** https://modelcontextprotocol.io/specification
- **Repository:** https://github.com/modelcontextprotocol/modelcontextprotocol
- **TypeScript SDK:** https://github.com/modelcontextprotocol/typescript-sdk
- **Python SDK:** https://github.com/modelcontextprotocol/python-sdk
- **Official Servers:** https://github.com/modelcontextprotocol/servers

---

## Key Takeaways

1. **JSON-RPC 2.0 base** - Standard, well-understood protocol
2. **Three components** - Host, Client, Server with clear roles
3. **Six primitives** - Tools, Resources, Prompts, Sampling, Elicitation, Roots
4. **Capability negotiation** - Features discovered at runtime
5. **Transport flexibility** - STDIO, HTTP, SSE options
6. **Security built-in** - OAuth 2.1 support
7. **Bidirectional** - Server can request from client

---

*The MCP Specification provides the foundation for interoperable AI integrations. Understanding this protocol is essential for building tools that work across all MCP-compatible AI systems.*
