└── docs └── specification └── 2025-03-26 ├── architecture └── index.mdx ├── basic ├── authorization.mdx ├── index.mdx ├── lifecycle.mdx ├── transports.mdx └── utilities │ ├── cancellation.mdx │ ├── ping.mdx │ └── progress.mdx ├── changelog.mdx ├── client ├── roots.mdx └── sampling.mdx ├── index.mdx └── server ├── index.mdx ├── prompts.mdx ├── resource-picker.png ├── resources.mdx ├── slash-command.png ├── tools.mdx └── utilities ├── completion.mdx ├── logging.mdx └── pagination.mdx /docs/specification/2025-03-26/architecture/index.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Architecture 3 | --- 4 | 5 | The Model Context Protocol (MCP) follows a client-host-server architecture where each 6 | host can run multiple client instances. This architecture enables users to integrate AI 7 | capabilities across applications while maintaining clear security boundaries and 8 | isolating concerns. Built on JSON-RPC, MCP provides a stateful session protocol focused 9 | on context exchange and sampling coordination between clients and servers. 10 | 11 | ## Core Components 12 | 13 | ```mermaid 14 | graph LR 15 | subgraph "Application Host Process" 16 | H[Host] 17 | C1[Client 1] 18 | C2[Client 2] 19 | C3[Client 3] 20 | H --> C1 21 | H --> C2 22 | H --> C3 23 | end 24 | 25 | subgraph "Local machine" 26 | S1[Server 1
Files & Git] 27 | S2[Server 2
Database] 28 | R1[("Local
Resource A")] 29 | R2[("Local
Resource B")] 30 | 31 | C1 --> S1 32 | C2 --> S2 33 | S1 <--> R1 34 | S2 <--> R2 35 | end 36 | 37 | subgraph "Internet" 38 | S3[Server 3
External APIs] 39 | R3[("Remote
Resource C")] 40 | 41 | C3 --> S3 42 | S3 <--> R3 43 | end 44 | ``` 45 | 46 | ### Host 47 | 48 | The host process acts as the container and coordinator: 49 | 50 | - Creates and manages multiple client instances 51 | - Controls client connection permissions and lifecycle 52 | - Enforces security policies and consent requirements 53 | - Handles user authorization decisions 54 | - Coordinates AI/LLM integration and sampling 55 | - Manages context aggregation across clients 56 | 57 | ### Clients 58 | 59 | Each client is created by the host and maintains an isolated server connection: 60 | 61 | - Establishes one stateful session per server 62 | - Handles protocol negotiation and capability exchange 63 | - Routes protocol messages bidirectionally 64 | - Manages subscriptions and notifications 65 | - Maintains security boundaries between servers 66 | 67 | A host application creates and manages multiple clients, with each client having a 1:1 68 | relationship with a particular server. 69 | 70 | ### Servers 71 | 72 | Servers provide specialized context and capabilities: 73 | 74 | - Expose resources, tools and prompts via MCP primitives 75 | - Operate independently with focused responsibilities 76 | - Request sampling through client interfaces 77 | - Must respect security constraints 78 | - Can be local processes or remote services 79 | 80 | ## Design Principles 81 | 82 | MCP is built on several key design principles that inform its architecture and 83 | implementation: 84 | 85 | 1. **Servers should be extremely easy to build** 86 | 87 | - Host applications handle complex orchestration responsibilities 88 | - Servers focus on specific, well-defined capabilities 89 | - Simple interfaces minimize implementation overhead 90 | - Clear separation enables maintainable code 91 | 92 | 2. **Servers should be highly composable** 93 | 94 | - Each server provides focused functionality in isolation 95 | - Multiple servers can be combined seamlessly 96 | - Shared protocol enables interoperability 97 | - Modular design supports extensibility 98 | 99 | 3. **Servers should not be able to read the whole conversation, nor "see into" other 100 | servers** 101 | 102 | - Servers receive only necessary contextual information 103 | - Full conversation history stays with the host 104 | - Each server connection maintains isolation 105 | - Cross-server interactions are controlled by the host 106 | - Host process enforces security boundaries 107 | 108 | 4. **Features can be added to servers and clients progressively** 109 | - Core protocol provides minimal required functionality 110 | - Additional capabilities can be negotiated as needed 111 | - Servers and clients evolve independently 112 | - Protocol designed for future extensibility 113 | - Backwards compatibility is maintained 114 | 115 | ## Capability Negotiation 116 | 117 | The Model Context Protocol uses a capability-based negotiation system where clients and 118 | servers explicitly declare their supported features during initialization. Capabilities 119 | determine which protocol features and primitives are available during a session. 120 | 121 | - Servers declare capabilities like resource subscriptions, tool support, and prompt 122 | templates 123 | - Clients declare capabilities like sampling support and notification handling 124 | - Both parties must respect declared capabilities throughout the session 125 | - Additional capabilities can be negotiated through extensions to the protocol 126 | 127 | ```mermaid 128 | sequenceDiagram 129 | participant Host 130 | participant Client 131 | participant Server 132 | 133 | Host->>+Client: Initialize client 134 | Client->>+Server: Initialize session with capabilities 135 | Server-->>Client: Respond with supported capabilities 136 | 137 | Note over Host,Server: Active Session with Negotiated Features 138 | 139 | loop Client Requests 140 | Host->>Client: User- or model-initiated action 141 | Client->>Server: Request (tools/resources) 142 | Server-->>Client: Response 143 | Client-->>Host: Update UI or respond to model 144 | end 145 | 146 | loop Server Requests 147 | Server->>Client: Request (sampling) 148 | Client->>Host: Forward to AI 149 | Host-->>Client: AI response 150 | Client-->>Server: Response 151 | end 152 | 153 | loop Notifications 154 | Server--)Client: Resource updates 155 | Client--)Server: Status changes 156 | end 157 | 158 | Host->>Client: Terminate 159 | Client->>-Server: End session 160 | deactivate Server 161 | ``` 162 | 163 | Each capability unlocks specific protocol features for use during the session. For 164 | example: 165 | 166 | - Implemented [server features](/specification/2025-03-26/server) must be advertised in the 167 | server's capabilities 168 | - Emitting resource subscription notifications requires the server to declare 169 | subscription support 170 | - Tool invocation requires the server to declare tool capabilities 171 | - [Sampling](/specification/2025-03-26/client) requires the client to declare support in its 172 | capabilities 173 | 174 | This capability negotiation ensures clients and servers have a clear understanding of 175 | supported functionality while maintaining protocol extensibility. 176 | -------------------------------------------------------------------------------- /docs/specification/2025-03-26/basic/authorization.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Authorization 3 | --- 4 | 5 | **Protocol Revision**: 2025-03-26 6 | 7 | ## Introduction 8 | 9 | ### Purpose and Scope 10 | 11 | The Model Context Protocol provides authorization capabilities at the transport level, 12 | enabling MCP clients to make requests to restricted MCP servers on behalf of resource 13 | owners. This specification defines the authorization flow for HTTP-based transports. 14 | 15 | ### Protocol Requirements 16 | 17 | Authorization is **OPTIONAL** for MCP implementations. When supported: 18 | 19 | - Implementations using an HTTP-based transport **SHOULD** conform to this specification. 20 | - Implementations using an STDIO transport **SHOULD NOT** follow this specification, and 21 | instead retrieve credentials from the environment. 22 | - Implementations using alternative transports **MUST** follow established security best 23 | practices for their protocol. 24 | 25 | ### Standards Compliance 26 | 27 | This authorization mechanism is based on established specifications listed below, but 28 | implements a selected subset of their features to ensure security and interoperability 29 | while maintaining simplicity: 30 | 31 | - [OAuth 2.1 IETF DRAFT](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12) 32 | - OAuth 2.0 Authorization Server Metadata 33 | ([RFC8414](https://datatracker.ietf.org/doc/html/rfc8414)) 34 | - OAuth 2.0 Dynamic Client Registration Protocol 35 | ([RFC7591](https://datatracker.ietf.org/doc/html/rfc7591)) 36 | 37 | ## Authorization Flow 38 | 39 | ### Overview 40 | 41 | 1. MCP auth implementations **MUST** implement OAuth 2.1 with appropriate security 42 | measures for both confidential and public clients. 43 | 44 | 2. MCP auth implementations **SHOULD** support the OAuth 2.0 Dynamic Client Registration 45 | Protocol ([RFC7591](https://datatracker.ietf.org/doc/html/rfc7591)). 46 | 47 | 3. MCP servers **SHOULD** and MCP clients **MUST** implement OAuth 2.0 Authorization 48 | Server Metadata ([RFC8414](https://datatracker.ietf.org/doc/html/rfc8414)). Servers 49 | that do not support Authorization Server Metadata **MUST** follow the default URI 50 | schema. 51 | 52 | ### OAuth Grant Types 53 | 54 | OAuth specifies different flows or grant types, which are different ways of obtaining an 55 | access token. Each of these targets different use cases and scenarios. 56 | 57 | MCP servers **SHOULD** support the OAuth grant types that best align with the intended 58 | audience. For instance: 59 | 60 | 1. Authorization Code: useful when the client is acting on behalf of a (human) end user. 61 | - For instance, an agent calls an MCP tool implemented by a SaaS system. 62 | 2. Client Credentials: the client is another application (not a human) 63 | - For instance, an agent calls a secure MCP tool to check inventory at a specific 64 | store. No need to impersonate the end user. 65 | 66 | ### Example: authorization code grant 67 | 68 | This demonstrates the OAuth 2.1 flow for the authorization code grant type, used for user 69 | auth. 70 | 71 | **NOTE**: The following example assumes the MCP server is also functioning as the 72 | authorization server. However, the authorization server may be deployed as its own 73 | distinct service. 74 | 75 | A human user completes the OAuth flow through a web browser, obtaining an access token 76 | that identifies them personally and allows the client to act on their behalf. 77 | 78 | When authorization is required and not yet proven by the client, servers **MUST** respond 79 | with _HTTP 401 Unauthorized_. 80 | 81 | Clients initiate the 82 | [OAuth 2.1 IETF DRAFT](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#name-authorization-code-grant) 83 | authorization flow after receiving the _HTTP 401 Unauthorized_. 84 | 85 | The following demonstrates the basic OAuth 2.1 for public clients using PKCE. 86 | 87 | ```mermaid 88 | sequenceDiagram 89 | participant B as User-Agent (Browser) 90 | participant C as Client 91 | participant M as MCP Server 92 | 93 | C->>M: MCP Request 94 | M->>C: HTTP 401 Unauthorized 95 | Note over C: Generate code_verifier and code_challenge 96 | C->>B: Open browser with authorization URL + code_challenge 97 | B->>M: GET /authorize 98 | Note over M: User logs in and authorizes 99 | M->>B: Redirect to callback URL with auth code 100 | B->>C: Callback with authorization code 101 | C->>M: Token Request with code + code_verifier 102 | M->>C: Access Token (+ Refresh Token) 103 | C->>M: MCP Request with Access Token 104 | Note over C,M: Begin standard MCP message exchange 105 | ``` 106 | 107 | ### Server Metadata Discovery 108 | 109 | For server capability discovery: 110 | 111 | - MCP clients _MUST_ follow the OAuth 2.0 Authorization Server Metadata protocol defined 112 | in [RFC8414](https://datatracker.ietf.org/doc/html/rfc8414). 113 | - MCP server _SHOULD_ follow the OAuth 2.0 Authorization Server Metadata protocol. 114 | - MCP servers that do not support the OAuth 2.0 Authorization Server Metadata protocol, 115 | _MUST_ support fallback URLs. 116 | 117 | The discovery flow is illustrated below: 118 | 119 | ```mermaid 120 | sequenceDiagram 121 | participant C as Client 122 | participant S as Server 123 | 124 | C->>S: GET /.well-known/oauth-authorization-server 125 | alt Discovery Success 126 | S->>C: 200 OK + Metadata Document 127 | Note over C: Use endpoints from metadata 128 | else Discovery Failed 129 | S->>C: 404 Not Found 130 | Note over C: Fall back to default endpoints 131 | end 132 | Note over C: Continue with authorization flow 133 | ``` 134 | 135 | #### Server Metadata Discovery Headers 136 | 137 | MCP clients _SHOULD_ include the header `MCP-Protocol-Version: ` during 138 | Server Metadata Discovery to allow the MCP server to respond based on the MCP protocol 139 | version. 140 | 141 | For example: `MCP-Protocol-Version: 2024-11-05` 142 | 143 | #### Authorization Base URL 144 | 145 | The authorization base URL **MUST** be determined from the MCP server URL by discarding 146 | any existing `path` component. For example: 147 | 148 | If the MCP server URL is `https://api.example.com/v1/mcp`, then: 149 | 150 | - The authorization base URL is `https://api.example.com` 151 | - The metadata endpoint **MUST** be at 152 | `https://api.example.com/.well-known/oauth-authorization-server` 153 | 154 | This ensures authorization endpoints are consistently located at the root level of the 155 | domain hosting the MCP server, regardless of any path components in the MCP server URL. 156 | 157 | #### Fallbacks for Servers without Metadata Discovery 158 | 159 | For servers that do not implement OAuth 2.0 Authorization Server Metadata, clients 160 | **MUST** use the following default endpoint paths relative to the [authorization base 161 | URL](#authorization-base-url): 162 | 163 | | Endpoint | Default Path | Description | 164 | | ---------------------- | ------------ | ------------------------------------ | 165 | | Authorization Endpoint | /authorize | Used for authorization requests | 166 | | Token Endpoint | /token | Used for token exchange & refresh | 167 | | Registration Endpoint | /register | Used for dynamic client registration | 168 | 169 | For example, with an MCP server hosted at `https://api.example.com/v1/mcp`, the default 170 | endpoints would be: 171 | 172 | - `https://api.example.com/authorize` 173 | - `https://api.example.com/token` 174 | - `https://api.example.com/register` 175 | 176 | Clients **MUST** first attempt to discover endpoints via the metadata document before 177 | falling back to default paths. When using default paths, all other protocol requirements 178 | remain unchanged. 179 | 180 | ### Dynamic Client Registration 181 | 182 | MCP clients and servers **SHOULD** support the 183 | [OAuth 2.0 Dynamic Client Registration Protocol](https://datatracker.ietf.org/doc/html/rfc7591) 184 | to allow MCP clients to obtain OAuth client IDs without user interaction. This provides a 185 | standardized way for clients to automatically register with new servers, which is crucial 186 | for MCP because: 187 | 188 | - Clients cannot know all possible servers in advance 189 | - Manual registration would create friction for users 190 | - It enables seamless connection to new servers 191 | - Servers can implement their own registration policies 192 | 193 | Any MCP servers that _do not_ support Dynamic Client Registration need to provide 194 | alternative ways to obtain a client ID (and, if applicable, client secret). For one of 195 | these servers, MCP clients will have to either: 196 | 197 | 1. Hardcode a client ID (and, if applicable, client secret) specifically for that MCP 198 | server, or 199 | 2. Present a UI to users that allows them to enter these details, after registering an 200 | OAuth client themselves (e.g., through a configuration interface hosted by the 201 | server). 202 | 203 | ### Authorization Flow Steps 204 | 205 | The complete Authorization flow proceeds as follows: 206 | 207 | ```mermaid 208 | sequenceDiagram 209 | participant B as User-Agent (Browser) 210 | participant C as Client 211 | participant M as MCP Server 212 | 213 | C->>M: GET /.well-known/oauth-authorization-server 214 | alt Server Supports Discovery 215 | M->>C: Authorization Server Metadata 216 | else No Discovery 217 | M->>C: 404 (Use default endpoints) 218 | end 219 | 220 | alt Dynamic Client Registration 221 | C->>M: POST /register 222 | M->>C: Client Credentials 223 | end 224 | 225 | Note over C: Generate PKCE Parameters 226 | C->>B: Open browser with authorization URL + code_challenge 227 | B->>M: Authorization Request 228 | Note over M: User /authorizes 229 | M->>B: Redirect to callback with authorization code 230 | B->>C: Authorization code callback 231 | C->>M: Token Request + code_verifier 232 | M->>C: Access Token (+ Refresh Token) 233 | C->>M: API Requests with Access Token 234 | ``` 235 | 236 | #### Decision Flow Overview 237 | 238 | ```mermaid 239 | flowchart TD 240 | A[Start Auth Flow] --> B{Check Metadata Discovery} 241 | B -->|Available| C[Use Metadata Endpoints] 242 | B -->|Not Available| D[Use Default Endpoints] 243 | 244 | C --> G{Check Registration Endpoint} 245 | D --> G 246 | 247 | G -->|Available| H[Perform Dynamic Registration] 248 | G -->|Not Available| I[Alternative Registration Required] 249 | 250 | H --> J[Start OAuth Flow] 251 | I --> J 252 | 253 | J --> K[Generate PKCE Parameters] 254 | K --> L[Request Authorization] 255 | L --> M[User Authorization] 256 | M --> N[Exchange Code for Tokens] 257 | N --> O[Use Access Token] 258 | ``` 259 | 260 | ### Access Token Usage 261 | 262 | #### Token Requirements 263 | 264 | Access token handling **MUST** conform to 265 | [OAuth 2.1 Section 5](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5) 266 | requirements for resource requests. Specifically: 267 | 268 | 1. MCP client **MUST** use the Authorization request header field 269 | [Section 5.1.1](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5.1.1): 270 | 271 | ``` 272 | Authorization: Bearer 273 | ``` 274 | 275 | Note that authorization **MUST** be included in every HTTP request from client to server, 276 | even if they are part of the same logical session. 277 | 278 | 2. Access tokens **MUST NOT** be included in the URI query string 279 | 280 | Example request: 281 | 282 | ```http 283 | GET /v1/contexts HTTP/1.1 284 | Host: mcp.example.com 285 | Authorization: Bearer eyJhbGciOiJIUzI1NiIs... 286 | ``` 287 | 288 | #### Token Handling 289 | 290 | Resource servers **MUST** validate access tokens as described in 291 | [Section 5.2](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5.2). 292 | If validation fails, servers **MUST** respond according to 293 | [Section 5.3](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5.3) 294 | error handling requirements. Invalid or expired tokens **MUST** receive a HTTP 401 295 | response. 296 | 297 | ### Security Considerations 298 | 299 | The following security requirements **MUST** be implemented: 300 | 301 | 1. Clients **MUST** securely store tokens following OAuth 2.0 best practices 302 | 2. Servers **SHOULD** enforce token expiration and rotation 303 | 3. All authorization endpoints **MUST** be served over HTTPS 304 | 4. Servers **MUST** validate redirect URIs to prevent open redirect vulnerabilities 305 | 5. Redirect URIs **MUST** be either localhost URLs or HTTPS URLs 306 | 307 | ### Error Handling 308 | 309 | Servers **MUST** return appropriate HTTP status codes for authorization errors: 310 | 311 | | Status Code | Description | Usage | 312 | | ----------- | ------------ | ------------------------------------------ | 313 | | 401 | Unauthorized | Authorization required or token invalid | 314 | | 403 | Forbidden | Invalid scopes or insufficient permissions | 315 | | 400 | Bad Request | Malformed authorization request | 316 | 317 | ### Implementation Requirements 318 | 319 | 1. Implementations **MUST** follow OAuth 2.1 security best practices 320 | 2. PKCE is **REQUIRED** for all clients 321 | 3. Token rotation **SHOULD** be implemented for enhanced security 322 | 4. Token lifetimes **SHOULD** be limited based on security requirements 323 | 324 | ### Third-Party Authorization Flow 325 | 326 | #### Overview 327 | 328 | MCP servers **MAY** support delegated authorization through third-party authorization 329 | servers. In this flow, the MCP server acts as both an OAuth client (to the third-party 330 | auth server) and an OAuth authorization server (to the MCP client). 331 | 332 | #### Flow Description 333 | 334 | The third-party authorization flow comprises these steps: 335 | 336 | 1. MCP client initiates standard OAuth flow with MCP server 337 | 2. MCP server redirects user to third-party authorization server 338 | 3. User authorizes with third-party server 339 | 4. Third-party server redirects back to MCP server with authorization code 340 | 5. MCP server exchanges code for third-party access token 341 | 6. MCP server generates its own access token bound to the third-party session 342 | 7. MCP server completes original OAuth flow with MCP client 343 | 344 | ```mermaid 345 | sequenceDiagram 346 | participant B as User-Agent (Browser) 347 | participant C as MCP Client 348 | participant M as MCP Server 349 | participant T as Third-Party Auth Server 350 | 351 | C->>M: Initial OAuth Request 352 | M->>B: Redirect to Third-Party /authorize 353 | B->>T: Authorization Request 354 | Note over T: User authorizes 355 | T->>B: Redirect to MCP Server callback 356 | B->>M: Authorization code 357 | M->>T: Exchange code for token 358 | T->>M: Third-party access token 359 | Note over M: Generate bound MCP token 360 | M->>B: Redirect to MCP Client callback 361 | B->>C: MCP authorization code 362 | C->>M: Exchange code for token 363 | M->>C: MCP access token 364 | ``` 365 | 366 | #### Session Binding Requirements 367 | 368 | MCP servers implementing third-party authorization **MUST**: 369 | 370 | 1. Maintain secure mapping between third-party tokens and issued MCP tokens 371 | 2. Validate third-party token status before honoring MCP tokens 372 | 3. Implement appropriate token lifecycle management 373 | 4. Handle third-party token expiration and renewal 374 | 375 | #### Security Considerations 376 | 377 | When implementing third-party authorization, servers **MUST**: 378 | 379 | 1. Validate all redirect URIs 380 | 2. Securely store third-party credentials 381 | 3. Implement appropriate session timeout handling 382 | 4. Consider security implications of token chaining 383 | 5. Implement proper error handling for third-party auth failures 384 | 385 | ## Best Practices 386 | 387 | #### Local clients as Public OAuth 2.1 Clients 388 | 389 | We strongly recommend that local clients implement OAuth 2.1 as a public client: 390 | 391 | 1. Utilizing code challenges (PKCE) for authorization requests to prevent interception 392 | attacks 393 | 2. Implementing secure token storage appropriate for the local system 394 | 3. Following token refresh best practices to maintain sessions 395 | 4. Properly handling token expiration and renewal 396 | 397 | #### Authorization Metadata Discovery 398 | 399 | We strongly recommend that all clients implement metadata discovery. This reduces the 400 | need for users to provide endpoints manually or clients to fallback to the defined 401 | defaults. 402 | 403 | #### Dynamic Client Registration 404 | 405 | Since clients do not know the set of MCP servers in advance, we strongly recommend the 406 | implementation of dynamic client registration. This allows applications to automatically 407 | register with the MCP server, and removes the need for users to obtain client ids 408 | manually. 409 | -------------------------------------------------------------------------------- /docs/specification/2025-03-26/basic/index.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Overview 3 | --- 4 | 5 | **Protocol Revision**: 2025-03-26 6 | 7 | The Model Context Protocol consists of several key components that work together: 8 | 9 | - **Base Protocol**: Core JSON-RPC message types 10 | - **Lifecycle Management**: Connection initialization, capability negotiation, and 11 | session control 12 | - **Server Features**: Resources, prompts, and tools exposed by servers 13 | - **Client Features**: Sampling and root directory lists provided by clients 14 | - **Utilities**: Cross-cutting concerns like logging and argument completion 15 | 16 | All implementations **MUST** support the base protocol and lifecycle management 17 | components. Other components **MAY** be implemented based on the specific needs of the 18 | application. 19 | 20 | These protocol layers establish clear separation of concerns while enabling rich 21 | interactions between clients and servers. The modular design allows implementations to 22 | support exactly the features they need. 23 | 24 | ## Messages 25 | 26 | All messages between MCP clients and servers **MUST** follow the 27 | [JSON-RPC 2.0](https://www.jsonrpc.org/specification) specification. The protocol defines 28 | these types of messages: 29 | 30 | ### Requests 31 | 32 | Requests are sent from the client to the server or vice versa, to initiate an operation. 33 | 34 | ```typescript 35 | { 36 | jsonrpc: "2.0"; 37 | id: string | number; 38 | method: string; 39 | params?: { 40 | [key: string]: unknown; 41 | }; 42 | } 43 | ``` 44 | 45 | - Requests **MUST** include a string or integer ID. 46 | - Unlike base JSON-RPC, the ID **MUST NOT** be `null`. 47 | - The request ID **MUST NOT** have been previously used by the requestor within the same 48 | session. 49 | 50 | ### Responses 51 | 52 | Responses are sent in reply to requests, containing the result or error of the operation. 53 | 54 | ```typescript 55 | { 56 | jsonrpc: "2.0"; 57 | id: string | number; 58 | result?: { 59 | [key: string]: unknown; 60 | } 61 | error?: { 62 | code: number; 63 | message: string; 64 | data?: unknown; 65 | } 66 | } 67 | ``` 68 | 69 | - Responses **MUST** include the same ID as the request they correspond to. 70 | - **Responses** are further sub-categorized as either **successful results** or 71 | **errors**. Either a `result` or an `error` **MUST** be set. A response **MUST NOT** 72 | set both. 73 | - Results **MAY** follow any JSON object structure, while errors **MUST** include an 74 | error code and message at minimum. 75 | - Error codes **MUST** be integers. 76 | 77 | ### Notifications 78 | 79 | Notifications are sent from the client to the server or vice versa, as a one-way message. 80 | The receiver **MUST NOT** send a response. 81 | 82 | ```typescript 83 | { 84 | jsonrpc: "2.0"; 85 | method: string; 86 | params?: { 87 | [key: string]: unknown; 88 | }; 89 | } 90 | ``` 91 | 92 | - Notifications **MUST NOT** include an ID. 93 | 94 | ### Batching 95 | 96 | JSON-RPC also defines a means to 97 | [batch multiple requests and notifications](https://www.jsonrpc.org/specification#batch), 98 | by sending them in an array. MCP implementations **MAY** support sending JSON-RPC 99 | batches, but **MUST** support receiving JSON-RPC batches. 100 | 101 | ## Auth 102 | 103 | MCP provides an [Authorization](/specification/2025-03-26/basic/authorization) framework for use with HTTP. 104 | Implementations using an HTTP-based transport **SHOULD** conform to this specification, 105 | whereas implementations using STDIO transport **SHOULD NOT** follow this specification, 106 | and instead retrieve credentials from the environment. 107 | 108 | Additionally, clients and servers **MAY** negotiate their own custom authentication and 109 | authorization strategies. 110 | 111 | For further discussions and contributions to the evolution of MCP’s auth mechanisms, join 112 | us in 113 | [GitHub Discussions](https://github.com/modelcontextprotocol/specification/discussions) 114 | to help shape the future of the protocol! 115 | 116 | ## Schema 117 | 118 | The full specification of the protocol is defined as a 119 | [TypeScript schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/2025-03-26/schema.ts). 120 | This is the source of truth for all protocol messages and structures. 121 | 122 | There is also a 123 | [JSON Schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/2025-03-26/schema.json), 124 | which is automatically generated from the TypeScript source of truth, for use with 125 | various automated tooling. 126 | -------------------------------------------------------------------------------- /docs/specification/2025-03-26/basic/lifecycle.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Lifecycle 3 | --- 4 | 5 | **Protocol Revision**: 2025-03-26 6 | 7 | The Model Context Protocol (MCP) defines a rigorous lifecycle for client-server 8 | connections that ensures proper capability negotiation and state management. 9 | 10 | 1. **Initialization**: Capability negotiation and protocol version agreement 11 | 2. **Operation**: Normal protocol communication 12 | 3. **Shutdown**: Graceful termination of the connection 13 | 14 | ```mermaid 15 | sequenceDiagram 16 | participant Client 17 | participant Server 18 | 19 | Note over Client,Server: Initialization Phase 20 | activate Client 21 | Client->>+Server: initialize request 22 | Server-->>Client: initialize response 23 | Client--)Server: initialized notification 24 | 25 | Note over Client,Server: Operation Phase 26 | rect rgb(200, 220, 250) 27 | note over Client,Server: Normal protocol operations 28 | end 29 | 30 | Note over Client,Server: Shutdown 31 | Client--)-Server: Disconnect 32 | deactivate Server 33 | Note over Client,Server: Connection closed 34 | ``` 35 | 36 | ## Lifecycle Phases 37 | 38 | ### Initialization 39 | 40 | The initialization phase **MUST** be the first interaction between client and server. 41 | During this phase, the client and server: 42 | 43 | - Establish protocol version compatibility 44 | - Exchange and negotiate capabilities 45 | - Share implementation details 46 | 47 | The client **MUST** initiate this phase by sending an `initialize` request containing: 48 | 49 | - Protocol version supported 50 | - Client capabilities 51 | - Client implementation information 52 | 53 | ```json 54 | { 55 | "jsonrpc": "2.0", 56 | "id": 1, 57 | "method": "initialize", 58 | "params": { 59 | "protocolVersion": "2025-03-26", 60 | "capabilities": { 61 | "roots": { 62 | "listChanged": true 63 | }, 64 | "sampling": {} 65 | }, 66 | "clientInfo": { 67 | "name": "ExampleClient", 68 | "version": "1.0.0" 69 | } 70 | } 71 | } 72 | ``` 73 | 74 | The initialize request **MUST NOT** be part of a JSON-RPC 75 | [batch](https://www.jsonrpc.org/specification#batch), as other requests and notifications 76 | are not possible until initialization has completed. This also permits backwards 77 | compatibility with prior protocol versions that do not explicitly support JSON-RPC 78 | batches. 79 | 80 | The server **MUST** respond with its own capabilities and information: 81 | 82 | ```json 83 | { 84 | "jsonrpc": "2.0", 85 | "id": 1, 86 | "result": { 87 | "protocolVersion": "2025-03-26", 88 | "capabilities": { 89 | "logging": {}, 90 | "prompts": { 91 | "listChanged": true 92 | }, 93 | "resources": { 94 | "subscribe": true, 95 | "listChanged": true 96 | }, 97 | "tools": { 98 | "listChanged": true 99 | } 100 | }, 101 | "serverInfo": { 102 | "name": "ExampleServer", 103 | "version": "1.0.0" 104 | }, 105 | "instructions": "Optional instructions for the client" 106 | } 107 | } 108 | ``` 109 | 110 | After successful initialization, the client **MUST** send an `initialized` notification 111 | to indicate it is ready to begin normal operations: 112 | 113 | ```json 114 | { 115 | "jsonrpc": "2.0", 116 | "method": "notifications/initialized" 117 | } 118 | ``` 119 | 120 | - The client **SHOULD NOT** send requests other than 121 | [pings](/specification/2025-03-26/basic/utilities/ping) before the server has responded to the 122 | `initialize` request. 123 | - The server **SHOULD NOT** send requests other than 124 | [pings](/specification/2025-03-26/basic/utilities/ping) and 125 | [logging](/specification/2025-03-26/server/utilities/logging) before receiving the `initialized` 126 | notification. 127 | 128 | #### Version Negotiation 129 | 130 | In the `initialize` request, the client **MUST** send a protocol version it supports. 131 | This **SHOULD** be the _latest_ version supported by the client. 132 | 133 | If the server supports the requested protocol version, it **MUST** respond with the same 134 | version. Otherwise, the server **MUST** respond with another protocol version it 135 | supports. This **SHOULD** be the _latest_ version supported by the server. 136 | 137 | If the client does not support the version in the server's response, it **SHOULD** 138 | disconnect. 139 | 140 | #### Capability Negotiation 141 | 142 | Client and server capabilities establish which optional protocol features will be 143 | available during the session. 144 | 145 | Key capabilities include: 146 | 147 | | Category | Capability | Description | 148 | | -------- | -------------- | ----------------------------------------------------------------------------------------- | 149 | | Client | `roots` | Ability to provide filesystem [roots](/specification/2025-03-26/client/roots) | 150 | | Client | `sampling` | Support for LLM [sampling](/specification/2025-03-26/client/sampling) requests | 151 | | Client | `experimental` | Describes support for non-standard experimental features | 152 | | Server | `prompts` | Offers [prompt templates](/specification/2025-03-26/server/prompts) | 153 | | Server | `resources` | Provides readable [resources](/specification/2025-03-26/server/resources) | 154 | | Server | `tools` | Exposes callable [tools](/specification/2025-03-26/server/tools) | 155 | | Server | `logging` | Emits structured [log messages](/specification/2025-03-26/server/utilities/logging) | 156 | | Server | `completions` | Supports argument [autocompletion](/specification/2025-03-26/server/utilities/completion) | 157 | | Server | `experimental` | Describes support for non-standard experimental features | 158 | 159 | Capability objects can describe sub-capabilities like: 160 | 161 | - `listChanged`: Support for list change notifications (for prompts, resources, and 162 | tools) 163 | - `subscribe`: Support for subscribing to individual items' changes (resources only) 164 | 165 | ### Operation 166 | 167 | During the operation phase, the client and server exchange messages according to the 168 | negotiated capabilities. 169 | 170 | Both parties **SHOULD**: 171 | 172 | - Respect the negotiated protocol version 173 | - Only use capabilities that were successfully negotiated 174 | 175 | ### Shutdown 176 | 177 | During the shutdown phase, one side (usually the client) cleanly terminates the protocol 178 | connection. No specific shutdown messages are defined—instead, the underlying transport 179 | mechanism should be used to signal connection termination: 180 | 181 | #### stdio 182 | 183 | For the stdio [transport](/specification/2025-03-26/basic/transports), the client **SHOULD** initiate 184 | shutdown by: 185 | 186 | 1. First, closing the input stream to the child process (the server) 187 | 2. Waiting for the server to exit, or sending `SIGTERM` if the server does not exit 188 | within a reasonable time 189 | 3. Sending `SIGKILL` if the server does not exit within a reasonable time after `SIGTERM` 190 | 191 | The server **MAY** initiate shutdown by closing its output stream to the client and 192 | exiting. 193 | 194 | #### HTTP 195 | 196 | For HTTP [transports](/specification/2025-03-26/basic/transports), shutdown is indicated by closing the 197 | associated HTTP connection(s). 198 | 199 | ## Timeouts 200 | 201 | Implementations **SHOULD** establish timeouts for all sent requests, to prevent hung 202 | connections and resource exhaustion. When the request has not received a success or error 203 | response within the timeout period, the sender **SHOULD** issue a [cancellation 204 | notification](/specification/2025-03-26/basic/utilities/cancellation) for that request and stop waiting for 205 | a response. 206 | 207 | SDKs and other middleware **SHOULD** allow these timeouts to be configured on a 208 | per-request basis. 209 | 210 | Implementations **MAY** choose to reset the timeout clock when receiving a [progress 211 | notification](/specification/2025-03-26/basic/utilities/progress) corresponding to the request, as this 212 | implies that work is actually happening. However, implementations **SHOULD** always 213 | enforce a maximum timeout, regardless of progress notifications, to limit the impact of a 214 | misbehaving client or server. 215 | 216 | ## Error Handling 217 | 218 | Implementations **SHOULD** be prepared to handle these error cases: 219 | 220 | - Protocol version mismatch 221 | - Failure to negotiate required capabilities 222 | - Request [timeouts](#timeouts) 223 | 224 | Example initialization error: 225 | 226 | ```json 227 | { 228 | "jsonrpc": "2.0", 229 | "id": 1, 230 | "error": { 231 | "code": -32602, 232 | "message": "Unsupported protocol version", 233 | "data": { 234 | "supported": ["2024-11-05"], 235 | "requested": "1.0.0" 236 | } 237 | } 238 | } 239 | ``` 240 | -------------------------------------------------------------------------------- /docs/specification/2025-03-26/basic/transports.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Transports 3 | --- 4 | 5 | **Protocol Revision**: 2025-03-26 6 | 7 | MCP uses JSON-RPC to encode messages. JSON-RPC messages **MUST** be UTF-8 encoded. 8 | 9 | The protocol currently defines two standard transport mechanisms for client-server 10 | communication: 11 | 12 | 1. [stdio](#stdio), communication over standard in and standard out 13 | 2. [Streamable HTTP](#streamable-http) 14 | 15 | Clients **SHOULD** support stdio whenever possible. 16 | 17 | It is also possible for clients and servers to implement 18 | [custom transports](#custom-transports) in a pluggable fashion. 19 | 20 | ## stdio 21 | 22 | In the **stdio** transport: 23 | 24 | - The client launches the MCP server as a subprocess. 25 | - The server reads JSON-RPC messages from its standard input (`stdin`) and sends messages 26 | to its standard output (`stdout`). 27 | - Messages may be JSON-RPC requests, notifications, responses—or a JSON-RPC 28 | [batch](https://www.jsonrpc.org/specification#batch) containing one or more requests 29 | and/or notifications. 30 | - Messages are delimited by newlines, and **MUST NOT** contain embedded newlines. 31 | - The server **MAY** write UTF-8 strings to its standard error (`stderr`) for logging 32 | purposes. Clients **MAY** capture, forward, or ignore this logging. 33 | - The server **MUST NOT** write anything to its `stdout` that is not a valid MCP message. 34 | - The client **MUST NOT** write anything to the server's `stdin` that is not a valid MCP 35 | message. 36 | 37 | ```mermaid 38 | sequenceDiagram 39 | participant Client 40 | participant Server Process 41 | 42 | Client->>+Server Process: Launch subprocess 43 | loop Message Exchange 44 | Client->>Server Process: Write to stdin 45 | Server Process->>Client: Write to stdout 46 | Server Process--)Client: Optional logs on stderr 47 | end 48 | Client->>Server Process: Close stdin, terminate subprocess 49 | deactivate Server Process 50 | ``` 51 | 52 | ## Streamable HTTP 53 | 54 | 55 | 56 | This replaces the [HTTP+SSE 57 | transport](/specification/2024-11-05/basic/transports#http-with-sse) from 58 | protocol version 2024-11-05. See the [backwards compatibility](#backwards-compatibility) 59 | guide below. 60 | 61 | 62 | 63 | In the **Streamable HTTP** transport, the server operates as an independent process that 64 | can handle multiple client connections. This transport uses HTTP POST and GET requests. 65 | Server can optionally make use of 66 | [Server-Sent Events](https://en.wikipedia.org/wiki/Server-sent_events) (SSE) to stream 67 | multiple server messages. This permits basic MCP servers, as well as more feature-rich 68 | servers supporting streaming and server-to-client notifications and requests. 69 | 70 | The server **MUST** provide a single HTTP endpoint path (hereafter referred to as the 71 | **MCP endpoint**) that supports both POST and GET methods. For example, this could be a 72 | URL like `https://example.com/mcp`. 73 | 74 | #### Security Warning 75 | 76 | When implementing Streamable HTTP transport: 77 | 78 | 1. Servers **MUST** validate the `Origin` header on all incoming connections to prevent DNS rebinding attacks 79 | 2. When running locally, servers **SHOULD** bind only to localhost (127.0.0.1) rather than all network interfaces (0.0.0.0) 80 | 3. Servers **SHOULD** implement proper authentication for all connections 81 | 82 | Without these protections, attackers could use DNS rebinding to interact with local MCP servers from remote websites. 83 | 84 | ### Sending Messages to the Server 85 | 86 | Every JSON-RPC message sent from the client **MUST** be a new HTTP POST request to the 87 | MCP endpoint. 88 | 89 | 1. The client **MUST** use HTTP POST to send JSON-RPC messages to the MCP endpoint. 90 | 2. The client **MUST** include an `Accept` header, listing both `application/json` and 91 | `text/event-stream` as supported content types. 92 | 3. The body of the POST request **MUST** be one of the following: 93 | - A single JSON-RPC _request_, _notification_, or _response_ 94 | - An array [batching](https://www.jsonrpc.org/specification#batch) one or more 95 | _requests and/or notifications_ 96 | - An array [batching](https://www.jsonrpc.org/specification#batch) one or more 97 | _responses_ 98 | 4. If the input consists solely of (any number of) JSON-RPC _responses_ or 99 | _notifications_: 100 | - If the server accepts the input, the server **MUST** return HTTP status code 202 101 | Accepted with no body. 102 | - If the server cannot accept the input, it **MUST** return an HTTP error status code 103 | (e.g., 400 Bad Request). The HTTP response body **MAY** comprise a JSON-RPC _error 104 | response_ that has no `id`. 105 | 5. If the input contains any number of JSON-RPC _requests_, the server **MUST** either 106 | return `Content-Type: text/event-stream`, to initiate an SSE stream, or 107 | `Content-Type: application/json`, to return one JSON object. The client **MUST** 108 | support both these cases. 109 | 6. If the server initiates an SSE stream: 110 | - The SSE stream **SHOULD** eventually include one JSON-RPC _response_ per each 111 | JSON-RPC _request_ sent in the POST body. These _responses_ **MAY** be 112 | [batched](https://www.jsonrpc.org/specification#batch). 113 | - The server **MAY** send JSON-RPC _requests_ and _notifications_ before sending a 114 | JSON-RPC _response_. These messages **SHOULD** relate to the originating client 115 | _request_. These _requests_ and _notifications_ **MAY** be 116 | [batched](https://www.jsonrpc.org/specification#batch). 117 | - The server **SHOULD NOT** close the SSE stream before sending a JSON-RPC _response_ 118 | per each received JSON-RPC _request_, unless the [session](#session-management) 119 | expires. 120 | - After all JSON-RPC _responses_ have been sent, the server **SHOULD** close the SSE 121 | stream. 122 | - Disconnection **MAY** occur at any time (e.g., due to network conditions). 123 | Therefore: 124 | - Disconnection **SHOULD NOT** be interpreted as the client cancelling its request. 125 | - To cancel, the client **SHOULD** explicitly send an MCP `CancelledNotification`. 126 | - To avoid message loss due to disconnection, the server **MAY** make the stream 127 | [resumable](#resumability-and-redelivery). 128 | 129 | ### Listening for Messages from the Server 130 | 131 | 1. The client **MAY** issue an HTTP GET to the MCP endpoint. This can be used to open an 132 | SSE stream, allowing the server to communicate to the client, without the client first 133 | sending data via HTTP POST. 134 | 2. The client **MUST** include an `Accept` header, listing `text/event-stream` as a 135 | supported content type. 136 | 3. The server **MUST** either return `Content-Type: text/event-stream` in response to 137 | this HTTP GET, or else return HTTP 405 Method Not Allowed, indicating that the server 138 | does not offer an SSE stream at this endpoint. 139 | 4. If the server initiates an SSE stream: 140 | - The server **MAY** send JSON-RPC _requests_ and _notifications_ on the stream. These 141 | _requests_ and _notifications_ **MAY** be 142 | [batched](https://www.jsonrpc.org/specification#batch). 143 | - These messages **SHOULD** be unrelated to any concurrently-running JSON-RPC 144 | _request_ from the client. 145 | - The server **MUST NOT** send a JSON-RPC _response_ on the stream **unless** 146 | [resuming](#resumability-and-redelivery) a stream associated with a previous client 147 | request. 148 | - The server **MAY** close the SSE stream at any time. 149 | - The client **MAY** close the SSE stream at any time. 150 | 151 | ### Multiple Connections 152 | 153 | 1. The client **MAY** remain connected to multiple SSE streams simultaneously. 154 | 2. The server **MUST** send each of its JSON-RPC messages on only one of the connected 155 | streams; that is, it **MUST NOT** broadcast the same message across multiple streams. 156 | - The risk of message loss **MAY** be mitigated by making the stream 157 | [resumable](#resumability-and-redelivery). 158 | 159 | ### Resumability and Redelivery 160 | 161 | To support resuming broken connections, and redelivering messages that might otherwise be 162 | lost: 163 | 164 | 1. Servers **MAY** attach an `id` field to their SSE events, as described in the 165 | [SSE standard](https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation). 166 | - If present, the ID **MUST** be globally unique across all streams within that 167 | [session](#session-management)—or all streams with that specific client, if session 168 | management is not in use. 169 | 2. If the client wishes to resume after a broken connection, it **SHOULD** issue an HTTP 170 | GET to the MCP endpoint, and include the 171 | [`Last-Event-ID`](https://html.spec.whatwg.org/multipage/server-sent-events.html#the-last-event-id-header) 172 | header to indicate the last event ID it received. 173 | - The server **MAY** use this header to replay messages that would have been sent 174 | after the last event ID, _on the stream that was disconnected_, and to resume the 175 | stream from that point. 176 | - The server **MUST NOT** replay messages that would have been delivered on a 177 | different stream. 178 | 179 | In other words, these event IDs should be assigned by servers on a _per-stream_ basis, to 180 | act as a cursor within that particular stream. 181 | 182 | ### Session Management 183 | 184 | An MCP "session" consists of logically related interactions between a client and a 185 | server, beginning with the [initialization phase](/specification/2025-03-26/basic/lifecycle). To support 186 | servers which want to establish stateful sessions: 187 | 188 | 1. A server using the Streamable HTTP transport **MAY** assign a session ID at 189 | initialization time, by including it in an `Mcp-Session-Id` header on the HTTP 190 | response containing the `InitializeResult`. 191 | - The session ID **SHOULD** be globally unique and cryptographically secure (e.g., a 192 | securely generated UUID, a JWT, or a cryptographic hash). 193 | - The session ID **MUST** only contain visible ASCII characters (ranging from 0x21 to 194 | 0x7E). 195 | 2. If an `Mcp-Session-Id` is returned by the server during initialization, clients using 196 | the Streamable HTTP transport **MUST** include it in the `Mcp-Session-Id` header on 197 | all of their subsequent HTTP requests. 198 | - Servers that require a session ID **SHOULD** respond to requests without an 199 | `Mcp-Session-Id` header (other than initialization) with HTTP 400 Bad Request. 200 | 3. The server **MAY** terminate the session at any time, after which it **MUST** respond 201 | to requests containing that session ID with HTTP 404 Not Found. 202 | 4. When a client receives HTTP 404 in response to a request containing an 203 | `Mcp-Session-Id`, it **MUST** start a new session by sending a new `InitializeRequest` 204 | without a session ID attached. 205 | 5. Clients that no longer need a particular session (e.g., because the user is leaving 206 | the client application) **SHOULD** send an HTTP DELETE to the MCP endpoint with the 207 | `Mcp-Session-Id` header, to explicitly terminate the session. 208 | - The server **MAY** respond to this request with HTTP 405 Method Not Allowed, 209 | indicating that the server does not allow clients to terminate sessions. 210 | 211 | ### Sequence Diagram 212 | 213 | ```mermaid 214 | sequenceDiagram 215 | participant Client 216 | participant Server 217 | 218 | note over Client, Server: initialization 219 | 220 | Client->>+Server: POST InitializeRequest 221 | Server->>-Client: InitializeResponse
Mcp-Session-Id: 1868a90c... 222 | 223 | Client->>+Server: POST InitializedNotification
Mcp-Session-Id: 1868a90c... 224 | Server->>-Client: 202 Accepted 225 | 226 | note over Client, Server: client requests 227 | Client->>+Server: POST ... request ...
Mcp-Session-Id: 1868a90c... 228 | 229 | alt single HTTP response 230 | Server->>Client: ... response ... 231 | else server opens SSE stream 232 | loop while connection remains open 233 | Server-)Client: ... SSE messages from server ... 234 | end 235 | Server-)Client: SSE event: ... response ... 236 | end 237 | deactivate Server 238 | 239 | note over Client, Server: client notifications/responses 240 | Client->>+Server: POST ... notification/response ...
Mcp-Session-Id: 1868a90c... 241 | Server->>-Client: 202 Accepted 242 | 243 | note over Client, Server: server requests 244 | Client->>+Server: GET
Mcp-Session-Id: 1868a90c... 245 | loop while connection remains open 246 | Server-)Client: ... SSE messages from server ... 247 | end 248 | deactivate Server 249 | 250 | ``` 251 | 252 | ### Backwards Compatibility 253 | 254 | Clients and servers can maintain backwards compatibility with the deprecated [HTTP+SSE 255 | transport](/specification/2024-11-05/basic/transports#http-with-sse) (from 256 | protocol version 2024-11-05) as follows: 257 | 258 | **Servers** wanting to support older clients should: 259 | 260 | - Continue to host both the SSE and POST endpoints of the old transport, alongside the 261 | new "MCP endpoint" defined for the Streamable HTTP transport. 262 | - It is also possible to combine the old POST endpoint and the new MCP endpoint, but 263 | this may introduce unneeded complexity. 264 | 265 | **Clients** wanting to support older servers should: 266 | 267 | 1. Accept an MCP server URL from the user, which may point to either a server using the 268 | old transport or the new transport. 269 | 2. Attempt to POST an `InitializeRequest` to the server URL, with an `Accept` header as 270 | defined above: 271 | - If it succeeds, the client can assume this is a server supporting the new Streamable 272 | HTTP transport. 273 | - If it fails with an HTTP 4xx status code (e.g., 405 Method Not Allowed or 404 Not 274 | Found): 275 | - Issue a GET request to the server URL, expecting that this will open an SSE stream 276 | and return an `endpoint` event as the first event. 277 | - When the `endpoint` event arrives, the client can assume this is a server running 278 | the old HTTP+SSE transport, and should use that transport for all subsequent 279 | communication. 280 | 281 | ## Custom Transports 282 | 283 | Clients and servers **MAY** implement additional custom transport mechanisms to suit 284 | their specific needs. The protocol is transport-agnostic and can be implemented over any 285 | communication channel that supports bidirectional message exchange. 286 | 287 | Implementers who choose to support custom transports **MUST** ensure they preserve the 288 | JSON-RPC message format and lifecycle requirements defined by MCP. Custom transports 289 | **SHOULD** document their specific connection establishment and message exchange patterns 290 | to aid interoperability. 291 | -------------------------------------------------------------------------------- /docs/specification/2025-03-26/basic/utilities/cancellation.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Cancellation 3 | --- 4 | 5 | **Protocol Revision**: 2025-03-26 6 | 7 | The Model Context Protocol (MCP) supports optional cancellation of in-progress requests 8 | through notification messages. Either side can send a cancellation notification to 9 | indicate that a previously-issued request should be terminated. 10 | 11 | ## Cancellation Flow 12 | 13 | When a party wants to cancel an in-progress request, it sends a `notifications/cancelled` 14 | notification containing: 15 | 16 | - The ID of the request to cancel 17 | - An optional reason string that can be logged or displayed 18 | 19 | ```json 20 | { 21 | "jsonrpc": "2.0", 22 | "method": "notifications/cancelled", 23 | "params": { 24 | "requestId": "123", 25 | "reason": "User requested cancellation" 26 | } 27 | } 28 | ``` 29 | 30 | ## Behavior Requirements 31 | 32 | 1. Cancellation notifications **MUST** only reference requests that: 33 | - Were previously issued in the same direction 34 | - Are believed to still be in-progress 35 | 2. The `initialize` request **MUST NOT** be cancelled by clients 36 | 3. Receivers of cancellation notifications **SHOULD**: 37 | - Stop processing the cancelled request 38 | - Free associated resources 39 | - Not send a response for the cancelled request 40 | 4. Receivers **MAY** ignore cancellation notifications if: 41 | - The referenced request is unknown 42 | - Processing has already completed 43 | - The request cannot be cancelled 44 | 5. The sender of the cancellation notification **SHOULD** ignore any response to the 45 | request that arrives afterward 46 | 47 | ## Timing Considerations 48 | 49 | Due to network latency, cancellation notifications may arrive after request processing 50 | has completed, and potentially after a response has already been sent. 51 | 52 | Both parties **MUST** handle these race conditions gracefully: 53 | 54 | ```mermaid 55 | sequenceDiagram 56 | participant Client 57 | participant Server 58 | 59 | Client->>Server: Request (ID: 123) 60 | Note over Server: Processing starts 61 | Client--)Server: notifications/cancelled (ID: 123) 62 | alt 63 | Note over Server: Processing may have
completed before
cancellation arrives 64 | else If not completed 65 | Note over Server: Stop processing 66 | end 67 | ``` 68 | 69 | ## Implementation Notes 70 | 71 | - Both parties **SHOULD** log cancellation reasons for debugging 72 | - Application UIs **SHOULD** indicate when cancellation is requested 73 | 74 | ## Error Handling 75 | 76 | Invalid cancellation notifications **SHOULD** be ignored: 77 | 78 | - Unknown request IDs 79 | - Already completed requests 80 | - Malformed notifications 81 | 82 | This maintains the "fire and forget" nature of notifications while allowing for race 83 | conditions in asynchronous communication. 84 | -------------------------------------------------------------------------------- /docs/specification/2025-03-26/basic/utilities/ping.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Ping 3 | --- 4 | 5 | **Protocol Revision**: 2025-03-26 6 | 7 | The Model Context Protocol includes an optional ping mechanism that allows either party 8 | to verify that their counterpart is still responsive and the connection is alive. 9 | 10 | ## Overview 11 | 12 | The ping functionality is implemented through a simple request/response pattern. Either 13 | the client or server can initiate a ping by sending a `ping` request. 14 | 15 | ## Message Format 16 | 17 | A ping request is a standard JSON-RPC request with no parameters: 18 | 19 | ```json 20 | { 21 | "jsonrpc": "2.0", 22 | "id": "123", 23 | "method": "ping" 24 | } 25 | ``` 26 | 27 | ## Behavior Requirements 28 | 29 | 1. The receiver **MUST** respond promptly with an empty response: 30 | 31 | ```json 32 | { 33 | "jsonrpc": "2.0", 34 | "id": "123", 35 | "result": {} 36 | } 37 | ``` 38 | 39 | 2. If no response is received within a reasonable timeout period, the sender **MAY**: 40 | - Consider the connection stale 41 | - Terminate the connection 42 | - Attempt reconnection procedures 43 | 44 | ## Usage Patterns 45 | 46 | ```mermaid 47 | sequenceDiagram 48 | participant Sender 49 | participant Receiver 50 | 51 | Sender->>Receiver: ping request 52 | Receiver->>Sender: empty response 53 | ``` 54 | 55 | ## Implementation Considerations 56 | 57 | - Implementations **SHOULD** periodically issue pings to detect connection health 58 | - The frequency of pings **SHOULD** be configurable 59 | - Timeouts **SHOULD** be appropriate for the network environment 60 | - Excessive pinging **SHOULD** be avoided to reduce network overhead 61 | 62 | ## Error Handling 63 | 64 | - Timeouts **SHOULD** be treated as connection failures 65 | - Multiple failed pings **MAY** trigger connection reset 66 | - Implementations **SHOULD** log ping failures for diagnostics 67 | -------------------------------------------------------------------------------- /docs/specification/2025-03-26/basic/utilities/progress.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Progress 3 | --- 4 | 5 | **Protocol Revision**: 2025-03-26 6 | 7 | The Model Context Protocol (MCP) supports optional progress tracking for long-running 8 | operations through notification messages. Either side can send progress notifications to 9 | provide updates about operation status. 10 | 11 | ## Progress Flow 12 | 13 | When a party wants to _receive_ progress updates for a request, it includes a 14 | `progressToken` in the request metadata. 15 | 16 | - Progress tokens **MUST** be a string or integer value 17 | - Progress tokens can be chosen by the sender using any means, but **MUST** be unique 18 | across all active requests. 19 | 20 | ```json 21 | { 22 | "jsonrpc": "2.0", 23 | "id": 1, 24 | "method": "some_method", 25 | "params": { 26 | "_meta": { 27 | "progressToken": "abc123" 28 | } 29 | } 30 | } 31 | ``` 32 | 33 | The receiver **MAY** then send progress notifications containing: 34 | 35 | - The original progress token 36 | - The current progress value so far 37 | - An optional "total" value 38 | - An optional "message" value 39 | 40 | ```json 41 | { 42 | "jsonrpc": "2.0", 43 | "method": "notifications/progress", 44 | "params": { 45 | "progressToken": "abc123", 46 | "progress": 50, 47 | "total": 100, 48 | "message": "Reticulating splines..." 49 | } 50 | } 51 | ``` 52 | 53 | - The `progress` value **MUST** increase with each notification, even if the total is 54 | unknown. 55 | - The `progress` and the `total` values **MAY** be floating point. 56 | - The `message` field **SHOULD** provide relevant human readable progress information. 57 | 58 | ## Behavior Requirements 59 | 60 | 1. Progress notifications **MUST** only reference tokens that: 61 | 62 | - Were provided in an active request 63 | - Are associated with an in-progress operation 64 | 65 | 2. Receivers of progress requests **MAY**: 66 | - Choose not to send any progress notifications 67 | - Send notifications at whatever frequency they deem appropriate 68 | - Omit the total value if unknown 69 | 70 | ```mermaid 71 | sequenceDiagram 72 | participant Sender 73 | participant Receiver 74 | 75 | Note over Sender,Receiver: Request with progress token 76 | Sender->>Receiver: Method request with progressToken 77 | 78 | Note over Sender,Receiver: Progress updates 79 | loop Progress Updates 80 | Receiver-->>Sender: Progress notification (0.2/1.0) 81 | Receiver-->>Sender: Progress notification (0.6/1.0) 82 | Receiver-->>Sender: Progress notification (1.0/1.0) 83 | end 84 | 85 | Note over Sender,Receiver: Operation complete 86 | Receiver->>Sender: Method response 87 | ``` 88 | 89 | ## Implementation Notes 90 | 91 | - Senders and receivers **SHOULD** track active progress tokens 92 | - Both parties **SHOULD** implement rate limiting to prevent flooding 93 | - Progress notifications **MUST** stop after completion 94 | -------------------------------------------------------------------------------- /docs/specification/2025-03-26/changelog.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Key Changes 3 | --- 4 | 5 | This document lists changes made to the Model Context Protocol (MCP) specification since 6 | the previous revision, [2024-11-05](/specification/2024-11-05). 7 | 8 | ## Major changes 9 | 10 | 1. Added a comprehensive **[authorization framework](/specification/2025-03-26/basic/authorization)** 11 | based on OAuth 2.1 (PR 12 | [#133](https://github.com/modelcontextprotocol/specification/pull/133)) 13 | 1. Replaced the previous HTTP+SSE transport with a more flexible **[Streamable HTTP 14 | transport](/specification/2025-03-26/basic/transports#streamable-http)** (PR 15 | [#206](https://github.com/modelcontextprotocol/specification/pull/206)) 16 | 1. Added support for JSON-RPC **[batching](https://www.jsonrpc.org/specification#batch)** 17 | (PR [#228](https://github.com/modelcontextprotocol/specification/pull/228)) 18 | 1. Added comprehensive **tool annotations** for better describing tool behavior, like 19 | whether it is read-only or destructive (PR 20 | [#185](https://github.com/modelcontextprotocol/specification/pull/185)) 21 | 22 | ## Other schema changes 23 | 24 | - Added `message` field to `ProgressNotification` to provide descriptive status updates 25 | - Added support for audio data, joining the existing text and image content types 26 | - Added `completions` capability to explicitly indicate support for argument 27 | autocompletion suggestions 28 | 29 | See 30 | [the updated schema](http://github.com/modelcontextprotocol/specification/tree/main/schema/2025-03-26/schema.ts) 31 | for more details. 32 | 33 | ## Full changelog 34 | 35 | For a complete list of all changes that have been made since the last protocol revision, 36 | [see GitHub](https://github.com/modelcontextprotocol/specification/compare/2024-11-05...2025-03-26). 37 | -------------------------------------------------------------------------------- /docs/specification/2025-03-26/client/roots.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Roots 3 | --- 4 | 5 | **Protocol Revision**: 2025-03-26 6 | 7 | The Model Context Protocol (MCP) provides a standardized way for clients to expose 8 | filesystem "roots" to servers. Roots define the boundaries of where servers can operate 9 | within the filesystem, allowing them to understand which directories and files they have 10 | access to. Servers can request the list of roots from supporting clients and receive 11 | notifications when that list changes. 12 | 13 | ## User Interaction Model 14 | 15 | Roots in MCP are typically exposed through workspace or project configuration interfaces. 16 | 17 | For example, implementations could offer a workspace/project picker that allows users to 18 | select directories and files the server should have access to. This can be combined with 19 | automatic workspace detection from version control systems or project files. 20 | 21 | However, implementations are free to expose roots through any interface pattern that 22 | suits their needs—the protocol itself does not mandate any specific user 23 | interaction model. 24 | 25 | ## Capabilities 26 | 27 | Clients that support roots **MUST** declare the `roots` capability during 28 | [initialization](/specification/2025-03-26/basic/lifecycle#initialization): 29 | 30 | ```json 31 | { 32 | "capabilities": { 33 | "roots": { 34 | "listChanged": true 35 | } 36 | } 37 | } 38 | ``` 39 | 40 | `listChanged` indicates whether the client will emit notifications when the list of roots 41 | changes. 42 | 43 | ## Protocol Messages 44 | 45 | ### Listing Roots 46 | 47 | To retrieve roots, servers send a `roots/list` request: 48 | 49 | **Request:** 50 | 51 | ```json 52 | { 53 | "jsonrpc": "2.0", 54 | "id": 1, 55 | "method": "roots/list" 56 | } 57 | ``` 58 | 59 | **Response:** 60 | 61 | ```json 62 | { 63 | "jsonrpc": "2.0", 64 | "id": 1, 65 | "result": { 66 | "roots": [ 67 | { 68 | "uri": "file:///home/user/projects/myproject", 69 | "name": "My Project" 70 | } 71 | ] 72 | } 73 | } 74 | ``` 75 | 76 | ### Root List Changes 77 | 78 | When roots change, clients that support `listChanged` **MUST** send a notification: 79 | 80 | ```json 81 | { 82 | "jsonrpc": "2.0", 83 | "method": "notifications/roots/list_changed" 84 | } 85 | ``` 86 | 87 | ## Message Flow 88 | 89 | ```mermaid 90 | sequenceDiagram 91 | participant Server 92 | participant Client 93 | 94 | Note over Server,Client: Discovery 95 | Server->>Client: roots/list 96 | Client-->>Server: Available roots 97 | 98 | Note over Server,Client: Changes 99 | Client--)Server: notifications/roots/list_changed 100 | Server->>Client: roots/list 101 | Client-->>Server: Updated roots 102 | ``` 103 | 104 | ## Data Types 105 | 106 | ### Root 107 | 108 | A root definition includes: 109 | 110 | - `uri`: Unique identifier for the root. This **MUST** be a `file://` URI in the current 111 | specification. 112 | - `name`: Optional human-readable name for display purposes. 113 | 114 | Example roots for different use cases: 115 | 116 | #### Project Directory 117 | 118 | ```json 119 | { 120 | "uri": "file:///home/user/projects/myproject", 121 | "name": "My Project" 122 | } 123 | ``` 124 | 125 | #### Multiple Repositories 126 | 127 | ```json 128 | [ 129 | { 130 | "uri": "file:///home/user/repos/frontend", 131 | "name": "Frontend Repository" 132 | }, 133 | { 134 | "uri": "file:///home/user/repos/backend", 135 | "name": "Backend Repository" 136 | } 137 | ] 138 | ``` 139 | 140 | ## Error Handling 141 | 142 | Clients **SHOULD** return standard JSON-RPC errors for common failure cases: 143 | 144 | - Client does not support roots: `-32601` (Method not found) 145 | - Internal errors: `-32603` 146 | 147 | Example error: 148 | 149 | ```json 150 | { 151 | "jsonrpc": "2.0", 152 | "id": 1, 153 | "error": { 154 | "code": -32601, 155 | "message": "Roots not supported", 156 | "data": { 157 | "reason": "Client does not have roots capability" 158 | } 159 | } 160 | } 161 | ``` 162 | 163 | ## Security Considerations 164 | 165 | 1. Clients **MUST**: 166 | 167 | - Only expose roots with appropriate permissions 168 | - Validate all root URIs to prevent path traversal 169 | - Implement proper access controls 170 | - Monitor root accessibility 171 | 172 | 2. Servers **SHOULD**: 173 | - Handle cases where roots become unavailable 174 | - Respect root boundaries during operations 175 | - Validate all paths against provided roots 176 | 177 | ## Implementation Guidelines 178 | 179 | 1. Clients **SHOULD**: 180 | 181 | - Prompt users for consent before exposing roots to servers 182 | - Provide clear user interfaces for root management 183 | - Validate root accessibility before exposing 184 | - Monitor for root changes 185 | 186 | 2. Servers **SHOULD**: 187 | - Check for roots capability before usage 188 | - Handle root list changes gracefully 189 | - Respect root boundaries in operations 190 | - Cache root information appropriately 191 | -------------------------------------------------------------------------------- /docs/specification/2025-03-26/client/sampling.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Sampling 3 | --- 4 | 5 | **Protocol Revision**: 2025-03-26 6 | 7 | The Model Context Protocol (MCP) provides a standardized way for servers to request LLM 8 | sampling ("completions" or "generations") from language models via clients. This flow 9 | allows clients to maintain control over model access, selection, and permissions while 10 | enabling servers to leverage AI capabilities—with no server API keys necessary. 11 | Servers can request text, audio, or image-based interactions and optionally include 12 | context from MCP servers in their prompts. 13 | 14 | ## User Interaction Model 15 | 16 | Sampling in MCP allows servers to implement agentic behaviors, by enabling LLM calls to 17 | occur _nested_ inside other MCP server features. 18 | 19 | Implementations are free to expose sampling through any interface pattern that suits 20 | their needs—the protocol itself does not mandate any specific user interaction 21 | model. 22 | 23 | 24 | 25 | For trust & safety and security, there **SHOULD** always 26 | be a human in the loop with the ability to deny sampling requests. 27 | 28 | Applications **SHOULD**: 29 | 30 | - Provide UI that makes it easy and intuitive to review sampling requests 31 | - Allow users to view and edit prompts before sending 32 | - Present generated responses for review before delivery 33 | 34 | 35 | 36 | ## Capabilities 37 | 38 | Clients that support sampling **MUST** declare the `sampling` capability during 39 | [initialization](/specification/2025-03-26/basic/lifecycle#initialization): 40 | 41 | ```json 42 | { 43 | "capabilities": { 44 | "sampling": {} 45 | } 46 | } 47 | ``` 48 | 49 | ## Protocol Messages 50 | 51 | ### Creating Messages 52 | 53 | To request a language model generation, servers send a `sampling/createMessage` request: 54 | 55 | **Request:** 56 | 57 | ```json 58 | { 59 | "jsonrpc": "2.0", 60 | "id": 1, 61 | "method": "sampling/createMessage", 62 | "params": { 63 | "messages": [ 64 | { 65 | "role": "user", 66 | "content": { 67 | "type": "text", 68 | "text": "What is the capital of France?" 69 | } 70 | } 71 | ], 72 | "modelPreferences": { 73 | "hints": [ 74 | { 75 | "name": "claude-3-sonnet" 76 | } 77 | ], 78 | "intelligencePriority": 0.8, 79 | "speedPriority": 0.5 80 | }, 81 | "systemPrompt": "You are a helpful assistant.", 82 | "maxTokens": 100 83 | } 84 | } 85 | ``` 86 | 87 | **Response:** 88 | 89 | ```json 90 | { 91 | "jsonrpc": "2.0", 92 | "id": 1, 93 | "result": { 94 | "role": "assistant", 95 | "content": { 96 | "type": "text", 97 | "text": "The capital of France is Paris." 98 | }, 99 | "model": "claude-3-sonnet-20240307", 100 | "stopReason": "endTurn" 101 | } 102 | } 103 | ``` 104 | 105 | ## Message Flow 106 | 107 | ```mermaid 108 | sequenceDiagram 109 | participant Server 110 | participant Client 111 | participant User 112 | participant LLM 113 | 114 | Note over Server,Client: Server initiates sampling 115 | Server->>Client: sampling/createMessage 116 | 117 | Note over Client,User: Human-in-the-loop review 118 | Client->>User: Present request for approval 119 | User-->>Client: Review and approve/modify 120 | 121 | Note over Client,LLM: Model interaction 122 | Client->>LLM: Forward approved request 123 | LLM-->>Client: Return generation 124 | 125 | Note over Client,User: Response review 126 | Client->>User: Present response for approval 127 | User-->>Client: Review and approve/modify 128 | 129 | Note over Server,Client: Complete request 130 | Client-->>Server: Return approved response 131 | ``` 132 | 133 | ## Data Types 134 | 135 | ### Messages 136 | 137 | Sampling messages can contain: 138 | 139 | #### Text Content 140 | 141 | ```json 142 | { 143 | "type": "text", 144 | "text": "The message content" 145 | } 146 | ``` 147 | 148 | #### Image Content 149 | 150 | ```json 151 | { 152 | "type": "image", 153 | "data": "base64-encoded-image-data", 154 | "mimeType": "image/jpeg" 155 | } 156 | ``` 157 | 158 | #### Audio Content 159 | 160 | ```json 161 | { 162 | "type": "audio", 163 | "data": "base64-encoded-audio-data", 164 | "mimeType": "audio/wav" 165 | } 166 | ``` 167 | 168 | ### Model Preferences 169 | 170 | Model selection in MCP requires careful abstraction since servers and clients may use 171 | different AI providers with distinct model offerings. A server cannot simply request a 172 | specific model by name since the client may not have access to that exact model or may 173 | prefer to use a different provider's equivalent model. 174 | 175 | To solve this, MCP implements a preference system that combines abstract capability 176 | priorities with optional model hints: 177 | 178 | #### Capability Priorities 179 | 180 | Servers express their needs through three normalized priority values (0-1): 181 | 182 | - `costPriority`: How important is minimizing costs? Higher values prefer cheaper models. 183 | - `speedPriority`: How important is low latency? Higher values prefer faster models. 184 | - `intelligencePriority`: How important are advanced capabilities? Higher values prefer 185 | more capable models. 186 | 187 | #### Model Hints 188 | 189 | While priorities help select models based on characteristics, `hints` allow servers to 190 | suggest specific models or model families: 191 | 192 | - Hints are treated as substrings that can match model names flexibly 193 | - Multiple hints are evaluated in order of preference 194 | - Clients **MAY** map hints to equivalent models from different providers 195 | - Hints are advisory—clients make final model selection 196 | 197 | For example: 198 | 199 | ```json 200 | { 201 | "hints": [ 202 | { "name": "claude-3-sonnet" }, // Prefer Sonnet-class models 203 | { "name": "claude" } // Fall back to any Claude model 204 | ], 205 | "costPriority": 0.3, // Cost is less important 206 | "speedPriority": 0.8, // Speed is very important 207 | "intelligencePriority": 0.5 // Moderate capability needs 208 | } 209 | ``` 210 | 211 | The client processes these preferences to select an appropriate model from its available 212 | options. For instance, if the client doesn't have access to Claude models but has Gemini, 213 | it might map the sonnet hint to `gemini-1.5-pro` based on similar capabilities. 214 | 215 | ## Error Handling 216 | 217 | Clients **SHOULD** return errors for common failure cases: 218 | 219 | Example error: 220 | 221 | ```json 222 | { 223 | "jsonrpc": "2.0", 224 | "id": 1, 225 | "error": { 226 | "code": -1, 227 | "message": "User rejected sampling request" 228 | } 229 | } 230 | ``` 231 | 232 | ## Security Considerations 233 | 234 | 1. Clients **SHOULD** implement user approval controls 235 | 2. Both parties **SHOULD** validate message content 236 | 3. Clients **SHOULD** respect model preference hints 237 | 4. Clients **SHOULD** implement rate limiting 238 | 5. Both parties **MUST** handle sensitive data appropriately 239 | -------------------------------------------------------------------------------- /docs/specification/2025-03-26/index.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Specification 3 | --- 4 | 5 | [Model Context Protocol](https://modelcontextprotocol.io) (MCP) is an open protocol that 6 | enables seamless integration between LLM applications and external data sources and 7 | tools. Whether you're building an AI-powered IDE, enhancing a chat interface, or creating 8 | custom AI workflows, MCP provides a standardized way to connect LLMs with the context 9 | they need. 10 | 11 | This specification defines the authoritative protocol requirements, based on the 12 | TypeScript schema in 13 | [schema.ts](https://github.com/modelcontextprotocol/specification/blob/main/schema/2025-03-26/schema.ts). 14 | 15 | For implementation guides and examples, visit 16 | [modelcontextprotocol.io](https://modelcontextprotocol.io). 17 | 18 | The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD 19 | NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be 20 | interpreted as described in [BCP 14](https://datatracker.ietf.org/doc/html/bcp14) 21 | [[RFC2119](https://datatracker.ietf.org/doc/html/rfc2119)] 22 | [[RFC8174](https://datatracker.ietf.org/doc/html/rfc8174)] when, and only when, they 23 | appear in all capitals, as shown here. 24 | 25 | ## Overview 26 | 27 | MCP provides a standardized way for applications to: 28 | 29 | - Share contextual information with language models 30 | - Expose tools and capabilities to AI systems 31 | - Build composable integrations and workflows 32 | 33 | The protocol uses [JSON-RPC](https://www.jsonrpc.org/) 2.0 messages to establish 34 | communication between: 35 | 36 | - **Hosts**: LLM applications that initiate connections 37 | - **Clients**: Connectors within the host application 38 | - **Servers**: Services that provide context and capabilities 39 | 40 | MCP takes some inspiration from the 41 | [Language Server Protocol](https://microsoft.github.io/language-server-protocol/), which 42 | standardizes how to add support for programming languages across a whole ecosystem of 43 | development tools. In a similar way, MCP standardizes how to integrate additional context 44 | and tools into the ecosystem of AI applications. 45 | 46 | ## Key Details 47 | 48 | ### Base Protocol 49 | 50 | - [JSON-RPC](https://www.jsonrpc.org/) message format 51 | - Stateful connections 52 | - Server and client capability negotiation 53 | 54 | ### Features 55 | 56 | Servers offer any of the following features to clients: 57 | 58 | - **Resources**: Context and data, for the user or the AI model to use 59 | - **Prompts**: Templated messages and workflows for users 60 | - **Tools**: Functions for the AI model to execute 61 | 62 | Clients may offer the following feature to servers: 63 | 64 | - **Sampling**: Server-initiated agentic behaviors and recursive LLM interactions 65 | 66 | ### Additional Utilities 67 | 68 | - Configuration 69 | - Progress tracking 70 | - Cancellation 71 | - Error reporting 72 | - Logging 73 | 74 | ## Security and Trust & Safety 75 | 76 | The Model Context Protocol enables powerful capabilities through arbitrary data access 77 | and code execution paths. With this power comes important security and trust 78 | considerations that all implementors must carefully address. 79 | 80 | ### Key Principles 81 | 82 | 1. **User Consent and Control** 83 | 84 | - Users must explicitly consent to and understand all data access and operations 85 | - Users must retain control over what data is shared and what actions are taken 86 | - Implementors should provide clear UIs for reviewing and authorizing activities 87 | 88 | 2. **Data Privacy** 89 | 90 | - Hosts must obtain explicit user consent before exposing user data to servers 91 | - Hosts must not transmit resource data elsewhere without user consent 92 | - User data should be protected with appropriate access controls 93 | 94 | 3. **Tool Safety** 95 | 96 | - Tools represent arbitrary code execution and must be treated with appropriate 97 | caution. 98 | - In particular, descriptions of tool behavior such as annotations should be 99 | considered untrusted, unless obtained from a trusted server. 100 | - Hosts must obtain explicit user consent before invoking any tool 101 | - Users should understand what each tool does before authorizing its use 102 | 103 | 4. **LLM Sampling Controls** 104 | - Users must explicitly approve any LLM sampling requests 105 | - Users should control: 106 | - Whether sampling occurs at all 107 | - The actual prompt that will be sent 108 | - What results the server can see 109 | - The protocol intentionally limits server visibility into prompts 110 | 111 | ### Implementation Guidelines 112 | 113 | While MCP itself cannot enforce these security principles at the protocol level, 114 | implementors **SHOULD**: 115 | 116 | 1. Build robust consent and authorization flows into their applications 117 | 2. Provide clear documentation of security implications 118 | 3. Implement appropriate access controls and data protections 119 | 4. Follow security best practices in their integrations 120 | 5. Consider privacy implications in their feature designs 121 | 122 | ## Learn More 123 | 124 | Explore the detailed specification for each protocol component: 125 | 126 | 127 | 132 | 137 | 142 | 147 | 148 | 149 | -------------------------------------------------------------------------------- /docs/specification/2025-03-26/server/index.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Overview 3 | --- 4 | 5 | **Protocol Revision**: 2025-03-26 6 | 7 | Servers provide the fundamental building blocks for adding context to language models via 8 | MCP. These primitives enable rich interactions between clients, servers, and language 9 | models: 10 | 11 | - **Prompts**: Pre-defined templates or instructions that guide language model 12 | interactions 13 | - **Resources**: Structured data or content that provides additional context to the model 14 | - **Tools**: Executable functions that allow models to perform actions or retrieve 15 | information 16 | 17 | Each primitive can be summarized in the following control hierarchy: 18 | 19 | | Primitive | Control | Description | Example | 20 | | --------- | ---------------------- | -------------------------------------------------- | ------------------------------- | 21 | | Prompts | User-controlled | Interactive templates invoked by user choice | Slash commands, menu options | 22 | | Resources | Application-controlled | Contextual data attached and managed by the client | File contents, git history | 23 | | Tools | Model-controlled | Functions exposed to the LLM to take actions | API POST requests, file writing | 24 | 25 | Explore these key primitives in more detail below: 26 | 27 | 28 | 33 | 38 | 43 | 44 | -------------------------------------------------------------------------------- /docs/specification/2025-03-26/server/prompts.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Prompts 3 | --- 4 | 5 | **Protocol Revision**: 2025-03-26 6 | 7 | The Model Context Protocol (MCP) provides a standardized way for servers to expose prompt 8 | templates to clients. Prompts allow servers to provide structured messages and 9 | instructions for interacting with language models. Clients can discover available 10 | prompts, retrieve their contents, and provide arguments to customize them. 11 | 12 | ## User Interaction Model 13 | 14 | Prompts are designed to be **user-controlled**, meaning they are exposed from servers to 15 | clients with the intention of the user being able to explicitly select them for use. 16 | 17 | Typically, prompts would be triggered through user-initiated commands in the user 18 | interface, which allows users to naturally discover and invoke available prompts. 19 | 20 | For example, as slash commands: 21 | 22 | ![Example of prompt exposed as slash command](/specification/2025-03-26/server/slash-command.png) 23 | 24 | However, implementors are free to expose prompts through any interface pattern that suits 25 | their needs—the protocol itself does not mandate any specific user interaction 26 | model. 27 | 28 | ## Capabilities 29 | 30 | Servers that support prompts **MUST** declare the `prompts` capability during 31 | [initialization](/specification/2025-03-26/basic/lifecycle#initialization): 32 | 33 | ```json 34 | { 35 | "capabilities": { 36 | "prompts": { 37 | "listChanged": true 38 | } 39 | } 40 | } 41 | ``` 42 | 43 | `listChanged` indicates whether the server will emit notifications when the list of 44 | available prompts changes. 45 | 46 | ## Protocol Messages 47 | 48 | ### Listing Prompts 49 | 50 | To retrieve available prompts, clients send a `prompts/list` request. This operation 51 | supports [pagination](/specification/2025-03-26/server/utilities/pagination). 52 | 53 | **Request:** 54 | 55 | ```json 56 | { 57 | "jsonrpc": "2.0", 58 | "id": 1, 59 | "method": "prompts/list", 60 | "params": { 61 | "cursor": "optional-cursor-value" 62 | } 63 | } 64 | ``` 65 | 66 | **Response:** 67 | 68 | ```json 69 | { 70 | "jsonrpc": "2.0", 71 | "id": 1, 72 | "result": { 73 | "prompts": [ 74 | { 75 | "name": "code_review", 76 | "description": "Asks the LLM to analyze code quality and suggest improvements", 77 | "arguments": [ 78 | { 79 | "name": "code", 80 | "description": "The code to review", 81 | "required": true 82 | } 83 | ] 84 | } 85 | ], 86 | "nextCursor": "next-page-cursor" 87 | } 88 | } 89 | ``` 90 | 91 | ### Getting a Prompt 92 | 93 | To retrieve a specific prompt, clients send a `prompts/get` request. Arguments may be 94 | auto-completed through [the completion API](/specification/2025-03-26/server/utilities/completion). 95 | 96 | **Request:** 97 | 98 | ```json 99 | { 100 | "jsonrpc": "2.0", 101 | "id": 2, 102 | "method": "prompts/get", 103 | "params": { 104 | "name": "code_review", 105 | "arguments": { 106 | "code": "def hello():\n print('world')" 107 | } 108 | } 109 | } 110 | ``` 111 | 112 | **Response:** 113 | 114 | ```json 115 | { 116 | "jsonrpc": "2.0", 117 | "id": 2, 118 | "result": { 119 | "description": "Code review prompt", 120 | "messages": [ 121 | { 122 | "role": "user", 123 | "content": { 124 | "type": "text", 125 | "text": "Please review this Python code:\ndef hello():\n print('world')" 126 | } 127 | } 128 | ] 129 | } 130 | } 131 | ``` 132 | 133 | ### List Changed Notification 134 | 135 | When the list of available prompts changes, servers that declared the `listChanged` 136 | capability **SHOULD** send a notification: 137 | 138 | ```json 139 | { 140 | "jsonrpc": "2.0", 141 | "method": "notifications/prompts/list_changed" 142 | } 143 | ``` 144 | 145 | ## Message Flow 146 | 147 | ```mermaid 148 | sequenceDiagram 149 | participant Client 150 | participant Server 151 | 152 | Note over Client,Server: Discovery 153 | Client->>Server: prompts/list 154 | Server-->>Client: List of prompts 155 | 156 | Note over Client,Server: Usage 157 | Client->>Server: prompts/get 158 | Server-->>Client: Prompt content 159 | 160 | opt listChanged 161 | Note over Client,Server: Changes 162 | Server--)Client: prompts/list_changed 163 | Client->>Server: prompts/list 164 | Server-->>Client: Updated prompts 165 | end 166 | ``` 167 | 168 | ## Data Types 169 | 170 | ### Prompt 171 | 172 | A prompt definition includes: 173 | 174 | - `name`: Unique identifier for the prompt 175 | - `description`: Optional human-readable description 176 | - `arguments`: Optional list of arguments for customization 177 | 178 | ### PromptMessage 179 | 180 | Messages in a prompt can contain: 181 | 182 | - `role`: Either "user" or "assistant" to indicate the speaker 183 | - `content`: One of the following content types: 184 | 185 | #### Text Content 186 | 187 | Text content represents plain text messages: 188 | 189 | ```json 190 | { 191 | "type": "text", 192 | "text": "The text content of the message" 193 | } 194 | ``` 195 | 196 | This is the most common content type used for natural language interactions. 197 | 198 | #### Image Content 199 | 200 | Image content allows including visual information in messages: 201 | 202 | ```json 203 | { 204 | "type": "image", 205 | "data": "base64-encoded-image-data", 206 | "mimeType": "image/png" 207 | } 208 | ``` 209 | 210 | The image data **MUST** be base64-encoded and include a valid MIME type. This enables 211 | multi-modal interactions where visual context is important. 212 | 213 | #### Audio Content 214 | 215 | Audio content allows including audio information in messages: 216 | 217 | ```json 218 | { 219 | "type": "audio", 220 | "data": "base64-encoded-audio-data", 221 | "mimeType": "audio/wav" 222 | } 223 | ``` 224 | 225 | The audio data MUST be base64-encoded and include a valid MIME type. This enables 226 | multi-modal interactions where audio context is important. 227 | 228 | #### Embedded Resources 229 | 230 | Embedded resources allow referencing server-side resources directly in messages: 231 | 232 | ```json 233 | { 234 | "type": "resource", 235 | "resource": { 236 | "uri": "resource://example", 237 | "mimeType": "text/plain", 238 | "text": "Resource content" 239 | } 240 | } 241 | ``` 242 | 243 | Resources can contain either text or binary (blob) data and **MUST** include: 244 | 245 | - A valid resource URI 246 | - The appropriate MIME type 247 | - Either text content or base64-encoded blob data 248 | 249 | Embedded resources enable prompts to seamlessly incorporate server-managed content like 250 | documentation, code samples, or other reference materials directly into the conversation 251 | flow. 252 | 253 | ## Error Handling 254 | 255 | Servers **SHOULD** return standard JSON-RPC errors for common failure cases: 256 | 257 | - Invalid prompt name: `-32602` (Invalid params) 258 | - Missing required arguments: `-32602` (Invalid params) 259 | - Internal errors: `-32603` (Internal error) 260 | 261 | ## Implementation Considerations 262 | 263 | 1. Servers **SHOULD** validate prompt arguments before processing 264 | 2. Clients **SHOULD** handle pagination for large prompt lists 265 | 3. Both parties **SHOULD** respect capability negotiation 266 | 267 | ## Security 268 | 269 | Implementations **MUST** carefully validate all prompt inputs and outputs to prevent 270 | injection attacks or unauthorized access to resources. 271 | -------------------------------------------------------------------------------- /docs/specification/2025-03-26/server/resource-picker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/docs/specification/2025-03-26/server/resource-picker.png -------------------------------------------------------------------------------- /docs/specification/2025-03-26/server/resources.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Resources 3 | --- 4 | 5 | **Protocol Revision**: 2025-03-26 6 | 7 | The Model Context Protocol (MCP) provides a standardized way for servers to expose 8 | resources to clients. Resources allow servers to share data that provides context to 9 | language models, such as files, database schemas, or application-specific information. 10 | Each resource is uniquely identified by a 11 | [URI](https://datatracker.ietf.org/doc/html/rfc3986). 12 | 13 | ## User Interaction Model 14 | 15 | Resources in MCP are designed to be **application-driven**, with host applications 16 | determining how to incorporate context based on their needs. 17 | 18 | For example, applications could: 19 | 20 | - Expose resources through UI elements for explicit selection, in a tree or list view 21 | - Allow the user to search through and filter available resources 22 | - Implement automatic context inclusion, based on heuristics or the AI model's selection 23 | 24 | ![Example of resource context picker](/specification/2025-03-26/server/resource-picker.png) 25 | 26 | However, implementations are free to expose resources through any interface pattern that 27 | suits their needs—the protocol itself does not mandate any specific user 28 | interaction model. 29 | 30 | ## Capabilities 31 | 32 | Servers that support resources **MUST** declare the `resources` capability: 33 | 34 | ```json 35 | { 36 | "capabilities": { 37 | "resources": { 38 | "subscribe": true, 39 | "listChanged": true 40 | } 41 | } 42 | } 43 | ``` 44 | 45 | The capability supports two optional features: 46 | 47 | - `subscribe`: whether the client can subscribe to be notified of changes to individual 48 | resources. 49 | - `listChanged`: whether the server will emit notifications when the list of available 50 | resources changes. 51 | 52 | Both `subscribe` and `listChanged` are optional—servers can support neither, 53 | either, or both: 54 | 55 | ```json 56 | { 57 | "capabilities": { 58 | "resources": {} // Neither feature supported 59 | } 60 | } 61 | ``` 62 | 63 | ```json 64 | { 65 | "capabilities": { 66 | "resources": { 67 | "subscribe": true // Only subscriptions supported 68 | } 69 | } 70 | } 71 | ``` 72 | 73 | ```json 74 | { 75 | "capabilities": { 76 | "resources": { 77 | "listChanged": true // Only list change notifications supported 78 | } 79 | } 80 | } 81 | ``` 82 | 83 | ## Protocol Messages 84 | 85 | ### Listing Resources 86 | 87 | To discover available resources, clients send a `resources/list` request. This operation 88 | supports [pagination](/specification/2025-03-26/server/utilities/pagination). 89 | 90 | **Request:** 91 | 92 | ```json 93 | { 94 | "jsonrpc": "2.0", 95 | "id": 1, 96 | "method": "resources/list", 97 | "params": { 98 | "cursor": "optional-cursor-value" 99 | } 100 | } 101 | ``` 102 | 103 | **Response:** 104 | 105 | ```json 106 | { 107 | "jsonrpc": "2.0", 108 | "id": 1, 109 | "result": { 110 | "resources": [ 111 | { 112 | "uri": "file:///project/src/main.rs", 113 | "name": "main.rs", 114 | "description": "Primary application entry point", 115 | "mimeType": "text/x-rust" 116 | } 117 | ], 118 | "nextCursor": "next-page-cursor" 119 | } 120 | } 121 | ``` 122 | 123 | ### Reading Resources 124 | 125 | To retrieve resource contents, clients send a `resources/read` request: 126 | 127 | **Request:** 128 | 129 | ```json 130 | { 131 | "jsonrpc": "2.0", 132 | "id": 2, 133 | "method": "resources/read", 134 | "params": { 135 | "uri": "file:///project/src/main.rs" 136 | } 137 | } 138 | ``` 139 | 140 | **Response:** 141 | 142 | ```json 143 | { 144 | "jsonrpc": "2.0", 145 | "id": 2, 146 | "result": { 147 | "contents": [ 148 | { 149 | "uri": "file:///project/src/main.rs", 150 | "mimeType": "text/x-rust", 151 | "text": "fn main() {\n println!(\"Hello world!\");\n}" 152 | } 153 | ] 154 | } 155 | } 156 | ``` 157 | 158 | ### Resource Templates 159 | 160 | Resource templates allow servers to expose parameterized resources using 161 | [URI templates](https://datatracker.ietf.org/doc/html/rfc6570). Arguments may be 162 | auto-completed through [the completion API](/specification/2025-03-26/server/utilities/completion). 163 | 164 | **Request:** 165 | 166 | ```json 167 | { 168 | "jsonrpc": "2.0", 169 | "id": 3, 170 | "method": "resources/templates/list" 171 | } 172 | ``` 173 | 174 | **Response:** 175 | 176 | ```json 177 | { 178 | "jsonrpc": "2.0", 179 | "id": 3, 180 | "result": { 181 | "resourceTemplates": [ 182 | { 183 | "uriTemplate": "file:///{path}", 184 | "name": "Project Files", 185 | "description": "Access files in the project directory", 186 | "mimeType": "application/octet-stream" 187 | } 188 | ] 189 | } 190 | } 191 | ``` 192 | 193 | ### List Changed Notification 194 | 195 | When the list of available resources changes, servers that declared the `listChanged` 196 | capability **SHOULD** send a notification: 197 | 198 | ```json 199 | { 200 | "jsonrpc": "2.0", 201 | "method": "notifications/resources/list_changed" 202 | } 203 | ``` 204 | 205 | ### Subscriptions 206 | 207 | The protocol supports optional subscriptions to resource changes. Clients can subscribe 208 | to specific resources and receive notifications when they change: 209 | 210 | **Subscribe Request:** 211 | 212 | ```json 213 | { 214 | "jsonrpc": "2.0", 215 | "id": 4, 216 | "method": "resources/subscribe", 217 | "params": { 218 | "uri": "file:///project/src/main.rs" 219 | } 220 | } 221 | ``` 222 | 223 | **Update Notification:** 224 | 225 | ```json 226 | { 227 | "jsonrpc": "2.0", 228 | "method": "notifications/resources/updated", 229 | "params": { 230 | "uri": "file:///project/src/main.rs" 231 | } 232 | } 233 | ``` 234 | 235 | ## Message Flow 236 | 237 | ```mermaid 238 | sequenceDiagram 239 | participant Client 240 | participant Server 241 | 242 | Note over Client,Server: Resource Discovery 243 | Client->>Server: resources/list 244 | Server-->>Client: List of resources 245 | 246 | Note over Client,Server: Resource Access 247 | Client->>Server: resources/read 248 | Server-->>Client: Resource contents 249 | 250 | Note over Client,Server: Subscriptions 251 | Client->>Server: resources/subscribe 252 | Server-->>Client: Subscription confirmed 253 | 254 | Note over Client,Server: Updates 255 | Server--)Client: notifications/resources/updated 256 | Client->>Server: resources/read 257 | Server-->>Client: Updated contents 258 | ``` 259 | 260 | ## Data Types 261 | 262 | ### Resource 263 | 264 | A resource definition includes: 265 | 266 | - `uri`: Unique identifier for the resource 267 | - `name`: Human-readable name 268 | - `description`: Optional description 269 | - `mimeType`: Optional MIME type 270 | - `size`: Optional size in bytes 271 | 272 | ### Resource Contents 273 | 274 | Resources can contain either text or binary data: 275 | 276 | #### Text Content 277 | 278 | ```json 279 | { 280 | "uri": "file:///example.txt", 281 | "mimeType": "text/plain", 282 | "text": "Resource content" 283 | } 284 | ``` 285 | 286 | #### Binary Content 287 | 288 | ```json 289 | { 290 | "uri": "file:///example.png", 291 | "mimeType": "image/png", 292 | "blob": "base64-encoded-data" 293 | } 294 | ``` 295 | 296 | ## Common URI Schemes 297 | 298 | The protocol defines several standard URI schemes. This list not 299 | exhaustive—implementations are always free to use additional, custom URI schemes. 300 | 301 | ### https:// 302 | 303 | Used to represent a resource available on the web. 304 | 305 | Servers **SHOULD** use this scheme only when the client is able to fetch and load the 306 | resource directly from the web on its own—that is, it doesn’t need to read the resource 307 | via the MCP server. 308 | 309 | For other use cases, servers **SHOULD** prefer to use another URI scheme, or define a 310 | custom one, even if the server will itself be downloading resource contents over the 311 | internet. 312 | 313 | ### file:// 314 | 315 | Used to identify resources that behave like a filesystem. However, the resources do not 316 | need to map to an actual physical filesystem. 317 | 318 | MCP servers **MAY** identify file:// resources with an 319 | [XDG MIME type](https://specifications.freedesktop.org/shared-mime-info-spec/0.14/ar01s02.html#id-1.3.14), 320 | like `inode/directory`, to represent non-regular files (such as directories) that don’t 321 | otherwise have a standard MIME type. 322 | 323 | ### git:// 324 | 325 | Git version control integration. 326 | 327 | ## Error Handling 328 | 329 | Servers **SHOULD** return standard JSON-RPC errors for common failure cases: 330 | 331 | - Resource not found: `-32002` 332 | - Internal errors: `-32603` 333 | 334 | Example error: 335 | 336 | ```json 337 | { 338 | "jsonrpc": "2.0", 339 | "id": 5, 340 | "error": { 341 | "code": -32002, 342 | "message": "Resource not found", 343 | "data": { 344 | "uri": "file:///nonexistent.txt" 345 | } 346 | } 347 | } 348 | ``` 349 | 350 | ## Security Considerations 351 | 352 | 1. Servers **MUST** validate all resource URIs 353 | 2. Access controls **SHOULD** be implemented for sensitive resources 354 | 3. Binary data **MUST** be properly encoded 355 | 4. Resource permissions **SHOULD** be checked before operations 356 | -------------------------------------------------------------------------------- /docs/specification/2025-03-26/server/slash-command.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/docs/specification/2025-03-26/server/slash-command.png -------------------------------------------------------------------------------- /docs/specification/2025-03-26/server/tools.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Tools 3 | --- 4 | 5 | **Protocol Revision**: 2025-03-26 6 | 7 | The Model Context Protocol (MCP) allows servers to expose tools that can be invoked by 8 | language models. Tools enable models to interact with external systems, such as querying 9 | databases, calling APIs, or performing computations. Each tool is uniquely identified by 10 | a name and includes metadata describing its schema. 11 | 12 | ## User Interaction Model 13 | 14 | Tools in MCP are designed to be **model-controlled**, meaning that the language model can 15 | discover and invoke tools automatically based on its contextual understanding and the 16 | user's prompts. 17 | 18 | However, implementations are free to expose tools through any interface pattern that 19 | suits their needs—the protocol itself does not mandate any specific user 20 | interaction model. 21 | 22 | 23 | 24 | For trust & safety and security, there **SHOULD** always 25 | be a human in the loop with the ability to deny tool invocations. 26 | 27 | Applications **SHOULD**: 28 | 29 | - Provide UI that makes clear which tools are being exposed to the AI model 30 | - Insert clear visual indicators when tools are invoked 31 | - Present confirmation prompts to the user for operations, to ensure a human is in the 32 | loop 33 | 34 | 35 | 36 | ## Capabilities 37 | 38 | Servers that support tools **MUST** declare the `tools` capability: 39 | 40 | ```json 41 | { 42 | "capabilities": { 43 | "tools": { 44 | "listChanged": true 45 | } 46 | } 47 | } 48 | ``` 49 | 50 | `listChanged` indicates whether the server will emit notifications when the list of 51 | available tools changes. 52 | 53 | ## Protocol Messages 54 | 55 | ### Listing Tools 56 | 57 | To discover available tools, clients send a `tools/list` request. This operation supports 58 | [pagination](/specification/2025-03-26/server/utilities/pagination). 59 | 60 | **Request:** 61 | 62 | ```json 63 | { 64 | "jsonrpc": "2.0", 65 | "id": 1, 66 | "method": "tools/list", 67 | "params": { 68 | "cursor": "optional-cursor-value" 69 | } 70 | } 71 | ``` 72 | 73 | **Response:** 74 | 75 | ```json 76 | { 77 | "jsonrpc": "2.0", 78 | "id": 1, 79 | "result": { 80 | "tools": [ 81 | { 82 | "name": "get_weather", 83 | "description": "Get current weather information for a location", 84 | "inputSchema": { 85 | "type": "object", 86 | "properties": { 87 | "location": { 88 | "type": "string", 89 | "description": "City name or zip code" 90 | } 91 | }, 92 | "required": ["location"] 93 | } 94 | } 95 | ], 96 | "nextCursor": "next-page-cursor" 97 | } 98 | } 99 | ``` 100 | 101 | ### Calling Tools 102 | 103 | To invoke a tool, clients send a `tools/call` request: 104 | 105 | **Request:** 106 | 107 | ```json 108 | { 109 | "jsonrpc": "2.0", 110 | "id": 2, 111 | "method": "tools/call", 112 | "params": { 113 | "name": "get_weather", 114 | "arguments": { 115 | "location": "New York" 116 | } 117 | } 118 | } 119 | ``` 120 | 121 | **Response:** 122 | 123 | ```json 124 | { 125 | "jsonrpc": "2.0", 126 | "id": 2, 127 | "result": { 128 | "content": [ 129 | { 130 | "type": "text", 131 | "text": "Current weather in New York:\nTemperature: 72°F\nConditions: Partly cloudy" 132 | } 133 | ], 134 | "isError": false 135 | } 136 | } 137 | ``` 138 | 139 | ### List Changed Notification 140 | 141 | When the list of available tools changes, servers that declared the `listChanged` 142 | capability **SHOULD** send a notification: 143 | 144 | ```json 145 | { 146 | "jsonrpc": "2.0", 147 | "method": "notifications/tools/list_changed" 148 | } 149 | ``` 150 | 151 | ## Message Flow 152 | 153 | ```mermaid 154 | sequenceDiagram 155 | participant LLM 156 | participant Client 157 | participant Server 158 | 159 | Note over Client,Server: Discovery 160 | Client->>Server: tools/list 161 | Server-->>Client: List of tools 162 | 163 | Note over Client,LLM: Tool Selection 164 | LLM->>Client: Select tool to use 165 | 166 | Note over Client,Server: Invocation 167 | Client->>Server: tools/call 168 | Server-->>Client: Tool result 169 | Client->>LLM: Process result 170 | 171 | Note over Client,Server: Updates 172 | Server--)Client: tools/list_changed 173 | Client->>Server: tools/list 174 | Server-->>Client: Updated tools 175 | ``` 176 | 177 | ## Data Types 178 | 179 | ### Tool 180 | 181 | A tool definition includes: 182 | 183 | - `name`: Unique identifier for the tool 184 | - `description`: Human-readable description of functionality 185 | - `inputSchema`: JSON Schema defining expected parameters 186 | - `annotations`: optional properties describing tool behavior 187 | 188 | 189 | 190 | For trust & safety and security, clients **MUST** consider 191 | tool annotations to be untrusted unless they come from trusted servers. 192 | 193 | 194 | 195 | ### Tool Result 196 | 197 | Tool results can contain multiple content items of different types: 198 | 199 | #### Text Content 200 | 201 | ```json 202 | { 203 | "type": "text", 204 | "text": "Tool result text" 205 | } 206 | ``` 207 | 208 | #### Image Content 209 | 210 | ```json 211 | { 212 | "type": "image", 213 | "data": "base64-encoded-data", 214 | "mimeType": "image/png" 215 | } 216 | ``` 217 | 218 | #### Audio Content 219 | 220 | ```json 221 | { 222 | "type": "audio", 223 | "data": "base64-encoded-audio-data", 224 | "mimeType": "audio/wav" 225 | } 226 | ``` 227 | 228 | #### Embedded Resources 229 | 230 | [Resources](/specification/2025-03-26/server/resources) **MAY** be embedded, to provide additional context 231 | or data, behind a URI that can be subscribed to or fetched again by the client later: 232 | 233 | ```json 234 | { 235 | "type": "resource", 236 | "resource": { 237 | "uri": "resource://example", 238 | "mimeType": "text/plain", 239 | "text": "Resource content" 240 | } 241 | } 242 | ``` 243 | 244 | ## Error Handling 245 | 246 | Tools use two error reporting mechanisms: 247 | 248 | 1. **Protocol Errors**: Standard JSON-RPC errors for issues like: 249 | 250 | - Unknown tools 251 | - Invalid arguments 252 | - Server errors 253 | 254 | 2. **Tool Execution Errors**: Reported in tool results with `isError: true`: 255 | - API failures 256 | - Invalid input data 257 | - Business logic errors 258 | 259 | Example protocol error: 260 | 261 | ```json 262 | { 263 | "jsonrpc": "2.0", 264 | "id": 3, 265 | "error": { 266 | "code": -32602, 267 | "message": "Unknown tool: invalid_tool_name" 268 | } 269 | } 270 | ``` 271 | 272 | Example tool execution error: 273 | 274 | ```json 275 | { 276 | "jsonrpc": "2.0", 277 | "id": 4, 278 | "result": { 279 | "content": [ 280 | { 281 | "type": "text", 282 | "text": "Failed to fetch weather data: API rate limit exceeded" 283 | } 284 | ], 285 | "isError": true 286 | } 287 | } 288 | ``` 289 | 290 | ## Security Considerations 291 | 292 | 1. Servers **MUST**: 293 | 294 | - Validate all tool inputs 295 | - Implement proper access controls 296 | - Rate limit tool invocations 297 | - Sanitize tool outputs 298 | 299 | 2. Clients **SHOULD**: 300 | - Prompt for user confirmation on sensitive operations 301 | - Show tool inputs to the user before calling the server, to avoid malicious or 302 | accidental data exfiltration 303 | - Validate tool results before passing to LLM 304 | - Implement timeouts for tool calls 305 | - Log tool usage for audit purposes 306 | -------------------------------------------------------------------------------- /docs/specification/2025-03-26/server/utilities/completion.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Completion 3 | --- 4 | 5 | **Protocol Revision**: 2025-03-26 6 | 7 | The Model Context Protocol (MCP) provides a standardized way for servers to offer 8 | argument autocompletion suggestions for prompts and resource URIs. This enables rich, 9 | IDE-like experiences where users receive contextual suggestions while entering argument 10 | values. 11 | 12 | ## User Interaction Model 13 | 14 | Completion in MCP is designed to support interactive user experiences similar to IDE code 15 | completion. 16 | 17 | For example, applications may show completion suggestions in a dropdown or popup menu as 18 | users type, with the ability to filter and select from available options. 19 | 20 | However, implementations are free to expose completion through any interface pattern that 21 | suits their needs—the protocol itself does not mandate any specific user 22 | interaction model. 23 | 24 | ## Capabilities 25 | 26 | Servers that support completions **MUST** declare the `completions` capability: 27 | 28 | ```json 29 | { 30 | "capabilities": { 31 | "completions": {} 32 | } 33 | } 34 | ``` 35 | 36 | ## Protocol Messages 37 | 38 | ### Requesting Completions 39 | 40 | To get completion suggestions, clients send a `completion/complete` request specifying 41 | what is being completed through a reference type: 42 | 43 | **Request:** 44 | 45 | ```json 46 | { 47 | "jsonrpc": "2.0", 48 | "id": 1, 49 | "method": "completion/complete", 50 | "params": { 51 | "ref": { 52 | "type": "ref/prompt", 53 | "name": "code_review" 54 | }, 55 | "argument": { 56 | "name": "language", 57 | "value": "py" 58 | } 59 | } 60 | } 61 | ``` 62 | 63 | **Response:** 64 | 65 | ```json 66 | { 67 | "jsonrpc": "2.0", 68 | "id": 1, 69 | "result": { 70 | "completion": { 71 | "values": ["python", "pytorch", "pyside"], 72 | "total": 10, 73 | "hasMore": true 74 | } 75 | } 76 | } 77 | ``` 78 | 79 | ### Reference Types 80 | 81 | The protocol supports two types of completion references: 82 | 83 | | Type | Description | Example | 84 | | -------------- | --------------------------- | --------------------------------------------------- | 85 | | `ref/prompt` | References a prompt by name | `{"type": "ref/prompt", "name": "code_review"}` | 86 | | `ref/resource` | References a resource URI | `{"type": "ref/resource", "uri": "file:///{path}"}` | 87 | 88 | ### Completion Results 89 | 90 | Servers return an array of completion values ranked by relevance, with: 91 | 92 | - Maximum 100 items per response 93 | - Optional total number of available matches 94 | - Boolean indicating if additional results exist 95 | 96 | ## Message Flow 97 | 98 | ```mermaid 99 | sequenceDiagram 100 | participant Client 101 | participant Server 102 | 103 | Note over Client: User types argument 104 | Client->>Server: completion/complete 105 | Server-->>Client: Completion suggestions 106 | 107 | Note over Client: User continues typing 108 | Client->>Server: completion/complete 109 | Server-->>Client: Refined suggestions 110 | ``` 111 | 112 | ## Data Types 113 | 114 | ### CompleteRequest 115 | 116 | - `ref`: A `PromptReference` or `ResourceReference` 117 | - `argument`: Object containing: 118 | - `name`: Argument name 119 | - `value`: Current value 120 | 121 | ### CompleteResult 122 | 123 | - `completion`: Object containing: 124 | - `values`: Array of suggestions (max 100) 125 | - `total`: Optional total matches 126 | - `hasMore`: Additional results flag 127 | 128 | ## Error Handling 129 | 130 | Servers **SHOULD** return standard JSON-RPC errors for common failure cases: 131 | 132 | - Method not found: `-32601` (Capability not supported) 133 | - Invalid prompt name: `-32602` (Invalid params) 134 | - Missing required arguments: `-32602` (Invalid params) 135 | - Internal errors: `-32603` (Internal error) 136 | 137 | ## Implementation Considerations 138 | 139 | 1. Servers **SHOULD**: 140 | 141 | - Return suggestions sorted by relevance 142 | - Implement fuzzy matching where appropriate 143 | - Rate limit completion requests 144 | - Validate all inputs 145 | 146 | 2. Clients **SHOULD**: 147 | - Debounce rapid completion requests 148 | - Cache completion results where appropriate 149 | - Handle missing or partial results gracefully 150 | 151 | ## Security 152 | 153 | Implementations **MUST**: 154 | 155 | - Validate all completion inputs 156 | - Implement appropriate rate limiting 157 | - Control access to sensitive suggestions 158 | - Prevent completion-based information disclosure 159 | -------------------------------------------------------------------------------- /docs/specification/2025-03-26/server/utilities/logging.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Logging 3 | --- 4 | 5 | **Protocol Revision**: 2025-03-26 6 | 7 | The Model Context Protocol (MCP) provides a standardized way for servers to send 8 | structured log messages to clients. Clients can control logging verbosity by setting 9 | minimum log levels, with servers sending notifications containing severity levels, 10 | optional logger names, and arbitrary JSON-serializable data. 11 | 12 | ## User Interaction Model 13 | 14 | Implementations are free to expose logging through any interface pattern that suits their 15 | needs—the protocol itself does not mandate any specific user interaction model. 16 | 17 | ## Capabilities 18 | 19 | Servers that emit log message notifications **MUST** declare the `logging` capability: 20 | 21 | ```json 22 | { 23 | "capabilities": { 24 | "logging": {} 25 | } 26 | } 27 | ``` 28 | 29 | ## Log Levels 30 | 31 | The protocol follows the standard syslog severity levels specified in 32 | [RFC 5424](https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1): 33 | 34 | | Level | Description | Example Use Case | 35 | | --------- | -------------------------------- | -------------------------- | 36 | | debug | Detailed debugging information | Function entry/exit points | 37 | | info | General informational messages | Operation progress updates | 38 | | notice | Normal but significant events | Configuration changes | 39 | | warning | Warning conditions | Deprecated feature usage | 40 | | error | Error conditions | Operation failures | 41 | | critical | Critical conditions | System component failures | 42 | | alert | Action must be taken immediately | Data corruption detected | 43 | | emergency | System is unusable | Complete system failure | 44 | 45 | ## Protocol Messages 46 | 47 | ### Setting Log Level 48 | 49 | To configure the minimum log level, clients **MAY** send a `logging/setLevel` request: 50 | 51 | **Request:** 52 | 53 | ```json 54 | { 55 | "jsonrpc": "2.0", 56 | "id": 1, 57 | "method": "logging/setLevel", 58 | "params": { 59 | "level": "info" 60 | } 61 | } 62 | ``` 63 | 64 | ### Log Message Notifications 65 | 66 | Servers send log messages using `notifications/message` notifications: 67 | 68 | ```json 69 | { 70 | "jsonrpc": "2.0", 71 | "method": "notifications/message", 72 | "params": { 73 | "level": "error", 74 | "logger": "database", 75 | "data": { 76 | "error": "Connection failed", 77 | "details": { 78 | "host": "localhost", 79 | "port": 5432 80 | } 81 | } 82 | } 83 | } 84 | ``` 85 | 86 | ## Message Flow 87 | 88 | ```mermaid 89 | sequenceDiagram 90 | participant Client 91 | participant Server 92 | 93 | Note over Client,Server: Configure Logging 94 | Client->>Server: logging/setLevel (info) 95 | Server-->>Client: Empty Result 96 | 97 | Note over Client,Server: Server Activity 98 | Server--)Client: notifications/message (info) 99 | Server--)Client: notifications/message (warning) 100 | Server--)Client: notifications/message (error) 101 | 102 | Note over Client,Server: Level Change 103 | Client->>Server: logging/setLevel (error) 104 | Server-->>Client: Empty Result 105 | Note over Server: Only sends error level
and above 106 | ``` 107 | 108 | ## Error Handling 109 | 110 | Servers **SHOULD** return standard JSON-RPC errors for common failure cases: 111 | 112 | - Invalid log level: `-32602` (Invalid params) 113 | - Configuration errors: `-32603` (Internal error) 114 | 115 | ## Implementation Considerations 116 | 117 | 1. Servers **SHOULD**: 118 | 119 | - Rate limit log messages 120 | - Include relevant context in data field 121 | - Use consistent logger names 122 | - Remove sensitive information 123 | 124 | 2. Clients **MAY**: 125 | - Present log messages in the UI 126 | - Implement log filtering/search 127 | - Display severity visually 128 | - Persist log messages 129 | 130 | ## Security 131 | 132 | 1. Log messages **MUST NOT** contain: 133 | 134 | - Credentials or secrets 135 | - Personal identifying information 136 | - Internal system details that could aid attacks 137 | 138 | 2. Implementations **SHOULD**: 139 | - Rate limit messages 140 | - Validate all data fields 141 | - Control log access 142 | - Monitor for sensitive content 143 | -------------------------------------------------------------------------------- /docs/specification/2025-03-26/server/utilities/pagination.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Pagination 3 | --- 4 | 5 | **Protocol Revision**: 2025-03-26 6 | 7 | The Model Context Protocol (MCP) supports paginating list operations that may return 8 | large result sets. Pagination allows servers to yield results in smaller chunks rather 9 | than all at once. 10 | 11 | Pagination is especially important when connecting to external services over the 12 | internet, but also useful for local integrations to avoid performance issues with large 13 | data sets. 14 | 15 | ## Pagination Model 16 | 17 | Pagination in MCP uses an opaque cursor-based approach, instead of numbered pages. 18 | 19 | - The **cursor** is an opaque string token, representing a position in the result set 20 | - **Page size** is determined by the server, and clients **MUST NOT** assume a fixed page 21 | size 22 | 23 | ## Response Format 24 | 25 | Pagination starts when the server sends a **response** that includes: 26 | 27 | - The current page of results 28 | - An optional `nextCursor` field if more results exist 29 | 30 | ```json 31 | { 32 | "jsonrpc": "2.0", 33 | "id": "123", 34 | "result": { 35 | "resources": [...], 36 | "nextCursor": "eyJwYWdlIjogM30=" 37 | } 38 | } 39 | ``` 40 | 41 | ## Request Format 42 | 43 | After receiving a cursor, the client can _continue_ paginating by issuing a request 44 | including that cursor: 45 | 46 | ```json 47 | { 48 | "jsonrpc": "2.0", 49 | "method": "resources/list", 50 | "params": { 51 | "cursor": "eyJwYWdlIjogMn0=" 52 | } 53 | } 54 | ``` 55 | 56 | ## Pagination Flow 57 | 58 | ```mermaid 59 | sequenceDiagram 60 | participant Client 61 | participant Server 62 | 63 | Client->>Server: List Request (no cursor) 64 | loop Pagination Loop 65 | Server-->>Client: Page of results + nextCursor 66 | Client->>Server: List Request (with cursor) 67 | end 68 | ``` 69 | 70 | ## Operations Supporting Pagination 71 | 72 | The following MCP operations support pagination: 73 | 74 | - `resources/list` - List available resources 75 | - `resources/templates/list` - List resource templates 76 | - `prompts/list` - List available prompts 77 | - `tools/list` - List available tools 78 | 79 | ## Implementation Guidelines 80 | 81 | 1. Servers **SHOULD**: 82 | 83 | - Provide stable cursors 84 | - Handle invalid cursors gracefully 85 | 86 | 2. Clients **SHOULD**: 87 | 88 | - Treat a missing `nextCursor` as the end of results 89 | - Support both paginated and non-paginated flows 90 | 91 | 3. Clients **MUST** treat cursors as opaque tokens: 92 | - Don't make assumptions about cursor format 93 | - Don't attempt to parse or modify cursors 94 | - Don't persist cursors across sessions 95 | 96 | ## Error Handling 97 | 98 | Invalid cursors **SHOULD** result in an error with code -32602 (Invalid params). 99 | --------------------------------------------------------------------------------