Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Model Context Protocol
https://github.com/modelcontextprotocol/modelcontextprotocol
Admin
This repository contains the specification and protocol schema for the Model Context Protocol, with
...
Tokens:
349,469
Snippets:
2,058
Trust Score:
7.8
Update:
1 week ago
Context
Skills
Chat
Benchmark
60.6
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Model Context Protocol (MCP) Specification The Model Context Protocol (MCP) is an open protocol that enables seamless integration between LLM applications and external data sources and tools. Whether you're building an AI-powered IDE, enhancing a chat interface, or creating custom AI workflows, MCP provides a standardized way to connect LLMs with the context they need. The protocol uses JSON-RPC 2.0 messages to establish communication between hosts (LLM applications), clients (connectors within host applications), and servers (services providing context and capabilities). MCP supports three core server features: Resources (context and data for users or AI models), Prompts (templated messages and workflows), and Tools (functions for AI model execution). On the client side, it provides Sampling (server-initiated LLM interactions), Roots (filesystem boundaries), and Elicitation (requests for additional user information). The protocol supports two transport mechanisms: stdio (subprocess communication) and Streamable HTTP (independent server with optional Server-Sent Events). The current protocol revision is 2025-11-25. --- ## Connection Lifecycle - Initialize The initialization phase establishes protocol version compatibility, exchanges capabilities, and shares implementation details. Clients must initiate by sending an `initialize` request. ```json // Client Request { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2025-11-25", "capabilities": { "roots": { "listChanged": true }, "sampling": {}, "elicitation": { "form": {}, "url": {} } }, "clientInfo": { "name": "ExampleClient", "version": "1.0.0" } } } // Server Response { "jsonrpc": "2.0", "id": 1, "result": { "protocolVersion": "2025-11-25", "capabilities": { "logging": {}, "prompts": { "listChanged": true }, "resources": { "subscribe": true, "listChanged": true }, "tools": { "listChanged": true } }, "serverInfo": { "name": "ExampleServer", "version": "1.0.0" }, "instructions": "Optional instructions for the client" } } // Client then sends initialized notification { "jsonrpc": "2.0", "method": "notifications/initialized" } ``` --- ## Tools - List Available Tools Tools enable AI models to interact with external systems. Servers declare the `tools` capability and clients can discover available tools via `tools/list`. This operation supports pagination with optional cursor parameters. ```json // Request { "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": { "cursor": "optional-cursor-value" } } // Response { "jsonrpc": "2.0", "id": 1, "result": { "tools": [ { "name": "get_weather", "title": "Weather Information Provider", "description": "Get current weather information for a location", "inputSchema": { "type": "object", "properties": { "location": { "type": "string", "description": "City name or zip code" } }, "required": ["location"] } } ], "nextCursor": "next-page-cursor" } } ``` --- ## Tools - Call a Tool Clients invoke tools by sending `tools/call` requests with the tool name and arguments. Results can contain text, images, audio, resource links, or structured content. Tools may define output schemas for validation. ```json // Request { "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "get_weather", "arguments": { "location": "New York" } } } // Success Response { "jsonrpc": "2.0", "id": 2, "result": { "content": [ { "type": "text", "text": "Current weather in New York:\nTemperature: 72°F\nConditions: Partly cloudy" } ], "isError": false } } // Tool Execution Error Response (input validation) { "jsonrpc": "2.0", "id": 4, "result": { "content": [ { "type": "text", "text": "Invalid departure date: must be in the future. Current date is 08/08/2025." } ], "isError": true } } // Protocol Error (unknown tool) { "jsonrpc": "2.0", "id": 3, "error": { "code": -32602, "message": "Unknown tool: invalid_tool_name" } } ``` --- ## Tools - With Structured Output Schema Tools can define both input and output schemas for structured results. When an output schema is provided, servers must return structured content conforming to the schema. ```json // Tool Definition with Output Schema { "name": "get_weather_data", "title": "Weather Data Retriever", "description": "Get current weather data for a location", "inputSchema": { "type": "object", "properties": { "location": { "type": "string", "description": "City name or zip code" } }, "required": ["location"] }, "outputSchema": { "type": "object", "properties": { "temperature": { "type": "number", "description": "Temperature in celsius" }, "conditions": { "type": "string", "description": "Weather conditions" }, "humidity": { "type": "number", "description": "Humidity percentage" } }, "required": ["temperature", "conditions", "humidity"] } } // Response with Structured Content { "jsonrpc": "2.0", "id": 5, "result": { "content": [ { "type": "text", "text": "{\"temperature\": 22.5, \"conditions\": \"Partly cloudy\", \"humidity\": 65}" } ], "structuredContent": { "temperature": 22.5, "conditions": "Partly cloudy", "humidity": 65 } } } ``` --- ## Resources - List Resources Resources allow servers to share contextual data like files, database schemas, or application-specific information. Each resource is identified by a URI. ```json // Request { "jsonrpc": "2.0", "id": 1, "method": "resources/list", "params": { "cursor": "optional-cursor-value" } } // Response { "jsonrpc": "2.0", "id": 1, "result": { "resources": [ { "uri": "file:///project/src/main.rs", "name": "main.rs", "title": "Rust Application Main File", "description": "Primary application entry point", "mimeType": "text/x-rust", "annotations": { "audience": ["user", "assistant"], "priority": 0.8, "lastModified": "2025-01-12T15:00:58Z" } } ], "nextCursor": "next-page-cursor" } } ``` --- ## Resources - Read Resource Content Retrieve resource contents via `resources/read`. Resources can contain either text or binary (base64-encoded) data. ```json // Request { "jsonrpc": "2.0", "id": 2, "method": "resources/read", "params": { "uri": "file:///project/src/main.rs" } } // Text Response { "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}" } ] } } // Binary Response { "jsonrpc": "2.0", "id": 3, "result": { "contents": [ { "uri": "file:///example.png", "mimeType": "image/png", "blob": "base64-encoded-data" } ] } } ``` --- ## Resources - Subscribe to Changes Clients can subscribe to resource changes and receive notifications when resources are updated. Servers must declare `subscribe: true` in their resources capability. ```json // Subscribe Request { "jsonrpc": "2.0", "id": 4, "method": "resources/subscribe", "params": { "uri": "file:///project/src/main.rs" } } // Update Notification (server to client) { "jsonrpc": "2.0", "method": "notifications/resources/updated", "params": { "uri": "file:///project/src/main.rs" } } // List Changed Notification (server to client) { "jsonrpc": "2.0", "method": "notifications/resources/list_changed" } ``` --- ## Resources - Templates Resource templates expose parameterized resources using URI templates (RFC 6570). Arguments can be auto-completed through the completion API. ```json // Request { "jsonrpc": "2.0", "id": 3, "method": "resources/templates/list" } // Response { "jsonrpc": "2.0", "id": 3, "result": { "resourceTemplates": [ { "uriTemplate": "file:///{path}", "name": "Project Files", "title": "Project Files", "description": "Access files in the project directory", "mimeType": "application/octet-stream" } ] } } ``` --- ## Prompts - List and Get Prompts Prompts are templated messages for interacting with language models. They support arguments for customization and can contain text, images, audio, or embedded resources. ```json // List Prompts Request { "jsonrpc": "2.0", "id": 1, "method": "prompts/list", "params": { "cursor": "optional-cursor-value" } } // List Prompts Response { "jsonrpc": "2.0", "id": 1, "result": { "prompts": [ { "name": "code_review", "title": "Request Code Review", "description": "Asks the LLM to analyze code quality and suggest improvements", "arguments": [ { "name": "code", "description": "The code to review", "required": true } ] } ] } } // Get Prompt Request { "jsonrpc": "2.0", "id": 2, "method": "prompts/get", "params": { "name": "code_review", "arguments": { "code": "def hello():\n print('world')" } } } // Get Prompt Response { "jsonrpc": "2.0", "id": 2, "result": { "description": "Code review prompt", "messages": [ { "role": "user", "content": { "type": "text", "text": "Please review this Python code:\ndef hello():\n print('world')" } } ] } } ``` --- ## Sampling - Create Message Sampling allows servers to request LLM generations from clients. This enables agentic behaviors where servers can leverage AI capabilities without needing their own API keys. ```json // Request (Server to Client) { "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-sonnet" }], "intelligencePriority": 0.8, "speedPriority": 0.5 }, "systemPrompt": "You are a helpful assistant.", "maxTokens": 100 } } // Response (Client to Server) { "jsonrpc": "2.0", "id": 1, "result": { "role": "assistant", "content": { "type": "text", "text": "The capital of France is Paris." }, "model": "claude-3-sonnet-20240307", "stopReason": "endTurn" } } ``` --- ## Sampling - With Tool Use Servers can request LLM generations with tool use capabilities. The client's LLM can call tools, receive results, and continue the conversation in a multi-turn loop. ```json // Initial Request with Tools (Server to Client) { "jsonrpc": "2.0", "id": 1, "method": "sampling/createMessage", "params": { "messages": [ { "role": "user", "content": { "type": "text", "text": "What's the weather in Paris and London?" } } ], "tools": [ { "name": "get_weather", "description": "Get current weather for a city", "inputSchema": { "type": "object", "properties": { "city": { "type": "string" } }, "required": ["city"] } } ], "toolChoice": { "mode": "auto" }, "maxTokens": 1000 } } // Response with Tool Use (Client to Server) { "jsonrpc": "2.0", "id": 1, "result": { "role": "assistant", "content": [ { "type": "tool_use", "id": "call_abc123", "name": "get_weather", "input": { "city": "Paris" } }, { "type": "tool_use", "id": "call_def456", "name": "get_weather", "input": { "city": "London" } } ], "model": "claude-3-sonnet-20240307", "stopReason": "toolUse" } } // Follow-up with Tool Results (Server to Client) { "jsonrpc": "2.0", "id": 2, "method": "sampling/createMessage", "params": { "messages": [ { "role": "user", "content": { "type": "text", "text": "What's the weather in Paris and London?" } }, { "role": "assistant", "content": [ { "type": "tool_use", "id": "call_abc123", "name": "get_weather", "input": { "city": "Paris" } }, { "type": "tool_use", "id": "call_def456", "name": "get_weather", "input": { "city": "London" } } ]}, { "role": "user", "content": [ { "type": "tool_result", "toolUseId": "call_abc123", "content": [{ "type": "text", "text": "18°C, partly cloudy" }] }, { "type": "tool_result", "toolUseId": "call_def456", "content": [{ "type": "text", "text": "15°C, rainy" }] } ]} ], "tools": [{ "name": "get_weather", "description": "Get current weather", "inputSchema": { "type": "object", "properties": { "city": { "type": "string" } }, "required": ["city"] } }], "maxTokens": 1000 } } // Final Response (Client to Server) { "jsonrpc": "2.0", "id": 2, "result": { "role": "assistant", "content": { "type": "text", "text": "Paris: 18°C and partly cloudy. London: 15°C and rainy - bring an umbrella!" }, "model": "claude-3-sonnet-20240307", "stopReason": "endTurn" } } ``` --- ## Roots - List Filesystem Roots Roots define filesystem boundaries where servers can operate. Clients declare the `roots` capability and servers can query available roots. ```json // Request (Server to Client) { "jsonrpc": "2.0", "id": 1, "method": "roots/list" } // Response { "jsonrpc": "2.0", "id": 1, "result": { "roots": [ { "uri": "file:///home/user/projects/myproject", "name": "My Project" }, { "uri": "file:///home/user/repos/backend", "name": "Backend Repository" } ] } } // Root List Changed Notification (Client to Server) { "jsonrpc": "2.0", "method": "notifications/roots/list_changed" } ``` --- ## Elicitation - Form Mode Elicitation allows servers to request additional information from users. Form mode collects structured data with JSON Schema validation. ```json // Request (Server to Client) { "jsonrpc": "2.0", "id": 1, "method": "elicitation/create", "params": { "mode": "form", "message": "Please provide your contact information", "requestedSchema": { "type": "object", "properties": { "name": { "type": "string", "description": "Your full name" }, "email": { "type": "string", "format": "email", "description": "Your email" }, "age": { "type": "number", "minimum": 18 } }, "required": ["name", "email"] } } } // Response (User Accepted) { "jsonrpc": "2.0", "id": 1, "result": { "action": "accept", "content": { "name": "Monalisa Octocat", "email": "octocat@github.com", "age": 30 } } } // Response (User Declined) { "jsonrpc": "2.0", "id": 2, "result": { "action": "decline" } } ``` --- ## Elicitation - URL Mode URL mode directs users to external URLs for sensitive interactions (auth flows, payments) that must not pass through the MCP client. ```json // Request (Server to Client) { "jsonrpc": "2.0", "id": 3, "method": "elicitation/create", "params": { "mode": "url", "elicitationId": "550e8400-e29b-41d4-a716-446655440000", "url": "https://mcp.example.com/ui/set_api_key", "message": "Please provide your API key to continue." } } // Response (User Consented to Navigate) { "jsonrpc": "2.0", "id": 3, "result": { "action": "accept" } } // Completion Notification (Server to Client, after out-of-band interaction completes) { "jsonrpc": "2.0", "method": "notifications/elicitation/complete", "params": { "elicitationId": "550e8400-e29b-41d4-a716-446655440000" } } ``` --- ## Completion - Argument Auto-Complete Servers can provide autocompletion suggestions for prompt arguments and resource template parameters. ```json // Request { "jsonrpc": "2.0", "id": 1, "method": "completion/complete", "params": { "ref": { "type": "ref/prompt", "name": "code_review" }, "argument": { "name": "language", "value": "py" } } } // Response { "jsonrpc": "2.0", "id": 1, "result": { "completion": { "values": ["python", "pytorch", "pyside"], "total": 10, "hasMore": true } } } // Request with Context (previous arguments) { "jsonrpc": "2.0", "id": 2, "method": "completion/complete", "params": { "ref": { "type": "ref/prompt", "name": "code_review" }, "argument": { "name": "framework", "value": "fla" }, "context": { "arguments": { "language": "python" } } } } // Response with Context-Aware Suggestions { "jsonrpc": "2.0", "id": 2, "result": { "completion": { "values": ["flask"], "total": 1, "hasMore": false } } } ``` --- ## Logging - Set Level and Receive Messages Servers can emit structured log messages. Clients control verbosity by setting minimum log levels (debug, info, notice, warning, error, critical, alert, emergency). ```json // Set Log Level Request (Client to Server) { "jsonrpc": "2.0", "id": 1, "method": "logging/setLevel", "params": { "level": "info" } } // Log Message Notification (Server to Client) { "jsonrpc": "2.0", "method": "notifications/message", "params": { "level": "error", "logger": "database", "data": { "error": "Connection failed", "details": { "host": "localhost", "port": 5432 } } } } ``` --- ## Progress Tracking Long-running operations can report progress via notifications. Requests include a `progressToken` in metadata to receive updates. ```json // Request with Progress Token { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "long_operation", "arguments": {}, "_meta": { "progressToken": "abc123" } } } // Progress Notification { "jsonrpc": "2.0", "method": "notifications/progress", "params": { "progressToken": "abc123", "progress": 50, "total": 100, "message": "Processing files..." } } ``` --- ## Cancellation Either side can cancel in-progress requests by sending a cancellation notification with the request ID. ```json // Cancellation Notification { "jsonrpc": "2.0", "method": "notifications/cancelled", "params": { "requestId": "123", "reason": "User requested cancellation" } } ``` --- ## Streamable HTTP Transport For HTTP-based transport, clients POST JSON-RPC messages and may receive SSE streams for responses. Session management uses the `MCP-Session-Id` header. ```bash # Initialize via HTTP POST curl -X POST https://example.com/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2025-11-25", "capabilities": { "sampling": {} }, "clientInfo": { "name": "MyCLI", "version": "1.0.0" } } }' # Response includes session ID header: MCP-Session-Id: 1868a90c... # Subsequent requests include session ID and protocol version curl -X POST https://example.com/mcp \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -H "MCP-Session-Id: 1868a90c..." \ -H "MCP-Protocol-Version: 2025-11-25" \ -d '{ "jsonrpc": "2.0", "id": 2, "method": "tools/list" }' # Open SSE stream for server-initiated messages curl -X GET https://example.com/mcp \ -H "Accept: text/event-stream" \ -H "MCP-Session-Id: 1868a90c..." \ -H "MCP-Protocol-Version: 2025-11-25" # Terminate session curl -X DELETE https://example.com/mcp \ -H "MCP-Session-Id: 1868a90c..." ``` --- ## Summary The Model Context Protocol provides a comprehensive framework for integrating LLM applications with external tools and data sources. Primary use cases include: building AI-powered development environments that access file systems and execute tools; creating chat interfaces with dynamic context from databases, APIs, or documents; implementing agentic workflows where servers can request LLM completions and user input; and developing composable AI integrations with standardized discovery and invocation patterns. Integration patterns follow a client-server architecture using JSON-RPC 2.0 over stdio or HTTP transports. Servers expose capabilities (tools, resources, prompts, logging, completions) during initialization, and clients interact through typed request/response pairs. The protocol emphasizes security with user consent requirements, capability negotiation, input validation, and clear separation between trusted and untrusted data. For real-world implementations, developers should use the official TypeScript schema as the source of truth and leverage SDKs available for multiple programming languages at [modelcontextprotocol.io](https://modelcontextprotocol.io).