Add 'packages/mcp-spec/' from commit 'd06853c5e8'

git-subtree-dir: packages/mcp-spec
git-subtree-mainline: 02e421c1f1
git-subtree-split: d06853c5e8
This commit is contained in:
David Soria Parra 2024-09-24 21:56:32 +01:00
commit 929275eddf
No known key found for this signature in database
5 changed files with 4596 additions and 53 deletions

5
packages/mcp-spec/docs/guide/_index.md generated Normal file
View file

@ -0,0 +1,5 @@
---
title: Guide
cascade:
type: docs
---

171
packages/mcp-spec/docs/spec/_index.md generated Normal file
View file

@ -0,0 +1,171 @@
---
title: Model Cotext Protocol Specification
cascade:
type: docs
---
_**NOTE:** This is a very early draft. Feel free to discuss changes, requirements, etc._
# Goal
The Model Context Protocol (MCP) is an attempt to allow implementors to provide context to various LLM surfaces such as editors/IDEs, [claude.ai](https://claude.ai), etc., in a pluggable way. It separates the concerns of providing context from the LLM loop and its usage within.
This makes it **much** easier for anyone to script LLM applications for accomplishing their custom workflows, without the application needing to directly offer a large number of integrations.
# Terminology
The Model Context Protocol is inspired by Microsoft's [Language Server Protocol](https://microsoft.github.io/language-server-protocol/), with similar concepts:
* **Server**: a process or service providing context via MCP.
* **Client**: the initiator and client connection to a single MCP server. A message sent through a client is always directed to its one corresponding server.
* **Host**: a process or service which runs any number of MCP clients. [For example, your editor might be a host, claude.ai might be a host, etc.](#example-hosts)
* **Session**: a stateful session established between one client and server.
* **Message**: a message refers to one of the following types of [JSON-RPC](https://www.jsonrpc.org/) object:
* **Request:** a request includes a `method` and `params`, and can be sent by either the server or the client, asking the other for some information or to perform some operation.
* **Response:** a response includes a `result` or an `error`, and is sent *back* after a request, once processing has finished (successfully or unsuccessfully).
* **Notification:** a special type of a request that does not expect a response, notifications are emitted by either the server or client to unilaterally inform the other of an event or state change.
* **Capability**: a feature that the client or server supports. When an MCP connection is initiated, the client and server negotiate the capabilities that they both support, which affects the rest of the interaction.
## Primitives
On top of the base protocol, MCP introduces these unique primitives:
* **Resources**: anything that can be loaded as context for an LLM. *Servers* expose a list of resources, identified with [URIs](https://en.wikipedia.org/wiki/Uniform_Resource_Identifier), which the *client* can choose to read or (if supported) subscribe to. Resources can be text or binary data—there are no restrictions on their content.
* **Prompts**: prompts or prompt templates that the *server* can provide to the *client*, which the client can easily surface in the UI (e.g., as some sort of slash command).
* **Tools**: functionality that the *client* can invoke on the *server*, to perform effectful operations. The client can choose to [expose these tools directly to the LLM](https://docs.anthropic.com/en/docs/build-with-claude/tool-use) too, allowing it to decide when and how to use them.
* **Sampling**: *servers* can ask the *client* to sample from the LLM, which allows servers to implement agentic behaviors without having to implement sampling themselves. This also allows the client to combine the sampling request with *all of the other context it has*, making it much more intelligent—while avoiding needlessly exfiltrating information to servers.
```mermaid
flowchart LR
server["Server\n<i>Script on local machine, web service, etc.</i>"]
host["Host (client)\n<i>Editors, claude.ai, etc.</i>"]
host -->|"resource queries"| server
host -->|"invoke tools"| server
server -->|"sampling"| host
server -.->|"prompt templates"| host
server -.->|"resource contents"| host
```
## Control
In addition to basic primitives, MCP offers a set of control flow messages.
* **Logging:** Anything related to how the server processes logs.
* **Completion**: Supports completion of server arguments on the client side. See
# Use cases
Most use cases are around enabling people to build their own specific workflows and integrations. MCP enables engineers and teams to **tailor AI to their needs.**
The beauty of the Model Context Protocol is that it's **extremely composable**. You can imagine mixing and matching *any number* of the example servers below with any one of the hosts. Each individual server can be quite simple and limited, but *composed together*, you can get a super-powered AI!
## Example servers
* **File watcher**: read entire local directories, exposed as resources, and subscribe to changes. The server can provide a tool to write changes back to disk too!
* **Screen watcher**: follow along with the user, taking screenshots automatically, and exposing those as resources. The host can use this to automatically attach screen captures to LLM context.
* **Git integration**: could expose context like Git commit history, but probably *most* useful as a source of tools, like: "commit these changes," "merge this and resolve conflicts," etc.
* **GitHub integration**: read and expose GitHub resources: files, commits, pull requests, issues, etc. Could also expose one or more tools to modify GitHub resources, like "create a PR."
* **Asana integration**: similarly to GitHub—read/write Asana projects, tasks, etc.
* **Slack integration**: read context from Slack channels. Could also look for specially tagged messages, or invocations of [shortcuts](https://api.slack.com/interactivity/shortcuts), as sources of context. Could expose tools to post messages to Slack.
* **Google Workspace integration**: read and write emails, docs, etc.
* **IDEs and editors**: IDEs and editors can be [servers](#example-hosts-clients) as well as hosts! As servers, they can be a rich source of context like: output/status of tests, [ASTs](https://en.wikipedia.org/wiki/Abstract_syntax_tree) and parse trees, and "which files are currently open and being edited?"
A key design principle of MCP is that it should be *as simple as possible* to implement a server. We want anyone to be able to write, e.g., a local Python script of 100 or fewer lines and get a fully functioning server, with capabilities comparable to any of the above.
## Example hosts
* **IDEs and editors**: An MCP host inside an IDE or editor could support attaching any number of servers, which can be used to populate an in-editor LLM chat interface, as well as (e.g.) contextualize refactoring. In future, we could also imagine populating editors' command palette with all of the tools that MCP servers have made available.
* **claude.ai**: [Claude.ai](https://claude.ai) can become an MCP host, allowing users to connect any number of MCP servers. Resources from those servers could be automatically made available for attaching to any Project or Chat. Claude could also make use of the tools exposed by MCP servers to implement agentic behaviors, saving artifacts to disk or to web services, etc.!
* **Slack**: [Claude in Slack](https://www.anthropic.com/claude-in-slack) on steroids! Building an MCP host into Slack would open the door to much more complex interactions with LLMs via the platform—both in being able to read context from any number of places (for example, all the servers posited above), as well as being able to *take actions*, from Slack, via the tools that MCP servers expose.
# Protocol
## Initialization
MCP [sessions](lifecycle) begin with an initialization phase, where the client and server identify each other, and exchange information about their respective [capabilities](lifecycle#capability-descriptions).
The client can only begin requesting resources and invoking tools on the server, and the server can only begin requesting LLM sampling, after the client has issued the `initialized` notification:
```mermaid
sequenceDiagram
participant client as Client
participant server as Server
activate client
client -->>+ server: (connect over transport)
client -->> server: initialize
server -->> client: initialize_response
client --) server: initialized (notification)
loop while connected
alt client to server
client -->> server: request
server -->> client: response
else
client --) server: notification
else server to client
server -->> client: request
client -->> server: response
else
server --) client: notification
end
end
deactivate server
deactivate client
```
## Transports
An MCP server or client must implement one of the following transports. Different transports require different clients (but each can run within the same *host*).
### stdio
The client spawns the server process and manages its lifetime, and writes messages to it on the server's stdin. The server writes messages back to the client on its stdout.
Individual JSON-RPC messages are sent as newline-terminated JSON over the interface.
Anything the server writes to stderr MAY be captured as logging, but the client is also allowed to ignore it completely.
### SSE
A client can open a [Server-Sent Events](https://en.wikipedia.org/wiki/Server-sent_events) connection to a server, which the server will use to push all of its requests and responses to the client.
Upon connection, the server MUST issue a `endpoint` event (which is specific to MCP, not a default SSE event). The `data` associated with an `endpoint` event MUST be a URI for the client to use. The endpoint can be a relative or an absolute URI, but MUST always point to the same server origin. Cross-origin endpoints are not allowed, for security.
The client MUST issue individual JSON-RPC messages through the endpoint identified by the server, using HTTP POST requests—this allows the server to link these out-of-band messages with the ongoing SSE stream.
In turn, `message` events on the SSE stream will contain individual JSON-RPC messages from the server. The server MUST NOT send a `message` event until after the `endpoint` event has been issued.
This sequence diagram shows the MCP initialization flow over SSE, followed by open-ended communication between client and server, until ultimately the client disconnects:
```mermaid
sequenceDiagram
participant client as MCP Client
participant server as MCP Server
activate client
client->>+server: new EventSource("https://server/mcp")
server->>client: event: endpoint<br />data: /session?id=8cfc516c-…
client-->>server: POST https://server/session?id=…<br />{InitializeRequest}
server->>client: event: message<br />data: {InitializeResponse}
client--)server: POST https://server/session?id=…<br />{InitializedNotification}
loop client requests and responses
client--)server: POST https://server/session?id=…<br />{…}
end
loop server requests and responses
server-)client: event: message<br />data: {…}
end
client -x server: EventSource.close()
deactivate server
deactivate client
```
## Security and T&S considerations
This model, while making meaningful changes to productivity and product experience, is effectively a form of arbitrary data access and arbitrary code execution.
**Every interaction between MCP host and server will need informed user consent.** For example:
* Servers must only expose user data as [resources](resources) with the user's explicit consent. Hosts must not transmit that data elsewhere without the user's explicit consent.
* Hosts must not invoke tools on servers without the user's explicit consent, and understanding of what the tool will do.
* When a server initiates [sampling](sampling) via a host, the user must have control over:
* *Whether* sampling even occurs. (They may not want to be charged!)
* What the prompt that will actually be sampled is.
* *What the server sees* of the completion when sampling finishes.
This latter point is why the sampling primitives do not permit MCP servers to see the whole prompt—instead, the host remains in control, and can censor or modify it at will.

79
packages/mcp-spec/docs/spec/jsonrpc.md generated Normal file
View file

@ -0,0 +1,79 @@
---
title: Base Protocol
type: docs
weight: 1
---
The Model Context Protocol (MCP) defines a set of JSON-RPC methods for communication between clients and servers in AI-assisted applications. MCP uses [JSON-RPC 2.0](https://www.jsonrpc.org/specification) as its base protocol.
### Transport
MCP client **SHOULD** use one of the following transport mechanisms, but are free to use alternative transports where applicable.:
Standard Input/Output (STDIO)
: Communication occurs through the standard input and output streams. JSON-RPC
messages are sent as individual lines over these streams. Each message is a
complete JSON object serialized as a single line of text, terminated by a
newline character. The client writes requests to the server's standard input
and reads responses from the server's standard output. See [transports](transports.md) for more details.
HTTP with Server-Sent Events (SSE)
: This transport uses HTTP (1.1 or above) as the underlying protocol. The client sends
requests to the server using standard HTTP POST requests with JSON-RPC
payloads. For server-to-client communication, Server-Sent Events (SSE) are
employed. The server keeps an open connection to the client and sends
messages as SSE events. See [transports](transports.md) for more details.
### Message Format
All messages in MCP **MUST** follow the [JSON-RPC 2.0](https://www.jsonrpc.org/specification) specification. The protocol defines three types of messages:
1. Requests
2. Responses
3. Notifications
#### Requests
Requests are sent from the client to the server or vice versa. They **MUST** include a unique `id` and expect a response.
#### Responses
Responses are sent in reply to requests. They **MUST** include the same `id` as the corresponding request.
#### Notifications
Notifications are sent from the client to the server or vice versa. They do not expect a response and **MUST NOT** include an `id`.
### Base Protocol
The base protocol consists of the following JSON-RPC methods:
- `initialize`: Sent from the client to the server to initialize the connection.
- `initialized`: Sent from the client to the server after initialization is complete.
- `ping`: Sent by either party to check if the other is still alive.
Implementations **MUST** support these base protocol methods.
### Model Context Protocol specific methods
MCP defines methods based on JSON-RPC that clients and servers implement:
- [Lifecycle](lifecycle.md) handling
- [Resource](resources.md) management
- [Prompt](prompts.md) handling
- [Tool](tools.md) execution
- [Logging](logging.md)
- [Sampling](sampling.md)
### Authentication
Authentication mechanisms are not part of the core MCP specification. Implementations **MAY** provide authentication based on the transport they use..
### Versioning
The MCP version is declared in the `initialize` request and response. Clients and servers **MUST** agree on a compatible protocol version to proceed with communication.
## Specification
The conical specification can be found at [Model Context Protocol](http://github.com/modelcontextprotocol/spec/tree/main/spec/schema.ts). The specification of the data format
is available in TypeScript (source of truth) and JSON Schema format (generated).

205
packages/mcp-spec/docs/spec/lifecycle.md generated Normal file
View file

@ -0,0 +1,205 @@
---
title: Lifecycle Management
type: docs
weight: 2
---
The Model Context Protocol defines a specific lifecycle for client-server interactions. This lifecycle consists of the following stages:
Initialization
: The client sends an `initialize` request to the server, initiating the connection.
Capability Exchange
: The client and server exchange information about their supported features and protocol versions.
Normal Operation
: After successful initialization, the client and server can freely communicate using the agreed-upon protocol.
Shutdown
: The connection is terminated, typically initiated by the client when it no longer needs the server's services.
The initialization sequence in the Model Context Protocol follows these steps:
```mermaid
sequenceDiagram
participant Client
participant Server
Client->>Server: initialize request
Note over Client,Server: Includes protocol version, client capabilities
Server->>Client: InitializeResult
Note over Client,Server: Includes protocol version, server capabilities
Client->>Server: initialized notification
Note over Client,Server: Signals completion of initialization
rect rgb(200, 220, 240)
Note over Client,Server: Normal Operation
Client->>Server: Various requests (e.g., list resources, get prompts)
Server->>Client: Responses
Server->>Client: Requests (e.g., LLM sampling)
Client->>Server: Responses
end
Client->>Server: Shutdown (implementation-specific)
```
This sequence ensures that both parties are aware of each other's capabilities and agree on the protocol version to be used for further communication.
# Details
## Initialization
The initialization process **MUST** begin with the client sending an `initialize` request to the server. This request **MUST** include:
- The *protocol version* supported by the client as a numeric integer
- The client's capabilities
- Information about the client implementation
{{<tabs items="Spec (TS),Example">}}
{{<tab>}}
```typescript
export interface InitializeRequest extends Request {
method: "initialize";
params: {
protocolVersion: number;
capabilities: ClientCapabilities;
clientInfo: Implementation;
};
}
```
{{</tab>}}
{{<tab>}}
```json
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": 1,
"capabilities": {
"experimental": {},
"sampling": {}
},
"clientInfo": {
"name": "ExampleClient",
"version": "1.0.0"
}
}
}
```
{{</tab>}}
{{</tabs>}}
The server **MUST** respond to the initialize request with an `InitializeResult`. This response **MUST** include:
- The *protocol version* the server will use
- The server's capabilities
- Information about the server implementation
{{<tabs items="Spec (TS),Example">}}
{{<tab>}}
```typescript
export interface InitializeResult extends Result {
protocolVersion: number;
capabilities: ServerCapabilities;
serverInfo: Implementation;
}
```
{{</tab>}}
{{<tab>}}
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": 1,
"capabilities": {
"experimental": {},
"logging": {},
"prompts": {},
"resources": {
"subscribe": true
},
"tools": {}
},
"serverInfo": {
"name": "ExampleServer",
"version": "1.0.0"
}
}
}
```
{{</tab>}}
{{</tabs>}}
If the server cannot support the protocol version requested by the client, it **SHOULD** respond with an error.
## Capability Exchange
During the initialization process, both the client and server exchange their capabilities. This allows each party to understand what features and operations are supported by the other.
The client's capabilities are sent in the `initialize` request:
```typescript
export interface ClientCapabilities {
experimental?: { [key: string]: object };
sampling?: {};
}
```
The server's capabilities are sent in the `InitializeResult`:
```typescript
export interface ServerCapabilities {
experimental?: { [key: string]: object };
logging?: {};
prompts?: {};
resources?: {
subscribe?: boolean;
};
tools?: {};
}
```
Both parties **SHOULD** respect the capabilities declared by the other and **SHOULD NOT** attempt to use features that are not supported.
### Capability Descriptions
Client Capabilities:
- `experimental`: An object containing any experimental, non-standard capabilities supported by the client.
- `sampling`: If present, indicates that the client supports sampling from an LLM.
Server Capabilities:
- `experimental`: An object containing any experimental, non-standard capabilities supported by the server.
- `logging`: If present, indicates that the server supports controlling logging from client side.
- `prompts`: If present, indicates that the server offers prompt templates.
- `resources`: If present, indicates that the server offers resources to read. The `subscribe` property within this object indicates whether the server supports subscribing to resource updates.
- `tools`: If present, indicates that the server offers tools to call.
These capabilities allow the client and server to communicate their supported features, enabling them to adapt their behavior accordingly and utilize the full range of supported functionalities during their interaction.
## Normal Operation
After successful initialization, the client **MUST** send an `initialized` notification to the server:
```typescript
export interface InitializedNotification extends Notification {
method: "notifications/initialized";
}
```
Once the server receives this notification, both client and server can begin normal operation. During this phase:
1. The client **MAY** send requests to the server for various operations such as listing resources, getting prompts, or calling tools.
2. The server **MAY** send requests to the client for operations like sampling from an LLM.
3. Either party **MAY** send notifications to the other as needed.
Both parties **MUST** be prepared to handle requests and notifications at any time during normal operation.
## Shutdown
The Model Context Protocol does not define a specific shutdown procedure. However, implementations **SHOULD** consider the following guidelines:
1. The client **SHOULD** initiate the shutdown process when it no longer needs the server's services.
2. The server **SHOULD** gracefully terminate any ongoing operations when a shutdown is initiated.
3. Both parties **SHOULD** ensure that any resources are properly released during shutdown.
Throughout all stages of the lifecycle, both client and server **MUST** adhere to the JSON-RPC 2.0 specification for message formatting and error handling.

148
packages/mcp-spec/docs/spec/prompts.md generated Normal file
View file

@ -0,0 +1,148 @@
---
title: Prompts
type: docs
weight: 3
---
The Prompts API allows clients to retrieve information about available prompts and prompt templates from the server.
## Capabilities
To indicate support for the Prompts API, server and client **MUST** agree on the `prompts` capability in their capabilities during initialization.
## Request example
```mermaid
sequenceDiagram
participant Client
participant Server
Client->>Server: prompts/list
Server-->>Client: ListPromptsResult
Note over Client,Server: Client selects a prompt
Client->>Server: prompts/get
Server-->>Client: GetPromptResult
```
## List Prompts
The client **SHOULD** send a `prompts/list` request to retrieve a list of available prompts and prompt templates from the server.
### Request
- method: "prompts/list"
- params: none
### Response
The server **MUST** respond with a `ListPromptsResult` as defined in the TypeScript interface:
```typescript
export interface ListPromptsResult extends Result {
prompts: Prompt[];
}
```
Each `Prompt` object in the `prompts` array **MUST** conform to the following TypeScript interface:
```typescript
export interface Prompt {
name: string;
description?: string;
arguments?: {
name: string;
description?: string;
required?: boolean;
}[];
}
```
The server **MUST** include:
- prompts: An array of `Prompt` objects describing the available prompts/templates
Each `Prompt` object **MUST** contain:
- name: A string identifying the prompt/template
- description: An optional string describing the prompt (if provided)
- arguments: An optional array of argument definitions (if the prompt is a template)
Argument definitions, if present, **MUST** include:
- name: The argument name
- description: An optional description of the argument
- required: An optional boolean indicating if the argument is required
The server **SHOULD** provide descriptive names and descriptions to help clients understand the purpose and usage of each prompt or template.
## Get Prompt
To retrieve a specific prompt or instantiate a prompt template, the client **SHOULD** send a `prompts/get` request.
### Request
- method: "prompts/get"
- params:
- name: The name of the prompt/template to retrieve
- arguments: An optional object containing argument values for templates
### Response
The server **MUST** respond with a `GetPromptResult` containing:
- description: An optional string describing the prompt
- messages: An array of `SamplingMessage` objects representing the prompt content
Each `SamplingMessage` **MUST** have:
- role: Either "user" or "assistant"
- content: Either a text object or an image object
Text content objects **MUST** contain:
- type: "text"
- text: The text content
Image content objects **MUST** contain:
- type: "image"
- data: Base64-encoded image data
- mimeType: The MIME type of the image
Example response:
```json
{
"description": "A prompt for analyzing code quality",
"messages": [
{
"role": "user",
"content": {
"type": "text",
"text": "Please review the following code snippet and provide feedback on its quality and potential improvements:"
}
},
{
"role": "assistant",
"content": {
"type": "text",
"text": "Certainly! I'd be happy to review the code snippet and provide feedback on its quality and potential improvements. Please share the code you'd like me to analyze."
}
},
{
"role": "user",
"content": {
"type": "text",
"text": "{{code}}"
}
}
]
}
```
In this example, `{{code}}` is a placeholder that would be replaced with the actual code snippet when the prompt is used.
## Capabilities
To indicate support for the Prompts API, servers **MUST** include a `prompts` capability in their `ServerCapabilities` during initialization.
Clients **SHOULD** check for this capability before using the Prompts API.