# Anthropic Model Context Protocol (MCP) API Documentation
## Complete Coverage:
### **Protocol Overview:**
- **Core Architecture**: Client-Server communication model
- **Transport Mechanisms**: STDIO, SSE, HTTP, WebSocket support
- **Security Model**: OAuth 2.1 authorization flow
- **Message Format**: JSON-RPC 2.0 based protocol
### **Server Features:**
- **Resources**: Structured data and content context
- **Tools**: Executable functions for model actions
- **Prompts**: Pre-defined templates and instructions
- **Utilities**: Completion, logging, pagination support
### **Client Features:**
- **Roots**: File system access permissions
- **Sampling**: Model interaction and response handling
- **Authorization**: OAuth-based security flows
- **Lifecycle Management**: Connection and session handling
### **Implementation Support:**
- **Official SDKs**: Python, TypeScript, C#, Java, Kotlin
- **Server Registry**: Community-driven MCP server catalog
- **Integration Examples**: Real-world use cases and implementations
- **Development Tools**: Inspector, testing utilities, debugging guides
---
## Overview
**Model Context Protocol (MCP)** is an open protocol developed by Anthropic that standardizes how applications provide context to Large Language Models (LLMs). Think of MCP like a USB-C port for AI applications—it provides a standardized way to connect AI models to different data sources and tools.
### Key Benefits
- **Standardized Integration**: Universal protocol for connecting LLMs with external systems
- **Reduced Development Overhead**: Eliminate custom connectors for each data source
- **Scalable Architecture**: Single protocol replaces fragmented integrations
- **Security-First Design**: Built-in authorization and access controls
- **Cross-Platform Support**: Works across different AI applications and tools
---
## Architecture
### Core Components
```
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ LLM Client │ │ MCP Client │ │ MCP Server │
│ (Claude, etc.) │◄──►│ (Host App) │◄──►│ (Data Source) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
```
### Relationship Model
- **Host**: The application containing the LLM (e.g., Claude Desktop)
- **Client**: MCP client within the host that speaks the MCP protocol
- **Server**: MCP server that provides resources, tools, and prompts
- **Connection**: 1:1 relationship between each client and server
---
## Protocol Specification
### Base Protocol
#### JSON-RPC 2.0 Foundation
MCP is built on JSON-RPC 2.0, providing structured request-response communication.
#### Message Types
```typescript
// Request
{
"jsonrpc": "2.0",
"id": 1,
"method": "resources/list",
"params": { /* optional parameters */ }
}
// Response
{
"jsonrpc": "2.0",
"id": 1,
"result": { /* response data */ }
}
// Notification
{
"jsonrpc": "2.0",
"method": "notifications/initialized"
}
// Error
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32601,
"message": "Method not found"
}
}
```
### Transport Layer
#### Supported Transports
1. **STDIO Transport**: Process-based communication
2. **SSE Transport**: Server-Sent Events for web applications
3. **HTTP Transport**: RESTful API with OAuth 2.1 authorization
4. **WebSocket Transport**: Real-time bidirectional communication
#### STDIO Transport Example
```bash
# Server communication via stdin/stdout
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | your-mcp-server
```
#### HTTP Transport Example
```http
POST /mcp HTTP/1.1
Host: api.example.com
Authorization: Bearer <oauth_token>
Content-Type: application/json
{
"jsonrpc": "2.0",
"id": 1,
"method": "resources/list"
}
```
---
## Server Features
### 1. Resources
Resources provide structured data and content that adds context to language models.
#### Capabilities Declaration
```json
{
"capabilities": {
"resources": {
"subscribe": true,
"listChanged": true
}
}
}
```
#### List Resources
**Method**: `resources/list`
**Request**:
```json
{
"jsonrpc": "2.0",
"id": 1,
"method": "resources/list",
"params": {
"cursor": "optional-pagination-cursor"
}
}
```
**Response**:
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"resources": [
{
"uri": "file:///project/src/main.rs",
"name": "main.rs",
"description": "Primary application entry point",
"mimeType": "text/x-rust"
}
],
"nextCursor": "next-page-cursor"
}
}
```
#### Read Resource
**Method**: `resources/read`
**Request**:
```json
{
"jsonrpc": "2.0",
"id": 2,
"method": "resources/read",
"params": {
"uri": "file:///project/src/main.rs"
}
}
```
**Response**:
```json
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"contents": [
{
"uri": "file:///project/src/main.rs",
"mimeType": "text/x-rust",
"text": "fn main() {\n println!(\"Hello world!\");\n}"
}
]
}
}
```
#### Subscribe to Resource Changes
**Method**: `resources/subscribe`
```json
{
"jsonrpc": "2.0",
"id": 4,
"method": "resources/subscribe",
"params": {
"uri": "file:///project/src/main.rs"
}
}
```
#### Resource Templates
Servers can expose parameterized resources using URI templates:
```json
{
"resourceTemplates": [
{
"uriTemplate": "file:///{path}",
"name": "Project Files",
"description": "Access files in the project directory",
"mimeType": "application/octet-stream"
}
]
}
```
### 2. Tools
Tools are executable functions that allow models to perform actions or retrieve information.
#### Capabilities Declaration
```json
{
"capabilities": {
"tools": {
"listChanged": true
}
}
}
```
#### List Tools
**Method**: `tools/list`
**Response**:
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"tools": [
{
"name": "query_database",
"description": "Execute SQL queries against the database",
"inputSchema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "SQL query to execute"
}
},
"required": ["query"]
}
}
]
}
}
```
#### Call Tool
**Method**: `tools/call`
**Request**:
```json
{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "query_database",
"arguments": {
"query": "SELECT * FROM users LIMIT 10"
}
}
}
```
**Success Response**:
```json
{
"jsonrpc": "2.0",
"id": 3,
"result": {
"content": [
{
"type": "text",
"text": "Query returned 10 rows:\nid | name | email\n1 | John | john@example.com\n..."
}
]
}
}
```
**Error Response**:
```json
{
"jsonrpc": "2.0",
"id": 3,
"result": {
"content": [
{
"type": "text",
"text": "SQL Error: Table 'users' doesn't exist"
}
],
"isError": true
}
}
```
### 3. Prompts
Prompts provide pre-defined templates and instructions for language model interactions.
#### Capabilities Declaration
```json
{
"capabilities": {
"prompts": {
"listChanged": true
}
}
}
```
#### List Prompts
**Method**: `prompts/list`
**Response**:
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"prompts": [
{
"name": "code_review",
"description": "Analyze code for potential improvements",
"arguments": [
{
"name": "code",
"description": "The code to review",
"required": true
},
{
"name": "language",
"description": "Programming language",
"required": false
}
]
}
]
}
}
```
#### Get Prompt
**Method**: `prompts/get`
**Request**:
```json
{
"jsonrpc": "2.0",
"id": 2,
"method": "prompts/get",
"params": {
"name": "code_review",
"arguments": {
"code": "def hello():\n print('world')",
"language": "python"
}
}
}
```
**Response**:
```json
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"description": "Analyze code for potential improvements",
"messages": [
{
"role": "user",
"content": {
"type": "text",
"text": "Please review this Python code:\n\ndef hello():\n print('world')\n\nProvide feedback on style, efficiency, and best practices."
}
}
]
}
}
```
#### Embedded Resources in Prompts
```json
{
"messages": [
{
"role": "user",
"content": {
"type": "resource",
"resource": {
"uri": "resource://documentation",
"mimeType": "text/markdown",
"text": "# API Documentation\n..."
}
}
}
]
}
```
---
## Client Features
### 1. Roots
Roots define file system access permissions for MCP servers.
#### List Roots
**Method**: `roots/list`
**Response**:
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"roots": [
{
"uri": "file:///home/user/projects",
"name": "Projects Directory"
}
]
}
}
```
### 2. Sampling
Sampling allows servers to request the client to interact with language models.
#### Create Message
**Method**: `sampling/createMessage`
**Request**:
```json
{
"jsonrpc": "2.0",
"id": 1,
"method": "sampling/createMessage",
"params": {
"messages": [
{
"role": "user",
"content": {
"type": "text",
"text": "What is the capital of France?"
}
}
],
"modelPreferences": {
"hints": [
{
"name": "claude-3-5-sonnet"
}
],
"costPriority": 0.7,
"speedPriority": 0.3,
"intelligencePriority": 0.9
}
}
}
```
**Response**:
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"role": "assistant",
"content": {
"type": "text",
"text": "The capital of France is Paris."
},
"model": "claude-3-5-sonnet-20241022",
"stopReason": "end_turn"
}
}
```
---
## Authorization
### OAuth 2.1 Flow
MCP implements OAuth 2.1 with PKCE for secure authorization.
#### Discovery Endpoint
**GET** `/.well-known/oauth-authorization-server`
```json
{
"issuer": "https://api.example.com",
"authorization_endpoint": "https://api.example.com/oauth/authorize",
"token_endpoint": "https://api.example.com/oauth/token",
"response_types_supported": ["code"],
"grant_types_supported": ["authorization_code"],
"code_challenge_methods_supported": ["S256"]
}
```
#### Authorization Flow
1. **Discovery**: Client discovers authorization endpoints
2. **Authorization Request**: Redirect user to authorization server
3. **Authorization Grant**: User grants permission
4. **Token Exchange**: Exchange authorization code for access token
5. **API Access**: Use access token for MCP requests
#### Authorization Request
```http
GET /oauth/authorize?
response_type=code&
client_id=your_client_id&
redirect_uri=http://localhost:8080/callback&
scope=mcp&
state=random_state&
code_challenge=code_challenge&
code_challenge_method=S256
```
#### Token Exchange
```http
POST /oauth/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&
code=authorization_code&
redirect_uri=http://localhost:8080/callback&
client_id=your_client_id&
code_verifier=code_verifier
```
---
## Lifecycle Management
### Initialization
```json
// Client sends initialize request
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {
"roots": { "listChanged": true },
"sampling": {}
},
"clientInfo": {
"name": "MyMCPClient",
"version": "1.0.0"
}
}
}
// Server responds
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2024-11-05",
"capabilities": {
"resources": { "subscribe": true, "listChanged": true },
"tools": { "listChanged": true },
"prompts": { "listChanged": true }
},
"serverInfo": {
"name": "MyMCPServer",
"version": "1.0.0"
}
}
}
// Client sends initialized notification
{
"jsonrpc": "2.0",
"method": "notifications/initialized"
}
```
### Ping/Pong
```json
// Ping
{
"jsonrpc": "2.0",
"id": 1,
"method": "ping"
}
// Pong
{
"jsonrpc": "2.0",
"id": 1,
"result": {}
}
```
---
## Utilities
### Completion
Auto-completion support for arguments and resource URIs.
**Method**: `completion/complete`
```json
{
"jsonrpc": "2.0",
"id": 1,
"method": "completion/complete",
"params": {
"ref": {
"type": "ref/promptArgument",
"name": "code_review",
"argumentName": "language"
},
"argument": {
"name": "language",
"value": "py"
}
}
}
```
### Logging
**Method**: `notifications/message`
```json
{
"jsonrpc": "2.0",
"method": "notifications/message",
"params": {
"level": "info",
"message": "Server started successfully",
"data": {
"timestamp": "2024-11-05T10:30:00Z"
}
}
}
```
### Progress Notifications
```json
{
"jsonrpc": "2.0",
"method": "notifications/progress",
"params": {
"progressToken": "operation-123",
"progress": 50,
"total": 100
}
}
```
---
## SDKs and Implementation
### Python SDK
#### Installation
```bash
pip install mcp
```
#### Server Example
```python
from mcp.server.fastmcp import FastMCP
from mcp.server.models import Tool
import asyncio
# Create server
mcp = FastMCP("My MCP Server")
@mcp.tool()
def calculate_sum(a: int, b: int) -> int:
"""Add two numbers together."""
return a + b
@mcp.resource("config://settings")
def get_settings() -> str:
"""Get application settings."""
return "debug=true\nport=8080"
async def main():
# Run the server using stdin/stdout
import mcp.server.stdio
async with mcp.server.stdio.stdio_server() as server:
await server.run()
if __name__ == "__main__":
asyncio.run(main())
```
#### Client Example
```python
from mcp.client import Client
from mcp.client.stdio import stdio_client
async def main():
# Connect to MCP server
async with stdio_client(["python", "server.py"]) as client:
# List available tools
tools = await client.list_tools()
print("Available tools:", [tool.name for tool in tools])
# Call a tool
result = await client.call_tool("calculate_sum", {"a": 5, "b": 3})
print("Result:", result.content[0].text)
asyncio.run(main())
```
### TypeScript SDK
#### Installation
```bash
npm install @modelcontextprotocol/sdk
```
#### Server Example
```typescript
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
const server = new Server({
name: "my-mcp-server",
version: "1.0.0"
}, {
capabilities: {
tools: {},
resources: {}
}
});
// Add a tool
server.setRequestHandler('tools/list', async () => ({
tools: [{
name: "echo",
description: "Echo back the input",
inputSchema: {
type: "object",
properties: {
message: { type: "string" }
}
}
}]
}));
server.setRequestHandler('tools/call', async (request) => {
if (request.params.name === "echo") {
return {
content: [{
type: "text",
text: request.params.arguments.message
}]
};
}
throw new Error("Unknown tool");
});
// Start server
const transport = new StdioServerTransport();
await server.connect(transport);
```
### C# SDK
#### Installation
```bash
dotnet add package ModelContextProtocol
```
#### Server Example
```csharp
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ModelContextProtocol;
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddMcp(mcp =>
{
mcp.WithTool("echo", "Echo back the input", EchoAsync);
});
var app = builder.Build();
await app.RunAsync();
static async Task<string> EchoAsync(string message)
{
await Task.Delay(100); // Simulate async work
return $"Echo: {message}";
}
```
---
## Server Registry
### Community Servers
Popular MCP servers available in the community:
#### File System
```bash
npx @modelcontextprotocol/server-filesystem /path/to/directory
```
#### Git Repository
```bash
npx @modelcontextprotocol/server-git /path/to/repo
```
#### PostgreSQL Database
```bash
npx @modelcontextprotocol/server-postgres postgresql://user:pass@host/db
```
#### Google Drive
```bash
npx @modelcontextprotocol/server-gdrive
```
#### Slack
```bash
npx @modelcontextprotocol/server-slack
```
### Registry API
The community registry provides discovery of MCP servers:
#### List Servers
**GET** `https://registry.modelcontextprotocol.io/api/servers`
```json
{
"servers": [
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"name": "filesystem",
"description": "Access local filesystem",
"url": "https://github.com/modelcontextprotocol/servers",
"packages": [
{
"registry_name": "npm",
"name": "@modelcontextprotocol/server-filesystem",
"version": "0.2.0"
}
]
}
]
}
```
---
## Integration Examples
### Claude Desktop
Configure MCP servers in Claude Desktop's configuration:
```json
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["@modelcontextprotocol/server-filesystem", "/Users/username/Documents"]
},
"git": {
"command": "npx",
"args": ["@modelcontextprotocol/server-git", "/Users/username/projects"]
}
}
}
```
### Web Application Integration
```typescript
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
// Connect to MCP server via SSE
const transport = new SSEClientTransport(
new URL('https://api.example.com/mcp/sse')
);
const client = new Client({
name: "web-app",
version: "1.0.0"
}, {
capabilities: {
sampling: {}
}
});
await client.connect(transport);
// Use the client
const tools = await client.request('tools/list', {});
console.log('Available tools:', tools.tools);
```
---
## Development Tools
### MCP Inspector
Visual testing tool for MCP servers:
```bash
npx @modelcontextprotocol/inspector python server.py
```
Access at `http://localhost:5173` to:
- View server capabilities
- Test tool invocations
- Inspect resource contents
- Debug protocol messages
### Debugging
#### Enable Debug Logging
```bash
# Python
export MCP_LOG_LEVEL=debug
python server.py
# Node.js
DEBUG=mcp:* node server.js
```
#### Common Debug Scenarios
1. **Connection Issues**: Check transport configuration
2. **Tool Failures**: Validate input schemas
3. **Resource Access**: Verify URI permissions
4. **Authorization**: Check OAuth flow
---
## Best Practices
### Security
1. **Always validate inputs** to tools and resources
2. **Implement proper authorization** for sensitive operations
3. **Use least privilege principle** for file system access
4. **Sanitize user-provided URIs** to prevent path traversal
5. **Implement rate limiting** for expensive operations
### Performance
1. **Use pagination** for large result sets
2. **Implement resource subscriptions** for real-time updates
3. **Cache frequently accessed resources**
4. **Use streaming** for large file transfers
5. **Optimize tool execution** times
### Error Handling
1. **Return meaningful error messages**
2. **Use appropriate HTTP status codes** for HTTP transport
3. **Implement graceful degradation**
4. **Log errors** for debugging
5. **Provide fallback mechanisms**
### Development
1. **Use type-safe SDKs** when available
2. **Implement comprehensive testing**
3. **Follow semantic versioning**
4. **Document server capabilities** clearly
5. **Provide usage examples**
---
## Error Codes
### JSON-RPC Errors
- `-32700`: Parse error
- `-32600`: Invalid Request
- `-32601`: Method not found
- `-32602`: Invalid params
- `-32603`: Internal error
### MCP-Specific Errors
- `-32001`: Server not initialized
- `-32002`: Resource not found
- `-32003`: Tool execution failed
- `-32004`: Authorization required
- `-32005`: Rate limit exceeded
---
## Versioning
### Protocol Versions
- **2024-11-05**: Current stable version
- **2025-03-26**: Latest version with authorization
- **draft**: Development version
### Compatibility
- Servers MUST declare supported protocol version
- Clients SHOULD support multiple protocol versions
- Breaking changes require new protocol version
---
## Contributing
### Specification Development
- Repository: https://github.com/modelcontextprotocol/modelcontextprotocol
- Discussions: GitHub Discussions
- Issues: GitHub Issues
### SDK Development
- Python SDK: https://github.com/modelcontextprotocol/python-sdk
- TypeScript SDK: https://github.com/modelcontextprotocol/typescript-sdk
- C# SDK: https://github.com/modelcontextprotocol/csharp-sdk
### Community
- Discord: MCP Community Server
- Documentation: https://modelcontextprotocol.io
- Registry: https://registry.modelcontextprotocol.io
---
*Last updated: January 2025*
*Protocol Version: 2025-03-26 (Latest)*
*Specification: https://spec.modelcontextprotocol.io*