···11+---
22+title: Architecture
33+cascade:
44+ type: docs
55+weight: 10
66+---
77+88+The Model Context Protocol (MCP) follows a client-host-server architecture where each
99+host can run multiple client instances. This architecture enables users to integrate AI
1010+capabilities across applications while maintaining clear security boundaries and
1111+isolating concerns. Built on JSON-RPC, MCP provides a stateful session protocol focused
1212+on context exchange and sampling coordination between clients and servers.
1313+1414+## Core Components
1515+1616+```mermaid
1717+graph LR
1818+ subgraph "Application Host Process"
1919+ H[Host]
2020+ C1[Client 1]
2121+ C2[Client 2]
2222+ C3[Client 3]
2323+ H --> C1
2424+ H --> C2
2525+ H --> C3
2626+ end
2727+2828+ subgraph "Local machine"
2929+ S1[Server 1<br>Files & Git]
3030+ S2[Server 2<br>Database]
3131+ R1[("Local<br>Resource A")]
3232+ R2[("Local<br>Resource B")]
3333+3434+ C1 --> S1
3535+ C2 --> S2
3636+ S1 <--> R1
3737+ S2 <--> R2
3838+ end
3939+4040+ subgraph "Internet"
4141+ S3[Server 3<br>External APIs]
4242+ R3[("Remote<br>Resource C")]
4343+4444+ C3 --> S3
4545+ S3 <--> R3
4646+ end
4747+```
4848+4949+### Host
5050+5151+The host process acts as the container and coordinator:
5252+5353+- Creates and manages multiple client instances
5454+- Controls client connection permissions and lifecycle
5555+- Enforces security policies and consent requirements
5656+- Handles user authorization decisions
5757+- Coordinates AI/LLM integration and sampling
5858+- Manages context aggregation across clients
5959+6060+### Clients
6161+6262+Each client is created by the host and maintains an isolated server connection:
6363+6464+- Establishes one stateful session per server
6565+- Handles protocol negotiation and capability exchange
6666+- Routes protocol messages bidirectionally
6767+- Manages subscriptions and notifications
6868+- Maintains security boundaries between servers
6969+7070+A host application creates and manages multiple clients, with each client having a 1:1
7171+relationship with a particular server.
7272+7373+### Servers
7474+7575+Servers provide specialized context and capabilities:
7676+7777+- Expose resources, tools and prompts via MCP primitives
7878+- Operate independently with focused responsibilities
7979+- Request sampling through client interfaces
8080+- Must respect security constraints
8181+- Can be local processes or remote services
8282+8383+## Design Principles
8484+8585+MCP is built on several key design principles that inform its architecture and
8686+implementation:
8787+8888+1. **Servers should be extremely easy to build**
8989+9090+ - Host applications handle complex orchestration responsibilities
9191+ - Servers focus on specific, well-defined capabilities
9292+ - Simple interfaces minimize implementation overhead
9393+ - Clear separation enables maintainable code
9494+9595+2. **Servers should be highly composable**
9696+9797+ - Each server provides focused functionality in isolation
9898+ - Multiple servers can be combined seamlessly
9999+ - Shared protocol enables interoperability
100100+ - Modular design supports extensibility
101101+102102+3. **Servers should not be able to read the whole conversation, nor "see into" other
103103+ servers**
104104+105105+ - Servers receive only necessary contextual information
106106+ - Full conversation history stays with the host
107107+ - Each server connection maintains isolation
108108+ - Cross-server interactions are controlled by the host
109109+ - Host process enforces security boundaries
110110+111111+4. **Features can be added to servers and clients progressively**
112112+ - Core protocol provides minimal required functionality
113113+ - Additional capabilities can be negotiated as needed
114114+ - Servers and clients evolve independently
115115+ - Protocol designed for future extensibility
116116+ - Backwards compatibility is maintained
117117+118118+## Capability Negotiation
119119+120120+The Model Context Protocol uses a capability-based negotiation system where clients and
121121+servers explicitly declare their supported features during initialization. Capabilities
122122+determine which protocol features and primitives are available during a session.
123123+124124+- Servers declare capabilities like resource subscriptions, tool support, and prompt
125125+ templates
126126+- Clients declare capabilities like sampling support and notification handling
127127+- Both parties must respect declared capabilities throughout the session
128128+- Additional capabilities can be negotiated through extensions to the protocol
129129+130130+```mermaid
131131+sequenceDiagram
132132+ participant Host
133133+ participant Client
134134+ participant Server
135135+136136+ Host->>+Client: Initialize client
137137+ Client->>+Server: Initialize session with capabilities
138138+ Server-->>Client: Respond with supported capabilities
139139+140140+ Note over Host,Server: Active Session with Negotiated Features
141141+142142+ loop Client Requests
143143+ Host->>Client: User- or model-initiated action
144144+ Client->>Server: Request (tools/resources)
145145+ Server-->>Client: Response
146146+ Client-->>Host: Update UI or respond to model
147147+ end
148148+149149+ loop Server Requests
150150+ Server->>Client: Request (sampling)
151151+ Client->>Host: Forward to AI
152152+ Host-->>Client: AI response
153153+ Client-->>Server: Response
154154+ end
155155+156156+ loop Notifications
157157+ Server--)Client: Resource updates
158158+ Client--)Server: Status changes
159159+ end
160160+161161+ Host->>Client: Terminate
162162+ Client->>-Server: End session
163163+ deactivate Server
164164+```
165165+166166+Each capability unlocks specific protocol features for use during the session. For
167167+example:
168168+169169+- Implemented [server features]({{< ref "../server" >}}) must be advertised in the
170170+ server's capabilities
171171+- Emitting resource subscription notifications requires the server to declare
172172+ subscription support
173173+- Tool invocation requires the server to declare tool capabilities
174174+- [Sampling]({{< ref "../client" >}}) requires the client to declare support in its
175175+ capabilities
176176+177177+This capability negotiation ensures clients and servers have a clear understanding of
178178+supported functionality while maintaining protocol extensibility.
+4
spec/README.md
···11+These specifications are snapshots from
22+https://github.com/modelcontextprotocol/specification/tree/main/docs/specification/2025-03-26
33+44+to help with the agentic prompting.
+386
spec/authorization.md
···11+---
22+title: Authorization
33+type: docs
44+weight: 15
55+---
66+77+{{< callout type="info" >}} **Protocol Revision**: 2025-03-26 {{< /callout >}}
88+99+## 1. Introduction
1010+1111+### 1.1 Purpose and Scope
1212+1313+The Model Context Protocol provides authorization capabilities at the transport level,
1414+enabling MCP clients to make requests to restricted MCP servers on behalf of resource
1515+owners. This specification defines the authorization flow for HTTP-based transports.
1616+1717+### 1.2 Protocol Requirements
1818+1919+Authorization is **OPTIONAL** for MCP implementations. When supported:
2020+2121+- Implementations using an HTTP-based transport **SHOULD** conform to this specification.
2222+- Implementations using an STDIO transport **SHOULD NOT** follow this specification, and
2323+ instead retrieve credentials from the environment.
2424+- Implementations using alternative transports **MUST** follow established security best
2525+ practices for their protocol.
2626+2727+### 1.3 Standards Compliance
2828+2929+This authorization mechanism is based on established specifications listed below, but
3030+implements a selected subset of their features to ensure security and interoperability
3131+while maintaining simplicity:
3232+3333+- [OAuth 2.1 IETF DRAFT](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12)
3434+- OAuth 2.0 Authorization Server Metadata
3535+ ([RFC8414](https://datatracker.ietf.org/doc/html/rfc8414))
3636+- OAuth 2.0 Dynamic Client Registration Protocol
3737+ ([RFC7591](https://datatracker.ietf.org/doc/html/rfc7591))
3838+3939+## 2. Authorization Flow
4040+4141+### 2.1 Overview
4242+4343+1. MCP auth implementations **MUST** implement OAuth 2.1 with appropriate security
4444+ measures for both confidential and public clients.
4545+4646+2. MCP auth implementations **SHOULD** support the OAuth 2.0 Dynamic Client Registration
4747+ Protocol ([RFC7591](https://datatracker.ietf.org/doc/html/rfc7591)).
4848+4949+3. MCP servers **SHOULD** and MCP clients **MUST** implement OAuth 2.0 Authorization
5050+ Server Metadata ([RFC8414](https://datatracker.ietf.org/doc/html/rfc8414)). Servers
5151+ that do not support Authorization Server Metadata **MUST** follow the default URI
5252+ schema.
5353+5454+### 2.2 Basic OAuth 2.1 Authorization
5555+5656+When authorization is required and not yet proven by the client, servers **MUST** respond
5757+with _HTTP 401 Unauthorized_.
5858+5959+Clients initiate the
6060+[OAuth 2.1 IETF DRAFT](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12)
6161+authorization flow after receiving the _HTTP 401 Unauthorized_.
6262+6363+The following demonstrates the basic OAuth 2.1 for public clients using PKCE.
6464+6565+```mermaid
6666+sequenceDiagram
6767+ participant B as User-Agent (Browser)
6868+ participant C as Client
6969+ participant M as MCP Server
7070+7171+ C->>M: MCP Request
7272+ M->>C: HTTP 401 Unauthorized
7373+ Note over C: Generate code_verifier and code_challenge
7474+ C->>B: Open browser with authorization URL + code_challenge
7575+ B->>M: GET /authorize
7676+ Note over M: User logs in and authorizes
7777+ M->>B: Redirect to callback URL with auth code
7878+ B->>C: Callback with authorization code
7979+ C->>M: Token Request with code + code_verifier
8080+ M->>C: Access Token (+ Refresh Token)
8181+ C->>M: MCP Request with Access Token
8282+ Note over C,M: Begin standard MCP message exchange
8383+```
8484+8585+### 2.3 Server Metadata Discovery
8686+8787+For server capability discovery:
8888+8989+- MCP clients _MUST_ follow the OAuth 2.0 Authorization Server Metadata protocol defined
9090+ in [RFC8414](https://datatracker.ietf.org/doc/html/rfc8414).
9191+- MCP server _SHOULD_ follow the OAuth 2.0 Authorization Server Metadata protocol.
9292+- MCP servers that do not support the OAuth 2.0 Authorization Server Metadata protocol,
9393+ _MUST_ support fallback URLs.
9494+9595+The discovery flow is illustrated below:
9696+9797+```mermaid
9898+sequenceDiagram
9999+ participant C as Client
100100+ participant S as Server
101101+102102+ C->>S: GET /.well-known/oauth-authorization-server
103103+ alt Discovery Success
104104+ S->>C: 200 OK + Metadata Document
105105+ Note over C: Use endpoints from metadata
106106+ else Discovery Failed
107107+ S->>C: 404 Not Found
108108+ Note over C: Fall back to default endpoints
109109+ end
110110+ Note over C: Continue with authorization flow
111111+```
112112+113113+#### 2.3.1 Server Metadata Discovery Headers
114114+115115+MCP clients _SHOULD_ include the header `MCP-Protocol-Version: <protocol-version>` during
116116+Server Metadata Discovery to allow the MCP server to respond based on the MCP protocol
117117+version.
118118+119119+For example: `MCP-Protocol-Version: 2024-11-05`
120120+121121+#### 2.3.2 Authorization Base URL
122122+123123+The authorization base URL **MUST** be determined from the MCP server URL by discarding
124124+any existing `path` component. For example:
125125+126126+If the MCP server URL is `https://api.example.com/v1/mcp`, then:
127127+128128+- The authorization base URL is `https://api.example.com`
129129+- The metadata endpoint **MUST** be at
130130+ `https://api.example.com/.well-known/oauth-authorization-server`
131131+132132+This ensures authorization endpoints are consistently located at the root level of the
133133+domain hosting the MCP server, regardless of any path components in the MCP server URL.
134134+135135+#### 2.3.3 Fallbacks for Servers without Metadata Discovery
136136+137137+For servers that do not implement OAuth 2.0 Authorization Server Metadata, clients
138138+**MUST** use the following default endpoint paths relative to the authorization base URL
139139+(as defined in [Section 2.3.2](#232-authorization-base-url)):
140140+141141+| Endpoint | Default Path | Description |
142142+| ---------------------- | ------------ | ------------------------------------ |
143143+| Authorization Endpoint | /authorize | Used for authorization requests |
144144+| Token Endpoint | /token | Used for token exchange & refresh |
145145+| Registration Endpoint | /register | Used for dynamic client registration |
146146+147147+For example, with an MCP server hosted at `https://api.example.com/v1/mcp`, the default
148148+endpoints would be:
149149+150150+- `https://api.example.com/authorize`
151151+- `https://api.example.com/token`
152152+- `https://api.example.com/register`
153153+154154+Clients **MUST** first attempt to discover endpoints via the metadata document before
155155+falling back to default paths. When using default paths, all other protocol requirements
156156+remain unchanged.
157157+158158+### 2.3 Dynamic Client Registration
159159+160160+MCP clients and servers **SHOULD** support the
161161+[OAuth 2.0 Dynamic Client Registration Protocol](https://datatracker.ietf.org/doc/html/rfc7591)
162162+to allow MCP clients to obtain OAuth client IDs without user interaction. This provides a
163163+standardized way for clients to automatically register with new servers, which is crucial
164164+for MCP because:
165165+166166+- Clients cannot know all possible servers in advance
167167+- Manual registration would create friction for users
168168+- It enables seamless connection to new servers
169169+- Servers can implement their own registration policies
170170+171171+Any MCP servers that _do not_ support Dynamic Client Registration need to provide
172172+alternative ways to obtain a client ID (and, if applicable, client secret). For one of
173173+these servers, MCP clients will have to either:
174174+175175+1. Hardcode a client ID (and, if applicable, client secret) specifically for that MCP
176176+ server, or
177177+2. Present a UI to users that allows them to enter these details, after registering an
178178+ OAuth client themselves (e.g., through a configuration interface hosted by the
179179+ server).
180180+181181+### 2.4 Authorization Flow Steps
182182+183183+The complete Authorization flow proceeds as follows:
184184+185185+```mermaid
186186+sequenceDiagram
187187+ participant B as User-Agent (Browser)
188188+ participant C as Client
189189+ participant M as MCP Server
190190+191191+ C->>M: GET /.well-known/oauth-authorization-server
192192+ alt Server Supports Discovery
193193+ M->>C: Authorization Server Metadata
194194+ else No Discovery
195195+ M->>C: 404 (Use default endpoints)
196196+ end
197197+198198+ alt Dynamic Client Registration
199199+ C->>M: POST /register
200200+ M->>C: Client Credentials
201201+ end
202202+203203+ Note over C: Generate PKCE Parameters
204204+ C->>B: Open browser with authorization URL + code_challenge
205205+ B->>M: Authorization Request
206206+ Note over M: User /authorizes
207207+ M->>B: Redirect to callback with authorization code
208208+ B->>C: Authorization code callback
209209+ C->>M: Token Request + code_verifier
210210+ M->>C: Access Token (+ Refresh Token)
211211+ C->>M: API Requests with Access Token
212212+```
213213+214214+#### 2.4.1 Decision Flow Overview
215215+216216+```mermaid
217217+flowchart TD
218218+ A[Start Auth Flow] --> B{Check Metadata Discovery}
219219+ B -->|Available| C[Use Metadata Endpoints]
220220+ B -->|Not Available| D[Use Default Endpoints]
221221+222222+ C --> G{Check Registration Endpoint}
223223+ D --> G
224224+225225+ G -->|Available| H[Perform Dynamic Registration]
226226+ G -->|Not Available| I[Alternative Registration Required]
227227+228228+ H --> J[Start OAuth Flow]
229229+ I --> J
230230+231231+ J --> K[Generate PKCE Parameters]
232232+ K --> L[Request Authorization]
233233+ L --> M[User Authorization]
234234+ M --> N[Exchange Code for Tokens]
235235+ N --> O[Use Access Token]
236236+```
237237+238238+### 2.5 Access Token Usage
239239+240240+#### 2.5.1 Token Requirements
241241+242242+Access token handling **MUST** conform to
243243+[OAuth 2.1 Section 5](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5)
244244+requirements for resource requests. Specifically:
245245+246246+1. MCP client **MUST** use the Authorization request header field
247247+ [Section 5.1.1](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5.1.1):
248248+249249+```
250250+Authorization: Bearer <access-token>
251251+```
252252+253253+Note that authorization **MUST** be included in every HTTP request from client to server,
254254+even if they are part of the same logical session.
255255+256256+2. Access tokens **MUST NOT** be included in the URI query string
257257+258258+Example request:
259259+260260+```http
261261+GET /v1/contexts HTTP/1.1
262262+Host: mcp.example.com
263263+Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
264264+```
265265+266266+#### 2.5.2 Token Handling
267267+268268+Resource servers **MUST** validate access tokens as described in
269269+[Section 5.2](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5.2).
270270+If validation fails, servers **MUST** respond according to
271271+[Section 5.3](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5.3)
272272+error handling requirements. Invalid or expired tokens **MUST** receive a HTTP 401
273273+response.
274274+275275+### 2.6 Security Considerations
276276+277277+The following security requirements **MUST** be implemented:
278278+279279+1. Clients **MUST** securely store tokens following OAuth 2.0 best practices
280280+2. Servers **SHOULD** enforce token expiration and rotation
281281+3. All authorization endpoints **MUST** be served over HTTPS
282282+4. Servers **MUST** validate redirect URIs to prevent open redirect vulnerabilities
283283+5. Redirect URIs **MUST** be either localhost URLs or HTTPS URLs
284284+285285+### 2.7 Error Handling
286286+287287+Servers **MUST** return appropriate HTTP status codes for authorization errors:
288288+289289+| Status Code | Description | Usage |
290290+| ----------- | ------------ | ------------------------------------------ |
291291+| 401 | Unauthorized | Authorization required or token invalid |
292292+| 403 | Forbidden | Invalid scopes or insufficient permissions |
293293+| 400 | Bad Request | Malformed authorization request |
294294+295295+### 2.8 Implementation Requirements
296296+297297+1. Implementations **MUST** follow OAuth 2.1 security best practices
298298+2. PKCE is **REQUIRED** for all clients
299299+3. Token rotation **SHOULD** be implemented for enhanced security
300300+4. Token lifetimes **SHOULD** be limited based on security requirements
301301+302302+### 2.9 Third-Party Authorization Flow
303303+304304+#### 2.9.1 Overview
305305+306306+MCP servers **MAY** support delegated authorization through third-party authorization
307307+servers. In this flow, the MCP server acts as both an OAuth client (to the third-party
308308+auth server) and an OAuth authorization server (to the MCP client).
309309+310310+#### 2.9.2 Flow Description
311311+312312+The third-party authorization flow comprises these steps:
313313+314314+1. MCP client initiates standard OAuth flow with MCP server
315315+2. MCP server redirects user to third-party authorization server
316316+3. User authorizes with third-party server
317317+4. Third-party server redirects back to MCP server with authorization code
318318+5. MCP server exchanges code for third-party access token
319319+6. MCP server generates its own access token bound to the third-party session
320320+7. MCP server completes original OAuth flow with MCP client
321321+322322+```mermaid
323323+sequenceDiagram
324324+ participant B as User-Agent (Browser)
325325+ participant C as MCP Client
326326+ participant M as MCP Server
327327+ participant T as Third-Party Auth Server
328328+329329+ C->>M: Initial OAuth Request
330330+ M->>B: Redirect to Third-Party /authorize
331331+ B->>T: Authorization Request
332332+ Note over T: User authorizes
333333+ T->>B: Redirect to MCP Server callback
334334+ B->>M: Authorization code
335335+ M->>T: Exchange code for token
336336+ T->>M: Third-party access token
337337+ Note over M: Generate bound MCP token
338338+ M->>B: Redirect to MCP Client callback
339339+ B->>C: MCP authorization code
340340+ C->>M: Exchange code for token
341341+ M->>C: MCP access token
342342+```
343343+344344+#### 2.9.3 Session Binding Requirements
345345+346346+MCP servers implementing third-party authorization **MUST**:
347347+348348+1. Maintain secure mapping between third-party tokens and issued MCP tokens
349349+2. Validate third-party token status before honoring MCP tokens
350350+3. Implement appropriate token lifecycle management
351351+4. Handle third-party token expiration and renewal
352352+353353+#### 2.9.4 Security Considerations
354354+355355+When implementing third-party authorization, servers **MUST**:
356356+357357+1. Validate all redirect URIs
358358+2. Securely store third-party credentials
359359+3. Implement appropriate session timeout handling
360360+4. Consider security implications of token chaining
361361+5. Implement proper error handling for third-party auth failures
362362+363363+## 3. Best Practices
364364+365365+#### 3.1 Local clients as Public OAuth 2.1 Clients
366366+367367+We strongly recommend that local clients implement OAuth 2.1 as a public client:
368368+369369+1. Utilizing code challenges (PKCE) for authorization requests to prevent interception
370370+ attacks
371371+2. Implementing secure token storage appropriate for the local system
372372+3. Following token refresh best practices to maintain sessions
373373+4. Properly handling token expiration and renewal
374374+375375+#### 3.2 Authorization Metadata Discovery
376376+377377+We strongly recommend that all clients implement metadata discovery. This reduces the
378378+need for users to provide endpoints manually or clients to fallback to the defined
379379+defaults.
380380+381381+#### 3.3 Dynamic Client Registration
382382+383383+Since clients do not know the set of MCP servers in advance, we strongly recommend the
384384+implementation of dynamic client registration. This allows applications to automatically
385385+register with the MCP server, and removes the need for users to obtain client ids
386386+manually.
+239
spec/lifecycle.md
···11+---
22+title: Lifecycle
33+type: docs
44+weight: 30
55+---
66+77+{{< callout type="info" >}} **Protocol Revision**: 2025-03-26 {{< /callout >}}
88+99+The Model Context Protocol (MCP) defines a rigorous lifecycle for client-server
1010+connections that ensures proper capability negotiation and state management.
1111+1212+1. **Initialization**: Capability negotiation and protocol version agreement
1313+2. **Operation**: Normal protocol communication
1414+3. **Shutdown**: Graceful termination of the connection
1515+1616+```mermaid
1717+sequenceDiagram
1818+ participant Client
1919+ participant Server
2020+2121+ Note over Client,Server: Initialization Phase
2222+ activate Client
2323+ Client->>+Server: initialize request
2424+ Server-->>Client: initialize response
2525+ Client--)Server: initialized notification
2626+2727+ Note over Client,Server: Operation Phase
2828+ rect rgb(200, 220, 250)
2929+ note over Client,Server: Normal protocol operations
3030+ end
3131+3232+ Note over Client,Server: Shutdown
3333+ Client--)-Server: Disconnect
3434+ deactivate Server
3535+ Note over Client,Server: Connection closed
3636+```
3737+3838+## Lifecycle Phases
3939+4040+### Initialization
4141+4242+The initialization phase **MUST** be the first interaction between client and server.
4343+During this phase, the client and server:
4444+4545+- Establish protocol version compatibility
4646+- Exchange and negotiate capabilities
4747+- Share implementation details
4848+4949+The client **MUST** initiate this phase by sending an `initialize` request containing:
5050+5151+- Protocol version supported
5252+- Client capabilities
5353+- Client implementation information
5454+5555+```json
5656+{
5757+ "jsonrpc": "2.0",
5858+ "id": 1,
5959+ "method": "initialize",
6060+ "params": {
6161+ "protocolVersion": "2024-11-05",
6262+ "capabilities": {
6363+ "roots": {
6464+ "listChanged": true
6565+ },
6666+ "sampling": {}
6767+ },
6868+ "clientInfo": {
6969+ "name": "ExampleClient",
7070+ "version": "1.0.0"
7171+ }
7272+ }
7373+}
7474+```
7575+7676+The initialize request **MUST NOT** be part of a JSON-RPC
7777+[batch](https://www.jsonrpc.org/specification#batch), as other requests and notifications
7878+are not possible until initialization has completed. This also permits backwards
7979+compatibility with prior protocol versions that do not explicitly support JSON-RPC
8080+batches.
8181+8282+The server **MUST** respond with its own capabilities and information:
8383+8484+```json
8585+{
8686+ "jsonrpc": "2.0",
8787+ "id": 1,
8888+ "result": {
8989+ "protocolVersion": "2024-11-05",
9090+ "capabilities": {
9191+ "logging": {},
9292+ "prompts": {
9393+ "listChanged": true
9494+ },
9595+ "resources": {
9696+ "subscribe": true,
9797+ "listChanged": true
9898+ },
9999+ "tools": {
100100+ "listChanged": true
101101+ }
102102+ },
103103+ "serverInfo": {
104104+ "name": "ExampleServer",
105105+ "version": "1.0.0"
106106+ }
107107+ }
108108+}
109109+```
110110+111111+After successful initialization, the client **MUST** send an `initialized` notification
112112+to indicate it is ready to begin normal operations:
113113+114114+```json
115115+{
116116+ "jsonrpc": "2.0",
117117+ "method": "notifications/initialized"
118118+}
119119+```
120120+121121+- The client **SHOULD NOT** send requests other than
122122+ [pings]({{< ref "utilities/ping" >}}) before the server has responded to the
123123+ `initialize` request.
124124+- The server **SHOULD NOT** send requests other than
125125+ [pings]({{< ref "utilities/ping" >}}) and
126126+ [logging]({{< ref "../server/utilities/logging" >}}) before receiving the `initialized`
127127+ notification.
128128+129129+#### Version Negotiation
130130+131131+In the `initialize` request, the client **MUST** send a protocol version it supports.
132132+This **SHOULD** be the _latest_ version supported by the client.
133133+134134+If the server supports the requested protocol version, it **MUST** respond with the same
135135+version. Otherwise, the server **MUST** respond with another protocol version it
136136+supports. This **SHOULD** be the _latest_ version supported by the server.
137137+138138+If the client does not support the version in the server's response, it **SHOULD**
139139+disconnect.
140140+141141+#### Capability Negotiation
142142+143143+Client and server capabilities establish which optional protocol features will be
144144+available during the session.
145145+146146+Key capabilities include:
147147+148148+| Category | Capability | Description |
149149+| -------- | -------------- | -------------------------------------------------------------------------- |
150150+| Client | `roots` | Ability to provide filesystem [roots]({{< ref "../client/roots" >}}) |
151151+| Client | `sampling` | Support for LLM [sampling]({{< ref "../client/sampling" >}}) requests |
152152+| Client | `experimental` | Describes support for non-standard experimental features |
153153+| Server | `prompts` | Offers [prompt templates]({{< ref "../server/prompts" >}}) |
154154+| Server | `resources` | Provides readable [resources]({{< ref "../server/resources" >}}) |
155155+| Server | `tools` | Exposes callable [tools]({{< ref "../server/tools" >}}) |
156156+| Server | `logging` | Emits structured [log messages]({{< ref "../server/utilities/logging" >}}) |
157157+| Server | `experimental` | Describes support for non-standard experimental features |
158158+159159+Capability objects can describe sub-capabilities like:
160160+161161+- `listChanged`: Support for list change notifications (for prompts, resources, and
162162+ tools)
163163+- `subscribe`: Support for subscribing to individual items' changes (resources only)
164164+165165+### Operation
166166+167167+During the operation phase, the client and server exchange messages according to the
168168+negotiated capabilities.
169169+170170+Both parties **SHOULD**:
171171+172172+- Respect the negotiated protocol version
173173+- Only use capabilities that were successfully negotiated
174174+175175+### Shutdown
176176+177177+During the shutdown phase, one side (usually the client) cleanly terminates the protocol
178178+connection. No specific shutdown messages are defined—instead, the underlying transport
179179+mechanism should be used to signal connection termination:
180180+181181+#### stdio
182182+183183+For the stdio [transport]({{< ref "transports" >}}), the client **SHOULD** initiate
184184+shutdown by:
185185+186186+1. First, closing the input stream to the child process (the server)
187187+2. Waiting for the server to exit, or sending `SIGTERM` if the server does not exit
188188+ within a reasonable time
189189+3. Sending `SIGKILL` if the server does not exit within a reasonable time after `SIGTERM`
190190+191191+The server **MAY** initiate shutdown by closing its output stream to the client and
192192+exiting.
193193+194194+#### HTTP
195195+196196+For HTTP [transports]({{< ref "transports" >}}), shutdown is indicated by closing the
197197+associated HTTP connection(s).
198198+199199+## Timeouts
200200+201201+Implementations **SHOULD** establish timeouts for all sent requests, to prevent hung
202202+connections and resource exhaustion. When the request has not received a success or error
203203+response within the timeout period, the sender **SHOULD** issue a [cancellation
204204+notification]({{< ref "utilities/cancellation" >}}) for that request and stop waiting for
205205+a response.
206206+207207+SDKs and other middleware **SHOULD** allow these timeouts to be configured on a
208208+per-request basis.
209209+210210+Implementations **MAY** choose to reset the timeout clock when receiving a [progress
211211+notification]({{< ref "utilities/progress" >}}) corresponding to the request, as this
212212+implies that work is actually happening. However, implementations **SHOULD** always
213213+enforce a maximum timeout, regardless of progress notifications, to limit the impact of a
214214+misbehaving client or server.
215215+216216+## Error Handling
217217+218218+Implementations **SHOULD** be prepared to handle these error cases:
219219+220220+- Protocol version mismatch
221221+- Failure to negotiate required capabilities
222222+- Request [timeouts](#timeouts)
223223+224224+Example initialization error:
225225+226226+```json
227227+{
228228+ "jsonrpc": "2.0",
229229+ "id": 1,
230230+ "error": {
231231+ "code": -32602,
232232+ "message": "Unsupported protocol version",
233233+ "data": {
234234+ "supported": ["2024-11-05"],
235235+ "requested": "1.0.0"
236236+ }
237237+ }
238238+}
239239+```
+265
spec/prompts.md
···11+---
22+title: Prompts
33+weight: 10
44+---
55+66+{{< callout type="info" >}} **Protocol Revision**: 2025-03-26 {{< /callout >}}
77+88+The Model Context Protocol (MCP) provides a standardized way for servers to expose prompt
99+templates to clients. Prompts allow servers to provide structured messages and
1010+instructions for interacting with language models. Clients can discover available
1111+prompts, retrieve their contents, and provide arguments to customize them.
1212+1313+## User Interaction Model
1414+1515+Prompts are designed to be **user-controlled**, meaning they are exposed from servers to
1616+clients with the intention of the user being able to explicitly select them for use.
1717+1818+Typically, prompts would be triggered through user-initiated commands in the user
1919+interface, which allows users to naturally discover and invoke available prompts.
2020+2121+For example, as slash commands:
2222+2323+
2424+2525+However, implementors are free to expose prompts through any interface pattern that suits
2626+their needs—the protocol itself does not mandate any specific user interaction
2727+model.
2828+2929+## Capabilities
3030+3131+Servers that support prompts **MUST** declare the `prompts` capability during
3232+[initialization]({{< ref "../basic/lifecycle#initialization" >}}):
3333+3434+/draft`json { "capabilities": { "prompts": { "listChanged": true } } }
3535+3636+````
3737+3838+`listChanged` indicates whether the server will emit notifications when the list of
3939+available prompts changes.
4040+4141+## Protocol Messages
4242+4343+### Listing Prompts
4444+4545+To retrieve available prompts, clients send a `prompts/list` request. This operation
4646+supports [pagination]({{< ref "utilities/pagination" >}}).
4747+4848+**Request:**
4949+5050+```json
5151+{
5252+ "jsonrpc": "2.0",
5353+ "id": 1,
5454+ "method": "prompts/list",
5555+ "params": {
5656+ "cursor": "optional-cursor-value"
5757+ }
5858+}
5959+````
6060+6161+**Response:**
6262+6363+```json
6464+{
6565+ "jsonrpc": "2.0",
6666+ "id": 1,
6767+ "result": {
6868+ "prompts": [
6969+ {
7070+ "name": "code_review",
7171+ "description": "Asks the LLM to analyze code quality and suggest improvements",
7272+ "arguments": [
7373+ {
7474+ "name": "code",
7575+ "description": "The code to review",
7676+ "required": true
7777+ }
7878+ ]
7979+ }
8080+ ],
8181+ "nextCursor": "next-page-cursor"
8282+ }
8383+}
8484+```
8585+8686+### Getting a Prompt
8787+8888+To retrieve a specific prompt, clients send a `prompts/get` request. Arguments may be
8989+auto-completed through [the completion API]({{< ref "utilities/completion" >}}).
9090+9191+**Request:**
9292+9393+```json
9494+{
9595+ "jsonrpc": "2.0",
9696+ "id": 2,
9797+ "method": "prompts/get",
9898+ "params": {
9999+ "name": "code_review",
100100+ "arguments": {
101101+ "code": "def hello():\n print('world')"
102102+ }
103103+ }
104104+}
105105+```
106106+107107+**Response:**
108108+109109+```json
110110+{
111111+ "jsonrpc": "2.0",
112112+ "id": 2,
113113+ "result": {
114114+ "description": "Code review prompt",
115115+ "messages": [
116116+ {
117117+ "role": "user",
118118+ "content": {
119119+ "type": "text",
120120+ "text": "Please review this Python code:\ndef hello():\n print('world')"
121121+ }
122122+ }
123123+ ]
124124+ }
125125+}
126126+```
127127+128128+### List Changed Notification
129129+130130+When the list of available prompts changes, servers that declared the `listChanged`
131131+capability **SHOULD** send a notification:
132132+133133+```json
134134+{
135135+ "jsonrpc": "2.0",
136136+ "method": "notifications/prompts/list_changed"
137137+}
138138+```
139139+140140+## Message Flow
141141+142142+```mermaid
143143+sequenceDiagram
144144+ participant Client
145145+ participant Server
146146+147147+ Note over Client,Server: Discovery
148148+ Client->>Server: prompts/list
149149+ Server-->>Client: List of prompts
150150+151151+ Note over Client,Server: Usage
152152+ Client->>Server: prompts/get
153153+ Server-->>Client: Prompt content
154154+155155+ opt listChanged
156156+ Note over Client,Server: Changes
157157+ Server--)Client: prompts/list_changed
158158+ Client->>Server: prompts/list
159159+ Server-->>Client: Updated prompts
160160+ end
161161+```
162162+163163+## Data Types
164164+165165+### Prompt
166166+167167+A prompt definition includes:
168168+169169+- `name`: Unique identifier for the prompt
170170+- `description`: Optional human-readable description
171171+- `arguments`: Optional list of arguments for customization
172172+173173+### PromptMessage
174174+175175+Messages in a prompt can contain:
176176+177177+- `role`: Either "user" or "assistant" to indicate the speaker
178178+- `content`: One of the following content types:
179179+180180+#### Text Content
181181+182182+Text content represents plain text messages:
183183+184184+```json
185185+{
186186+ "type": "text",
187187+ "text": "The text content of the message"
188188+}
189189+```
190190+191191+This is the most common content type used for natural language interactions.
192192+193193+#### Image Content
194194+195195+Image content allows including visual information in messages:
196196+197197+```json
198198+{
199199+ "type": "image",
200200+ "data": "base64-encoded-image-data",
201201+ "mimeType": "image/png"
202202+}
203203+```
204204+205205+The image data **MUST** be base64-encoded and include a valid MIME type. This enables
206206+multi-modal interactions where visual context is important.
207207+208208+#### Audio Content
209209+210210+Audio content allows including audio information in messages:
211211+212212+```json
213213+{
214214+ "type": "audio",
215215+ "data": "base64-encoded-audio-data",
216216+ "mimeType": "audio/wav"
217217+}
218218+```
219219+220220+The audio data MUST be base64-encoded and include a valid MIME type. This enables
221221+multi-modal interactions where audio context is important.
222222+223223+#### Embedded Resources
224224+225225+Embedded resources allow referencing server-side resources directly in messages:
226226+227227+```json
228228+{
229229+ "type": "resource",
230230+ "resource": {
231231+ "uri": "resource://example",
232232+ "mimeType": "text/plain",
233233+ "text": "Resource content"
234234+ }
235235+}
236236+```
237237+238238+Resources can contain either text or binary (blob) data and **MUST** include:
239239+240240+- A valid resource URI
241241+- The appropriate MIME type
242242+- Either text content or base64-encoded blob data
243243+244244+Embedded resources enable prompts to seamlessly incorporate server-managed content like
245245+documentation, code samples, or other reference materials directly into the conversation
246246+flow.
247247+248248+## Error Handling
249249+250250+Servers **SHOULD** return standard JSON-RPC errors for common failure cases:
251251+252252+- Invalid prompt name: `-32602` (Invalid params)
253253+- Missing required arguments: `-32602` (Invalid params)
254254+- Internal errors: `-32603` (Internal error)
255255+256256+## Implementation Considerations
257257+258258+1. Servers **SHOULD** validate prompt arguments before processing
259259+2. Clients **SHOULD** handle pagination for large prompt lists
260260+3. Both parties **SHOULD** respect capability negotiation
261261+262262+## Security
263263+264264+Implementations **MUST** carefully validate all prompt inputs and outputs to prevent
265265+injection attacks or unauthorized access to resources.
+357
spec/resources.md
···11+---
22+title: Resources
33+type: docs
44+weight: 20
55+---
66+77+{{< callout type="info" >}} **Protocol Revision**: 2025-03-26 {{< /callout >}}
88+99+The Model Context Protocol (MCP) provides a standardized way for servers to expose
1010+resources to clients. Resources allow servers to share data that provides context to
1111+language models, such as files, database schemas, or application-specific information.
1212+Each resource is uniquely identified by a
1313+[URI](https://datatracker.ietf.org/doc/html/rfc3986).
1414+1515+## User Interaction Model
1616+1717+Resources in MCP are designed to be **application-driven**, with host applications
1818+determining how to incorporate context based on their needs.
1919+2020+For example, applications could:
2121+2222+- Expose resources through UI elements for explicit selection, in a tree or list view
2323+- Allow the user to search through and filter available resources
2424+- Implement automatic context inclusion, based on heuristics or the AI model's selection
2525+2626+
2727+2828+However, implementations are free to expose resources through any interface pattern that
2929+suits their needs—the protocol itself does not mandate any specific user
3030+interaction model.
3131+3232+## Capabilities
3333+3434+Servers that support resources **MUST** declare the `resources` capability:
3535+3636+```json
3737+{
3838+ "capabilities": {
3939+ "resources": {
4040+ "subscribe": true,
4141+ "listChanged": true
4242+ }
4343+ }
4444+}
4545+```
4646+4747+The capability supports two optional features:
4848+4949+- `subscribe`: whether the client can subscribe to be notified of changes to individual
5050+ resources.
5151+- `listChanged`: whether the server will emit notifications when the list of available
5252+ resources changes.
5353+5454+Both `subscribe` and `listChanged` are optional—servers can support neither,
5555+either, or both:
5656+5757+```json
5858+{
5959+ "capabilities": {
6060+ "resources": {} // Neither feature supported
6161+ }
6262+}
6363+```
6464+6565+```json
6666+{
6767+ "capabilities": {
6868+ "resources": {
6969+ "subscribe": true // Only subscriptions supported
7070+ }
7171+ }
7272+}
7373+```
7474+7575+```json
7676+{
7777+ "capabilities": {
7878+ "resources": {
7979+ "listChanged": true // Only list change notifications supported
8080+ }
8181+ }
8282+}
8383+```
8484+8585+## Protocol Messages
8686+8787+### Listing Resources
8888+8989+To discover available resources, clients send a `resources/list` request. This operation
9090+supports [pagination]({{< ref "utilities/pagination" >}}).
9191+9292+**Request:**
9393+9494+```json
9595+{
9696+ "jsonrpc": "2.0",
9797+ "id": 1,
9898+ "method": "resources/list",
9999+ "params": {
100100+ "cursor": "optional-cursor-value"
101101+ }
102102+}
103103+```
104104+105105+**Response:**
106106+107107+```json
108108+{
109109+ "jsonrpc": "2.0",
110110+ "id": 1,
111111+ "result": {
112112+ "resources": [
113113+ {
114114+ "uri": "file:///project/src/main.rs",
115115+ "name": "main.rs",
116116+ "description": "Primary application entry point",
117117+ "mimeType": "text/x-rust"
118118+ }
119119+ ],
120120+ "nextCursor": "next-page-cursor"
121121+ }
122122+}
123123+```
124124+125125+### Reading Resources
126126+127127+To retrieve resource contents, clients send a `resources/read` request:
128128+129129+**Request:**
130130+131131+```json
132132+{
133133+ "jsonrpc": "2.0",
134134+ "id": 2,
135135+ "method": "resources/read",
136136+ "params": {
137137+ "uri": "file:///project/src/main.rs"
138138+ }
139139+}
140140+```
141141+142142+**Response:**
143143+144144+```json
145145+{
146146+ "jsonrpc": "2.0",
147147+ "id": 2,
148148+ "result": {
149149+ "contents": [
150150+ {
151151+ "uri": "file:///project/src/main.rs",
152152+ "mimeType": "text/x-rust",
153153+ "text": "fn main() {\n println!(\"Hello world!\");\n}"
154154+ }
155155+ ]
156156+ }
157157+}
158158+```
159159+160160+### Resource Templates
161161+162162+Resource templates allow servers to expose parameterized resources using
163163+[URI templates](https://datatracker.ietf.org/doc/html/rfc6570). Arguments may be
164164+auto-completed through [the completion API]({{< ref "utilities/completion" >}}).
165165+166166+**Request:**
167167+168168+```json
169169+{
170170+ "jsonrpc": "2.0",
171171+ "id": 3,
172172+ "method": "resources/templates/list"
173173+}
174174+```
175175+176176+**Response:**
177177+178178+```json
179179+{
180180+ "jsonrpc": "2.0",
181181+ "id": 3,
182182+ "result": {
183183+ "resourceTemplates": [
184184+ {
185185+ "uriTemplate": "file:///{path}",
186186+ "name": "Project Files",
187187+ "description": "Access files in the project directory",
188188+ "mimeType": "application/octet-stream"
189189+ }
190190+ ]
191191+ }
192192+}
193193+```
194194+195195+### List Changed Notification
196196+197197+When the list of available resources changes, servers that declared the `listChanged`
198198+capability **SHOULD** send a notification:
199199+200200+```json
201201+{
202202+ "jsonrpc": "2.0",
203203+ "method": "notifications/resources/list_changed"
204204+}
205205+```
206206+207207+### Subscriptions
208208+209209+The protocol supports optional subscriptions to resource changes. Clients can subscribe
210210+to specific resources and receive notifications when they change:
211211+212212+**Subscribe Request:**
213213+214214+```json
215215+{
216216+ "jsonrpc": "2.0",
217217+ "id": 4,
218218+ "method": "resources/subscribe",
219219+ "params": {
220220+ "uri": "file:///project/src/main.rs"
221221+ }
222222+}
223223+```
224224+225225+**Update Notification:**
226226+227227+```json
228228+{
229229+ "jsonrpc": "2.0",
230230+ "method": "notifications/resources/updated",
231231+ "params": {
232232+ "uri": "file:///project/src/main.rs"
233233+ }
234234+}
235235+```
236236+237237+## Message Flow
238238+239239+```mermaid
240240+sequenceDiagram
241241+ participant Client
242242+ participant Server
243243+244244+ Note over Client,Server: Resource Discovery
245245+ Client->>Server: resources/list
246246+ Server-->>Client: List of resources
247247+248248+ Note over Client,Server: Resource Access
249249+ Client->>Server: resources/read
250250+ Server-->>Client: Resource contents
251251+252252+ Note over Client,Server: Subscriptions
253253+ Client->>Server: resources/subscribe
254254+ Server-->>Client: Subscription confirmed
255255+256256+ Note over Client,Server: Updates
257257+ Server--)Client: notifications/resources/updated
258258+ Client->>Server: resources/read
259259+ Server-->>Client: Updated contents
260260+```
261261+262262+## Data Types
263263+264264+### Resource
265265+266266+A resource definition includes:
267267+268268+- `uri`: Unique identifier for the resource
269269+- `name`: Human-readable name
270270+- `description`: Optional description
271271+- `mimeType`: Optional MIME type
272272+- `size`: Optional size in bytes
273273+274274+### Resource Contents
275275+276276+Resources can contain either text or binary data:
277277+278278+#### Text Content
279279+280280+```json
281281+{
282282+ "uri": "file:///example.txt",
283283+ "mimeType": "text/plain",
284284+ "text": "Resource content"
285285+}
286286+```
287287+288288+#### Binary Content
289289+290290+```json
291291+{
292292+ "uri": "file:///example.png",
293293+ "mimeType": "image/png",
294294+ "blob": "base64-encoded-data"
295295+}
296296+```
297297+298298+## Common URI Schemes
299299+300300+The protocol defines several standard URI schemes. This list not
301301+exhaustive—implementations are always free to use additional, custom URI schemes.
302302+303303+### https://
304304+305305+Used to represent a resource available on the web.
306306+307307+Servers **SHOULD** use this scheme only when the client is able to fetch and load the
308308+resource directly from the web on its own—that is, it doesn’t need to read the resource
309309+via the MCP server.
310310+311311+For other use cases, servers **SHOULD** prefer to use another URI scheme, or define a
312312+custom one, even if the server will itself be downloading resource contents over the
313313+internet.
314314+315315+### file://
316316+317317+Used to identify resources that behave like a filesystem. However, the resources do not
318318+need to map to an actual physical filesystem.
319319+320320+MCP servers **MAY** identify file:// resources with an
321321+[XDG MIME type](https://specifications.freedesktop.org/shared-mime-info-spec/0.14/ar01s02.html#id-1.3.14),
322322+like `inode/directory`, to represent non-regular files (such as directories) that don’t
323323+otherwise have a standard MIME type.
324324+325325+### git://
326326+327327+Git version control integration.
328328+329329+## Error Handling
330330+331331+Servers **SHOULD** return standard JSON-RPC errors for common failure cases:
332332+333333+- Resource not found: `-32002`
334334+- Internal errors: `-32603`
335335+336336+Example error:
337337+338338+```json
339339+{
340340+ "jsonrpc": "2.0",
341341+ "id": 5,
342342+ "error": {
343343+ "code": -32002,
344344+ "message": "Resource not found",
345345+ "data": {
346346+ "uri": "file:///nonexistent.txt"
347347+ }
348348+ }
349349+}
350350+```
351351+352352+## Security Considerations
353353+354354+1. Servers **MUST** validate all resource URIs
355355+2. Access controls **SHOULD** be implemented for sensitive resources
356356+3. Binary data **MUST** be properly encoded
357357+4. Resource permissions **SHOULD** be checked before operations
spec/slash-command.png
This is a binary file and will not be displayed.
+299
spec/tools.md
···11+---
22+title: Tools
33+type: docs
44+weight: 40
55+---
66+77+{{< callout type="info" >}} **Protocol Revision**: 2025-03-26 {{< /callout >}}
88+99+The Model Context Protocol (MCP) allows servers to expose tools that can be invoked by
1010+language models. Tools enable models to interact with external systems, such as querying
1111+databases, calling APIs, or performing computations. Each tool is uniquely identified by
1212+a name and includes metadata describing its schema.
1313+1414+## User Interaction Model
1515+1616+Tools in MCP are designed to be **model-controlled**, meaning that the language model can
1717+discover and invoke tools automatically based on its contextual understanding and the
1818+user's prompts.
1919+2020+However, implementations are free to expose tools through any interface pattern that
2121+suits their needs—the protocol itself does not mandate any specific user
2222+interaction model.
2323+2424+{{< callout type="warning" >}} For trust & safety and security, there **SHOULD** always
2525+be a human in the loop with the ability to deny tool invocations.
2626+2727+Applications **SHOULD**:
2828+2929+- Provide UI that makes clear which tools are being exposed to the AI model
3030+- Insert clear visual indicators when tools are invoked
3131+- Present confirmation prompts to the user for operations, to ensure a human is in the
3232+ loop {{< /callout >}}
3333+3434+## Capabilities
3535+3636+Servers that support tools **MUST** declare the `tools` capability:
3737+3838+```json
3939+{
4040+ "capabilities": {
4141+ "tools": {
4242+ "listChanged": true
4343+ }
4444+ }
4545+}
4646+```
4747+4848+`listChanged` indicates whether the server will emit notifications when the list of
4949+available tools changes.
5050+5151+## Protocol Messages
5252+5353+### Listing Tools
5454+5555+To discover available tools, clients send a `tools/list` request. This operation supports
5656+[pagination]({{< ref "utilities/pagination" >}}).
5757+5858+**Request:**
5959+6060+```json
6161+{
6262+ "jsonrpc": "2.0",
6363+ "id": 1,
6464+ "method": "tools/list",
6565+ "params": {
6666+ "cursor": "optional-cursor-value"
6767+ }
6868+}
6969+```
7070+7171+**Response:**
7272+7373+```json
7474+{
7575+ "jsonrpc": "2.0",
7676+ "id": 1,
7777+ "result": {
7878+ "tools": [
7979+ {
8080+ "name": "get_weather",
8181+ "description": "Get current weather information for a location",
8282+ "inputSchema": {
8383+ "type": "object",
8484+ "properties": {
8585+ "location": {
8686+ "type": "string",
8787+ "description": "City name or zip code"
8888+ }
8989+ },
9090+ "required": ["location"]
9191+ }
9292+ }
9393+ ],
9494+ "nextCursor": "next-page-cursor"
9595+ }
9696+}
9797+```
9898+9999+### Calling Tools
100100+101101+To invoke a tool, clients send a `tools/call` request:
102102+103103+**Request:**
104104+105105+```json
106106+{
107107+ "jsonrpc": "2.0",
108108+ "id": 2,
109109+ "method": "tools/call",
110110+ "params": {
111111+ "name": "get_weather",
112112+ "arguments": {
113113+ "location": "New York"
114114+ }
115115+ }
116116+}
117117+```
118118+119119+**Response:**
120120+121121+```json
122122+{
123123+ "jsonrpc": "2.0",
124124+ "id": 2,
125125+ "result": {
126126+ "content": [
127127+ {
128128+ "type": "text",
129129+ "text": "Current weather in New York:\nTemperature: 72°F\nConditions: Partly cloudy"
130130+ }
131131+ ],
132132+ "isError": false
133133+ }
134134+}
135135+```
136136+137137+### List Changed Notification
138138+139139+When the list of available tools changes, servers that declared the `listChanged`
140140+capability **SHOULD** send a notification:
141141+142142+```json
143143+{
144144+ "jsonrpc": "2.0",
145145+ "method": "notifications/tools/list_changed"
146146+}
147147+```
148148+149149+## Message Flow
150150+151151+```mermaid
152152+sequenceDiagram
153153+ participant LLM
154154+ participant Client
155155+ participant Server
156156+157157+ Note over Client,Server: Discovery
158158+ Client->>Server: tools/list
159159+ Server-->>Client: List of tools
160160+161161+ Note over Client,LLM: Tool Selection
162162+ LLM->>Client: Select tool to use
163163+164164+ Note over Client,Server: Invocation
165165+ Client->>Server: tools/call
166166+ Server-->>Client: Tool result
167167+ Client->>LLM: Process result
168168+169169+ Note over Client,Server: Updates
170170+ Server--)Client: tools/list_changed
171171+ Client->>Server: tools/list
172172+ Server-->>Client: Updated tools
173173+```
174174+175175+## Data Types
176176+177177+### Tool
178178+179179+A tool definition includes:
180180+181181+- `name`: Unique identifier for the tool
182182+- `description`: Human-readable description of functionality
183183+- `inputSchema`: JSON Schema defining expected parameters
184184+- `annotations`: optional properties describing tool behavior
185185+186186+{{< callout type="warning" >}} For trust & safety and security, clients **MUST** consider
187187+tool annotations to be untrusted unless they come from trusted servers. {{< /callout >}}
188188+189189+### Tool Result
190190+191191+Tool results can contain multiple content items of different types:
192192+193193+#### Text Content
194194+195195+```json
196196+{
197197+ "type": "text",
198198+ "text": "Tool result text"
199199+}
200200+```
201201+202202+#### Image Content
203203+204204+```json
205205+{
206206+ "type": "image",
207207+ "data": "base64-encoded-data",
208208+ "mimeType": "image/png"
209209+}
210210+```
211211+212212+#### Audio Content
213213+214214+```json
215215+{
216216+ "type": "audio",
217217+ "data": "base64-encoded-audio-data",
218218+ "mimeType": "audio/wav"
219219+}
220220+```
221221+222222+#### Embedded Resources
223223+224224+[Resources]({{< ref "resources" >}}) **MAY** be embedded, to provide additional context
225225+or data, behind a URI that can be subscribed to or fetched again by the client later:
226226+227227+```json
228228+{
229229+ "type": "resource",
230230+ "resource": {
231231+ "uri": "resource://example",
232232+ "mimeType": "text/plain",
233233+ "text": "Resource content"
234234+ }
235235+}
236236+```
237237+238238+## Error Handling
239239+240240+Tools use two error reporting mechanisms:
241241+242242+1. **Protocol Errors**: Standard JSON-RPC errors for issues like:
243243+244244+ - Unknown tools
245245+ - Invalid arguments
246246+ - Server errors
247247+248248+2. **Tool Execution Errors**: Reported in tool results with `isError: true`:
249249+ - API failures
250250+ - Invalid input data
251251+ - Business logic errors
252252+253253+Example protocol error:
254254+255255+```json
256256+{
257257+ "jsonrpc": "2.0",
258258+ "id": 3,
259259+ "error": {
260260+ "code": -32602,
261261+ "message": "Unknown tool: invalid_tool_name"
262262+ }
263263+}
264264+```
265265+266266+Example tool execution error:
267267+268268+```json
269269+{
270270+ "jsonrpc": "2.0",
271271+ "id": 4,
272272+ "result": {
273273+ "content": [
274274+ {
275275+ "type": "text",
276276+ "text": "Failed to fetch weather data: API rate limit exceeded"
277277+ }
278278+ ],
279279+ "isError": true
280280+ }
281281+}
282282+```
283283+284284+## Security Considerations
285285+286286+1. Servers **MUST**:
287287+288288+ - Validate all tool inputs
289289+ - Implement proper access controls
290290+ - Rate limit tool invocations
291291+ - Sanitize tool outputs
292292+293293+2. Clients **SHOULD**:
294294+ - Prompt for user confirmation on sensitive operations
295295+ - Show tool inputs to the user before calling the server, to avoid malicious or
296296+ accidental data exfiltration
297297+ - Validate tool results before passing to LLM
298298+ - Implement timeouts for tool calls
299299+ - Log tool usage for audit purposes
+278
spec/transports.md
···11+---
22+title: Transports
33+type: docs
44+weight: 10
55+---
66+77+{{< callout type="info" >}} **Protocol Revision**: 2025-03-26 {{< /callout >}}
88+99+MCP uses JSON-RPC to encode messages. JSON-RPC messages **MUST** be UTF-8 encoded.
1010+1111+The protocol currently defines two standard transport mechanisms for client-server
1212+communication:
1313+1414+1. [stdio](#stdio), communication over standard in and standard out
1515+2. [Streamable HTTP](#streamable-http)
1616+1717+Clients **SHOULD** support stdio whenever possible.
1818+1919+It is also possible for clients and servers to implement
2020+[custom transports](#custom-transports) in a pluggable fashion.
2121+2222+## stdio
2323+2424+In the **stdio** transport:
2525+2626+- The client launches the MCP server as a subprocess.
2727+- The server reads JSON-RPC messages from its standard input (`stdin`) and sends messages
2828+ to its standard output (`stdout`).
2929+- Messages may be JSON-RPC requests, notifications, responses—or a JSON-RPC
3030+ [batch](https://www.jsonrpc.org/specification#batch) containing one or more requests
3131+ and/or notifications.
3232+- Messages are delimited by newlines, and **MUST NOT** contain embedded newlines.
3333+- The server **MAY** write UTF-8 strings to its standard error (`stderr`) for logging
3434+ purposes. Clients **MAY** capture, forward, or ignore this logging.
3535+- The server **MUST NOT** write anything to its `stdout` that is not a valid MCP message.
3636+- The client **MUST NOT** write anything to the server's `stdin` that is not a valid MCP
3737+ message.
3838+3939+```mermaid
4040+sequenceDiagram
4141+ participant Client
4242+ participant Server Process
4343+4444+ Client->>+Server Process: Launch subprocess
4545+ loop Message Exchange
4646+ Client->>Server Process: Write to stdin
4747+ Server Process->>Client: Write to stdout
4848+ Server Process--)Client: Optional logs on stderr
4949+ end
5050+ Client->>Server Process: Close stdin, terminate subprocess
5151+ deactivate Server Process
5252+```
5353+5454+## Streamable HTTP
5555+5656+{{< callout type="info" >}} This replaces the [HTTP+SSE
5757+transport]({{< ref "/specification/2024-11-05/basic/transports#http-with-sse" >}}) from
5858+protocol version 2024-11-05. See the [backwards compatibility](#backwards-compatibility)
5959+guide below. {{< /callout >}}
6060+6161+In the **Streamable HTTP** transport, the server operates as an independent process that
6262+can handle multiple client connections. This transport uses HTTP POST and GET requests.
6363+Server can optionally make use of
6464+[Server-Sent Events](https://en.wikipedia.org/wiki/Server-sent_events) (SSE) to stream
6565+multiple server messages. This permits basic MCP servers, as well as more feature-rich
6666+servers supporting streaming and server-to-client notifications and requests.
6767+6868+The server **MUST** provide a single HTTP endpoint path (hereafter referred to as the
6969+**MCP endpoint**) that supports both POST and GET methods. For example, this could be a
7070+URL like `https://example.com/mcp`.
7171+7272+### Sending Messages to the Server
7373+7474+Every JSON-RPC message sent from the client **MUST** be a new HTTP POST request to the
7575+MCP endpoint.
7676+7777+1. The client **MUST** use HTTP POST to send JSON-RPC messages to the MCP endpoint.
7878+2. The client **MUST** include an `Accept` header, listing both `application/json` and
7979+ `text/event-stream` as supported content types.
8080+3. The body of the POST request **MUST** be one of the following:
8181+ - A single JSON-RPC _request_, _notification_, or _response_
8282+ - An array [batching](https://www.jsonrpc.org/specification#batch) one or more
8383+ _requests and/or notifications_
8484+ - An array [batching](https://www.jsonrpc.org/specification#batch) one or more
8585+ _responses_
8686+4. If the input consists solely of (any number of) JSON-RPC _responses_ or
8787+ _notifications_:
8888+ - If the server accepts the input, the server **MUST** return HTTP status code 202
8989+ Accepted with no body.
9090+ - If the server cannot accept the input, it **MUST** return an HTTP error status code
9191+ (e.g., 400 Bad Request). The HTTP response body **MAY** comprise a JSON-RPC _error
9292+ response_ that has no `id`.
9393+5. If the input contains any number of JSON-RPC _requests_, the server **MUST** either
9494+ return `Content-Type: text/event-stream`, to initiate an SSE stream, or
9595+ `Content-Type: application/json`, to return one JSON object. The client **MUST**
9696+ support both these cases.
9797+6. If the server initiates an SSE stream:
9898+ - The SSE stream **SHOULD** eventually include one JSON-RPC _response_ per each
9999+ JSON-RPC _request_ sent in the POST body. These _responses_ **MAY** be
100100+ [batched](https://www.jsonrpc.org/specification#batch).
101101+ - The server **MAY** send JSON-RPC _requests_ and _notifications_ before sending a
102102+ JSON-RPC _response_. These messages **SHOULD** relate to the originating client
103103+ _request_. These _requests_ and _notifications_ **MAY** be
104104+ [batched](https://www.jsonrpc.org/specification#batch).
105105+ - The server **SHOULD NOT** close the SSE stream before sending a JSON-RPC _response_
106106+ per each received JSON-RPC _request_, unless the [session](#session-management)
107107+ expires.
108108+ - After all JSON-RPC _responses_ have been sent, the server **SHOULD** close the SSE
109109+ stream.
110110+ - Disconnection **MAY** occur at any time (e.g., due to network conditions).
111111+ Therefore:
112112+ - Disconnection **SHOULD NOT** be interpreted as the client cancelling its request.
113113+ - To cancel, the client **SHOULD** explicitly send an MCP `CancelledNotification`.
114114+ - To avoid message loss due to disconnection, the server **MAY** make the stream
115115+ [resumable](#resumability-and-redelivery).
116116+117117+### Listening for Messages from the Server
118118+119119+1. The client **MAY** issue an HTTP GET to the MCP endpoint. This can be used to open an
120120+ SSE stream, allowing the server to communicate to the client, without the client first
121121+ sending data via HTTP POST.
122122+2. The client **MUST** include an `Accept` header, listing `text/event-stream` as a
123123+ supported content type.
124124+3. The server **MUST** either return `Content-Type: text/event-stream` in response to
125125+ this HTTP GET, or else return HTTP 405 Method Not Allowed, indicating that the server
126126+ does not offer an SSE stream at this endpoint.
127127+4. If the server initiates an SSE stream:
128128+ - The server **MAY** send JSON-RPC _requests_ and _notifications_ on the stream. These
129129+ _requests_ and _notifications_ **MAY** be
130130+ [batched](https://www.jsonrpc.org/specification#batch).
131131+ - These messages **SHOULD** be unrelated to any concurrently-running JSON-RPC
132132+ _request_ from the client.
133133+ - The server **MUST NOT** send a JSON-RPC _response_ on the stream **unless**
134134+ [resuming](#resumability-and-redelivery) a stream associated with a previous client
135135+ request.
136136+ - The server **MAY** close the SSE stream at any time.
137137+ - The client **MAY** close the SSE stream at any time.
138138+139139+### Multiple Connections
140140+141141+1. The client **MAY** remain connected to multiple SSE streams simultaneously.
142142+2. The server **MUST** send each of its JSON-RPC messages on only one of the connected
143143+ streams; that is, it **MUST NOT** broadcast the same message across multiple streams.
144144+ - The risk of message loss **MAY** be mitigated by making the stream
145145+ [resumable](#resumability-and-redelivery).
146146+147147+### Resumability and Redelivery
148148+149149+To support resuming broken connections, and redelivering messages that might otherwise be
150150+lost:
151151+152152+1. Servers **MAY** attach an `id` field to their SSE events, as described in the
153153+ [SSE standard](https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation).
154154+ - If present, the ID **MUST** be globally unique across all streams within that
155155+ [session](#session-management)—or all streams with that specific client, if session
156156+ management is not in use.
157157+2. If the client wishes to resume after a broken connection, it **SHOULD** issue an HTTP
158158+ GET to the MCP endpoint, and include the
159159+ [`Last-Event-ID`](https://html.spec.whatwg.org/multipage/server-sent-events.html#the-last-event-id-header)
160160+ header to indicate the last event ID it received.
161161+ - The server **MAY** use this header to replay messages that would have been sent
162162+ after the last event ID, _on the stream that was disconnected_, and to resume the
163163+ stream from that point.
164164+ - The server **MUST NOT** replay messages that would have been delivered on a
165165+ different stream.
166166+167167+In other words, these event IDs should be assigned by servers on a _per-stream_ basis, to
168168+act as a cursor within that particular stream.
169169+170170+### Session Management
171171+172172+An MCP "session" consists of logically related interactions between a client and a
173173+server, beginning with the [initialization phase]({{< ref "lifecycle" >}}). To support
174174+servers which want to establish stateful sessions:
175175+176176+1. A server using the Streamable HTTP transport **MAY** assign a session ID at
177177+ initialization time, by including it in an `Mcp-Session-Id` header on the HTTP
178178+ response containing the `InitializeResult`.
179179+ - The session ID **SHOULD** be globally unique and cryptographically secure (e.g., a
180180+ securely generated UUID, a JWT, or a cryptographic hash).
181181+ - The session ID **MUST** only contain visible ASCII characters (ranging from 0x21 to
182182+ 0x7E).
183183+2. If an `Mcp-Session-Id` is returned by the server during initialization, clients using
184184+ the Streamable HTTP transport **MUST** include it in the `Mcp-Session-Id` header on
185185+ all of their subsequent HTTP requests.
186186+ - Servers that require a session ID **SHOULD** respond to requests without an
187187+ `Mcp-Session-Id` header (other than initialization) with HTTP 400 Bad Request.
188188+3. The server **MAY** terminate the session at any time, after which it **MUST** respond
189189+ to requests containing that session ID with HTTP 404 Not Found.
190190+4. When a client receives HTTP 404 in response to a request containing an
191191+ `Mcp-Session-Id`, it **MUST** start a new session by sending a new `InitializeRequest`
192192+ without a session ID attached.
193193+5. Clients that no longer need a particular session (e.g., because the user is leaving
194194+ the client application) **SHOULD** send an HTTP DELETE to the MCP endpoint with the
195195+ `Mcp-Session-Id` header, to explicitly terminate the session.
196196+ - The server **MAY** respond to this request with HTTP 405 Method Not Allowed,
197197+ indicating that the server does not allow clients to terminate sessions.
198198+199199+### Sequence Diagram
200200+201201+```mermaid
202202+sequenceDiagram
203203+ participant Client
204204+ participant Server
205205+206206+ note over Client, Server: initialization
207207+208208+ Client->>+Server: POST InitializeRequest
209209+ Server->>-Client: InitializeResponse<br>Mcp-Session-Id: 1868a90c...
210210+211211+ Client->>+Server: POST InitializedNotification<br>Mcp-Session-Id: 1868a90c...
212212+ Server->>-Client: 202 Accepted
213213+214214+ note over Client, Server: client requests
215215+ Client->>+Server: POST ... request ...<br>Mcp-Session-Id: 1868a90c...
216216+217217+ alt single HTTP response
218218+ Server->>Client: ... response ...
219219+ else server opens SSE stream
220220+ loop while connection remains open
221221+ Server-)Client: ... SSE messages from server ...
222222+ end
223223+ Server-)Client: SSE event: ... response ...
224224+ end
225225+ deactivate Server
226226+227227+ note over Client, Server: client notifications/responses
228228+ Client->>+Server: POST ... notification/response ...<br>Mcp-Session-Id: 1868a90c...
229229+ Server->>-Client: 202 Accepted
230230+231231+ note over Client, Server: server requests
232232+ Client->>+Server: GET<br>Mcp-Session-Id: 1868a90c...
233233+ loop while connection remains open
234234+ Server-)Client: ... SSE messages from server ...
235235+ end
236236+ deactivate Server
237237+238238+```
239239+240240+### Backwards Compatibility
241241+242242+Clients and servers can maintain backwards compatibility with the deprecated [HTTP+SSE
243243+transport]({{< ref "/specification/2024-11-05/basic/transports#http-with-sse" >}}) (from
244244+protocol version 2024-11-05) as follows:
245245+246246+**Servers** wanting to support older clients should:
247247+248248+- Continue to host both the SSE and POST endpoints of the old transport, alongside the
249249+ new "MCP endpoint" defined for the Streamable HTTP transport.
250250+ - It is also possible to combine the old POST endpoint and the new MCP endpoint, but
251251+ this may introduce unneeded complexity.
252252+253253+**Clients** wanting to support older servers should:
254254+255255+1. Accept an MCP server URL from the user, which may point to either a server using the
256256+ old transport or the new transport.
257257+2. Attempt to POST an `InitializeRequest` to the server URL, with an `Accept` header as
258258+ defined above:
259259+ - If it succeeds, the client can assume this is a server supporting the new Streamable
260260+ HTTP transport.
261261+ - If it fails with an HTTP 4xx status code (e.g., 405 Method Not Allowed or 404 Not
262262+ Found):
263263+ - Issue a GET request to the server URL, expecting that this will open an SSE stream
264264+ and return an `endpoint` event as the first event.
265265+ - When the `endpoint` event arrives, the client can assume this is a server running
266266+ the old HTTP+SSE transport, and should use that transport for all subsequent
267267+ communication.
268268+269269+## Custom Transports
270270+271271+Clients and servers **MAY** implement additional custom transport mechanisms to suit
272272+their specific needs. The protocol is transport-agnostic and can be implemented over any
273273+communication channel that supports bidirectional message exchange.
274274+275275+Implementers who choose to support custom transports **MUST** ensure they preserve the
276276+JSON-RPC message format and lifecycle requirements defined by MCP. Custom transports
277277+**SHOULD** document their specific connection establishment and message exchange patterns
278278+to aid interoperability.