diff --git a/.github/workflows/markdown-format.yml b/.github/workflows/markdown-format.yml new file mode 100644 index 0000000..db069a2 --- /dev/null +++ b/.github/workflows/markdown-format.yml @@ -0,0 +1,26 @@ +name: Markdown Format Check + +on: + push: + paths: + - '**/*.md' + pull_request: + paths: + - '**/*.md' + +jobs: + format: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + + - name: Install dependencies + run: npm ci + + - name: Check markdown formatting + run: npm run format:check \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 05c32c6..49fbcf9 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -2,124 +2,115 @@ ## Our Pledge -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, religion, or sexual identity -and orientation. +We as members, contributors, and leaders pledge to make participation in our community a +harassment-free experience for everyone, regardless of age, body size, visible or +invisible disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal appearance, +race, religion, or sexual identity and orientation. -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, +inclusive, and healthy community. ## Our Standards -Examples of behavior that contributes to a positive environment for our -community include: +Examples of behavior that contributes to a positive environment for our community +include: -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the - overall community +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes, and + learning from the experience +- Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: -* The use of sexualized language or imagery, and sexual attention or - advances of any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email - address, without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting +- The use of sexualized language or imagery, and sexual attention or advances of any kind +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email address, without + their explicit permission +- Other conduct which could reasonably be considered inappropriate in a professional + setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. +acceptable behavior and will take appropriate and fair corrective action in response to +any behavior that they deem inappropriate, threatening, offensive, or harmful. -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. +Community leaders have the right and responsibility to remove, edit, or reject comments, +commits, code, wiki edits, issues, and other contributions that are not aligned to this +Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official e-mail address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. +This Code of Conduct applies within all community spaces, and also applies when an +individual is officially representing the community in public spaces. Examples of +representing our community include using an official e-mail address, posting via an +official social media account, or acting as an appointed representative at an online or +offline event. ## Enforcement -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -mcp-coc@anthropic.com. -All complaints will be reviewed and investigated promptly and fairly. +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to +the community leaders responsible for enforcement at mcp-coc@anthropic.com. All +complaints will be reviewed and investigated promptly and fairly. -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. +All community leaders are obligated to respect the privacy and security of the reporter +of any incident. ## Enforcement Guidelines -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: +Community leaders will follow these Community Impact Guidelines in determining the +consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. +**Consequence**: A private, written warning from community leaders, providing clarity +around the nature of the violation and an explanation of why the behavior was +inappropriate. A public apology may be requested. ### 2. Warning -**Community Impact**: A violation through a single incident or series -of actions. +**Community Impact**: A violation through a single incident or series of actions. -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or -permanent ban. +**Consequence**: A warning with consequences for continued behavior. No interaction with +the people involved, including unsolicited interaction with those enforcing the Code of +Conduct, for a specified period of time. This includes avoiding interactions in community +spaces as well as external channels like social media. Violating these terms may lead to +a temporary or permanent ban. ### 3. Temporary Ban -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. +**Community Impact**: A serious violation of community standards, including sustained +inappropriate behavior. -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. +**Consequence**: A temporary ban from any sort of interaction or public communication +with the community for a specified period of time. No public or private interaction with +the people involved, including unsolicited interaction with those enforcing the Code of +Conduct, is allowed during this period. Violating these terms may lead to a permanent +ban. ### 4. Permanent Ban -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. +**Community Impact**: Demonstrating a pattern of violation of community standards, +including sustained inappropriate behavior, harassment of an individual, or aggression +toward or disparagement of classes of individuals. -**Consequence**: A permanent ban from any sort of public interaction within -the community. +**Consequence**: A permanent ban from any sort of public interaction within the +community. ## Attribution -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 2.0, available at -https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, +available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. -Community Impact Guidelines were inspired by [Mozilla's code of conduct -enforcement ladder](https://github.com/mozilla/diversity). +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 942dcad..b4172ed 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,7 @@ # Contributing to Model Context Protocol -Thank you for your interest in contributing to the Model Context Protocol specification! This document outlines how to contribute to this project. +Thank you for your interest in contributing to the Model Context Protocol specification! +This document outlines how to contribute to this project. ## Prerequisites @@ -17,34 +18,40 @@ The following software is required to work on the spec: 1. Fork the repository 2. Clone your fork: + ```bash git clone https://github.com/YOUR-USERNAME/specification.git cd specification ``` 3. Install dependencies: + ```bash nvm install # install correct Node version npm install # install dependencies ``` ## Making Changes -Note that schema changes are made to `schema.ts`. `schema.json` is generated from `schema.ts` -using `npm run validate:schema`. + +Note that schema changes are made to `schema.ts`. `schema.json` is generated from +`schema.ts` using `npm run validate:schema`. 1. Create a new branch: + ```bash git checkout -b feature/your-feature-name ``` 2. Make your changes 3. Validate your changes: + ```bash npm run validate:schema # validate schema npm run generate:json # generate JSON schema ``` 4. Run docs locally (optional): + ```bash npm run serve:docs ``` @@ -58,7 +65,8 @@ npm run serve:docs ## Code of Conduct -This project follows a Code of Conduct. Please review it in [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md). +This project follows a Code of Conduct. Please review it in +[CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md). ## Questions @@ -66,7 +74,8 @@ If you have questions, please create an issue in the repository. ## License -By contributing, you agree that your contributions will be licensed under the MIT License. +By contributing, you agree that your contributions will be licensed under the MIT +License. ## Security diff --git a/README.md b/README.md index bda8953..5ce65af 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,15 @@ This repo contains the specification and protocol schema for the Model Context Protocol. -The schema is [defined in TypeScript](schema/schema.ts) first, but [made available as JSON Schema](schema/schema.json) as well, for wider compatibility. +The schema is [defined in TypeScript](schema/schema.ts) first, but +[made available as JSON Schema](schema/schema.json) as well, for wider compatibility. ## Contributing -Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute to this project. +Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute to this +project. ## License -This project is licensed under the MIT License—see the [LICENSE](LICENSE) file for details. +This project is licensed under the MIT License—see the [LICENSE](LICENSE) file for +details. diff --git a/SECURITY.md b/SECURITY.md index 8c09400..89c2024 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,14 +1,21 @@ # Security Policy + Thank you for helping us keep the SDKs and systems they interact with secure. ## Reporting Security Issues -This SDK is maintained by [Anthropic](https://www.anthropic.com/) as part of the Model Context Protocol project. +This SDK is maintained by [Anthropic](https://www.anthropic.com/) as part of the Model +Context Protocol project. -The security of our systems and user data is Anthropic’s top priority. We appreciate the work of security researchers acting in good faith in identifying and reporting potential vulnerabilities. +The security of our systems and user data is Anthropic’s top priority. We appreciate the +work of security researchers acting in good faith in identifying and reporting potential +vulnerabilities. -Our security program is managed on HackerOne and we ask that any validated vulnerability in this functionality be reported through their [submission form](https://hackerone.com/anthropic-vdp/reports/new?type=team&report_type=vulnerability). +Our security program is managed on HackerOne and we ask that any validated vulnerability +in this functionality be reported through their +[submission form](https://hackerone.com/anthropic-vdp/reports/new?type=team&report_type=vulnerability). ## Vulnerability Disclosure Program -Our Vulnerability Program Guidelines are defined on our [HackerOne program page](https://hackerone.com/anthropic-vdp). +Our Vulnerability Program Guidelines are defined on our +[HackerOne program page](https://hackerone.com/anthropic-vdp). diff --git a/docs/resources/_index.md b/docs/resources/_index.md index 0c54b07..e88f7f4 100644 --- a/docs/resources/_index.md +++ b/docs/resources/_index.md @@ -6,11 +6,23 @@ sidebar: exclude: true --- -The Model Context Protocol (MCP) provides multiple resources for documentation and implementation: +The Model Context Protocol (MCP) provides multiple resources for documentation and +implementation: -- **User Documentation**: Visit [modelcontextprotocol.io](https://modelcontextprotocol.io) for comprehensive user-facing documentation -- **Python SDK**: The Python implementation is available at [github.com/modelcontextprotocol/python-sdk](https://github.com/modelcontextprotocol/python-sdk) - [Discussions](https://github.com/modelcontextprotocol/python-sdk/discussions) -- **Specification**: The core specification is available at [github.com/modelcontextprotocol/specification](https://github.com/modelcontextprotocol/specification) - [Discussions](https://github.com/modelcontextprotocol/specification/discussions) -- **TypeScript SDK**: The TypeScript implementation can be found at [github.com/modelcontextprotocol/typescript-sdk](https://github.com/modelcontextprotocol/typescript-sdk) - [Discussions](https://github.com/modelcontextprotocol/typescript-sdk/discussions) +- **User Documentation**: Visit + [modelcontextprotocol.io](https://modelcontextprotocol.io) for comprehensive + user-facing documentation +- **Python SDK**: The Python implementation is available at + [github.com/modelcontextprotocol/python-sdk](https://github.com/modelcontextprotocol/python-sdk) - + [Discussions](https://github.com/modelcontextprotocol/python-sdk/discussions) +- **Specification**: The core specification is available at + [github.com/modelcontextprotocol/specification](https://github.com/modelcontextprotocol/specification) - + [Discussions](https://github.com/modelcontextprotocol/specification/discussions) +- **TypeScript SDK**: The TypeScript implementation can be found at + [github.com/modelcontextprotocol/typescript-sdk](https://github.com/modelcontextprotocol/typescript-sdk) - + [Discussions](https://github.com/modelcontextprotocol/typescript-sdk/discussions) -For questions or discussions, please open a discussion in the appropriate GitHub repository based on your implementation or use case. You can also visit the [Model Context Protocol organization on GitHub](https://github.com/modelcontextprotocol) to see all repositories and ongoing development. +For questions or discussions, please open a discussion in the appropriate GitHub +repository based on your implementation or use case. You can also visit the +[Model Context Protocol organization on GitHub](https://github.com/modelcontextprotocol) +to see all repositories and ongoing development. diff --git a/docs/specification/2024-11-05/_index.md b/docs/specification/2024-11-05/_index.md index ab427bf..b5ff269 100644 --- a/docs/specification/2024-11-05/_index.md +++ b/docs/specification/2024-11-05/_index.md @@ -8,17 +8,28 @@ aliases: - /latest --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} -[Model Context Protocol](https://modelcontextprotocol.io) (MCP) is an open protocol that enables seamless integration between LLM applications and external data sources and tools. Whether you're building an AI-powered IDE, enhancing a chat interface, or creating custom AI workflows, MCP provides a standardized way to connect LLMs with the context they need. +[Model Context Protocol](https://modelcontextprotocol.io) (MCP) is an open protocol that +enables seamless integration between LLM applications and external data sources and +tools. Whether you're building an AI-powered IDE, enhancing a chat interface, or creating +custom AI workflows, MCP provides a standardized way to connect LLMs with the context +they need. -This specification defines the authoritative protocol requirements, based on the TypeScript schema in [schema.ts](https://github.com/modelcontextprotocol/specification/2024-11-05/blob/main/schema/schema.ts). +This specification defines the authoritative protocol requirements, based on the +TypeScript schema in +[schema.ts](https://github.com/modelcontextprotocol/specification/2024-11-05/blob/main/schema/schema.ts). -For implementation guides and examples, visit [modelcontextprotocol.io](https://modelcontextprotocol.io). +For implementation guides and examples, visit +[modelcontextprotocol.io](https://modelcontextprotocol.io). -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [BCP 14](https://datatracker.ietf.org/doc/html/bcp14) [[RFC2119](https://datatracker.ietf.org/doc/html/rfc2119)] [[RFC8174](https://datatracker.ietf.org/doc/html/rfc8174)] when, and only when, they appear in all capitals, as shown here. +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD +NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be +interpreted as described in [BCP 14](https://datatracker.ietf.org/doc/html/bcp14) +[[RFC2119](https://datatracker.ietf.org/doc/html/rfc2119)] +[[RFC8174](https://datatracker.ietf.org/doc/html/rfc8174)] when, and only when, they +appear in all capitals, as shown here. ## Overview @@ -28,17 +39,23 @@ MCP provides a standardized way for applications to: - Expose tools and capabilities to AI systems - Build composable integrations and workflows -The protocol uses [JSON-RPC](https://www.jsonrpc.org/) 2.0 messages to establish communication between: +The protocol uses [JSON-RPC](https://www.jsonrpc.org/) 2.0 messages to establish +communication between: - **Hosts**: LLM applications that initiate connections - **Clients**: Connectors within the host application - **Servers**: Services that provide context and capabilities -MCP takes some inspiration from the [Language Server Protocol](https://microsoft.github.io/language-server-protocol/), which standardizes how to add support for programming languages across a whole ecosystem of development tools. In a similar way, MCP standardizes how to integrate additional context and tools into the ecosystem of AI applications. +MCP takes some inspiration from the +[Language Server Protocol](https://microsoft.github.io/language-server-protocol/), which +standardizes how to add support for programming languages across a whole ecosystem of +development tools. In a similar way, MCP standardizes how to integrate additional context +and tools into the ecosystem of AI applications. ## Key Details ### Base Protocol + - [JSON-RPC](https://www.jsonrpc.org/) message format - Stateful connections - Server and client capability negotiation @@ -65,22 +82,28 @@ Clients may offer the following feature to servers: ## Security and Trust & Safety -The Model Context Protocol enables powerful capabilities through arbitrary data access and code execution paths. With this power comes important security and trust considerations that all implementors must carefully address. +The Model Context Protocol enables powerful capabilities through arbitrary data access +and code execution paths. With this power comes important security and trust +considerations that all implementors must carefully address. ### Key Principles 1. **User Consent and Control** + - Users must explicitly consent to and understand all data access and operations - Users must retain control over what data is shared and what actions are taken - Implementors should provide clear UIs for reviewing and authorizing activities 2. **Data Privacy** + - Hosts must obtain explicit user consent before exposing user data to servers - Hosts must not transmit resource data elsewhere without user consent - User data should be protected with appropriate access controls 3. **Tool Safety** - - Tools represent arbitrary code execution and must be treated with appropriate caution + + - Tools represent arbitrary code execution and must be treated with appropriate + caution - Hosts must obtain explicit user consent before invoking any tool - Users should understand what each tool does before authorizing its use @@ -94,7 +117,8 @@ The Model Context Protocol enables powerful capabilities through arbitrary data ### Implementation Guidelines -While MCP itself cannot enforce these security principles at the protocol level, implementors **SHOULD**: +While MCP itself cannot enforce these security principles at the protocol level, +implementors **SHOULD**: 1. Build robust consent and authorization flows into their applications 2. Provide clear documentation of security implications @@ -106,10 +130,8 @@ While MCP itself cannot enforce these security principles at the protocol level, Explore the detailed specification for each protocol component: -{{< cards >}} - {{< card link="architecture" title="Architecture" icon="template" >}} - {{< card link="basic" title="Base Protocol" icon="code" >}} - {{< card link="server" title="Server Features" icon="server" >}} - {{< card link="client" title="Client Features" icon="user" >}} - {{< card link="contributing" title="Contributing" icon="pencil" >}} -{{< /cards >}} +{{< cards >}} {{< card link="architecture" title="Architecture" icon="template" >}} +{{< card link="basic" title="Base Protocol" icon="code" >}} +{{< card link="server" title="Server Features" icon="server" >}} +{{< card link="client" title="Client Features" icon="user" >}} +{{< card link="contributing" title="Contributing" icon="pencil" >}} {{< /cards >}} diff --git a/docs/specification/2024-11-05/architecture/_index.md b/docs/specification/2024-11-05/architecture/_index.md index 5f9fa7b..d6f5cf3 100644 --- a/docs/specification/2024-11-05/architecture/_index.md +++ b/docs/specification/2024-11-05/architecture/_index.md @@ -5,7 +5,11 @@ cascade: weight: 1 --- -The Model Context Protocol (MCP) follows a client-host-server architecture where each host can run multiple client instances. This architecture enables users to integrate AI capabilities across applications while maintaining clear security boundaries and isolating concerns. Built on JSON-RPC, MCP provides a stateful session protocol focused on context exchange and sampling coordination between clients and servers. +The Model Context Protocol (MCP) follows a client-host-server architecture where each +host can run multiple client instances. This architecture enables users to integrate AI +capabilities across applications while maintaining clear security boundaries and +isolating concerns. Built on JSON-RPC, MCP provides a stateful session protocol focused +on context exchange and sampling coordination between clients and servers. ## Core Components @@ -43,7 +47,9 @@ graph LR ``` ### Host + The host process acts as the container and coordinator: + - Creates and manages multiple client instances - Controls client connection permissions and lifecycle - Enforces security policies and consent requirements @@ -52,17 +58,22 @@ The host process acts as the container and coordinator: - Manages context aggregation across clients ### Clients + Each client is created by the host and maintains an isolated server connection: + - Establishes one stateful session per server - Handles protocol negotiation and capability exchange - Routes protocol messages bidirectionally - Manages subscriptions and notifications - Maintains security boundaries between servers -A host application creates and manages multiple clients, with each client having a 1:1 relationship with a particular server. +A host application creates and manages multiple clients, with each client having a 1:1 +relationship with a particular server. ### Servers + Servers provide specialized context and capabilities: + - Expose resources, tools and prompts via MCP primitives - Operate independently with focused responsibilities - Request sampling through client interfaces @@ -71,48 +82,59 @@ Servers provide specialized context and capabilities: ## Design Principles -MCP is built on several key design principles that inform its architecture and implementation: +MCP is built on several key design principles that inform its architecture and +implementation: 1. **Servers should be extremely easy to build** - - Host applications handle complex orchestration responsibilities - - Servers focus on specific, well-defined capabilities - - Simple interfaces minimize implementation overhead - - Clear separation enables maintainable code + + - Host applications handle complex orchestration responsibilities + - Servers focus on specific, well-defined capabilities + - Simple interfaces minimize implementation overhead + - Clear separation enables maintainable code 2. **Servers should be highly composable** - - Each server provides focused functionality in isolation - - Multiple servers can be combined seamlessly - - Shared protocol enables interoperability - - Modular design supports extensibility - -3. **Servers should not be able to read the whole conversation, nor "see into" other servers** - - Servers receive only necessary contextual information - - Full conversation history stays with the host - - Each server connection maintains isolation - - Cross-server interactions are controlled by the host - - Host process enforces security boundaries + + - Each server provides focused functionality in isolation + - Multiple servers can be combined seamlessly + - Shared protocol enables interoperability + - Modular design supports extensibility + +3. **Servers should not be able to read the whole conversation, nor "see into" other + servers** + + - Servers receive only necessary contextual information + - Full conversation history stays with the host + - Each server connection maintains isolation + - Cross-server interactions are controlled by the host + - Host process enforces security boundaries 4. **Features can be added to servers and clients progressively** - - Core protocol provides minimal required functionality - - Additional capabilities can be negotiated as needed - - Servers and clients evolve independently - - Protocol designed for future extensibility - - Backwards compatibility is maintained + - Core protocol provides minimal required functionality + - Additional capabilities can be negotiated as needed + - Servers and clients evolve independently + - Protocol designed for future extensibility + - Backwards compatibility is maintained ## Message Types -MCP defines three core message types based on [JSON-RPC 2.0](https://www.jsonrpc.org/specification): + +MCP defines three core message types based on +[JSON-RPC 2.0](https://www.jsonrpc.org/specification): - **Requests**: Bidirectional messages with method and parameters expecting a response - **Responses**: Successful results or errors matching specific request IDs - **Notifications**: One-way messages requiring no response -Each message type follows the JSON-RPC 2.0 specification for structure and delivery semantics. +Each message type follows the JSON-RPC 2.0 specification for structure and delivery +semantics. ## Capability Negotiation -The Model Context Protocol uses a capability-based negotiation system where clients and servers explicitly declare their supported features during initialization. Capabilities determine which protocol features and primitives are available during a session. +The Model Context Protocol uses a capability-based negotiation system where clients and +servers explicitly declare their supported features during initialization. Capabilities +determine which protocol features and primitives are available during a session. -- Servers declare capabilities like resource subscriptions, tool support, and prompt templates +- Servers declare capabilities like resource subscriptions, tool support, and prompt + templates - Clients declare capabilities like sampling support and notification handling - Both parties must respect declared capabilities throughout the session - Additional capabilities can be negotiated through extensions to the protocol @@ -153,10 +175,16 @@ sequenceDiagram deactivate Server ``` -Each capability unlocks specific protocol features for use during the session. For example: -- Implemented [server features]({{< ref "/specification/2024-11-05/server" >}}) must be advertised in the server's capabilities -- Emitting resource subscription notifications requires the server to declare subscription support +Each capability unlocks specific protocol features for use during the session. For +example: + +- Implemented [server features]({{< ref "/specification/2024-11-05/server" >}}) must be + advertised in the server's capabilities +- Emitting resource subscription notifications requires the server to declare + subscription support - Tool invocation requires the server to declare tool capabilities -- [Sampling]({{< ref "/specification/2024-11-05/client" >}}) requires the client to declare support in its capabilities +- [Sampling]({{< ref "/specification/2024-11-05/client" >}}) requires the client to + declare support in its capabilities -This capability negotiation ensures clients and servers have a clear understanding of supported functionality while maintaining protocol extensibility. +This capability negotiation ensures clients and servers have a clear understanding of +supported functionality while maintaining protocol extensibility. diff --git a/docs/specification/2024-11-05/basic/_index.md b/docs/specification/2024-11-05/basic/_index.md index 4ec2903..35b2d5c 100644 --- a/docs/specification/2024-11-05/basic/_index.md +++ b/docs/specification/2024-11-05/basic/_index.md @@ -5,53 +5,70 @@ cascade: weight: 2 --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} -All messages between MCP clients and servers **MUST** follow the [JSON-RPC 2.0](https://www.jsonrpc.org/specification) specification. The protocol defines three fundamental types of messages: +All messages between MCP clients and servers **MUST** follow the +[JSON-RPC 2.0](https://www.jsonrpc.org/specification) specification. The protocol defines +three fundamental types of messages: -| Type | Description | Requirements | -|----------------|----------------------------------------|----------------------------------------| -| `Requests` | Messages sent to initiate an operation | Must include unique ID and method name | -| `Responses` | Messages sent in reply to requests | Must include same ID as request | -| `Notifications`| One-way messages with no reply | Must not include an ID | +| Type | Description | Requirements | +| --------------- | -------------------------------------- | -------------------------------------- | +| `Requests` | Messages sent to initiate an operation | Must include unique ID and method name | +| `Responses` | Messages sent in reply to requests | Must include same ID as request | +| `Notifications` | One-way messages with no reply | Must not include an ID | -**Responses** are further sub-categorized as either **successful results** or **errors**. Results can follow any JSON object structure, while errors must include an error code and message at minimum. +**Responses** are further sub-categorized as either **successful results** or **errors**. +Results can follow any JSON object structure, while errors must include an error code and +message at minimum. ## Protocol Layers The Model Context Protocol consists of several key components that work together: - **Base Protocol**: Core JSON-RPC message types -- **Lifecycle Management**: Connection initialization, capability negotiation, and session control +- **Lifecycle Management**: Connection initialization, capability negotiation, and + session control - **Server Features**: Resources, prompts, and tools exposed by servers - **Client Features**: Sampling and root directory lists provided by clients - **Utilities**: Cross-cutting concerns like logging and argument completion -All implementations **MUST** support the base protocol and lifecycle management components. Other components **MAY** be implemented based on the specific needs of the application. +All implementations **MUST** support the base protocol and lifecycle management +components. Other components **MAY** be implemented based on the specific needs of the +application. -These protocol layers establish clear separation of concerns while enabling rich interactions between clients and servers. The modular design allows implementations to support exactly the features they need. +These protocol layers establish clear separation of concerns while enabling rich +interactions between clients and servers. The modular design allows implementations to +support exactly the features they need. See the following pages for more details on the different components: {{< cards >}} - {{< card link="/specification/2024-11-05/basic/lifecycle" title="Lifecycle" icon="refresh" >}} - {{< card link="/specification/2024-11-05/server/resources" title="Resources" icon="document" >}} - {{< card link="/specification/2024-11-05/server/prompts" title="Prompts" icon="chat-alt-2" >}} - {{< card link="/specification/2024-11-05/server/tools" title="Tools" icon="adjustments" >}} - {{< card link="/specification/2024-11-05/server/utilities/logging" title="Logging" icon="annotation" >}} - {{< card link="/specification/2024-11-05/client/sampling" title="Sampling" icon="code" >}} +{{< card link="/specification/2024-11-05/basic/lifecycle" title="Lifecycle" icon="refresh" >}} +{{< card link="/specification/2024-11-05/server/resources" title="Resources" icon="document" >}} +{{< card link="/specification/2024-11-05/server/prompts" title="Prompts" icon="chat-alt-2" >}} +{{< card link="/specification/2024-11-05/server/tools" title="Tools" icon="adjustments" >}} +{{< card link="/specification/2024-11-05/server/utilities/logging" title="Logging" icon="annotation" >}} +{{< card link="/specification/2024-11-05/client/sampling" title="Sampling" icon="code" >}} {{< /cards >}} ## Auth -Authentication and authorization are not currently part of the core MCP specification, but we are considering ways to introduce them in future. Join us in [GitHub Discussions](https://github.com/modelcontextprotocol/specification/2024-11-05/discussions) to help shape the future of the protocol! +Authentication and authorization are not currently part of the core MCP specification, +but we are considering ways to introduce them in future. Join us in +[GitHub Discussions](https://github.com/modelcontextprotocol/specification/2024-11-05/discussions) +to help shape the future of the protocol! -Clients and servers **MAY** negotiate their own custom authentication and authorization strategies. +Clients and servers **MAY** negotiate their own custom authentication and authorization +strategies. ## Schema -The full specification of the protocol is defined as a [TypeScript schema](http://github.com/modelcontextprotocol/specification/2024-11-05/tree/main/schema/schema.ts). This is the source of truth for all protocol messages and structures. +The full specification of the protocol is defined as a +[TypeScript schema](http://github.com/modelcontextprotocol/specification/2024-11-05/tree/main/schema/schema.ts). +This is the source of truth for all protocol messages and structures. -There is also a [JSON Schema](http://github.com/modelcontextprotocol/specification/2024-11-05/tree/main/schema/schema.json), which is automatically generated from the TypeScript source of truth, for use with various automated tooling. +There is also a +[JSON Schema](http://github.com/modelcontextprotocol/specification/2024-11-05/tree/main/schema/schema.json), +which is automatically generated from the TypeScript source of truth, for use with +various automated tooling. diff --git a/docs/specification/2024-11-05/basic/lifecycle.md b/docs/specification/2024-11-05/basic/lifecycle.md index 789eb4a..41342bb 100644 --- a/docs/specification/2024-11-05/basic/lifecycle.md +++ b/docs/specification/2024-11-05/basic/lifecycle.md @@ -4,11 +4,11 @@ type: docs weight: 30 --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} -The Model Context Protocol (MCP) defines a rigorous lifecycle for client-server connections that ensures proper capability negotiation and state management. +The Model Context Protocol (MCP) defines a rigorous lifecycle for client-server +connections that ensures proper capability negotiation and state management. 1. **Initialization**: Capability negotiation and protocol version agreement 2. **Operation**: Normal protocol communication @@ -40,7 +40,8 @@ sequenceDiagram ### Initialization -The initialization phase **MUST** be the first interaction between client and server. During this phase, the client and server: +The initialization phase **MUST** be the first interaction between client and server. +During this phase, the client and server: - Establish protocol version compatibility - Exchange and negotiate capabilities @@ -102,7 +103,8 @@ The server **MUST** respond with its own capabilities and information: } ``` -After successful initialization, the client **MUST** send an `initialized` notification to indicate it is ready to begin normal operations: +After successful initialization, the client **MUST** send an `initialized` notification +to indicate it is ready to begin normal operations: ```json { @@ -111,41 +113,54 @@ After successful initialization, the client **MUST** send an `initialized` notif } ``` -* The client **SHOULD NOT** send requests other than [pings]({{< ref "/specification/2024-11-05/basic/utilities/ping" >}}) before the server has responded to the `initialize` request. -* The server **SHOULD NOT** send requests other than [pings]({{< ref "/specification/2024-11-05/basic/utilities/ping" >}}) and [logging]({{< ref "/specification/2024-11-05/server/utilities/logging" >}}) before receiving the `initialized` notification. +- The client **SHOULD NOT** send requests other than + [pings]({{< ref "/specification/2024-11-05/basic/utilities/ping" >}}) before the server + has responded to the `initialize` request. +- The server **SHOULD NOT** send requests other than + [pings]({{< ref "/specification/2024-11-05/basic/utilities/ping" >}}) and + [logging]({{< ref "/specification/2024-11-05/server/utilities/logging" >}}) before + receiving the `initialized` notification. #### Version Negotiation -In the `initialize` request, the client **MUST** send a protocol version it supports. This **SHOULD** be the _latest_ version supported by the client. +In the `initialize` request, the client **MUST** send a protocol version it supports. +This **SHOULD** be the _latest_ version supported by the client. -If the server supports the requested protocol version, it **MUST** respond with the same version. Otherwise, the server **MUST** respond with another protocol version it supports. This **SHOULD** be the _latest_ version supported by the server. +If the server supports the requested protocol version, it **MUST** respond with the same +version. Otherwise, the server **MUST** respond with another protocol version it +supports. This **SHOULD** be the _latest_ version supported by the server. -If the client does not support the version in the server's response, it **SHOULD** disconnect. +If the client does not support the version in the server's response, it **SHOULD** +disconnect. #### Capability Negotiation -Client and server capabilities establish which optional protocol features will be available during the session. +Client and server capabilities establish which optional protocol features will be +available during the session. Key capabilities include: -| Category | Capability | Description | -|----------|--------------- |-------------| -| Client | `roots` | Ability to provide filesystem [roots]({{< ref "/specification/2024-11-05/client/roots" >}}) | -| Client | `sampling` | Support for LLM [sampling]({{< ref "/specification/2024-11-05/client/sampling" >}}) requests | -| Client | `experimental` | Describes support for non-standard experimental features | -| Server | `prompts` | Offers [prompt templates]({{< ref "/specification/2024-11-05/server/prompts" >}}) | -| Server | `resources` | Provides readable [resources]({{< ref "/specification/2024-11-05/server/resources" >}}) | -| Server | `tools` | Exposes callable [tools]({{< ref "/specification/2024-11-05/server/tools" >}}) | +| Category | Capability | Description | +| -------- | -------------- | ------------------------------------------------------------------------------------------------- | +| Client | `roots` | Ability to provide filesystem [roots]({{< ref "/specification/2024-11-05/client/roots" >}}) | +| Client | `sampling` | Support for LLM [sampling]({{< ref "/specification/2024-11-05/client/sampling" >}}) requests | +| Client | `experimental` | Describes support for non-standard experimental features | +| Server | `prompts` | Offers [prompt templates]({{< ref "/specification/2024-11-05/server/prompts" >}}) | +| Server | `resources` | Provides readable [resources]({{< ref "/specification/2024-11-05/server/resources" >}}) | +| Server | `tools` | Exposes callable [tools]({{< ref "/specification/2024-11-05/server/tools" >}}) | | Server | `logging` | Emits structured [log messages]({{< ref "/specification/2024-11-05/server/utilities/logging" >}}) | -| Server | `experimental` | Describes support for non-standard experimental features | +| Server | `experimental` | Describes support for non-standard experimental features | Capability objects can describe sub-capabilities like: -- `listChanged`: Support for list change notifications (for prompts, resources, and tools) + +- `listChanged`: Support for list change notifications (for prompts, resources, and + tools) - `subscribe`: Support for subscribing to individual items' changes (resources only) ### Operation -During the operation phase, the client and server exchange messages according to the negotiated capabilities. +During the operation phase, the client and server exchange messages according to the +negotiated capabilities. Both parties **SHOULD**: @@ -154,21 +169,27 @@ Both parties **SHOULD**: ### Shutdown -During the shutdown phase, one side (usually the client) cleanly terminates the protocol connection. No specific shutdown messages are defined—instead, the underlying transport mechanism should be used to signal connection termination: +During the shutdown phase, one side (usually the client) cleanly terminates the protocol +connection. No specific shutdown messages are defined—instead, the underlying transport +mechanism should be used to signal connection termination: #### stdio -For the stdio [transport]({{< ref "/specification/2024-11-05/basic/transports" >}}), the client **SHOULD** initiate shutdown by: +For the stdio [transport]({{< ref "/specification/2024-11-05/basic/transports" >}}), the +client **SHOULD** initiate shutdown by: 1. First, closing the input stream to the child process (the server) -2. Waiting for the server to exit, or sending `SIGTERM` if the server does not exit within a reasonable time +2. Waiting for the server to exit, or sending `SIGTERM` if the server does not exit + within a reasonable time 3. Sending `SIGKILL` if the server does not exit within a reasonable time after `SIGTERM` -The server **MAY** initiate shutdown by closing its output stream to the client and exiting. +The server **MAY** initiate shutdown by closing its output stream to the client and +exiting. #### HTTP -For HTTP [transports]({{< ref "/specification/2024-11-05/basic/transports" >}}), shutdown is indicated by closing the associated HTTP connection(s). +For HTTP [transports]({{< ref "/specification/2024-11-05/basic/transports" >}}), shutdown +is indicated by closing the associated HTTP connection(s). ## Error Handling @@ -179,9 +200,11 @@ Implementations **SHOULD** be prepared to handle these error cases: - Initialize request timeout - Shutdown timeout -Implementations **SHOULD** implement appropriate timeouts for all requests, to prevent hung connections and resource exhaustion. +Implementations **SHOULD** implement appropriate timeouts for all requests, to prevent +hung connections and resource exhaustion. Example initialization error: + ```json { "jsonrpc": "2.0", diff --git a/docs/specification/2024-11-05/basic/messages.md b/docs/specification/2024-11-05/basic/messages.md index 3a5a2ac..a979ce5 100644 --- a/docs/specification/2024-11-05/basic/messages.md +++ b/docs/specification/2024-11-05/basic/messages.md @@ -3,11 +3,13 @@ title: Messages type: docs weight: 20 --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} + +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} -All messages in MCP **MUST** follow the [JSON-RPC 2.0](https://www.jsonrpc.org/specification) specification. The protocol defines three types of messages: +All messages in MCP **MUST** follow the +[JSON-RPC 2.0](https://www.jsonrpc.org/specification) specification. The protocol defines +three types of messages: ## Requests @@ -24,9 +26,10 @@ Requests are sent from the client to the server or vice versa. } ``` -* Requests **MUST** include a string or integer ID. -* Unlike base JSON-RPC, the ID **MUST NOT** be `null`. -* The request ID **MUST NOT** have been previously used by the requestor within the same session. +- Requests **MUST** include a string or integer ID. +- Unlike base JSON-RPC, the ID **MUST NOT** be `null`. +- The request ID **MUST NOT** have been previously used by the requestor within the same + session. ## Responses @@ -47,13 +50,14 @@ Responses are sent in reply to requests. } ``` -* Responses **MUST** include the same ID as the request they correspond to. -* Either a `result` or an `error` **MUST** be set. A response **MUST NOT** set both. -* Error codes **MUST** be integers. +- Responses **MUST** include the same ID as the request they correspond to. +- Either a `result` or an `error` **MUST** be set. A response **MUST NOT** set both. +- Error codes **MUST** be integers. ## Notifications -Notifications are sent from the client to the server or vice versa. They do not expect a response. +Notifications are sent from the client to the server or vice versa. They do not expect a +response. ```typescript { @@ -65,4 +69,4 @@ Notifications are sent from the client to the server or vice versa. They do not } ``` -* Notifications **MUST NOT** include an ID. +- Notifications **MUST NOT** include an ID. diff --git a/docs/specification/2024-11-05/basic/transports.md b/docs/specification/2024-11-05/basic/transports.md index b749707..192492b 100644 --- a/docs/specification/2024-11-05/basic/transports.md +++ b/docs/specification/2024-11-05/basic/transports.md @@ -3,26 +3,33 @@ title: Transports type: docs weight: 40 --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} + +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} MCP currently defines two standard transport mechanisms for client-server communication: + 1. [stdio](#stdio), communication over standard in and standard out 2. [HTTP with Server-Sent Events](#http-with-sse) (SSE) Clients **SHOULD** support stdio whenever possible. -It is also possible for clients and servers to implement [custom transports](#custom-transports) in a pluggable fashion. +It is also possible for clients and servers to implement +[custom transports](#custom-transports) in a pluggable fashion. ## stdio + In the **stdio** transport: -* The client launches the MCP server as a subprocess. -* The server receives JSON-RPC messages on its standard input (`stdin`) and writes responses to its standard output (`stdout`). -* Messages are delimited by newlines, and **MUST NOT** contain embedded newlines. -* The server **MAY** write UTF-8 strings to its standard error (`stderr`) for logging purposes. Clients **MAY** capture, forward, or ignore this logging. -* The server **MUST NOT** write anything to its `stdout` that is not a valid MCP message. -* The client **MUST NOT** write anything to the server's `stdin` that is not a valid MCP message. + +- The client launches the MCP server as a subprocess. +- The server receives JSON-RPC messages on its standard input (`stdin`) and writes + responses to its standard output (`stdout`). +- Messages are delimited by newlines, and **MUST NOT** contain embedded newlines. +- The server **MAY** write UTF-8 strings to its standard error (`stderr`) for logging + purposes. Clients **MAY** capture, forward, or ignore this logging. +- The server **MUST NOT** write anything to its `stdout` that is not a valid MCP message. +- The client **MUST NOT** write anything to the server's `stdin` that is not a valid MCP + message. ```mermaid sequenceDiagram @@ -40,16 +47,22 @@ sequenceDiagram ``` ## HTTP with SSE -In the **SSE** transport, the server operates as an independent process that can handle multiple client connections. + +In the **SSE** transport, the server operates as an independent process that can handle +multiple client connections. The server **MUST** provide two endpoints: -1. An SSE endpoint, for clients to establish a connection and receive messages from the server +1. An SSE endpoint, for clients to establish a connection and receive messages from the + server 2. A regular HTTP POST endpoint for clients to send messages to the server -When a client connects, the server **MUST** send an `endpoint` event containing a URI for the client to use for sending messages. All subsequent client messages **MUST** be sent as HTTP POST requests to this endpoint. +When a client connects, the server **MUST** send an `endpoint` event containing a URI for +the client to use for sending messages. All subsequent client messages **MUST** be sent +as HTTP POST requests to this endpoint. -Server messages are sent as SSE `message` events, with the message content encoded as JSON in the event data. +Server messages are sent as SSE `message` events, with the message content encoded as +JSON in the event data. ```mermaid sequenceDiagram @@ -67,6 +80,11 @@ sequenceDiagram ## Custom Transports -Clients and servers **MAY** implement additional custom transport mechanisms to suit their specific needs. The protocol is transport-agnostic and can be implemented over any communication channel that supports bidirectional message exchange. +Clients and servers **MAY** implement additional custom transport mechanisms to suit +their specific needs. The protocol is transport-agnostic and can be implemented over any +communication channel that supports bidirectional message exchange. -Implementers who choose to support custom transports **MUST** ensure they preserve the JSON-RPC message format and lifecycle requirements defined by MCP. Custom transports **SHOULD** document their specific connection establishment and message exchange patterns to aid interoperability. +Implementers who choose to support custom transports **MUST** ensure they preserve the +JSON-RPC message format and lifecycle requirements defined by MCP. Custom transports +**SHOULD** document their specific connection establishment and message exchange patterns +to aid interoperability. diff --git a/docs/specification/2024-11-05/basic/utilities/_index.md b/docs/specification/2024-11-05/basic/utilities/_index.md index 5abbf2b..04ec76e 100644 --- a/docs/specification/2024-11-05/basic/utilities/_index.md +++ b/docs/specification/2024-11-05/basic/utilities/_index.md @@ -2,14 +2,11 @@ title: Utilities --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} These optional features enhance the base protocol functionality with various utilities. -{{< cards >}} - {{< card link="ping" title="Ping" icon="status-online" >}} - {{< card link="cancellation" title="Cancellation" icon="x" >}} - {{< card link="progress" title="Progress" icon="clock" >}} -{{< /cards >}} +{{< cards >}} {{< card link="ping" title="Ping" icon="status-online" >}} +{{< card link="cancellation" title="Cancellation" icon="x" >}} +{{< card link="progress" title="Progress" icon="clock" >}} {{< /cards >}} diff --git a/docs/specification/2024-11-05/basic/utilities/cancellation.md b/docs/specification/2024-11-05/basic/utilities/cancellation.md index 0694a8c..8795021 100644 --- a/docs/specification/2024-11-05/basic/utilities/cancellation.md +++ b/docs/specification/2024-11-05/basic/utilities/cancellation.md @@ -3,15 +3,17 @@ title: Cancellation weight: 10 --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} -The Model Context Protocol (MCP) supports optional cancellation of in-progress requests through notification messages. Either side can send a cancellation notification to indicate that a previously-issued request should be terminated. +The Model Context Protocol (MCP) supports optional cancellation of in-progress requests +through notification messages. Either side can send a cancellation notification to +indicate that a previously-issued request should be terminated. ## Cancellation Flow -When a party wants to cancel an in-progress request, it sends a `notifications/cancelled` notification containing: +When a party wants to cancel an in-progress request, it sends a `notifications/cancelled` +notification containing: - The ID of the request to cancel - An optional reason string that can be logged or displayed @@ -41,11 +43,13 @@ When a party wants to cancel an in-progress request, it sends a `notifications/c - The referenced request is unknown - Processing has already completed - The request cannot be cancelled -5. The sender of the cancellation notification **SHOULD** ignore any response to the request that arrives afterward +5. The sender of the cancellation notification **SHOULD** ignore any response to the + request that arrives afterward ## Timing Considerations -Due to network latency, cancellation notifications may arrive after request processing has completed, and potentially after a response has already been sent. +Due to network latency, cancellation notifications may arrive after request processing +has completed, and potentially after a response has already been sent. Both parties **MUST** handle these race conditions gracefully: @@ -57,7 +61,7 @@ sequenceDiagram Client->>Server: Request (ID: 123) Note over Server: Processing starts Client--)Server: notifications/cancelled (ID: 123) - alt + alt Note over Server: Processing may have
completed before
cancellation arrives else If not completed Note over Server: Stop processing @@ -77,4 +81,5 @@ Invalid cancellation notifications **SHOULD** be ignored: - Already completed requests - Malformed notifications -This maintains the "fire and forget" nature of notifications while allowing for race conditions in asynchronous communication. +This maintains the "fire and forget" nature of notifications while allowing for race +conditions in asynchronous communication. diff --git a/docs/specification/2024-11-05/basic/utilities/ping.md b/docs/specification/2024-11-05/basic/utilities/ping.md index 2ac305e..00aa47d 100644 --- a/docs/specification/2024-11-05/basic/utilities/ping.md +++ b/docs/specification/2024-11-05/basic/utilities/ping.md @@ -3,15 +3,16 @@ title: Ping weight: 5 --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} -The Model Context Protocol includes an optional ping mechanism that allows either party to verify that their counterpart is still responsive and the connection is alive. +The Model Context Protocol includes an optional ping mechanism that allows either party +to verify that their counterpart is still responsive and the connection is alive. ## Overview -The ping functionality is implemented through a simple request/response pattern. Either the client or server can initiate a ping by sending a `ping` request. +The ping functionality is implemented through a simple request/response pattern. Either +the client or server can initiate a ping by sending a `ping` request. ## Message Format diff --git a/docs/specification/2024-11-05/basic/utilities/progress.md b/docs/specification/2024-11-05/basic/utilities/progress.md index 1bb4d2e..8381d8a 100644 --- a/docs/specification/2024-11-05/basic/utilities/progress.md +++ b/docs/specification/2024-11-05/basic/utilities/progress.md @@ -2,18 +2,22 @@ title: Progress weight: 30 --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} + +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} -The Model Context Protocol (MCP) supports optional progress tracking for long-running operations through notification messages. Either side can send progress notifications to provide updates about operation status. +The Model Context Protocol (MCP) supports optional progress tracking for long-running +operations through notification messages. Either side can send progress notifications to +provide updates about operation status. ## Progress Flow -When a party wants to _receive_ progress updates for a request, it includes a `progressToken` in the request metadata. +When a party wants to _receive_ progress updates for a request, it includes a +`progressToken` in the request metadata. -* Progress tokens **MUST** be a string or integer value -* Progress tokens can be chosen by the sender using any means, but **MUST** be unique across all active requests. +- Progress tokens **MUST** be a string or integer value +- Progress tokens can be chosen by the sender using any means, but **MUST** be unique + across all active requests. ```json { @@ -46,12 +50,14 @@ The receiver **MAY** then send progress notifications containing: } ``` -* The `progress` value **MUST** increase with each notification, even if the total is unknown. -* The `progress` and the `total` values **MAY** be floating point. +- The `progress` value **MUST** increase with each notification, even if the total is + unknown. +- The `progress` and the `total` values **MAY** be floating point. ## Behavior Requirements 1. Progress notifications **MUST** only reference tokens that: + - Were provided in an active request - Are associated with an in-progress operation diff --git a/docs/specification/2024-11-05/basic/versioning.md b/docs/specification/2024-11-05/basic/versioning.md index c60ae2f..81affa7 100644 --- a/docs/specification/2024-11-05/basic/versioning.md +++ b/docs/specification/2024-11-05/basic/versioning.md @@ -4,14 +4,21 @@ type: docs weight: 80 --- -The Model Context Protocol uses string-based version identifiers following the format `YYYY-MM-DD`, to indicate the last date backwards incompatible changes were made. +The Model Context Protocol uses string-based version identifiers following the format +`YYYY-MM-DD`, to indicate the last date backwards incompatible changes were made. -The current protocol version is **{{< param protocolRevision >}}**. [See all revisions]({{< ref "/specification/2024-11-05/revisions" >}}). +The current protocol version is **{{< param protocolRevision >}}**. [See all +revisions]({{< ref "/specification/2024-11-05/revisions" >}}). -{{< callout type="info" >}} - The protocol version will _not_ be incremented when the protocol is updated, as long as the changes maintain backwards compatibility. This allows for incremental improvements while preserving interoperability. -{{< /callout >}} +{{< callout type="info" >}} The protocol version will _not_ be incremented when the +protocol is updated, as long as the changes maintain backwards compatibility. This allows +for incremental improvements while preserving interoperability. {{< /callout >}} -Version negotiation happens during [initialization]({{< ref "/specification/2024-11-05/basic/lifecycle#initialization" >}}). Clients and servers **MAY** support multiple protocol versions simultaneously, but they **MUST** agree on a single version to use for the session. +Version negotiation happens during +[initialization]({{< ref "/specification/2024-11-05/basic/lifecycle#initialization" >}}). +Clients and servers **MAY** support multiple protocol versions simultaneously, but they +**MUST** agree on a single version to use for the session. -The protocol provides appropriate error handling if version negotiation fails, allowing clients to gracefully terminate connections when they cannot find a version compatible with the server. +The protocol provides appropriate error handling if version negotiation fails, allowing +clients to gracefully terminate connections when they cannot find a version compatible +with the server. diff --git a/docs/specification/2024-11-05/client/_index.md b/docs/specification/2024-11-05/client/_index.md index d09ef5a..09c94d9 100644 --- a/docs/specification/2024-11-05/client/_index.md +++ b/docs/specification/2024-11-05/client/_index.md @@ -5,13 +5,10 @@ cascade: weight: 4 --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} Clients can implement additional features to enrich connected MCP servers: - -{{< cards >}} - {{< card link="roots" title="Roots" icon="folder" >}} - {{< card link="sampling" title="Sampling" icon="annotation" >}} -{{< /cards >}} + +{{< cards >}} {{< card link="roots" title="Roots" icon="folder" >}} +{{< card link="sampling" title="Sampling" icon="annotation" >}} {{< /cards >}} diff --git a/docs/specification/2024-11-05/client/roots.md b/docs/specification/2024-11-05/client/roots.md index a463e71..878f9d5 100644 --- a/docs/specification/2024-11-05/client/roots.md +++ b/docs/specification/2024-11-05/client/roots.md @@ -4,23 +4,31 @@ type: docs weight: 40 --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} -The Model Context Protocol (MCP) provides a standardized way for clients to expose filesystem "roots" to servers. Roots define the boundaries of where servers can operate within the filesystem, allowing them to understand which directories and files they have access to. Servers can request the list of roots from supporting clients and receive notifications when that list changes. +The Model Context Protocol (MCP) provides a standardized way for clients to expose +filesystem "roots" to servers. Roots define the boundaries of where servers can operate +within the filesystem, allowing them to understand which directories and files they have +access to. Servers can request the list of roots from supporting clients and receive +notifications when that list changes. ## User Interaction Model Roots in MCP are typically exposed through workspace or project configuration interfaces. -For example, implementations could offer a workspace/project picker that allows users to select directories and files the server should have access to. This can be combined with automatic workspace detection from version control systems or project files. +For example, implementations could offer a workspace/project picker that allows users to +select directories and files the server should have access to. This can be combined with +automatic workspace detection from version control systems or project files. -However, implementations are free to expose roots through any interface pattern that suits their needs—the protocol itself does not mandate any specific user interaction model. +However, implementations are free to expose roots through any interface pattern that +suits their needs—the protocol itself does not mandate any specific user +interaction model. ## Capabilities -Clients that support roots **MUST** declare the `roots` capability during [initialization]({{< ref "/specification/2024-11-05/basic/lifecycle#initialization" >}}): +Clients that support roots **MUST** declare the `roots` capability during +[initialization]({{< ref "/specification/2024-11-05/basic/lifecycle#initialization" >}}): ```json { @@ -32,7 +40,8 @@ Clients that support roots **MUST** declare the `roots` capability during [initi } ``` -`listChanged` indicates whether the client will emit notifications when the list of roots changes. +`listChanged` indicates whether the client will emit notifications when the list of roots +changes. ## Protocol Messages @@ -41,6 +50,7 @@ Clients that support roots **MUST** declare the `roots` capability during [initi To retrieve roots, servers send a `roots/list` request: **Request:** + ```json { "jsonrpc": "2.0", @@ -50,6 +60,7 @@ To retrieve roots, servers send a `roots/list` request: ``` **Response:** + ```json { "jsonrpc": "2.0", @@ -99,12 +110,14 @@ sequenceDiagram A root definition includes: -- `uri`: Unique identifier for the root. This **MUST** be a `file://` URI in the current specification. +- `uri`: Unique identifier for the root. This **MUST** be a `file://` URI in the current + specification. - `name`: Optional human-readable name for display purposes. Example roots for different use cases: #### Project Directory + ```json { "uri": "file:///home/user/projects/myproject", @@ -113,6 +126,7 @@ Example roots for different use cases: ``` #### Multiple Repositories + ```json [ { @@ -134,6 +148,7 @@ Clients **SHOULD** return standard JSON-RPC errors for common failure cases: - Internal errors: `-32603` Example error: + ```json { "jsonrpc": "2.0", @@ -151,6 +166,7 @@ Example error: ## Security Considerations 1. Clients **MUST**: + - Only expose roots with appropriate permissions - Validate all root URIs to prevent path traversal - Implement proper access controls @@ -164,6 +180,7 @@ Example error: ## Implementation Guidelines 1. Clients **SHOULD**: + - Prompt users for consent before exposing roots to servers - Provide clear user interfaces for root management - Validate root accessibility before exposing diff --git a/docs/specification/2024-11-05/client/sampling.md b/docs/specification/2024-11-05/client/sampling.md index 7a35533..6275b79 100644 --- a/docs/specification/2024-11-05/client/sampling.md +++ b/docs/specification/2024-11-05/client/sampling.md @@ -4,30 +4,38 @@ type: docs weight: 40 --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} -The Model Context Protocol (MCP) provides a standardized way for servers to request LLM sampling ("completions" or "generations") from language models via clients. This flow allows clients to maintain control over model access, selection, and permissions while enabling servers to leverage AI capabilities—with no server API keys necessary. Servers can request text or image-based interactions and optionally include context from MCP servers in their prompts. +The Model Context Protocol (MCP) provides a standardized way for servers to request LLM +sampling ("completions" or "generations") from language models via clients. This flow +allows clients to maintain control over model access, selection, and permissions while +enabling servers to leverage AI capabilities—with no server API keys necessary. +Servers can request text or image-based interactions and optionally include context from +MCP servers in their prompts. ## User Interaction Model -Sampling in MCP allows servers to implement agentic behaviors, by enabling LLM calls to occur _nested_ inside other MCP server features. +Sampling in MCP allows servers to implement agentic behaviors, by enabling LLM calls to +occur _nested_ inside other MCP server features. -Implementations are free to expose sampling through any interface pattern that suits their needs—the protocol itself does not mandate any specific user interaction model. +Implementations are free to expose sampling through any interface pattern that suits +their needs—the protocol itself does not mandate any specific user interaction +model. -{{< callout type="warning" >}} - For trust & safety and security, there **SHOULD** always be a human in the loop with the ability to deny sampling requests. - - Applications **SHOULD**: - * Provide UI that makes it easy and intuitive to review sampling requests - * Allow users to view and edit prompts before sending - * Present generated responses for review before delivery -{{< /callout >}} +{{< callout type="warning" >}} For trust & safety and security, there **SHOULD** always +be a human in the loop with the ability to deny sampling requests. + +Applications **SHOULD**: + +- Provide UI that makes it easy and intuitive to review sampling requests +- Allow users to view and edit prompts before sending +- Present generated responses for review before delivery {{< /callout >}} ## Capabilities -Clients that support sampling **MUST** declare the `sampling` capability during [initialization]({{< ref "/specification/2024-11-05/basic/lifecycle#initialization" >}}): +Clients that support sampling **MUST** declare the `sampling` capability during +[initialization]({{< ref "/specification/2024-11-05/basic/lifecycle#initialization" >}}): ```json { @@ -44,6 +52,7 @@ Clients that support sampling **MUST** declare the `sampling` capability during To request a language model generation, servers send a `sampling/createMessage` request: **Request:** + ```json { "jsonrpc": "2.0", @@ -75,6 +84,7 @@ To request a language model generation, servers send a `sampling/createMessage` ``` **Response:** + ```json { "jsonrpc": "2.0", @@ -126,6 +136,7 @@ sequenceDiagram Sampling messages can contain: #### Text Content + ```json { "type": "text", @@ -134,6 +145,7 @@ Sampling messages can contain: ``` #### Image Content + ```json { "type": "image", @@ -144,9 +156,13 @@ Sampling messages can contain: ### Model Preferences -Model selection in MCP requires careful abstraction since servers and clients may use different AI providers with distinct model offerings. A server cannot simply request a specific model by name since the client may not have access to that exact model or may prefer to use a different provider's equivalent model. +Model selection in MCP requires careful abstraction since servers and clients may use +different AI providers with distinct model offerings. A server cannot simply request a +specific model by name since the client may not have access to that exact model or may +prefer to use a different provider's equivalent model. -To solve this, MCP implements a preference system that combines abstract capability priorities with optional model hints: +To solve this, MCP implements a preference system that combines abstract capability +priorities with optional model hints: #### Capability Priorities @@ -154,11 +170,13 @@ Servers express their needs through three normalized priority values (0-1): - `costPriority`: How important is minimizing costs? Higher values prefer cheaper models. - `speedPriority`: How important is low latency? Higher values prefer faster models. -- `intelligencePriority`: How important are advanced capabilities? Higher values prefer more capable models. +- `intelligencePriority`: How important are advanced capabilities? Higher values prefer + more capable models. #### Model Hints -While priorities help select models based on characteristics, `hints` allow servers to suggest specific models or model families: +While priorities help select models based on characteristics, `hints` allow servers to +suggest specific models or model families: - Hints are treated as substrings that can match model names flexibly - Multiple hints are evaluated in order of preference @@ -166,25 +184,29 @@ While priorities help select models based on characteristics, `hints` allow serv - Hints are advisory—clients make final model selection For example: + ```json { "hints": [ - {"name": "claude-3-sonnet"}, // Prefer Sonnet-class models - {"name": "claude"} // Fall back to any Claude model + { "name": "claude-3-sonnet" }, // Prefer Sonnet-class models + { "name": "claude" } // Fall back to any Claude model ], - "costPriority": 0.3, // Cost is less important - "speedPriority": 0.8, // Speed is very important - "intelligencePriority": 0.5 // Moderate capability needs + "costPriority": 0.3, // Cost is less important + "speedPriority": 0.8, // Speed is very important + "intelligencePriority": 0.5 // Moderate capability needs } ``` -The client processes these preferences to select an appropriate model from its available options. For instance, if the client doesn't have access to Claude models but has Gemini, it might map the sonnet hint to `gemini-1.5-pro` based on similar capabilities. +The client processes these preferences to select an appropriate model from its available +options. For instance, if the client doesn't have access to Claude models but has Gemini, +it might map the sonnet hint to `gemini-1.5-pro` based on similar capabilities. ## Error Handling Clients **SHOULD** return errors for common failure cases: Example error: + ```json { "jsonrpc": "2.0", diff --git a/docs/specification/2024-11-05/contributing/_index.md b/docs/specification/2024-11-05/contributing/_index.md index 563b2ea..2fed4ee 100644 --- a/docs/specification/2024-11-05/contributing/_index.md +++ b/docs/specification/2024-11-05/contributing/_index.md @@ -6,8 +6,12 @@ cascade: breadcrumbs: false --- -We welcome contributions from the community! Please review our [contributing guidelines](https://github.com/modelcontextprotocol/specification/2024-11-05/blob/main/CONTRIBUTING.md) for details on how to submit changes. +We welcome contributions from the community! Please review our +[contributing guidelines](https://github.com/modelcontextprotocol/specification/2024-11-05/blob/main/CONTRIBUTING.md) +for details on how to submit changes. -All contributors must adhere to our [Code of Conduct](https://github.com/modelcontextprotocol/specification/2024-11-05/blob/main/CODE_OF_CONDUCT.md). +All contributors must adhere to our +[Code of Conduct](https://github.com/modelcontextprotocol/specification/2024-11-05/blob/main/CODE_OF_CONDUCT.md). -For questions and discussions, please use [GitHub Discussions](https://github.com/modelcontextprotocol/specification/2024-11-05/discussions). +For questions and discussions, please use +[GitHub Discussions](https://github.com/modelcontextprotocol/specification/2024-11-05/discussions). diff --git a/docs/specification/2024-11-05/revisions/2024-11-05.md b/docs/specification/2024-11-05/revisions/2024-11-05.md index 465a00d..5ef43ab 100644 --- a/docs/specification/2024-11-05/revisions/2024-11-05.md +++ b/docs/specification/2024-11-05/revisions/2024-11-05.md @@ -2,4 +2,6 @@ title: 2024-11-05 (Current) weight: 1 --- -This is the current version of the specification. This revision may continue to receive backwards compatible changes. + +This is the current version of the specification. This revision may continue to receive +backwards compatible changes. diff --git a/docs/specification/2024-11-05/revisions/_index.md b/docs/specification/2024-11-05/revisions/_index.md index 0508d01..26f50e3 100644 --- a/docs/specification/2024-11-05/revisions/_index.md +++ b/docs/specification/2024-11-05/revisions/_index.md @@ -4,10 +4,14 @@ cascade: type: docs --- -This page lists the different revisions of the Model Context Protocol. See [Versioning]({{< ref "/specification/2024-11-05/basic/versioning" >}}) for more information about how the protocol is versioned. +This page lists the different revisions of the Model Context Protocol. See +[Versioning]({{< ref "/specification/2024-11-05/basic/versioning" >}}) for more +information about how the protocol is versioned. Revisions may be marked as: -* **Draft**: in-progress specifications, not yet ready for consumption. -* **Current**: the current protocol version, which is ready for use and may continue to receive [backwards compatible changes]({{< ref "/specification/2024-11-05/basic/versioning" >}}). -* **Final**: past, complete specifications that will not be changed. +- **Draft**: in-progress specifications, not yet ready for consumption. +- **Current**: the current protocol version, which is ready for use and may continue to + receive [backwards compatible + changes]({{< ref "/specification/2024-11-05/basic/versioning" >}}). +- **Final**: past, complete specifications that will not be changed. diff --git a/docs/specification/2024-11-05/server/_index.md b/docs/specification/2024-11-05/server/_index.md index 096d28f..a60b721 100644 --- a/docs/specification/2024-11-05/server/_index.md +++ b/docs/specification/2024-11-05/server/_index.md @@ -5,28 +5,29 @@ cascade: weight: 3 --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} -Servers provide the fundamental building blocks for adding context to language models via MCP. These primitives enable rich interactions between clients, servers, and language models: +Servers provide the fundamental building blocks for adding context to language models via +MCP. These primitives enable rich interactions between clients, servers, and language +models: -- **Prompts**: Pre-defined templates or instructions that guide language model interactions +- **Prompts**: Pre-defined templates or instructions that guide language model + interactions - **Resources**: Structured data or content that provides additional context to the model -- **Tools**: Executable functions that allow models to perform actions or retrieve information +- **Tools**: Executable functions that allow models to perform actions or retrieve + information Each primitive can be summarized in the following control hierarchy: -| Primitive | Control | Description | Example | -|-----------|------------------------|----------------------------------------------------|------------------------------| -| Prompts | User-controlled | Interactive templates invoked by user choice | Slash commands, menu options | -| Resources | Application-controlled | Contextual data attached and managed by the client | File contents, git history | -| Tools | Model-controlled | Functions exposed to the LLM to take actions | API POST requests, file writing | +| Primitive | Control | Description | Example | +| --------- | ---------------------- | -------------------------------------------------- | ------------------------------- | +| Prompts | User-controlled | Interactive templates invoked by user choice | Slash commands, menu options | +| Resources | Application-controlled | Contextual data attached and managed by the client | File contents, git history | +| Tools | Model-controlled | Functions exposed to the LLM to take actions | API POST requests, file writing | Explore these key primitives in more detail below: -{{< cards >}} - {{< card link="prompts" title="Prompts" icon="chat-alt-2" >}} - {{< card link="resources" title="Resources" icon="document" >}} - {{< card link="tools" title="Tools" icon="adjustments" >}} -{{< /cards >}} +{{< cards >}} {{< card link="prompts" title="Prompts" icon="chat-alt-2" >}} +{{< card link="resources" title="Resources" icon="document" >}} +{{< card link="tools" title="Tools" icon="adjustments" >}} {{< /cards >}} diff --git a/docs/specification/2024-11-05/server/prompts.md b/docs/specification/2024-11-05/server/prompts.md index 2ac3663..f8dfc3a 100644 --- a/docs/specification/2024-11-05/server/prompts.md +++ b/docs/specification/2024-11-05/server/prompts.md @@ -3,27 +3,35 @@ title: Prompts weight: 10 --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} -The Model Context Protocol (MCP) provides a standardized way for servers to expose prompt templates to clients. Prompts allow servers to provide structured messages and instructions for interacting with language models. Clients can discover available prompts, retrieve their contents, and provide arguments to customize them. +The Model Context Protocol (MCP) provides a standardized way for servers to expose prompt +templates to clients. Prompts allow servers to provide structured messages and +instructions for interacting with language models. Clients can discover available +prompts, retrieve their contents, and provide arguments to customize them. ## User Interaction Model -Prompts are designed to be **user-controlled**, meaning they are exposed from servers to clients with the intention of the user being able to explicitly select them for use. +Prompts are designed to be **user-controlled**, meaning they are exposed from servers to +clients with the intention of the user being able to explicitly select them for use. -Typically, prompts would be triggered through user-initiated commands in the user interface, which allows users to naturally discover and invoke available prompts. +Typically, prompts would be triggered through user-initiated commands in the user +interface, which allows users to naturally discover and invoke available prompts. For example, as slash commands: ![Example of prompt exposed as slash command](slash-command.png) -However, implementors are free to expose prompts through any interface pattern that suits their needs—the protocol itself does not mandate any specific user interaction model. +However, implementors are free to expose prompts through any interface pattern that suits +their needs—the protocol itself does not mandate any specific user interaction +model. ## Capabilities -Servers that support prompts **MUST** declare the `prompts` capability during [initialization]({{< ref "/specification/2024-11-05/basic/lifecycle#initialization" >}}): +Servers that support prompts **MUST** declare the `prompts` capability during +[initialization]({{< ref "/specification/2024-11-05/basic/lifecycle#initialization" >}}): + ```json { "capabilities": { @@ -34,15 +42,19 @@ Servers that support prompts **MUST** declare the `prompts` capability during [i } ``` -`listChanged` indicates whether the server will emit notifications when the list of available prompts changes. +`listChanged` indicates whether the server will emit notifications when the list of +available prompts changes. ## Protocol Messages ### Listing Prompts -To retrieve available prompts, clients send a `prompts/list` request. This operation supports [pagination]({{< ref "/specification/2024-11-05/server/utilities/pagination" >}}). +To retrieve available prompts, clients send a `prompts/list` request. This operation +supports +[pagination]({{< ref "/specification/2024-11-05/server/utilities/pagination" >}}). **Request:** + ```json { "jsonrpc": "2.0", @@ -55,6 +67,7 @@ To retrieve available prompts, clients send a `prompts/list` request. This opera ``` **Response:** + ```json { "jsonrpc": "2.0", @@ -80,9 +93,12 @@ To retrieve available prompts, clients send a `prompts/list` request. This opera ### Getting a Prompt -To retrieve a specific prompt, clients send a `prompts/get` request. Arguments may be auto-completed through [the completion API]({{< ref "/specification/2024-11-05/server/utilities/completion" >}}). +To retrieve a specific prompt, clients send a `prompts/get` request. Arguments may be +auto-completed through [the completion +API]({{< ref "/specification/2024-11-05/server/utilities/completion" >}}). **Request:** + ```json { "jsonrpc": "2.0", @@ -98,6 +114,7 @@ To retrieve a specific prompt, clients send a `prompts/get` request. Arguments m ``` **Response:** + ```json { "jsonrpc": "2.0", @@ -119,7 +136,8 @@ To retrieve a specific prompt, clients send a `prompts/get` request. Arguments m ### List Changed Notification -When the list of available prompts changes, servers that declared the `listChanged` capability **SHOULD** send a notification: +When the list of available prompts changes, servers that declared the `listChanged` +capability **SHOULD** send a notification: ```json { @@ -169,17 +187,22 @@ Messages in a prompt can contain: - `content`: One of the following content types: #### Text Content + Text content represents plain text messages: + ```json { "type": "text", "text": "The text content of the message" } ``` + This is the most common content type used for natural language interactions. #### Image Content + Image content allows including visual information in messages: + ```json { "type": "image", @@ -187,10 +210,14 @@ Image content allows including visual information in messages: "mimeType": "image/png" } ``` -The image data **MUST** be base64-encoded and include a valid MIME type. This enables multi-modal interactions where visual context is important. + +The image data **MUST** be base64-encoded and include a valid MIME type. This enables +multi-modal interactions where visual context is important. #### Embedded Resources + Embedded resources allow referencing server-side resources directly in messages: + ```json { "type": "resource", @@ -203,11 +230,14 @@ Embedded resources allow referencing server-side resources directly in messages: ``` Resources can contain either text or binary (blob) data and **MUST** include: + - A valid resource URI - The appropriate MIME type - Either text content or base64-encoded blob data -Embedded resources enable prompts to seamlessly incorporate server-managed content like documentation, code samples, or other reference materials directly into the conversation flow. +Embedded resources enable prompts to seamlessly incorporate server-managed content like +documentation, code samples, or other reference materials directly into the conversation +flow. ## Error Handling @@ -225,4 +255,5 @@ Servers **SHOULD** return standard JSON-RPC errors for common failure cases: ## Security -Implementations **MUST** carefully validate all prompt inputs and outputs to prevent injection attacks or unauthorized access to resources. +Implementations **MUST** carefully validate all prompt inputs and outputs to prevent +injection attacks or unauthorized access to resources. diff --git a/docs/specification/2024-11-05/server/resources.md b/docs/specification/2024-11-05/server/resources.md index ce8d020..88ffc7e 100644 --- a/docs/specification/2024-11-05/server/resources.md +++ b/docs/specification/2024-11-05/server/resources.md @@ -4,24 +4,31 @@ type: docs weight: 20 --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} -The Model Context Protocol (MCP) provides a standardized way for servers to expose resources to clients. Resources allow servers to share data that provides context to language models, such as files, database schemas, or application-specific information. Each resource is uniquely identified by a [URI](https://datatracker.ietf.org/doc/html/rfc3986). +The Model Context Protocol (MCP) provides a standardized way for servers to expose +resources to clients. Resources allow servers to share data that provides context to +language models, such as files, database schemas, or application-specific information. +Each resource is uniquely identified by a +[URI](https://datatracker.ietf.org/doc/html/rfc3986). ## User Interaction Model -Resources in MCP are designed to be **application-driven**, with host applications determining how to incorporate context based on their needs. +Resources in MCP are designed to be **application-driven**, with host applications +determining how to incorporate context based on their needs. For example, applications could: -* Expose resources through UI elements for explicit selection, in a tree or list view -* Allow the user to search through and filter available resources -* Implement automatic context inclusion, based on heuristics or the AI model's selection + +- Expose resources through UI elements for explicit selection, in a tree or list view +- Allow the user to search through and filter available resources +- Implement automatic context inclusion, based on heuristics or the AI model's selection ![Example of resource context picker](resource-picker.png) -However, implementations are free to expose resources through any interface pattern that suits their needs—the protocol itself does not mandate any specific user interaction model. +However, implementations are free to expose resources through any interface pattern that +suits their needs—the protocol itself does not mandate any specific user +interaction model. ## Capabilities @@ -39,15 +46,19 @@ Servers that support resources **MUST** declare the `resources` capability: ``` The capability supports two optional features: -- `subscribe`: whether the client can subscribe to be notified of changes to individual resources. -- `listChanged`: whether the server will emit notifications when the list of available resources changes. -Both `subscribe` and `listChanged` are optional—servers can support neither, either, or both: +- `subscribe`: whether the client can subscribe to be notified of changes to individual + resources. +- `listChanged`: whether the server will emit notifications when the list of available + resources changes. + +Both `subscribe` and `listChanged` are optional—servers can support neither, +either, or both: ```json { "capabilities": { - "resources": {} // Neither feature supported + "resources": {} // Neither feature supported } } ``` @@ -56,7 +67,7 @@ Both `subscribe` and `listChanged` are optional—servers can support neithe { "capabilities": { "resources": { - "subscribe": true // Only subscriptions supported + "subscribe": true // Only subscriptions supported } } } @@ -66,7 +77,7 @@ Both `subscribe` and `listChanged` are optional—servers can support neithe { "capabilities": { "resources": { - "listChanged": true // Only list change notifications supported + "listChanged": true // Only list change notifications supported } } } @@ -76,9 +87,12 @@ Both `subscribe` and `listChanged` are optional—servers can support neithe ### Listing Resources -To discover available resources, clients send a `resources/list` request. This operation supports [pagination]({{< ref "/specification/2024-11-05/server/utilities/pagination" >}}). +To discover available resources, clients send a `resources/list` request. This operation +supports +[pagination]({{< ref "/specification/2024-11-05/server/utilities/pagination" >}}). **Request:** + ```json { "jsonrpc": "2.0", @@ -91,6 +105,7 @@ To discover available resources, clients send a `resources/list` request. This o ``` **Response:** + ```json { "jsonrpc": "2.0", @@ -114,6 +129,7 @@ To discover available resources, clients send a `resources/list` request. This o To retrieve resource contents, clients send a `resources/read` request: **Request:** + ```json { "jsonrpc": "2.0", @@ -126,6 +142,7 @@ To retrieve resource contents, clients send a `resources/read` request: ``` **Response:** + ```json { "jsonrpc": "2.0", @@ -144,9 +161,13 @@ To retrieve resource contents, clients send a `resources/read` request: ### Resource Templates -Resource templates allow servers to expose parameterized resources using [URI templates](https://datatracker.ietf.org/doc/html/rfc6570). Arguments may be auto-completed through [the completion API]({{< ref "/specification/2024-11-05/server/utilities/completion" >}}). +Resource templates allow servers to expose parameterized resources using +[URI templates](https://datatracker.ietf.org/doc/html/rfc6570). Arguments may be +auto-completed through [the completion +API]({{< ref "/specification/2024-11-05/server/utilities/completion" >}}). **Request:** + ```json { "jsonrpc": "2.0", @@ -156,6 +177,7 @@ Resource templates allow servers to expose parameterized resources using [URI te ``` **Response:** + ```json { "jsonrpc": "2.0", @@ -175,7 +197,8 @@ Resource templates allow servers to expose parameterized resources using [URI te ### List Changed Notification -When the list of available resources changes, servers that declared the `listChanged` capability **SHOULD** send a notification: +When the list of available resources changes, servers that declared the `listChanged` +capability **SHOULD** send a notification: ```json { @@ -186,9 +209,11 @@ When the list of available resources changes, servers that declared the `listCha ### Subscriptions -The protocol supports optional subscriptions to resource changes. Clients can subscribe to specific resources and receive notifications when they change: +The protocol supports optional subscriptions to resource changes. Clients can subscribe +to specific resources and receive notifications when they change: **Subscribe Request:** + ```json { "jsonrpc": "2.0", @@ -201,6 +226,7 @@ The protocol supports optional subscriptions to resource changes. Clients can su ``` **Update Notification:** + ```json { "jsonrpc": "2.0", @@ -252,6 +278,7 @@ A resource definition includes: Resources can contain either text or binary data: #### Text Content + ```json { "uri": "file:///example.txt", @@ -261,6 +288,7 @@ Resources can contain either text or binary data: ``` #### Binary Content + ```json { "uri": "file:///example.png", @@ -271,21 +299,30 @@ Resources can contain either text or binary data: ## Common URI Schemes -The protocol defines several standard URI schemes. This list not exhaustive—implementations are always free to use additional, custom URI schemes. +The protocol defines several standard URI schemes. This list not +exhaustive—implementations are always free to use additional, custom URI schemes. ### https:// Used to represent a resource available on the web. -Servers **SHOULD** use this scheme only when the client is able to fetch and load the resource directly from the web on its own—that is, it doesn’t need to read the resource via the MCP server. +Servers **SHOULD** use this scheme only when the client is able to fetch and load the +resource directly from the web on its own—that is, it doesn’t need to read the resource +via the MCP server. -For other use cases, servers **SHOULD** prefer to use another URI scheme, or define a custom one, even if the server will itself be downloading resource contents over the internet. +For other use cases, servers **SHOULD** prefer to use another URI scheme, or define a +custom one, even if the server will itself be downloading resource contents over the +internet. ### file:// -Used to identify resources that behave like a filesystem. However, the resources do not need to map to an actual physical filesystem. +Used to identify resources that behave like a filesystem. However, the resources do not +need to map to an actual physical filesystem. -MCP servers **MAY** identify file:// resources with an [XDG MIME type](https://specifications.freedesktop.org/shared-mime-info-spec/0.14/ar01s02.html#id-1.3.14), like `inode/directory`, to represent non-regular files (such as directories) that don’t otherwise have a standard MIME type. +MCP servers **MAY** identify file:// resources with an +[XDG MIME type](https://specifications.freedesktop.org/shared-mime-info-spec/0.14/ar01s02.html#id-1.3.14), +like `inode/directory`, to represent non-regular files (such as directories) that don’t +otherwise have a standard MIME type. ### git:// @@ -299,6 +336,7 @@ Servers **SHOULD** return standard JSON-RPC errors for common failure cases: - Internal errors: `-32603` Example error: + ```json { "jsonrpc": "2.0", diff --git a/docs/specification/2024-11-05/server/tools.md b/docs/specification/2024-11-05/server/tools.md index 56669da..f635c8c 100644 --- a/docs/specification/2024-11-05/server/tools.md +++ b/docs/specification/2024-11-05/server/tools.md @@ -4,26 +4,33 @@ type: docs weight: 40 --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} -The Model Context Protocol (MCP) allows servers to expose tools that can be invoked by language models. Tools enable models to interact with external systems, such as querying databases, calling APIs, or performing computations. Each tool is uniquely identified by a name and includes metadata describing its schema. +The Model Context Protocol (MCP) allows servers to expose tools that can be invoked by +language models. Tools enable models to interact with external systems, such as querying +databases, calling APIs, or performing computations. Each tool is uniquely identified by +a name and includes metadata describing its schema. ## User Interaction Model -Tools in MCP are designed to be **model-controlled**, meaning that the language model can discover and invoke tools automatically based on its contextual understanding and the user's prompts. +Tools in MCP are designed to be **model-controlled**, meaning that the language model can +discover and invoke tools automatically based on its contextual understanding and the +user's prompts. -However, implementations are free to expose tools through any interface pattern that suits their needs—the protocol itself does not mandate any specific user interaction model. +However, implementations are free to expose tools through any interface pattern that +suits their needs—the protocol itself does not mandate any specific user +interaction model. -{{< callout type="warning" >}} - For trust & safety and security, there **SHOULD** always be a human in the loop with the ability to deny tool invocations. - - Applications **SHOULD**: - * Provide UI that makes clear which tools are being exposed to the AI model - * Insert clear visual indicators when tools are invoked - * Present confirmation prompts to the user for operations, to ensure a human is in the loop -{{< /callout >}} +{{< callout type="warning" >}} For trust & safety and security, there **SHOULD** always +be a human in the loop with the ability to deny tool invocations. + +Applications **SHOULD**: + +- Provide UI that makes clear which tools are being exposed to the AI model +- Insert clear visual indicators when tools are invoked +- Present confirmation prompts to the user for operations, to ensure a human is in the + loop {{< /callout >}} ## Capabilities @@ -39,15 +46,18 @@ Servers that support tools **MUST** declare the `tools` capability: } ``` -`listChanged` indicates whether the server will emit notifications when the list of available tools changes. +`listChanged` indicates whether the server will emit notifications when the list of +available tools changes. ## Protocol Messages ### Listing Tools -To discover available tools, clients send a `tools/list` request. This operation supports [pagination]({{< ref "/specification/2024-11-05/server/utilities/pagination" >}}). +To discover available tools, clients send a `tools/list` request. This operation supports +[pagination]({{< ref "/specification/2024-11-05/server/utilities/pagination" >}}). **Request:** + ```json { "jsonrpc": "2.0", @@ -60,6 +70,7 @@ To discover available tools, clients send a `tools/list` request. This operation ``` **Response:** + ```json { "jsonrpc": "2.0", @@ -91,6 +102,7 @@ To discover available tools, clients send a `tools/list` request. This operation To invoke a tool, clients send a `tools/call` request: **Request:** + ```json { "jsonrpc": "2.0", @@ -106,15 +118,18 @@ To invoke a tool, clients send a `tools/call` request: ``` **Response:** + ```json { "jsonrpc": "2.0", "id": 2, "result": { - "content": [{ - "type": "text", - "text": "Current weather in New York:\nTemperature: 72°F\nConditions: Partly cloudy" - }], + "content": [ + { + "type": "text", + "text": "Current weather in New York:\nTemperature: 72°F\nConditions: Partly cloudy" + } + ], "isError": false } } @@ -122,7 +137,8 @@ To invoke a tool, clients send a `tools/call` request: ### List Changed Notification -When the list of available tools changes, servers that declared the `listChanged` capability **SHOULD** send a notification: +When the list of available tools changes, servers that declared the `listChanged` +capability **SHOULD** send a notification: ```json { @@ -172,6 +188,7 @@ A tool definition includes: Tool results can contain multiple content items of different types: #### Text Content + ```json { "type": "text", @@ -180,6 +197,7 @@ Tool results can contain multiple content items of different types: ``` #### Image Content + ```json { "type": "image", @@ -190,7 +208,9 @@ Tool results can contain multiple content items of different types: #### Embedded Resources -[Resources]({{< ref "/specification/2024-11-05/server/resources" >}}) **MAY** be embedded, to provide additional context or data, behind a URI that can be subscribed to or fetched again by the client later: +[Resources]({{< ref "/specification/2024-11-05/server/resources" >}}) **MAY** be +embedded, to provide additional context or data, behind a URI that can be subscribed to +or fetched again by the client later: ```json { @@ -208,6 +228,7 @@ Tool results can contain multiple content items of different types: Tools use two error reporting mechanisms: 1. **Protocol Errors**: Standard JSON-RPC errors for issues like: + - Unknown tools - Invalid arguments - Server errors @@ -218,6 +239,7 @@ Tools use two error reporting mechanisms: - Business logic errors Example protocol error: + ```json { "jsonrpc": "2.0", @@ -230,15 +252,18 @@ Example protocol error: ``` Example tool execution error: + ```json { "jsonrpc": "2.0", "id": 4, "result": { - "content": [{ - "type": "text", - "text": "Failed to fetch weather data: API rate limit exceeded" - }], + "content": [ + { + "type": "text", + "text": "Failed to fetch weather data: API rate limit exceeded" + } + ], "isError": true } } @@ -247,6 +272,7 @@ Example tool execution error: ## Security Considerations 1. Servers **MUST**: + - Validate all tool inputs - Implement proper access controls - Rate limit tool invocations @@ -254,7 +280,8 @@ Example tool execution error: 2. Clients **SHOULD**: - Prompt for user confirmation on sensitive operations - - Show tool inputs to the user before calling the server, to avoid malicious or accidental data exfiltration + - Show tool inputs to the user before calling the server, to avoid malicious or + accidental data exfiltration - Validate tool results before passing to LLM - Implement timeouts for tool calls - Log tool usage for audit purposes diff --git a/docs/specification/2024-11-05/server/utilities/_index.md b/docs/specification/2024-11-05/server/utilities/_index.md index 4a0d96a..9ec6981 100644 --- a/docs/specification/2024-11-05/server/utilities/_index.md +++ b/docs/specification/2024-11-05/server/utilities/_index.md @@ -2,14 +2,11 @@ title: Utilities --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} These optional features can be used to enhance server functionality. -{{< cards >}} - {{< card link="completion" title="Completion" icon="at-symbol" >}} - {{< card link="logging" title="Logging" icon="terminal" >}} - {{< card link="pagination" title="Pagination" icon="collection" >}} -{{< /cards >}} +{{< cards >}} {{< card link="completion" title="Completion" icon="at-symbol" >}} +{{< card link="logging" title="Logging" icon="terminal" >}} +{{< card link="pagination" title="Pagination" icon="collection" >}} {{< /cards >}} diff --git a/docs/specification/2024-11-05/server/utilities/completion.md b/docs/specification/2024-11-05/server/utilities/completion.md index 7c43c4c..6277ece 100644 --- a/docs/specification/2024-11-05/server/utilities/completion.md +++ b/docs/specification/2024-11-05/server/utilities/completion.md @@ -2,27 +2,35 @@ title: Completion --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} -The Model Context Protocol (MCP) provides a standardized way for servers to offer argument autocompletion suggestions for prompts and resource URIs. This enables rich, IDE-like experiences where users receive contextual suggestions while entering argument values. +The Model Context Protocol (MCP) provides a standardized way for servers to offer +argument autocompletion suggestions for prompts and resource URIs. This enables rich, +IDE-like experiences where users receive contextual suggestions while entering argument +values. ## User Interaction Model -Completion in MCP is designed to support interactive user experiences similar to IDE code completion. +Completion in MCP is designed to support interactive user experiences similar to IDE code +completion. -For example, applications may show completion suggestions in a dropdown or popup menu as users type, with the ability to filter and select from available options. +For example, applications may show completion suggestions in a dropdown or popup menu as +users type, with the ability to filter and select from available options. -However, implementations are free to expose completion through any interface pattern that suits their needs—the protocol itself does not mandate any specific user interaction model. +However, implementations are free to expose completion through any interface pattern that +suits their needs—the protocol itself does not mandate any specific user +interaction model. ## Protocol Messages ### Requesting Completions -To get completion suggestions, clients send a `completion/complete` request specifying what is being completed through a reference type: +To get completion suggestions, clients send a `completion/complete` request specifying +what is being completed through a reference type: **Request:** + ```json { "jsonrpc": "2.0", @@ -42,6 +50,7 @@ To get completion suggestions, clients send a `completion/complete` request spec ``` **Response:** + ```json { "jsonrpc": "2.0", @@ -60,10 +69,10 @@ To get completion suggestions, clients send a `completion/complete` request spec The protocol supports two types of completion references: -| Type | Description | Example | -|------|-------------|---------| -| `ref/prompt` | References a prompt by name | `{"type": "ref/prompt", "name": "code_review"}` | -| `ref/resource` | References a resource URI | `{"type": "ref/resource", "uri": "file:///{path}"}` | +| Type | Description | Example | +| -------------- | --------------------------- | --------------------------------------------------- | +| `ref/prompt` | References a prompt by name | `{"type": "ref/prompt", "name": "code_review"}` | +| `ref/resource` | References a resource URI | `{"type": "ref/resource", "uri": "file:///{path}"}` | ### Completion Results @@ -92,12 +101,14 @@ sequenceDiagram ## Data Types ### CompleteRequest + - `ref`: A `PromptReference` or `ResourceReference` - `argument`: Object containing: - `name`: Argument name - `value`: Current value ### CompleteResult + - `completion`: Object containing: - `values`: Array of suggestions (max 100) - `total`: Optional total matches @@ -106,6 +117,7 @@ sequenceDiagram ## Implementation Considerations 1. Servers **SHOULD**: + - Return suggestions sorted by relevance - Implement fuzzy matching where appropriate - Rate limit completion requests @@ -119,6 +131,7 @@ sequenceDiagram ## Security Implementations **MUST**: + - Validate all completion inputs - Implement appropriate rate limiting - Control access to sensitive suggestions diff --git a/docs/specification/2024-11-05/server/utilities/logging.md b/docs/specification/2024-11-05/server/utilities/logging.md index 3104b4f..67a3ec3 100644 --- a/docs/specification/2024-11-05/server/utilities/logging.md +++ b/docs/specification/2024-11-05/server/utilities/logging.md @@ -2,15 +2,18 @@ title: Logging --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} -The Model Context Protocol (MCP) provides a standardized way for servers to send structured log messages to clients. Clients can control logging verbosity by setting minimum log levels, with servers sending notifications containing severity levels, optional logger names, and arbitrary JSON-serializable data. +The Model Context Protocol (MCP) provides a standardized way for servers to send +structured log messages to clients. Clients can control logging verbosity by setting +minimum log levels, with servers sending notifications containing severity levels, +optional logger names, and arbitrary JSON-serializable data. ## User Interaction Model -Implementations are free to expose logging through any interface pattern that suits their needs—the protocol itself does not mandate any specific user interaction model. +Implementations are free to expose logging through any interface pattern that suits their +needs—the protocol itself does not mandate any specific user interaction model. ## Capabilities @@ -26,18 +29,19 @@ Servers that emit log message notifications **MUST** declare the `logging` capab ## Log Levels -The protocol follows the standard syslog severity levels specified in [RFC 5424](https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1): +The protocol follows the standard syslog severity levels specified in +[RFC 5424](https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1): -| Level | Description | Example Use Case | -|------------|--------------------------------------|----------------------------------------| -| debug | Detailed debugging information | Function entry/exit points | -| info | General informational messages | Operation progress updates | -| notice | Normal but significant events | Configuration changes | -| warning | Warning conditions | Deprecated feature usage | -| error | Error conditions | Operation failures | -| critical | Critical conditions | System component failures | -| alert | Action must be taken immediately | Data corruption detected | -| emergency | System is unusable | Complete system failure | +| Level | Description | Example Use Case | +| --------- | -------------------------------- | -------------------------- | +| debug | Detailed debugging information | Function entry/exit points | +| info | General informational messages | Operation progress updates | +| notice | Normal but significant events | Configuration changes | +| warning | Warning conditions | Deprecated feature usage | +| error | Error conditions | Operation failures | +| critical | Critical conditions | System component failures | +| alert | Action must be taken immediately | Data corruption detected | +| emergency | System is unusable | Complete system failure | ## Protocol Messages @@ -46,6 +50,7 @@ The protocol follows the standard syslog severity levels specified in [RFC 5424] To configure the minimum log level, clients **MAY** send a `logging/setLevel` request: **Request:** + ```json { "jsonrpc": "2.0", @@ -111,6 +116,7 @@ Servers **SHOULD** return standard JSON-RPC errors for common failure cases: ## Implementation Considerations 1. Servers **SHOULD**: + - Rate limit log messages - Include relevant context in data field - Use consistent logger names @@ -125,6 +131,7 @@ Servers **SHOULD** return standard JSON-RPC errors for common failure cases: ## Security 1. Log messages **MUST NOT** contain: + - Credentials or secrets - Personal identifying information - Internal system details that could aid attacks diff --git a/docs/specification/2024-11-05/server/utilities/pagination.md b/docs/specification/2024-11-05/server/utilities/pagination.md index c5d951f..5c230eb 100644 --- a/docs/specification/2024-11-05/server/utilities/pagination.md +++ b/docs/specification/2024-11-05/server/utilities/pagination.md @@ -1,24 +1,29 @@ --- title: Pagination --- -{{< callout type="info" >}} -**Protocol Revision**: {{< param protocolRevision >}} + +{{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} {{< /callout >}} -The Model Context Protocol (MCP) supports paginating list operations that may return large result sets. Pagination allows servers to yield results in smaller chunks rather than all at once. +The Model Context Protocol (MCP) supports paginating list operations that may return +large result sets. Pagination allows servers to yield results in smaller chunks rather +than all at once. -Pagination is especially important when connecting to external services over the internet, but also useful for local integrations to avoid performance issues with large data sets. +Pagination is especially important when connecting to external services over the +internet, but also useful for local integrations to avoid performance issues with large +data sets. ## Pagination Model Pagination in MCP uses an opaque cursor-based approach, instead of numbered pages. -* The **cursor** is an opaque string token, representing a position in the result set -* **Page size** is determined by the server, and **MAY NOT** be fixed +- The **cursor** is an opaque string token, representing a position in the result set +- **Page size** is determined by the server, and **MAY NOT** be fixed ## Response Format Pagination starts when the server sends a **response** that includes: + - The current page of results - An optional `nextCursor` field if more results exist @@ -35,7 +40,8 @@ Pagination starts when the server sends a **response** that includes: ## Request Format -After receiving a cursor, the client can _continue_ paginating by issuing a request including that cursor: +After receiving a cursor, the client can _continue_ paginating by issuing a request +including that cursor: ```json { @@ -73,10 +79,12 @@ The following MCP operations support pagination: ## Implementation Guidelines 1. Servers **SHOULD**: + - Provide stable cursors - Handle invalid cursors gracefully 2. Clients **SHOULD**: + - Treat a missing `nextCursor` as the end of results - Support both paginated and non-paginated flows diff --git a/docs/specification/CLAUDE.md b/docs/specification/CLAUDE.md new file mode 100644 index 0000000..bb8d9e7 --- /dev/null +++ b/docs/specification/CLAUDE.md @@ -0,0 +1,117 @@ +# Documentation Style Guide + +## General Structure + +1. Every markdown file MUST start with a frontmatter section containing: + + ```yaml + --- + title: [Page Title] + type: docs + weight: [numeric weight for ordering] + --- + ``` + +2. After frontmatter, include the protocol revision callout: + ```markdown + {{< callout type="info" >}} **Protocol Revision**: {{< param protocolRevision >}} + {{< /callout >}} + ``` + +## Writing Style + +1. Technical Requirements + + - Use RFC 2119 keywords (MUST, SHOULD, MAY) in all capitals when specifying + requirements + - Each requirement should be clear and unambiguous + - Include code examples for technical concepts + +2. Code Blocks + + - Use TypeScript for interface and type definitions + - Include language identifier in code fence (```typescript) + - Format code consistently with 2-space indentation + +3. Lists and Structure + + - Use bullet points for related items without hierarchy + - Use numbered lists for sequential steps or prioritized items + - Indent sub-bullets consistently + +4. Technical Accuracy + - All code examples must be syntactically correct + - Reference official specifications when applicable + - Include links to related documentation + +## Content Organization + +1. Page Structure + + - Start with a brief overview/introduction + - Use clear H2 (##) and H3 (###) headings + - Group related concepts under common headings + - End with relevant links or next steps if applicable + +2. Section Hierarchy + + - Use H1 (#) for document title only + - Use H2 (##) for major sections + - Use H3 (###) for subsections + - Avoid going deeper than H4 + +3. Cross-References + - Use relative links for internal references + - Use absolute links for external references + - Include hover text for non-obvious links + +## Formatting Conventions + +1. Code and Technical Terms + + - Use backticks for inline code and technical terms + - Use code blocks for multi-line code examples + - Use proper syntax highlighting + +2. Emphasis + + - Use bold (\*\*) for important terms and concepts + - Use italics (\*) sparingly, mainly for emphasis + - Avoid underlining + +3. Tables + - Use tables for structured data comparison + - Include header row + - Align columns consistently + +## Special Elements + +1. Callouts + + - Use for important notices or version information + - Include type (info, warning, etc.) + - Keep content concise + +2. Cards + - Use for navigation sections + - Include relevant icons + - Keep titles short and descriptive + +## Language and Tone + +1. Voice + + - Use active voice + - Be direct and concise + - Maintain technical precision + +2. Terminology + + - Use consistent terminology throughout + - Define technical terms on first use + - Follow industry standard terminology + +3. Audience + - Write for technical implementers + - Assume familiarity with basic concepts + - Explain complex concepts clearly diff --git a/docs/specification/draft/_index.md b/docs/specification/draft/_index.md index daf3167..376948b 100644 --- a/docs/specification/draft/_index.md +++ b/docs/specification/draft/_index.md @@ -6,17 +6,27 @@ breadcrumbs: false weight: 10 --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} -[Model Context Protocol](https://modelcontextprotocol.io) (MCP) is an open protocol that enables seamless integration between LLM applications and external data sources and tools. Whether you're building an AI-powered IDE, enhancing a chat interface, or creating custom AI workflows, MCP provides a standardized way to connect LLMs with the context they need. +[Model Context Protocol](https://modelcontextprotocol.io) (MCP) is an open protocol that +enables seamless integration between LLM applications and external data sources and +tools. Whether you're building an AI-powered IDE, enhancing a chat interface, or creating +custom AI workflows, MCP provides a standardized way to connect LLMs with the context +they need. -This specification defines the authoritative protocol requirements, based on the TypeScript schema in [schema.ts](https://github.com/modelcontextprotocol/specification/draft/blob/main/schema/schema.ts). +This specification defines the authoritative protocol requirements, based on the +TypeScript schema in +[schema.ts](https://github.com/modelcontextprotocol/specification/draft/blob/main/schema/schema.ts). -For implementation guides and examples, visit [modelcontextprotocol.io](https://modelcontextprotocol.io). +For implementation guides and examples, visit +[modelcontextprotocol.io](https://modelcontextprotocol.io). -The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [BCP 14](https://datatracker.ietf.org/doc/html/bcp14) [[RFC2119](https://datatracker.ietf.org/doc/html/rfc2119)] [[RFC8174](https://datatracker.ietf.org/doc/html/rfc8174)] when, and only when, they appear in all capitals, as shown here. +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD +NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be +interpreted as described in [BCP 14](https://datatracker.ietf.org/doc/html/bcp14) +[[RFC2119](https://datatracker.ietf.org/doc/html/rfc2119)] +[[RFC8174](https://datatracker.ietf.org/doc/html/rfc8174)] when, and only when, they +appear in all capitals, as shown here. ## Overview @@ -26,17 +36,23 @@ MCP provides a standardized way for applications to: - Expose tools and capabilities to AI systems - Build composable integrations and workflows -The protocol uses [JSON-RPC](https://www.jsonrpc.org/) 2.0 messages to establish communication between: +The protocol uses [JSON-RPC](https://www.jsonrpc.org/) 2.0 messages to establish +communication between: - **Hosts**: LLM applications that initiate connections - **Clients**: Connectors within the host application - **Servers**: Services that provide context and capabilities -MCP takes some inspiration from the [Language Server Protocol](https://microsoft.github.io/language-server-protocol/), which standardizes how to add support for programming languages across a whole ecosystem of development tools. In a similar way, MCP standardizes how to integrate additional context and tools into the ecosystem of AI applications. +MCP takes some inspiration from the +[Language Server Protocol](https://microsoft.github.io/language-server-protocol/), which +standardizes how to add support for programming languages across a whole ecosystem of +development tools. In a similar way, MCP standardizes how to integrate additional context +and tools into the ecosystem of AI applications. ## Key Details ### Base Protocol + - [JSON-RPC](https://www.jsonrpc.org/) message format - Stateful connections - Server and client capability negotiation @@ -63,22 +79,28 @@ Clients may offer the following feature to servers: ## Security and Trust & Safety -The Model Context Protocol enables powerful capabilities through arbitrary data access and code execution paths. With this power comes important security and trust considerations that all implementors must carefully address. +The Model Context Protocol enables powerful capabilities through arbitrary data access +and code execution paths. With this power comes important security and trust +considerations that all implementors must carefully address. ### Key Principles 1. **User Consent and Control** + - Users must explicitly consent to and understand all data access and operations - Users must retain control over what data is shared and what actions are taken - Implementors should provide clear UIs for reviewing and authorizing activities 2. **Data Privacy** + - Hosts must obtain explicit user consent before exposing user data to servers - Hosts must not transmit resource data elsewhere without user consent - User data should be protected with appropriate access controls 3. **Tool Safety** - - Tools represent arbitrary code execution and must be treated with appropriate caution + + - Tools represent arbitrary code execution and must be treated with appropriate + caution - Hosts must obtain explicit user consent before invoking any tool - Users should understand what each tool does before authorizing its use @@ -92,7 +114,8 @@ The Model Context Protocol enables powerful capabilities through arbitrary data ### Implementation Guidelines -While MCP itself cannot enforce these security principles at the protocol level, implementors **SHOULD**: +While MCP itself cannot enforce these security principles at the protocol level, +implementors **SHOULD**: 1. Build robust consent and authorization flows into their applications 2. Provide clear documentation of security implications @@ -104,10 +127,8 @@ While MCP itself cannot enforce these security principles at the protocol level, Explore the detailed specification for each protocol component: -{{< cards >}} - {{< card link="architecture" title="Architecture" icon="template" >}} - {{< card link="basic" title="Base Protocol" icon="code" >}} - {{< card link="server" title="Server Features" icon="server" >}} - {{< card link="client" title="Client Features" icon="user" >}} - {{< card link="contributing" title="Contributing" icon="pencil" >}} -{{< /cards >}} +{{< cards >}} {{< card link="architecture" title="Architecture" icon="template" >}} +{{< card link="basic" title="Base Protocol" icon="code" >}} +{{< card link="server" title="Server Features" icon="server" >}} +{{< card link="client" title="Client Features" icon="user" >}} +{{< card link="contributing" title="Contributing" icon="pencil" >}} {{< /cards >}} diff --git a/docs/specification/draft/architecture/_index.md b/docs/specification/draft/architecture/_index.md index 30aaf0f..9a6be76 100644 --- a/docs/specification/draft/architecture/_index.md +++ b/docs/specification/draft/architecture/_index.md @@ -5,7 +5,11 @@ cascade: weight: 1 --- -The Model Context Protocol (MCP) follows a client-host-server architecture where each host can run multiple client instances. This architecture enables users to integrate AI capabilities across applications while maintaining clear security boundaries and isolating concerns. Built on JSON-RPC, MCP provides a stateful session protocol focused on context exchange and sampling coordination between clients and servers. +The Model Context Protocol (MCP) follows a client-host-server architecture where each +host can run multiple client instances. This architecture enables users to integrate AI +capabilities across applications while maintaining clear security boundaries and +isolating concerns. Built on JSON-RPC, MCP provides a stateful session protocol focused +on context exchange and sampling coordination between clients and servers. ## Core Components @@ -43,7 +47,9 @@ graph LR ``` ### Host + The host process acts as the container and coordinator: + - Creates and manages multiple client instances - Controls client connection permissions and lifecycle - Enforces security policies and consent requirements @@ -52,17 +58,22 @@ The host process acts as the container and coordinator: - Manages context aggregation across clients ### Clients + Each client is created by the host and maintains an isolated server connection: + - Establishes one stateful session per server - Handles protocol negotiation and capability exchange - Routes protocol messages bidirectionally - Manages subscriptions and notifications - Maintains security boundaries between servers -A host application creates and manages multiple clients, with each client having a 1:1 relationship with a particular server. +A host application creates and manages multiple clients, with each client having a 1:1 +relationship with a particular server. ### Servers + Servers provide specialized context and capabilities: + - Expose resources, tools and prompts via MCP primitives - Operate independently with focused responsibilities - Request sampling through client interfaces @@ -71,48 +82,59 @@ Servers provide specialized context and capabilities: ## Design Principles -MCP is built on several key design principles that inform its architecture and implementation: +MCP is built on several key design principles that inform its architecture and +implementation: 1. **Servers should be extremely easy to build** - - Host applications handle complex orchestration responsibilities - - Servers focus on specific, well-defined capabilities - - Simple interfaces minimize implementation overhead - - Clear separation enables maintainable code + + - Host applications handle complex orchestration responsibilities + - Servers focus on specific, well-defined capabilities + - Simple interfaces minimize implementation overhead + - Clear separation enables maintainable code 2. **Servers should be highly composable** - - Each server provides focused functionality in isolation - - Multiple servers can be combined seamlessly - - Shared protocol enables interoperability - - Modular design supports extensibility - -3. **Servers should not be able to read the whole conversation, nor "see into" other servers** - - Servers receive only necessary contextual information - - Full conversation history stays with the host - - Each server connection maintains isolation - - Cross-server interactions are controlled by the host - - Host process enforces security boundaries + + - Each server provides focused functionality in isolation + - Multiple servers can be combined seamlessly + - Shared protocol enables interoperability + - Modular design supports extensibility + +3. **Servers should not be able to read the whole conversation, nor "see into" other + servers** + + - Servers receive only necessary contextual information + - Full conversation history stays with the host + - Each server connection maintains isolation + - Cross-server interactions are controlled by the host + - Host process enforces security boundaries 4. **Features can be added to servers and clients progressively** - - Core protocol provides minimal required functionality - - Additional capabilities can be negotiated as needed - - Servers and clients evolve independently - - Protocol designed for future extensibility - - Backwards compatibility is maintained + - Core protocol provides minimal required functionality + - Additional capabilities can be negotiated as needed + - Servers and clients evolve independently + - Protocol designed for future extensibility + - Backwards compatibility is maintained ## Message Types -MCP defines three core message types based on [JSON-RPC 2.0](https://www.jsonrpc.org/specification): + +MCP defines three core message types based on +[JSON-RPC 2.0](https://www.jsonrpc.org/specification): - **Requests**: Bidirectional messages with method and parameters expecting a response - **Responses**: Successful results or errors matching specific request IDs - **Notifications**: One-way messages requiring no response -Each message type follows the JSON-RPC 2.0 specification for structure and delivery semantics. +Each message type follows the JSON-RPC 2.0 specification for structure and delivery +semantics. ## Capability Negotiation -The Model Context Protocol uses a capability-based negotiation system where clients and servers explicitly declare their supported features during initialization. Capabilities determine which protocol features and primitives are available during a session. +The Model Context Protocol uses a capability-based negotiation system where clients and +servers explicitly declare their supported features during initialization. Capabilities +determine which protocol features and primitives are available during a session. -- Servers declare capabilities like resource subscriptions, tool support, and prompt templates +- Servers declare capabilities like resource subscriptions, tool support, and prompt + templates - Clients declare capabilities like sampling support and notification handling - Both parties must respect declared capabilities throughout the session - Additional capabilities can be negotiated through extensions to the protocol @@ -153,10 +175,16 @@ sequenceDiagram deactivate Server ``` -Each capability unlocks specific protocol features for use during the session. For example: -- Implemented [server features]({{< ref "/specification/draft/server" >}}) must be advertised in the server's capabilities -- Emitting resource subscription notifications requires the server to declare subscription support +Each capability unlocks specific protocol features for use during the session. For +example: + +- Implemented [server features]({{< ref "/specification/draft/server" >}}) must be + advertised in the server's capabilities +- Emitting resource subscription notifications requires the server to declare + subscription support - Tool invocation requires the server to declare tool capabilities -- [Sampling]({{< ref "/specification/draft/client" >}}) requires the client to declare support in its capabilities +- [Sampling]({{< ref "/specification/draft/client" >}}) requires the client to declare + support in its capabilities -This capability negotiation ensures clients and servers have a clear understanding of supported functionality while maintaining protocol extensibility. +This capability negotiation ensures clients and servers have a clear understanding of +supported functionality while maintaining protocol extensibility. diff --git a/docs/specification/draft/basic/_index.md b/docs/specification/draft/basic/_index.md index 3676785..e1e2a6f 100644 --- a/docs/specification/draft/basic/_index.md +++ b/docs/specification/draft/basic/_index.md @@ -5,53 +5,69 @@ cascade: weight: 2 --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} -All messages between MCP clients and servers **MUST** follow the [JSON-RPC 2.0](https://www.jsonrpc.org/specification) specification. The protocol defines three fundamental types of messages: +All messages between MCP clients and servers **MUST** follow the +[JSON-RPC 2.0](https://www.jsonrpc.org/specification) specification. The protocol defines +three fundamental types of messages: -| Type | Description | Requirements | -|----------------|----------------------------------------|----------------------------------------| -| `Requests` | Messages sent to initiate an operation | Must include unique ID and method name | -| `Responses` | Messages sent in reply to requests | Must include same ID as request | -| `Notifications`| One-way messages with no reply | Must not include an ID | +| Type | Description | Requirements | +| --------------- | -------------------------------------- | -------------------------------------- | +| `Requests` | Messages sent to initiate an operation | Must include unique ID and method name | +| `Responses` | Messages sent in reply to requests | Must include same ID as request | +| `Notifications` | One-way messages with no reply | Must not include an ID | -**Responses** are further sub-categorized as either **successful results** or **errors**. Results can follow any JSON object structure, while errors must include an error code and message at minimum. +**Responses** are further sub-categorized as either **successful results** or **errors**. +Results can follow any JSON object structure, while errors must include an error code and +message at minimum. ## Protocol Layers The Model Context Protocol consists of several key components that work together: - **Base Protocol**: Core JSON-RPC message types -- **Lifecycle Management**: Connection initialization, capability negotiation, and session control +- **Lifecycle Management**: Connection initialization, capability negotiation, and + session control - **Server Features**: Resources, prompts, and tools exposed by servers - **Client Features**: Sampling and root directory lists provided by clients - **Utilities**: Cross-cutting concerns like logging and argument completion -All implementations **MUST** support the base protocol and lifecycle management components. Other components **MAY** be implemented based on the specific needs of the application. +All implementations **MUST** support the base protocol and lifecycle management +components. Other components **MAY** be implemented based on the specific needs of the +application. -These protocol layers establish clear separation of concerns while enabling rich interactions between clients and servers. The modular design allows implementations to support exactly the features they need. +These protocol layers establish clear separation of concerns while enabling rich +interactions between clients and servers. The modular design allows implementations to +support exactly the features they need. See the following pages for more details on the different components: {{< cards >}} - {{< card link="/specification/draft/basic/lifecycle" title="Lifecycle" icon="refresh" >}} - {{< card link="/specification/draft/server/resources" title="Resources" icon="document" >}} - {{< card link="/specification/draft/server/prompts" title="Prompts" icon="chat-alt-2" >}} - {{< card link="/specification/draft/server/tools" title="Tools" icon="adjustments" >}} - {{< card link="/specification/draft/server/utilities/logging" title="Logging" icon="annotation" >}} - {{< card link="/specification/draft/client/sampling" title="Sampling" icon="code" >}} +{{< card link="/specification/draft/basic/lifecycle" title="Lifecycle" icon="refresh" >}} +{{< card link="/specification/draft/server/resources" title="Resources" icon="document" >}} +{{< card link="/specification/draft/server/prompts" title="Prompts" icon="chat-alt-2" >}} +{{< card link="/specification/draft/server/tools" title="Tools" icon="adjustments" >}} +{{< card link="/specification/draft/server/utilities/logging" title="Logging" icon="annotation" >}} +{{< card link="/specification/draft/client/sampling" title="Sampling" icon="code" >}} {{< /cards >}} ## Auth -Authentication and authorization are not currently part of the core MCP specification, but we are considering ways to introduce them in future. Join us in [GitHub Discussions](https://github.com/modelcontextprotocol/specification/draft/discussions) to help shape the future of the protocol! +Authentication and authorization are not currently part of the core MCP specification, +but we are considering ways to introduce them in future. Join us in +[GitHub Discussions](https://github.com/modelcontextprotocol/specification/draft/discussions) +to help shape the future of the protocol! -Clients and servers **MAY** negotiate their own custom authentication and authorization strategies. +Clients and servers **MAY** negotiate their own custom authentication and authorization +strategies. ## Schema -The full specification of the protocol is defined as a [TypeScript schema](http://github.com/modelcontextprotocol/specification/draft/tree/main/schema/schema.ts). This is the source of truth for all protocol messages and structures. +The full specification of the protocol is defined as a +[TypeScript schema](http://github.com/modelcontextprotocol/specification/draft/tree/main/schema/schema.ts). +This is the source of truth for all protocol messages and structures. -There is also a [JSON Schema](http://github.com/modelcontextprotocol/specification/draft/tree/main/schema/schema.json), which is automatically generated from the TypeScript source of truth, for use with various automated tooling. +There is also a +[JSON Schema](http://github.com/modelcontextprotocol/specification/draft/tree/main/schema/schema.json), +which is automatically generated from the TypeScript source of truth, for use with +various automated tooling. diff --git a/docs/specification/draft/basic/authentication.md b/docs/specification/draft/basic/authentication.md new file mode 100644 index 0000000..45b108f --- /dev/null +++ b/docs/specification/draft/basic/authentication.md @@ -0,0 +1,417 @@ +--- +title: Authentication +type: docs +weight: 15 +--- + +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} + +## 1. Introduction + +### 1.1 Purpose and Scope + +The Model Context Protocol provides authentication capabilities at the transport level, +enabling MCP clients to make requests to restricted resources on behalf of resource +owners. This specification defines the authentication flow for HTTP+SSE transport. + +### 1.2 Protocol Requirements + +MCP clients and servers supporting HTTP+SSE transport **SHOULD** implement this +specification, though they **MAY** support additional authentication mechanisms. +Implementations using alternative transports **MAY** implement authentication according +to the best practices for their specific transport. + +For deployments supporting third-party clients or servers via HTTP+SSE, implementations +**SHOULD** expect authentication as defined in this document. However, controlled +environment deployments like corporate networks **MAY** implement alternative methods +such as certificate-based authentication. + +### 1.3 Standards Compliance + +This authentication mechanism implements following specifications but recommends a +specific subsets: + +- [OAuth 2.1 IETF DRAFT](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12) +- OAuth 2.0 Authentication Server Metadata + ([RFC8414](https://datatracker.ietf.org/doc/html/rfc8414)) +- OAuth 2.0 Dynamic Client Registration Protocol + ([RFC7591](https://datatracker.ietf.org/doc/html/rfc7591)) + +## 2. Authentication Flow + +### 2.1 Overview + +MCP is designed to support interactive, user-facing developer tools that connect to +arbitrary servers. This leads to two key design decisions: + +1. All MCP clients **MUST** be treated as public OAuth 2.1 clients, as they cannot + securely store client secrets when distributed to end users + +2. PKCE **MUST** be implemented by all clients to prevent authorization code interception + attacks, which is especially important for locally-running tools + +3. All MCP implementations **MUST** support the OAuth 2.0 Dynamic Client Registration + Protocol ([RFC7591](https://datatracker.ietf.org/doc/html/rfc7591)), with the + exception of servers that only listen on loopback interfaces (e.g. localhost for + native application authentication). + +4. All MCP implementations **SHOULD** implement OAuth 2.0 Authentication Server Metadata + ([RFC8414](https://datatracker.ietf.org/doc/html/rfc8414)). Servers that do not + support Authentication Server Metadata **MUST** follow the default URI schema. + +### 2.2 Basic OAuth 2.1 Authentication + +When authentication is required, servers **MUST** respond with HTTP 401 Unauthorized. The +basic +[OAuth 2.1 IETF DRAFT](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12) +authentication flow with PKCE comprises the following sequence: + +```mermaid +sequenceDiagram + participant B as User-Agent (Browser) + participant C as Client + participant M as MCP Server + + C->>M: MCP Request + M->>C: HTTP 401 Unauthorized + Note over C: Generate code_verifier and code_challenge + C->>B: Open browser with authorization URL + code_challenge + B->>M: GET /authorize + Note over M: User logs in and authorizes + M->>B: Redirect to callback URL with auth code + B->>C: Callback with authorization code + C->>M: Token Request with code + code_verifier + M->>C: Access Token + Refresh Token + C->>M: MCP Request with Access Token + Note over C,M: Begin standard MCP message exchange +``` + +### 2.3 Server Metadata Discovery + +Since MCP clients need to connect to previously unknown servers, automated server +capability discovery is essential. The metadata discovery mechanism allows clients to: + +- Locate the OAuth endpoints without manual configuration +- Determine supported authentication features +- Adapt to server-specific requirements +- Enable zero-configuration connections to new servers + +The discovery flow is illustrated below: + +```mermaid +sequenceDiagram + participant C as Client + participant S as Server + + C->>S: GET /.well-known/oauth-authorization-server + alt Discovery Success + S->>C: 200 OK + Metadata Document + Note over C: Use endpoints from metadata + else Discovery Failed + S->>C: 404 Not Found + Note over C: Fall back to default endpoints + end + Note over C: Continue with authentication flow +``` + +#### 2.3.1 Discovery Document Location + +MCP servers **SHOULD** implement OAuth 2.0 Authentication Server Metadata +[RFC8414](https://datatracker.ietf.org/doc/html/rfc8414) by exposing a discovery document +at: + +``` +/.well-known/oauth-authorization-server +``` + +#### 2.3.2 Required Fields + +The discovery document **MUST** include the following fields: + +| Field | Description | +| -------------------------------- | ---------------------------------- | +| authorization_endpoint | Authorization request endpoint URL | +| token_endpoint | Token exchange endpoint URL | +| registration_endpoint | Client registration endpoint URL | +| code_challenge_methods_supported | Supported PKCE methods | +| response_types_supported | Supported OAuth response types | +| grant_types_supported | Supported OAuth grant types | + +Example discovery document: + +```json +{ + "issuer": "https://mcp.example.com", + "authorization_endpoint": "https://mcp.example.com/authorize", + "token_endpoint": "https://mcp.example.com/token", + "registration_endpoint": "https://mcp.example.com/register", + "code_challenge_methods_supported": ["S256"], + "response_types_supported": ["code"], + "grant_types_supported": ["authorization_code", "refresh_token"], + "scopes_supported": ["mcp"] +} +``` + +#### 2.3.3 Fallback for Servers without Server Metadata Discovery + +For servers that do not implement OAuth 2.0 Authentication Server Metadata, clients +**MUST** use the following default endpoint paths relative to the server's base URL: + +| Endpoint | Default Path | Description | +| ---------------------- | ------------ | ------------------------------------ | +| Authorization Endpoint | /authorize | Used for authorization requests | +| Token Endpoint | /token | Used for token exchange & refresh | +| Registration Endpoint | /register | Used for dynamic client registration | + +These default paths **MUST** be used when: + +1. The /.well-known/oauth-authorization-server endpoint returns a 404 status code +2. The metadata document cannot be retrieved or parsed +3. Required endpoints are missing from the metadata document + +Clients **SHOULD** first attempt to discover endpoints via the metadata document before +falling back to default paths. When using default paths, all other protocol requirements +remain unchanged. + +Example default endpoints for https://mcp.example.com: + +``` +https://mcp.example.com/authorize +https://mcp.example.com/token +https://mcp.example.com/register +``` + +### 2.3 Client Registration Requirements + +MCP defines two distinct registration scenarios based on the redirect URI: + +#### 2.3.1 Localhost Redirect URIs + +When using localhost redirect URIs (http://localhost:{port} or http://127.0.0.1:{port}), +clients: + +- Do **NOT** require dynamic registration +- **MUST** use PKCE +- **MAY** proceed directly to authorization +- **MUST NOT** require client secrets + +This exception for localhost is explicitly supported by OAuth 2.1 for public clients and +provides a secure flow through the combination of PKCE and localhost-only redirects. + +#### 2.3.2 Non-Localhost Redirect URIs + +For all other redirect URIs, dynamic client registration is **REQUIRED**. This provides a +standardized way for clients to automatically register with new servers, which is crucial +for MCP because: + +- Clients cannot know all possible servers in advance +- Manual registration would create friction for users +- It enables seamless connection to new servers +- Servers can implement their own registration policies + +#### 2.3.3 Registration Process + +For non-localhost scenarios, clients register with the server by making a POST request to +the registration endpoint with their client metadata: + +``` +POST /register HTTP/1.1 +Content-Type: application/json + +{ + "client_name": "Example MCP Client", + "redirect_uris": ["https://example.com/callback"], + "token_endpoint_auth_method": "none", + "grant_types": ["authorization_code", "refresh_token"], + "response_types": ["code"], + "scope": "mcp" +} +``` + +#### 2.3.4 Server Response + +The server responds with client credentials: + +```json +{ + "client_id": "s6BhdRkqt3", + "client_secret": null, + "registration_access_token": "reg-23410913-abewfq", + "registration_client_uri": "https://mcp.example.com/register/s6BhdRkqt3", + "client_id_issued_at": 2893256800 +} +``` + +### 2.4 Authentication Flow Steps + +The complete authentication flow proceeds as follows: + +1. Client discovers server metadata (if supported) +2. For non-localhost redirect URIs, client **MUST** register dynamically with server +3. Client generates PKCE code_verifier and code_challenge +4. Client requests authorization with code_challenge +5. User authenticates and authorizes the client +6. Server returns authorization code +7. Client exchanges code and code_verifier for tokens +8. Client uses access token for API requests + +**NOTE**: Dynamic registration (step 2) is only required when using non-localhost +redirect URIs. Clients using localhost redirect URIs may skip this step. + +Flow diagram: + +```mermaid +sequenceDiagram + participant B as User-Agent (Browser) + participant C as Client + participant M as MCP Server + + C->>M: GET /.well-known/oauth-authorization-server + alt Server Supports Discovery + M->>C: Authorization Server Metadata + else No Discovery + M->>C: 404 (Use default endpoints) + end + + alt Non-Localhost Redirect URI + C->>M: POST /register + M->>C: Client Credentials + end + + Note over C: Generate PKCE Parameters + C->>B: Open browser with authorization URL + code_challenge + B->>M: Authorization Request + Note over M: User authenticates/authorizes + M->>B: Redirect to callback with authorization code + B->>C: Authorization code callback + C->>M: Token Request + code_verifier + M->>C: Access Token + Refresh Token + C->>M: API Requests with Access Token +``` + +### 2.5 Access Token Usage + +#### 2.5.1 Token Requirements + +Access token handling **MUST** conform to +[OAuth 2.1 Section 5](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5) +requirements for resource requests. Specifically: + +1. Access tokens **MUST** be included using one of the two methods defined in + [Section 5.1](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5.1) + +2. The preferred method is using the Authorization header with Bearer scheme per + [Section 5.1.1](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5.1.1): + +``` +Authorization: Bearer +``` + +3. Form-encoded body parameters per + [Section 5.1.2](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5.1.2) + **MAY** be supported as a fallback + +4. Access tokens **MUST NOT** be included in the URI query string + +Example request: + +```http +GET /v1/contexts HTTP/1.1 +Host: mcp.example.com +Authorization: Bearer eyJhbGciOiJIUzI1NiIs... +``` + +#### 2.5.2 Token Handling + +Resource servers **MUST** validate access tokens as described in +[Section 5.2](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5.2). +If validation fails, servers **MUST** respond according to +[Section 5.3](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-5.3) +error handling requirements. Invalid or expired tokens **MUST** receive a HTTP 401 +response with a WWW-Authenticate header indicating the error. + +### 2.6 Security Considerations + +The following security requirements **MUST** be implemented: + +1. Clients **MUST** securely store tokens following OAuth 2.0 best practices +2. Servers **SHOULD** enforce token expiration and rotation +3. All authorization endpoints **MUST** be served over HTTPS +4. Servers **MUST** validate redirect URIs to prevent open redirect vulnerabilities +5. Redirect URIs **MUST** be either localhost URLs or HTTPS URLs + +### 2.7 Error Handling + +Servers **MUST** return appropriate HTTP status codes for authentication errors: + +| Status Code | Description | Usage | +| ----------- | ------------ | ------------------------------------------ | +| 401 | Unauthorized | Authentication required or token invalid | +| 403 | Forbidden | Invalid scopes or insufficient permissions | +| 400 | Bad Request | Malformed authentication request | + +### 2.8 Implementation Requirements + +1. Implementations **MUST** follow OAuth 2.1 security best practices +2. PKCE is **REQUIRED** for all clients +3. Refresh token rotation **SHOULD** be implemented for enhanced security +4. Token lifetimes **SHOULD** be limited based on security requirements + +### 2.9 Third-Party Authentication Flow + +#### 2.9.1 Overview + +MCP servers **MAY** support delegated authentication through third-party authorization servers. In this flow, the MCP server acts as both an OAuth client (to the third-party auth server) and an OAuth authorization server (to the MCP client). + +#### 2.9.2 Flow Description + +The third-party authentication flow comprises these steps: + +1. MCP client initiates standard OAuth flow with MCP server +2. MCP server redirects user to third-party authorization server +3. User authenticates with third-party server +4. Third-party server redirects back to MCP server with authorization code +5. MCP server exchanges code for third-party access token +6. MCP server generates its own access token bound to the third-party session +7. MCP server completes original OAuth flow with MCP client + +```mermaid +sequenceDiagram + participant B as User-Agent (Browser) + participant C as MCP Client + participant M as MCP Server + participant T as Third-Party Auth Server + + C->>M: Initial OAuth Request + M->>B: Redirect to Third-Party /authorize + B->>T: Authorization Request + Note over T: User authenticates + T->>B: Redirect to MCP Server callback + B->>M: Authorization code + M->>T: Exchange code for token + T->>M: Third-party access token + Note over M: Generate bound MCP token + M->>B: Redirect to MCP Client callback + B->>C: MCP authorization code + C->>M: Exchange code for token + M->>C: MCP access token +``` + +#### 2.9.3 Session Binding Requirements + +MCP servers implementing third-party authentication **MUST**: + +1. Maintain secure mapping between third-party tokens and issued MCP tokens +2. Validate third-party token status before honoring MCP tokens +3. Implement appropriate token lifecycle management +4. Handle third-party token expiration and renewal + +#### 2.9.4 Security Considerations + +When implementing third-party authentication, servers **MUST**: + +1. Validate all redirect URIs +2. Securely store third-party credentials +3. Implement appropriate session timeout handling +4. Consider security implications of token chaining +5. Implement proper error handling for third-party auth failures diff --git a/docs/specification/draft/basic/lifecycle.md b/docs/specification/draft/basic/lifecycle.md index 995f84b..a861224 100644 --- a/docs/specification/draft/basic/lifecycle.md +++ b/docs/specification/draft/basic/lifecycle.md @@ -4,11 +4,10 @@ type: docs weight: 30 --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} -The Model Context Protocol (MCP) defines a rigorous lifecycle for client-server connections that ensures proper capability negotiation and state management. +The Model Context Protocol (MCP) defines a rigorous lifecycle for client-server +connections that ensures proper capability negotiation and state management. 1. **Initialization**: Capability negotiation and protocol version agreement 2. **Operation**: Normal protocol communication @@ -40,12 +39,15 @@ sequenceDiagram ### Initialization -The initialization phase **MUST** be the first interaction between client and server. During this phase, the client and server: +The initialization phase **MUST** be the first interaction between client and server. +During this phase, the client and server: - Establish protocol version compatibility - Exchange and negotiate capabilities - Share implementation details +#### Initial Request + The client **MUST** initiate this phase by sending an `initialize` request containing: - Protocol version supported @@ -73,6 +75,8 @@ The client **MUST** initiate this phase by sending an `initialize` request conta } ``` +#### Server Response + The server **MUST** respond with its own capabilities and information: ```json @@ -102,7 +106,42 @@ The server **MUST** respond with its own capabilities and information: } ``` -After successful initialization, the client **MUST** send an `initialized` notification to indicate it is ready to begin normal operations: +#### Upgrading Transports + +The server **MAY** request a transport change by including an `upgrade` field in the +initialize response: + +```json +{ + "jsonrpc": "2.0", + "id": 1, + "result": { + "protocolVersion": "2024-11-05", + "upgrade": { + "endpoint": "http://localhost:8080", + "transport": "http+sse" + }, + "serverInfo": { + "name": "ExampleServer", + "version": "1.0.0" + } + } +} +``` + +When receiving an upgrade response, the client **MUST**: + +1. Close the current transport connection +2. Connect to the specified endpoint using the new transport +3. Perform initialization again on the new transport + +Clients **MUST** track transport history and **MUST NOT** accept upgrades to previously +used transports to prevent upgrade loops. + +#### Initialization Complete + +After successful initialization, the client **MUST** send an `initialized` notification +to indicate it is ready to begin normal operations: ```json { @@ -111,41 +150,54 @@ After successful initialization, the client **MUST** send an `initialized` notif } ``` -* The client **SHOULD NOT** send requests other than [pings]({{< ref "/specification/draft/basic/utilities/ping" >}}) before the server has responded to the `initialize` request. -* The server **SHOULD NOT** send requests other than [pings]({{< ref "/specification/draft/basic/utilities/ping" >}}) and [logging]({{< ref "/specification/draft/server/utilities/logging" >}}) before receiving the `initialized` notification. +- The client **SHOULD NOT** send requests other than + [pings]({{< ref "/specification/draft/basic/utilities/ping" >}}) before the server has + responded to the `initialize` request. +- The server **SHOULD NOT** send requests other than + [pings]({{< ref "/specification/draft/basic/utilities/ping" >}}) and + [logging]({{< ref "/specification/draft/server/utilities/logging" >}}) before receiving + the `initialized` notification. #### Version Negotiation -In the `initialize` request, the client **MUST** send a protocol version it supports. This **SHOULD** be the _latest_ version supported by the client. +In the `initialize` request, the client **MUST** send a protocol version it supports. +This **SHOULD** be the _latest_ version supported by the client. -If the server supports the requested protocol version, it **MUST** respond with the same version. Otherwise, the server **MUST** respond with another protocol version it supports. This **SHOULD** be the _latest_ version supported by the server. +If the server supports the requested protocol version, it **MUST** respond with the same +version. Otherwise, the server **MUST** respond with another protocol version it +supports. This **SHOULD** be the _latest_ version supported by the server. -If the client does not support the version in the server's response, it **SHOULD** disconnect. +If the client does not support the version in the server's response, it **SHOULD** +disconnect. #### Capability Negotiation -Client and server capabilities establish which optional protocol features will be available during the session. +Client and server capabilities establish which optional protocol features will be +available during the session. Key capabilities include: -| Category | Capability | Description | -|----------|--------------- |-------------| -| Client | `roots` | Ability to provide filesystem [roots]({{< ref "/specification/draft/client/roots" >}}) | -| Client | `sampling` | Support for LLM [sampling]({{< ref "/specification/draft/client/sampling" >}}) requests | -| Client | `experimental` | Describes support for non-standard experimental features | -| Server | `prompts` | Offers [prompt templates]({{< ref "/specification/draft/server/prompts" >}}) | -| Server | `resources` | Provides readable [resources]({{< ref "/specification/draft/server/resources" >}}) | -| Server | `tools` | Exposes callable [tools]({{< ref "/specification/draft/server/tools" >}}) | +| Category | Capability | Description | +| -------- | -------------- | -------------------------------------------------------------------------------------------- | +| Client | `roots` | Ability to provide filesystem [roots]({{< ref "/specification/draft/client/roots" >}}) | +| Client | `sampling` | Support for LLM [sampling]({{< ref "/specification/draft/client/sampling" >}}) requests | +| Client | `experimental` | Describes support for non-standard experimental features | +| Server | `prompts` | Offers [prompt templates]({{< ref "/specification/draft/server/prompts" >}}) | +| Server | `resources` | Provides readable [resources]({{< ref "/specification/draft/server/resources" >}}) | +| Server | `tools` | Exposes callable [tools]({{< ref "/specification/draft/server/tools" >}}) | | Server | `logging` | Emits structured [log messages]({{< ref "/specification/draft/server/utilities/logging" >}}) | -| Server | `experimental` | Describes support for non-standard experimental features | +| Server | `experimental` | Describes support for non-standard experimental features | Capability objects can describe sub-capabilities like: -- `listChanged`: Support for list change notifications (for prompts, resources, and tools) + +- `listChanged`: Support for list change notifications (for prompts, resources, and + tools) - `subscribe`: Support for subscribing to individual items' changes (resources only) ### Operation -During the operation phase, the client and server exchange messages according to the negotiated capabilities. +During the operation phase, the client and server exchange messages according to the +negotiated capabilities. Both parties **SHOULD**: @@ -154,21 +206,27 @@ Both parties **SHOULD**: ### Shutdown -During the shutdown phase, one side (usually the client) cleanly terminates the protocol connection. No specific shutdown messages are defined—instead, the underlying transport mechanism should be used to signal connection termination: +During the shutdown phase, one side (usually the client) cleanly terminates the protocol +connection. No specific shutdown messages are defined—instead, the underlying transport +mechanism should be used to signal connection termination: #### stdio -For the stdio [transport]({{< ref "/specification/draft/basic/transports" >}}), the client **SHOULD** initiate shutdown by: +For the stdio [transport]({{< ref "/specification/draft/basic/transports" >}}), the +client **SHOULD** initiate shutdown by: 1. First, closing the input stream to the child process (the server) -2. Waiting for the server to exit, or sending `SIGTERM` if the server does not exit within a reasonable time +2. Waiting for the server to exit, or sending `SIGTERM` if the server does not exit + within a reasonable time 3. Sending `SIGKILL` if the server does not exit within a reasonable time after `SIGTERM` -The server **MAY** initiate shutdown by closing its output stream to the client and exiting. +The server **MAY** initiate shutdown by closing its output stream to the client and +exiting. #### HTTP -For HTTP [transports]({{< ref "/specification/draft/basic/transports" >}}), shutdown is indicated by closing the associated HTTP connection(s). +For HTTP [transports]({{< ref "/specification/draft/basic/transports" >}}), shutdown is +indicated by closing the associated HTTP connection(s). ## Error Handling @@ -179,9 +237,11 @@ Implementations **SHOULD** be prepared to handle these error cases: - Initialize request timeout - Shutdown timeout -Implementations **SHOULD** implement appropriate timeouts for all requests, to prevent hung connections and resource exhaustion. +Implementations **SHOULD** implement appropriate timeouts for all requests, to prevent +hung connections and resource exhaustion. Example initialization error: + ```json { "jsonrpc": "2.0", diff --git a/docs/specification/draft/basic/messages.md b/docs/specification/draft/basic/messages.md index c6899f1..1adf115 100644 --- a/docs/specification/draft/basic/messages.md +++ b/docs/specification/draft/basic/messages.md @@ -3,11 +3,12 @@ title: Messages type: docs weight: 20 --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} -All messages in MCP **MUST** follow the [JSON-RPC 2.0](https://www.jsonrpc.org/specification) specification. The protocol defines three types of messages: +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} + +All messages in MCP **MUST** follow the +[JSON-RPC 2.0](https://www.jsonrpc.org/specification) specification. The protocol defines +three types of messages: ## Requests @@ -24,9 +25,10 @@ Requests are sent from the client to the server or vice versa. } ``` -* Requests **MUST** include a string or integer ID. -* Unlike base JSON-RPC, the ID **MUST NOT** be `null`. -* The request ID **MUST NOT** have been previously used by the requestor within the same session. +- Requests **MUST** include a string or integer ID. +- Unlike base JSON-RPC, the ID **MUST NOT** be `null`. +- The request ID **MUST NOT** have been previously used by the requestor within the same + session. ## Responses @@ -47,13 +49,14 @@ Responses are sent in reply to requests. } ``` -* Responses **MUST** include the same ID as the request they correspond to. -* Either a `result` or an `error` **MUST** be set. A response **MUST NOT** set both. -* Error codes **MUST** be integers. +- Responses **MUST** include the same ID as the request they correspond to. +- Either a `result` or an `error` **MUST** be set. A response **MUST NOT** set both. +- Error codes **MUST** be integers. ## Notifications -Notifications are sent from the client to the server or vice versa. They do not expect a response. +Notifications are sent from the client to the server or vice versa. They do not expect a +response. ```typescript { @@ -65,4 +68,4 @@ Notifications are sent from the client to the server or vice versa. They do not } ``` -* Notifications **MUST NOT** include an ID. +- Notifications **MUST NOT** include an ID. diff --git a/docs/specification/draft/basic/transports.md b/docs/specification/draft/basic/transports.md index d612625..df5cf21 100644 --- a/docs/specification/draft/basic/transports.md +++ b/docs/specification/draft/basic/transports.md @@ -3,26 +3,32 @@ title: Transports type: docs weight: 10 --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} + +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} MCP currently defines two standard transport mechanisms for client-server communication: + 1. [stdio](#stdio), communication over standard in and standard out 2. [HTTP with Server-Sent Events](#http-with-sse) (SSE) Clients **SHOULD** support stdio whenever possible. -It is also possible for clients and servers to implement [custom transports](#custom-transports) in a pluggable fashion. +It is also possible for clients and servers to implement +[custom transports](#custom-transports) in a pluggable fashion. ## stdio + In the **stdio** transport: -* The client launches the MCP server as a subprocess. -* The server receives JSON-RPC messages on its standard input (`stdin`) and writes responses to its standard output (`stdout`). -* Messages are delimited by newlines, and **MUST NOT** contain embedded newlines. -* The server **MAY** write UTF-8 strings to its standard error (`stderr`) for logging purposes. Clients **MAY** capture, forward, or ignore this logging. -* The server **MUST NOT** write anything to its `stdout` that is not a valid MCP message. -* The client **MUST NOT** write anything to the server's `stdin` that is not a valid MCP message. + +- The client launches the MCP server as a subprocess. +- The server receives JSON-RPC messages on its standard input (`stdin`) and writes + responses to its standard output (`stdout`). +- Messages are delimited by newlines, and **MUST NOT** contain embedded newlines. +- The server **MAY** write UTF-8 strings to its standard error (`stderr`) for logging + purposes. Clients **MAY** capture, forward, or ignore this logging. +- The server **MUST NOT** write anything to its `stdout` that is not a valid MCP message. +- The client **MUST NOT** write anything to the server's `stdin` that is not a valid MCP + message. ```mermaid sequenceDiagram @@ -40,16 +46,22 @@ sequenceDiagram ``` ## HTTP with SSE -In the **SSE** transport, the server operates as an independent process that can handle multiple client connections. + +In the **SSE** transport, the server operates as an independent process that can handle +multiple client connections. The server **MUST** provide two endpoints: -1. An SSE endpoint, for clients to establish a connection and receive messages from the server +1. An SSE endpoint, for clients to establish a connection and receive messages from the + server 2. A regular HTTP POST endpoint for clients to send messages to the server -When a client connects, the server **MUST** send an `endpoint` event containing a URI for the client to use for sending messages. All subsequent client messages **MUST** be sent as HTTP POST requests to this endpoint. +When a client connects, the server **MUST** send an `endpoint` event containing a URI for +the client to use for sending messages. All subsequent client messages **MUST** be sent +as HTTP POST requests to this endpoint. -Server messages are sent as SSE `message` events, with the message content encoded as JSON in the event data. +Server messages are sent as SSE `message` events, with the message content encoded as +JSON in the event data. ```mermaid sequenceDiagram @@ -67,6 +79,11 @@ sequenceDiagram ## Custom Transports -Clients and servers **MAY** implement additional custom transport mechanisms to suit their specific needs. The protocol is transport-agnostic and can be implemented over any communication channel that supports bidirectional message exchange. +Clients and servers **MAY** implement additional custom transport mechanisms to suit +their specific needs. The protocol is transport-agnostic and can be implemented over any +communication channel that supports bidirectional message exchange. -Implementers who choose to support custom transports **MUST** ensure they preserve the JSON-RPC message format and lifecycle requirements defined by MCP. Custom transports **SHOULD** document their specific connection establishment and message exchange patterns to aid interoperability. +Implementers who choose to support custom transports **MUST** ensure they preserve the +JSON-RPC message format and lifecycle requirements defined by MCP. Custom transports +**SHOULD** document their specific connection establishment and message exchange patterns +to aid interoperability. diff --git a/docs/specification/draft/basic/transports/_index.md b/docs/specification/draft/basic/transports/_index.md new file mode 100644 index 0000000..df5cf21 --- /dev/null +++ b/docs/specification/draft/basic/transports/_index.md @@ -0,0 +1,89 @@ +--- +title: Transports +type: docs +weight: 10 +--- + +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} + +MCP currently defines two standard transport mechanisms for client-server communication: + +1. [stdio](#stdio), communication over standard in and standard out +2. [HTTP with Server-Sent Events](#http-with-sse) (SSE) + +Clients **SHOULD** support stdio whenever possible. + +It is also possible for clients and servers to implement +[custom transports](#custom-transports) in a pluggable fashion. + +## stdio + +In the **stdio** transport: + +- The client launches the MCP server as a subprocess. +- The server receives JSON-RPC messages on its standard input (`stdin`) and writes + responses to its standard output (`stdout`). +- Messages are delimited by newlines, and **MUST NOT** contain embedded newlines. +- The server **MAY** write UTF-8 strings to its standard error (`stderr`) for logging + purposes. Clients **MAY** capture, forward, or ignore this logging. +- The server **MUST NOT** write anything to its `stdout` that is not a valid MCP message. +- The client **MUST NOT** write anything to the server's `stdin` that is not a valid MCP + message. + +```mermaid +sequenceDiagram + participant Client + participant Server Process + + Client->>+Server Process: Launch subprocess + loop Message Exchange + Client->>Server Process: Write to stdin + Server Process->>Client: Write to stdout + Server Process--)Client: Optional logs on stderr + end + Client->>Server Process: Close stdin, terminate subprocess + deactivate Server Process +``` + +## HTTP with SSE + +In the **SSE** transport, the server operates as an independent process that can handle +multiple client connections. + +The server **MUST** provide two endpoints: + +1. An SSE endpoint, for clients to establish a connection and receive messages from the + server +2. A regular HTTP POST endpoint for clients to send messages to the server + +When a client connects, the server **MUST** send an `endpoint` event containing a URI for +the client to use for sending messages. All subsequent client messages **MUST** be sent +as HTTP POST requests to this endpoint. + +Server messages are sent as SSE `message` events, with the message content encoded as +JSON in the event data. + +```mermaid +sequenceDiagram + participant Client + participant Server + + Client->>Server: Open SSE connection + Server->>Client: endpoint event + loop Message Exchange + Client->>Server: HTTP POST messages + Server->>Client: SSE message events + end + Client->>Server: Close SSE connection +``` + +## Custom Transports + +Clients and servers **MAY** implement additional custom transport mechanisms to suit +their specific needs. The protocol is transport-agnostic and can be implemented over any +communication channel that supports bidirectional message exchange. + +Implementers who choose to support custom transports **MUST** ensure they preserve the +JSON-RPC message format and lifecycle requirements defined by MCP. Custom transports +**SHOULD** document their specific connection establishment and message exchange patterns +to aid interoperability. diff --git a/docs/specification/draft/basic/transports/upgrade.md b/docs/specification/draft/basic/transports/upgrade.md new file mode 100644 index 0000000..3163f94 --- /dev/null +++ b/docs/specification/draft/basic/transports/upgrade.md @@ -0,0 +1,91 @@ +# Transport Protocol Upgrade Mechanism + +## 1. Introduction + +This specification defines a protocol upgrade mechanism that enables MCP servers to +transition clients from one transport protocol to another during session initialization. +The primary use case is upgrading from transports with limited capabilities (like STDIO) +to more feature-rich transports that support additional functionality like +authentication. + +## 2. Upgrade Process + +### 2.1 Available Transports + +The `transport` field **MUST** specify one of the following standardized values: + +- `stdio` - Standard input/output transport +- `http+sse` - HTTP with Server-Sent Events transport + +Servers **SHOULD NOT** request upgrades from HTTP+SSE to STDIO as this would reduce +protocol capabilities. While the transport field supports custom values for +extensibility, any custom transport **MUST** provide at least the same capabilities as +the transport being upgraded from. + +Example custom transport upgrade: + +```json +{ + "upgrade": { + "endpoint": "grpc://new-server.example.com:50051", + "transport": "grpc" // Custom transport implementation + } +} +``` + +### 2.2 Initialization + +When a client connects using a transport that lacks required capabilities, the server +**MUST** include an `upgrade` field in its initialize response to indicate that a +transport upgrade is necessary. + +### 2.3 Upgrade Fields + +The `upgrade` object contains the following required fields: + +| Field | Type | Description | +| --------- | ------ | ----------------------------------- | +| endpoint | string | The URL of the new server endpoint | +| transport | string | The protocol identifier for the new | +| | | transport | + +### 2.4 Example Upgrade Flow + +During initialization with STDIO transport: + +```json +{ + "jsonrpc": "2.0", + "id": 1, + "result": { + "protocolVersion": "2024-11-05", + "upgrade": { + "endpoint": "http://new-server.example.com:8080", + "transport": "http+sse" + }, + "serverInfo": { + "name": "ExampleServer", + "version": "1.0.0" + } + } +} +``` + +### 2.5 Client Requirements + +Upon receiving an upgrade response, clients **MUST**: + +1. Terminate the existing connection +2. Establish a new connection using the specified transport protocol +3. Reinitialize the session with the new endpoint + +### 2.6 Authentication Flow + +The most common upgrade scenario is transitioning from STDIO to HTTP+SSE transport to +support authentication: + +1. Client connects via STDIO +2. Server requires authentication +3. Server responds with upgrade to HTTP+SSE +4. Client reconnects using HTTP+SSE +5. Authentication proceeds on new transport diff --git a/docs/specification/draft/basic/utilities/_index.md b/docs/specification/draft/basic/utilities/_index.md index df625ae..f9a9bee 100644 --- a/docs/specification/draft/basic/utilities/_index.md +++ b/docs/specification/draft/basic/utilities/_index.md @@ -2,14 +2,10 @@ title: Utilities --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} These optional features enhance the base protocol functionality with various utilities. -{{< cards >}} - {{< card link="ping" title="Ping" icon="status-online" >}} - {{< card link="cancellation" title="Cancellation" icon="x" >}} - {{< card link="progress" title="Progress" icon="clock" >}} -{{< /cards >}} +{{< cards >}} {{< card link="ping" title="Ping" icon="status-online" >}} +{{< card link="cancellation" title="Cancellation" icon="x" >}} +{{< card link="progress" title="Progress" icon="clock" >}} {{< /cards >}} diff --git a/docs/specification/draft/basic/utilities/cancellation.md b/docs/specification/draft/basic/utilities/cancellation.md index 9133644..d8e38d5 100644 --- a/docs/specification/draft/basic/utilities/cancellation.md +++ b/docs/specification/draft/basic/utilities/cancellation.md @@ -3,15 +3,16 @@ title: Cancellation weight: 10 --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} -The Model Context Protocol (MCP) supports optional cancellation of in-progress requests through notification messages. Either side can send a cancellation notification to indicate that a previously-issued request should be terminated. +The Model Context Protocol (MCP) supports optional cancellation of in-progress requests +through notification messages. Either side can send a cancellation notification to +indicate that a previously-issued request should be terminated. ## Cancellation Flow -When a party wants to cancel an in-progress request, it sends a `notifications/cancelled` notification containing: +When a party wants to cancel an in-progress request, it sends a `notifications/cancelled` +notification containing: - The ID of the request to cancel - An optional reason string that can be logged or displayed @@ -41,11 +42,13 @@ When a party wants to cancel an in-progress request, it sends a `notifications/c - The referenced request is unknown - Processing has already completed - The request cannot be cancelled -5. The sender of the cancellation notification **SHOULD** ignore any response to the request that arrives afterward +5. The sender of the cancellation notification **SHOULD** ignore any response to the + request that arrives afterward ## Timing Considerations -Due to network latency, cancellation notifications may arrive after request processing has completed, and potentially after a response has already been sent. +Due to network latency, cancellation notifications may arrive after request processing +has completed, and potentially after a response has already been sent. Both parties **MUST** handle these race conditions gracefully: @@ -57,7 +60,7 @@ sequenceDiagram Client->>Server: Request (ID: 123) Note over Server: Processing starts Client--)Server: notifications/cancelled (ID: 123) - alt + alt Note over Server: Processing may have
completed before
cancellation arrives else If not completed Note over Server: Stop processing @@ -77,4 +80,5 @@ Invalid cancellation notifications **SHOULD** be ignored: - Already completed requests - Malformed notifications -This maintains the "fire and forget" nature of notifications while allowing for race conditions in asynchronous communication. +This maintains the "fire and forget" nature of notifications while allowing for race +conditions in asynchronous communication. diff --git a/docs/specification/draft/basic/utilities/ping.md b/docs/specification/draft/basic/utilities/ping.md index 29b4287..ef1b1a7 100644 --- a/docs/specification/draft/basic/utilities/ping.md +++ b/docs/specification/draft/basic/utilities/ping.md @@ -3,15 +3,15 @@ title: Ping weight: 5 --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} -The Model Context Protocol includes an optional ping mechanism that allows either party to verify that their counterpart is still responsive and the connection is alive. +The Model Context Protocol includes an optional ping mechanism that allows either party +to verify that their counterpart is still responsive and the connection is alive. ## Overview -The ping functionality is implemented through a simple request/response pattern. Either the client or server can initiate a ping by sending a `ping` request. +The ping functionality is implemented through a simple request/response pattern. Either +the client or server can initiate a ping by sending a `ping` request. ## Message Format diff --git a/docs/specification/draft/basic/utilities/progress.md b/docs/specification/draft/basic/utilities/progress.md index 7233620..4eae2ba 100644 --- a/docs/specification/draft/basic/utilities/progress.md +++ b/docs/specification/draft/basic/utilities/progress.md @@ -2,18 +2,21 @@ title: Progress weight: 30 --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} -The Model Context Protocol (MCP) supports optional progress tracking for long-running operations through notification messages. Either side can send progress notifications to provide updates about operation status. +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} + +The Model Context Protocol (MCP) supports optional progress tracking for long-running +operations through notification messages. Either side can send progress notifications to +provide updates about operation status. ## Progress Flow -When a party wants to _receive_ progress updates for a request, it includes a `progressToken` in the request metadata. +When a party wants to _receive_ progress updates for a request, it includes a +`progressToken` in the request metadata. -* Progress tokens **MUST** be a string or integer value -* Progress tokens can be chosen by the sender using any means, but **MUST** be unique across all active requests. +- Progress tokens **MUST** be a string or integer value +- Progress tokens can be chosen by the sender using any means, but **MUST** be unique + across all active requests. ```json { @@ -46,12 +49,14 @@ The receiver **MAY** then send progress notifications containing: } ``` -* The `progress` value **MUST** increase with each notification, even if the total is unknown. -* The `progress` and the `total` values **MAY** be floating point. +- The `progress` value **MUST** increase with each notification, even if the total is + unknown. +- The `progress` and the `total` values **MAY** be floating point. ## Behavior Requirements 1. Progress notifications **MUST** only reference tokens that: + - Were provided in an active request - Are associated with an in-progress operation diff --git a/docs/specification/draft/basic/versioning.md b/docs/specification/draft/basic/versioning.md index 560937a..e272069 100644 --- a/docs/specification/draft/basic/versioning.md +++ b/docs/specification/draft/basic/versioning.md @@ -4,14 +4,21 @@ type: docs weight: 80 --- -The Model Context Protocol uses string-based version identifiers following the format `YYYY-MM-DD`, to indicate the last date backwards incompatible changes were made. +The Model Context Protocol uses string-based version identifiers following the format +`YYYY-MM-DD`, to indicate the last date backwards incompatible changes were made. -The current protocol version is **draft**. [See all revisions]({{< ref "/specification/draft/revisions" >}}). +The current protocol version is **draft**. [See all +revisions]({{< ref "/specification/draft/revisions" >}}). -{{< callout type="info" >}} - The protocol version will _not_ be incremented when the protocol is updated, as long as the changes maintain backwards compatibility. This allows for incremental improvements while preserving interoperability. -{{< /callout >}} +{{< callout type="info" >}} The protocol version will _not_ be incremented when the +protocol is updated, as long as the changes maintain backwards compatibility. This allows +for incremental improvements while preserving interoperability. {{< /callout >}} -Version negotiation happens during [initialization]({{< ref "/specification/draft/basic/lifecycle#initialization" >}}). Clients and servers **MAY** support multiple protocol versions simultaneously, but they **MUST** agree on a single version to use for the session. +Version negotiation happens during +[initialization]({{< ref "/specification/draft/basic/lifecycle#initialization" >}}). +Clients and servers **MAY** support multiple protocol versions simultaneously, but they +**MUST** agree on a single version to use for the session. -The protocol provides appropriate error handling if version negotiation fails, allowing clients to gracefully terminate connections when they cannot find a version compatible with the server. +The protocol provides appropriate error handling if version negotiation fails, allowing +clients to gracefully terminate connections when they cannot find a version compatible +with the server. diff --git a/docs/specification/draft/client/_index.md b/docs/specification/draft/client/_index.md index 30f5729..8a64644 100644 --- a/docs/specification/draft/client/_index.md +++ b/docs/specification/draft/client/_index.md @@ -5,13 +5,9 @@ cascade: weight: 4 --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} Clients can implement additional features to enrich connected MCP servers: - -{{< cards >}} - {{< card link="roots" title="Roots" icon="folder" >}} - {{< card link="sampling" title="Sampling" icon="annotation" >}} -{{< /cards >}} + +{{< cards >}} {{< card link="roots" title="Roots" icon="folder" >}} +{{< card link="sampling" title="Sampling" icon="annotation" >}} {{< /cards >}} diff --git a/docs/specification/draft/client/roots.md b/docs/specification/draft/client/roots.md index cfa8514..7cb1cf1 100644 --- a/docs/specification/draft/client/roots.md +++ b/docs/specification/draft/client/roots.md @@ -4,23 +4,30 @@ type: docs weight: 40 --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} -The Model Context Protocol (MCP) provides a standardized way for clients to expose filesystem "roots" to servers. Roots define the boundaries of where servers can operate within the filesystem, allowing them to understand which directories and files they have access to. Servers can request the list of roots from supporting clients and receive notifications when that list changes. +The Model Context Protocol (MCP) provides a standardized way for clients to expose +filesystem "roots" to servers. Roots define the boundaries of where servers can operate +within the filesystem, allowing them to understand which directories and files they have +access to. Servers can request the list of roots from supporting clients and receive +notifications when that list changes. ## User Interaction Model Roots in MCP are typically exposed through workspace or project configuration interfaces. -For example, implementations could offer a workspace/project picker that allows users to select directories and files the server should have access to. This can be combined with automatic workspace detection from version control systems or project files. +For example, implementations could offer a workspace/project picker that allows users to +select directories and files the server should have access to. This can be combined with +automatic workspace detection from version control systems or project files. -However, implementations are free to expose roots through any interface pattern that suits their needs—the protocol itself does not mandate any specific user interaction model. +However, implementations are free to expose roots through any interface pattern that +suits their needs—the protocol itself does not mandate any specific user +interaction model. ## Capabilities -Clients that support roots **MUST** declare the `roots` capability during [initialization]({{< ref "/specification/draft/basic/lifecycle#initialization" >}}): +Clients that support roots **MUST** declare the `roots` capability during +[initialization]({{< ref "/specification/draft/basic/lifecycle#initialization" >}}): ```json { @@ -32,7 +39,8 @@ Clients that support roots **MUST** declare the `roots` capability during [initi } ``` -`listChanged` indicates whether the client will emit notifications when the list of roots changes. +`listChanged` indicates whether the client will emit notifications when the list of roots +changes. ## Protocol Messages @@ -41,6 +49,7 @@ Clients that support roots **MUST** declare the `roots` capability during [initi To retrieve roots, servers send a `roots/list` request: **Request:** + ```json { "jsonrpc": "2.0", @@ -50,6 +59,7 @@ To retrieve roots, servers send a `roots/list` request: ``` **Response:** + ```json { "jsonrpc": "2.0", @@ -99,12 +109,14 @@ sequenceDiagram A root definition includes: -- `uri`: Unique identifier for the root. This **MUST** be a `file://` URI in the current specification. +- `uri`: Unique identifier for the root. This **MUST** be a `file://` URI in the current + specification. - `name`: Optional human-readable name for display purposes. Example roots for different use cases: #### Project Directory + ```json { "uri": "file:///home/user/projects/myproject", @@ -113,6 +125,7 @@ Example roots for different use cases: ``` #### Multiple Repositories + ```json [ { @@ -134,6 +147,7 @@ Clients **SHOULD** return standard JSON-RPC errors for common failure cases: - Internal errors: `-32603` Example error: + ```json { "jsonrpc": "2.0", @@ -151,6 +165,7 @@ Example error: ## Security Considerations 1. Clients **MUST**: + - Only expose roots with appropriate permissions - Validate all root URIs to prevent path traversal - Implement proper access controls @@ -164,6 +179,7 @@ Example error: ## Implementation Guidelines 1. Clients **SHOULD**: + - Prompt users for consent before exposing roots to servers - Provide clear user interfaces for root management - Validate root accessibility before exposing diff --git a/docs/specification/draft/client/sampling.md b/docs/specification/draft/client/sampling.md index f20bf5a..6f96835 100644 --- a/docs/specification/draft/client/sampling.md +++ b/docs/specification/draft/client/sampling.md @@ -4,30 +4,37 @@ type: docs weight: 40 --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} -The Model Context Protocol (MCP) provides a standardized way for servers to request LLM sampling ("completions" or "generations") from language models via clients. This flow allows clients to maintain control over model access, selection, and permissions while enabling servers to leverage AI capabilities—with no server API keys necessary. Servers can request text, audio, or image-based interactions and optionally include context from MCP servers in their prompts. +The Model Context Protocol (MCP) provides a standardized way for servers to request LLM +sampling ("completions" or "generations") from language models via clients. This flow +allows clients to maintain control over model access, selection, and permissions while +enabling servers to leverage AI capabilities—with no server API keys necessary. +Servers can request text, audio, or image-based interactions and optionally include +context from MCP servers in their prompts. ## User Interaction Model -Sampling in MCP allows servers to implement agentic behaviors, by enabling LLM calls to occur _nested_ inside other MCP server features. +Sampling in MCP allows servers to implement agentic behaviors, by enabling LLM calls to +occur _nested_ inside other MCP server features. -Implementations are free to expose sampling through any interface pattern that suits their needs—the protocol itself does not mandate any specific user interaction model. +Implementations are free to expose sampling through any interface pattern that suits +their needs—the protocol itself does not mandate any specific user interaction +model. -{{< callout type="warning" >}} - For trust & safety and security, there **SHOULD** always be a human in the loop with the ability to deny sampling requests. - - Applications **SHOULD**: - * Provide UI that makes it easy and intuitive to review sampling requests - * Allow users to view and edit prompts before sending - * Present generated responses for review before delivery -{{< /callout >}} +{{< callout type="warning" >}} For trust & safety and security, there **SHOULD** always +be a human in the loop with the ability to deny sampling requests. + +Applications **SHOULD**: + +- Provide UI that makes it easy and intuitive to review sampling requests +- Allow users to view and edit prompts before sending +- Present generated responses for review before delivery {{< /callout >}} ## Capabilities -Clients that support sampling **MUST** declare the `sampling` capability during [initialization]({{< ref "../basic/lifecycle#initialization" >}}): +Clients that support sampling **MUST** declare the `sampling` capability during +[initialization]({{< ref "../basic/lifecycle#initialization" >}}): ```json { @@ -44,6 +51,7 @@ Clients that support sampling **MUST** declare the `sampling` capability during To request a language model generation, servers send a `sampling/createMessage` request: **Request:** + ```json { "jsonrpc": "2.0", @@ -75,6 +83,7 @@ To request a language model generation, servers send a `sampling/createMessage` ``` **Response:** + ```json { "jsonrpc": "2.0", @@ -126,6 +135,7 @@ sequenceDiagram Sampling messages can contain: #### Text Content + ```json { "type": "text", @@ -134,6 +144,7 @@ Sampling messages can contain: ``` #### Image Content + ```json { "type": "image", @@ -143,6 +154,7 @@ Sampling messages can contain: ``` #### Audio Content + ```json { "type": "audio", @@ -151,12 +163,15 @@ Sampling messages can contain: } ``` - ### Model Preferences -Model selection in MCP requires careful abstraction since servers and clients may use different AI providers with distinct model offerings. A server cannot simply request a specific model by name since the client may not have access to that exact model or may prefer to use a different provider's equivalent model. +Model selection in MCP requires careful abstraction since servers and clients may use +different AI providers with distinct model offerings. A server cannot simply request a +specific model by name since the client may not have access to that exact model or may +prefer to use a different provider's equivalent model. -To solve this, MCP implements a preference system that combines abstract capability priorities with optional model hints: +To solve this, MCP implements a preference system that combines abstract capability +priorities with optional model hints: #### Capability Priorities @@ -164,11 +179,13 @@ Servers express their needs through three normalized priority values (0-1): - `costPriority`: How important is minimizing costs? Higher values prefer cheaper models. - `speedPriority`: How important is low latency? Higher values prefer faster models. -- `intelligencePriority`: How important are advanced capabilities? Higher values prefer more capable models. +- `intelligencePriority`: How important are advanced capabilities? Higher values prefer + more capable models. #### Model Hints -While priorities help select models based on characteristics, `hints` allow servers to suggest specific models or model families: +While priorities help select models based on characteristics, `hints` allow servers to +suggest specific models or model families: - Hints are treated as substrings that can match model names flexibly - Multiple hints are evaluated in order of preference @@ -176,25 +193,29 @@ While priorities help select models based on characteristics, `hints` allow serv - Hints are advisory—clients make final model selection For example: + ```json { "hints": [ - {"name": "claude-3-sonnet"}, // Prefer Sonnet-class models - {"name": "claude"} // Fall back to any Claude model + { "name": "claude-3-sonnet" }, // Prefer Sonnet-class models + { "name": "claude" } // Fall back to any Claude model ], - "costPriority": 0.3, // Cost is less important - "speedPriority": 0.8, // Speed is very important - "intelligencePriority": 0.5 // Moderate capability needs + "costPriority": 0.3, // Cost is less important + "speedPriority": 0.8, // Speed is very important + "intelligencePriority": 0.5 // Moderate capability needs } ``` -The client processes these preferences to select an appropriate model from its available options. For instance, if the client doesn't have access to Claude models but has Gemini, it might map the sonnet hint to `gemini-1.5-pro` based on similar capabilities. +The client processes these preferences to select an appropriate model from its available +options. For instance, if the client doesn't have access to Claude models but has Gemini, +it might map the sonnet hint to `gemini-1.5-pro` based on similar capabilities. ## Error Handling Clients **SHOULD** return errors for common failure cases: Example error: + ```json { "jsonrpc": "2.0", diff --git a/docs/specification/draft/contributing/_index.md b/docs/specification/draft/contributing/_index.md index 60162de..608fa24 100644 --- a/docs/specification/draft/contributing/_index.md +++ b/docs/specification/draft/contributing/_index.md @@ -6,8 +6,12 @@ cascade: breadcrumbs: false --- -We welcome contributions from the community! Please review our [contributing guidelines](https://github.com/modelcontextprotocol/specification/draft/blob/main/CONTRIBUTING.md) for details on how to submit changes. +We welcome contributions from the community! Please review our +[contributing guidelines](https://github.com/modelcontextprotocol/specification/draft/blob/main/CONTRIBUTING.md) +for details on how to submit changes. -All contributors must adhere to our [Code of Conduct](https://github.com/modelcontextprotocol/specification/draft/blob/main/CODE_OF_CONDUCT.md). +All contributors must adhere to our +[Code of Conduct](https://github.com/modelcontextprotocol/specification/draft/blob/main/CODE_OF_CONDUCT.md). -For questions and discussions, please use [GitHub Discussions](https://github.com/modelcontextprotocol/specification/draft/discussions). +For questions and discussions, please use +[GitHub Discussions](https://github.com/modelcontextprotocol/specification/draft/discussions). diff --git a/docs/specification/draft/revisions/2024-11-05.md b/docs/specification/draft/revisions/2024-11-05.md index 465a00d..5ef43ab 100644 --- a/docs/specification/draft/revisions/2024-11-05.md +++ b/docs/specification/draft/revisions/2024-11-05.md @@ -2,4 +2,6 @@ title: 2024-11-05 (Current) weight: 1 --- -This is the current version of the specification. This revision may continue to receive backwards compatible changes. + +This is the current version of the specification. This revision may continue to receive +backwards compatible changes. diff --git a/docs/specification/draft/revisions/_index.md b/docs/specification/draft/revisions/_index.md index e56a994..d1980ca 100644 --- a/docs/specification/draft/revisions/_index.md +++ b/docs/specification/draft/revisions/_index.md @@ -4,10 +4,14 @@ cascade: type: docs --- -This page lists the different revisions of the Model Context Protocol. See [Versioning]({{< ref "/specification/draft/basic/versioning" >}}) for more information about how the protocol is versioned. +This page lists the different revisions of the Model Context Protocol. See +[Versioning]({{< ref "/specification/draft/basic/versioning" >}}) for more information +about how the protocol is versioned. Revisions may be marked as: -* **Draft**: in-progress specifications, not yet ready for consumption. -* **Current**: the current protocol version, which is ready for use and may continue to receive [backwards compatible changes]({{< ref "/specification/draft/basic/versioning" >}}). -* **Final**: past, complete specifications that will not be changed. +- **Draft**: in-progress specifications, not yet ready for consumption. +- **Current**: the current protocol version, which is ready for use and may continue to + receive [backwards compatible + changes]({{< ref "/specification/draft/basic/versioning" >}}). +- **Final**: past, complete specifications that will not be changed. diff --git a/docs/specification/draft/server/_index.md b/docs/specification/draft/server/_index.md index 220e399..fb3411f 100644 --- a/docs/specification/draft/server/_index.md +++ b/docs/specification/draft/server/_index.md @@ -5,28 +5,28 @@ cascade: weight: 3 --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} -Servers provide the fundamental building blocks for adding context to language models via MCP. These primitives enable rich interactions between clients, servers, and language models: +Servers provide the fundamental building blocks for adding context to language models via +MCP. These primitives enable rich interactions between clients, servers, and language +models: -- **Prompts**: Pre-defined templates or instructions that guide language model interactions +- **Prompts**: Pre-defined templates or instructions that guide language model + interactions - **Resources**: Structured data or content that provides additional context to the model -- **Tools**: Executable functions that allow models to perform actions or retrieve information +- **Tools**: Executable functions that allow models to perform actions or retrieve + information Each primitive can be summarized in the following control hierarchy: -| Primitive | Control | Description | Example | -|-----------|------------------------|----------------------------------------------------|------------------------------| -| Prompts | User-controlled | Interactive templates invoked by user choice | Slash commands, menu options | -| Resources | Application-controlled | Contextual data attached and managed by the client | File contents, git history | -| Tools | Model-controlled | Functions exposed to the LLM to take actions | API POST requests, file writing | +| Primitive | Control | Description | Example | +| --------- | ---------------------- | -------------------------------------------------- | ------------------------------- | +| Prompts | User-controlled | Interactive templates invoked by user choice | Slash commands, menu options | +| Resources | Application-controlled | Contextual data attached and managed by the client | File contents, git history | +| Tools | Model-controlled | Functions exposed to the LLM to take actions | API POST requests, file writing | Explore these key primitives in more detail below: -{{< cards >}} - {{< card link="prompts" title="Prompts" icon="chat-alt-2" >}} - {{< card link="resources" title="Resources" icon="document" >}} - {{< card link="tools" title="Tools" icon="adjustments" >}} -{{< /cards >}} +{{< cards >}} {{< card link="prompts" title="Prompts" icon="chat-alt-2" >}} +{{< card link="resources" title="Resources" icon="document" >}} +{{< card link="tools" title="Tools" icon="adjustments" >}} {{< /cards >}} diff --git a/docs/specification/draft/server/prompts.md b/docs/specification/draft/server/prompts.md index 56aef5c..6deafe2 100644 --- a/docs/specification/draft/server/prompts.md +++ b/docs/specification/draft/server/prompts.md @@ -3,27 +3,34 @@ title: Prompts weight: 10 --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} -The Model Context Protocol (MCP) provides a standardized way for servers to expose prompt templates to clients. Prompts allow servers to provide structured messages and instructions for interacting with language models. Clients can discover available prompts, retrieve their contents, and provide arguments to customize them. +The Model Context Protocol (MCP) provides a standardized way for servers to expose prompt +templates to clients. Prompts allow servers to provide structured messages and +instructions for interacting with language models. Clients can discover available +prompts, retrieve their contents, and provide arguments to customize them. ## User Interaction Model -Prompts are designed to be **user-controlled**, meaning they are exposed from servers to clients with the intention of the user being able to explicitly select them for use. +Prompts are designed to be **user-controlled**, meaning they are exposed from servers to +clients with the intention of the user being able to explicitly select them for use. -Typically, prompts would be triggered through user-initiated commands in the user interface, which allows users to naturally discover and invoke available prompts. +Typically, prompts would be triggered through user-initiated commands in the user +interface, which allows users to naturally discover and invoke available prompts. For example, as slash commands: ![Example of prompt exposed as slash command](slash-command.png) -However, implementors are free to expose prompts through any interface pattern that suits their needs—the protocol itself does not mandate any specific user interaction model. +However, implementors are free to expose prompts through any interface pattern that suits +their needs—the protocol itself does not mandate any specific user interaction +model. ## Capabilities -Servers that support prompts **MUST** declare the `prompts` capability during [initialization]({{< ref "/specification/draft/basic/lifecycle#initialization" >}}): +Servers that support prompts **MUST** declare the `prompts` capability during +[initialization]({{< ref "/specification/draft/basic/lifecycle#initialization" >}}): + ```json { "capabilities": { @@ -34,15 +41,18 @@ Servers that support prompts **MUST** declare the `prompts` capability during [i } ``` -`listChanged` indicates whether the server will emit notifications when the list of available prompts changes. +`listChanged` indicates whether the server will emit notifications when the list of +available prompts changes. ## Protocol Messages ### Listing Prompts -To retrieve available prompts, clients send a `prompts/list` request. This operation supports [pagination]({{< ref "/specification/draft/server/utilities/pagination" >}}). +To retrieve available prompts, clients send a `prompts/list` request. This operation +supports [pagination]({{< ref "/specification/draft/server/utilities/pagination" >}}). **Request:** + ```json { "jsonrpc": "2.0", @@ -55,6 +65,7 @@ To retrieve available prompts, clients send a `prompts/list` request. This opera ``` **Response:** + ```json { "jsonrpc": "2.0", @@ -80,9 +91,12 @@ To retrieve available prompts, clients send a `prompts/list` request. This opera ### Getting a Prompt -To retrieve a specific prompt, clients send a `prompts/get` request. Arguments may be auto-completed through [the completion API]({{< ref "/specification/draft/server/utilities/completion" >}}). +To retrieve a specific prompt, clients send a `prompts/get` request. Arguments may be +auto-completed through [the completion +API]({{< ref "/specification/draft/server/utilities/completion" >}}). **Request:** + ```json { "jsonrpc": "2.0", @@ -98,6 +112,7 @@ To retrieve a specific prompt, clients send a `prompts/get` request. Arguments m ``` **Response:** + ```json { "jsonrpc": "2.0", @@ -119,7 +134,8 @@ To retrieve a specific prompt, clients send a `prompts/get` request. Arguments m ### List Changed Notification -When the list of available prompts changes, servers that declared the `listChanged` capability **SHOULD** send a notification: +When the list of available prompts changes, servers that declared the `listChanged` +capability **SHOULD** send a notification: ```json { @@ -169,17 +185,22 @@ Messages in a prompt can contain: - `content`: One of the following content types: #### Text Content + Text content represents plain text messages: + ```json { "type": "text", "text": "The text content of the message" } ``` + This is the most common content type used for natural language interactions. #### Image Content + Image content allows including visual information in messages: + ```json { "type": "image", @@ -187,10 +208,14 @@ Image content allows including visual information in messages: "mimeType": "image/png" } ``` -The image data **MUST** be base64-encoded and include a valid MIME type. This enables multi-modal interactions where visual context is important. + +The image data **MUST** be base64-encoded and include a valid MIME type. This enables +multi-modal interactions where visual context is important. #### Audio Content + Audio content allows including audio information in messages: + ```json { "type": "audio", @@ -198,10 +223,14 @@ Audio content allows including audio information in messages: "mimeType": "audio/wav" } ``` -The audio data MUST be base64-encoded and include a valid MIME type. This enables multi-modal interactions where audio context is important. + +The audio data MUST be base64-encoded and include a valid MIME type. This enables +multi-modal interactions where audio context is important. #### Embedded Resources + Embedded resources allow referencing server-side resources directly in messages: + ```json { "type": "resource", @@ -214,11 +243,14 @@ Embedded resources allow referencing server-side resources directly in messages: ``` Resources can contain either text or binary (blob) data and **MUST** include: + - A valid resource URI - The appropriate MIME type - Either text content or base64-encoded blob data -Embedded resources enable prompts to seamlessly incorporate server-managed content like documentation, code samples, or other reference materials directly into the conversation flow. +Embedded resources enable prompts to seamlessly incorporate server-managed content like +documentation, code samples, or other reference materials directly into the conversation +flow. ## Error Handling @@ -236,4 +268,5 @@ Servers **SHOULD** return standard JSON-RPC errors for common failure cases: ## Security -Implementations **MUST** carefully validate all prompt inputs and outputs to prevent injection attacks or unauthorized access to resources. +Implementations **MUST** carefully validate all prompt inputs and outputs to prevent +injection attacks or unauthorized access to resources. diff --git a/docs/specification/draft/server/resources.md b/docs/specification/draft/server/resources.md index 89d8021..6c1eea9 100644 --- a/docs/specification/draft/server/resources.md +++ b/docs/specification/draft/server/resources.md @@ -4,24 +4,30 @@ type: docs weight: 20 --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} -The Model Context Protocol (MCP) provides a standardized way for servers to expose resources to clients. Resources allow servers to share data that provides context to language models, such as files, database schemas, or application-specific information. Each resource is uniquely identified by a [URI](https://datatracker.ietf.org/doc/html/rfc3986). +The Model Context Protocol (MCP) provides a standardized way for servers to expose +resources to clients. Resources allow servers to share data that provides context to +language models, such as files, database schemas, or application-specific information. +Each resource is uniquely identified by a +[URI](https://datatracker.ietf.org/doc/html/rfc3986). ## User Interaction Model -Resources in MCP are designed to be **application-driven**, with host applications determining how to incorporate context based on their needs. +Resources in MCP are designed to be **application-driven**, with host applications +determining how to incorporate context based on their needs. For example, applications could: -* Expose resources through UI elements for explicit selection, in a tree or list view -* Allow the user to search through and filter available resources -* Implement automatic context inclusion, based on heuristics or the AI model's selection + +- Expose resources through UI elements for explicit selection, in a tree or list view +- Allow the user to search through and filter available resources +- Implement automatic context inclusion, based on heuristics or the AI model's selection ![Example of resource context picker](resource-picker.png) -However, implementations are free to expose resources through any interface pattern that suits their needs—the protocol itself does not mandate any specific user interaction model. +However, implementations are free to expose resources through any interface pattern that +suits their needs—the protocol itself does not mandate any specific user +interaction model. ## Capabilities @@ -39,15 +45,19 @@ Servers that support resources **MUST** declare the `resources` capability: ``` The capability supports two optional features: -- `subscribe`: whether the client can subscribe to be notified of changes to individual resources. -- `listChanged`: whether the server will emit notifications when the list of available resources changes. -Both `subscribe` and `listChanged` are optional—servers can support neither, either, or both: +- `subscribe`: whether the client can subscribe to be notified of changes to individual + resources. +- `listChanged`: whether the server will emit notifications when the list of available + resources changes. + +Both `subscribe` and `listChanged` are optional—servers can support neither, +either, or both: ```json { "capabilities": { - "resources": {} // Neither feature supported + "resources": {} // Neither feature supported } } ``` @@ -56,7 +66,7 @@ Both `subscribe` and `listChanged` are optional—servers can support neithe { "capabilities": { "resources": { - "subscribe": true // Only subscriptions supported + "subscribe": true // Only subscriptions supported } } } @@ -66,7 +76,7 @@ Both `subscribe` and `listChanged` are optional—servers can support neithe { "capabilities": { "resources": { - "listChanged": true // Only list change notifications supported + "listChanged": true // Only list change notifications supported } } } @@ -76,9 +86,11 @@ Both `subscribe` and `listChanged` are optional—servers can support neithe ### Listing Resources -To discover available resources, clients send a `resources/list` request. This operation supports [pagination]({{< ref "/specification/draft/server/utilities/pagination" >}}). +To discover available resources, clients send a `resources/list` request. This operation +supports [pagination]({{< ref "/specification/draft/server/utilities/pagination" >}}). **Request:** + ```json { "jsonrpc": "2.0", @@ -91,6 +103,7 @@ To discover available resources, clients send a `resources/list` request. This o ``` **Response:** + ```json { "jsonrpc": "2.0", @@ -114,6 +127,7 @@ To discover available resources, clients send a `resources/list` request. This o To retrieve resource contents, clients send a `resources/read` request: **Request:** + ```json { "jsonrpc": "2.0", @@ -126,6 +140,7 @@ To retrieve resource contents, clients send a `resources/read` request: ``` **Response:** + ```json { "jsonrpc": "2.0", @@ -144,9 +159,13 @@ To retrieve resource contents, clients send a `resources/read` request: ### Resource Templates -Resource templates allow servers to expose parameterized resources using [URI templates](https://datatracker.ietf.org/doc/html/rfc6570). Arguments may be auto-completed through [the completion API]({{< ref "/specification/draft/server/utilities/completion" >}}). +Resource templates allow servers to expose parameterized resources using +[URI templates](https://datatracker.ietf.org/doc/html/rfc6570). Arguments may be +auto-completed through [the completion +API]({{< ref "/specification/draft/server/utilities/completion" >}}). **Request:** + ```json { "jsonrpc": "2.0", @@ -156,6 +175,7 @@ Resource templates allow servers to expose parameterized resources using [URI te ``` **Response:** + ```json { "jsonrpc": "2.0", @@ -175,7 +195,8 @@ Resource templates allow servers to expose parameterized resources using [URI te ### List Changed Notification -When the list of available resources changes, servers that declared the `listChanged` capability **SHOULD** send a notification: +When the list of available resources changes, servers that declared the `listChanged` +capability **SHOULD** send a notification: ```json { @@ -186,9 +207,11 @@ When the list of available resources changes, servers that declared the `listCha ### Subscriptions -The protocol supports optional subscriptions to resource changes. Clients can subscribe to specific resources and receive notifications when they change: +The protocol supports optional subscriptions to resource changes. Clients can subscribe +to specific resources and receive notifications when they change: **Subscribe Request:** + ```json { "jsonrpc": "2.0", @@ -201,6 +224,7 @@ The protocol supports optional subscriptions to resource changes. Clients can su ``` **Update Notification:** + ```json { "jsonrpc": "2.0", @@ -252,6 +276,7 @@ A resource definition includes: Resources can contain either text or binary data: #### Text Content + ```json { "uri": "file:///example.txt", @@ -261,6 +286,7 @@ Resources can contain either text or binary data: ``` #### Binary Content + ```json { "uri": "file:///example.png", @@ -271,21 +297,30 @@ Resources can contain either text or binary data: ## Common URI Schemes -The protocol defines several standard URI schemes. This list not exhaustive—implementations are always free to use additional, custom URI schemes. +The protocol defines several standard URI schemes. This list not +exhaustive—implementations are always free to use additional, custom URI schemes. ### https:// Used to represent a resource available on the web. -Servers **SHOULD** use this scheme only when the client is able to fetch and load the resource directly from the web on its own—that is, it doesn’t need to read the resource via the MCP server. +Servers **SHOULD** use this scheme only when the client is able to fetch and load the +resource directly from the web on its own—that is, it doesn’t need to read the resource +via the MCP server. -For other use cases, servers **SHOULD** prefer to use another URI scheme, or define a custom one, even if the server will itself be downloading resource contents over the internet. +For other use cases, servers **SHOULD** prefer to use another URI scheme, or define a +custom one, even if the server will itself be downloading resource contents over the +internet. ### file:// -Used to identify resources that behave like a filesystem. However, the resources do not need to map to an actual physical filesystem. +Used to identify resources that behave like a filesystem. However, the resources do not +need to map to an actual physical filesystem. -MCP servers **MAY** identify file:// resources with an [XDG MIME type](https://specifications.freedesktop.org/shared-mime-info-spec/0.14/ar01s02.html#id-1.3.14), like `inode/directory`, to represent non-regular files (such as directories) that don’t otherwise have a standard MIME type. +MCP servers **MAY** identify file:// resources with an +[XDG MIME type](https://specifications.freedesktop.org/shared-mime-info-spec/0.14/ar01s02.html#id-1.3.14), +like `inode/directory`, to represent non-regular files (such as directories) that don’t +otherwise have a standard MIME type. ### git:// @@ -299,6 +334,7 @@ Servers **SHOULD** return standard JSON-RPC errors for common failure cases: - Internal errors: `-32603` Example error: + ```json { "jsonrpc": "2.0", diff --git a/docs/specification/draft/server/tools.md b/docs/specification/draft/server/tools.md index 0ebd140..8e061b9 100644 --- a/docs/specification/draft/server/tools.md +++ b/docs/specification/draft/server/tools.md @@ -4,26 +4,32 @@ type: docs weight: 40 --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} -The Model Context Protocol (MCP) allows servers to expose tools that can be invoked by language models. Tools enable models to interact with external systems, such as querying databases, calling APIs, or performing computations. Each tool is uniquely identified by a name and includes metadata describing its schema. +The Model Context Protocol (MCP) allows servers to expose tools that can be invoked by +language models. Tools enable models to interact with external systems, such as querying +databases, calling APIs, or performing computations. Each tool is uniquely identified by +a name and includes metadata describing its schema. ## User Interaction Model -Tools in MCP are designed to be **model-controlled**, meaning that the language model can discover and invoke tools automatically based on its contextual understanding and the user's prompts. +Tools in MCP are designed to be **model-controlled**, meaning that the language model can +discover and invoke tools automatically based on its contextual understanding and the +user's prompts. -However, implementations are free to expose tools through any interface pattern that suits their needs—the protocol itself does not mandate any specific user interaction model. +However, implementations are free to expose tools through any interface pattern that +suits their needs—the protocol itself does not mandate any specific user +interaction model. -{{< callout type="warning" >}} - For trust & safety and security, there **SHOULD** always be a human in the loop with the ability to deny tool invocations. - - Applications **SHOULD**: - * Provide UI that makes clear which tools are being exposed to the AI model - * Insert clear visual indicators when tools are invoked - * Present confirmation prompts to the user for operations, to ensure a human is in the loop -{{< /callout >}} +{{< callout type="warning" >}} For trust & safety and security, there **SHOULD** always +be a human in the loop with the ability to deny tool invocations. + +Applications **SHOULD**: + +- Provide UI that makes clear which tools are being exposed to the AI model +- Insert clear visual indicators when tools are invoked +- Present confirmation prompts to the user for operations, to ensure a human is in the + loop {{< /callout >}} ## Capabilities @@ -39,15 +45,18 @@ Servers that support tools **MUST** declare the `tools` capability: } ``` -`listChanged` indicates whether the server will emit notifications when the list of available tools changes. +`listChanged` indicates whether the server will emit notifications when the list of +available tools changes. ## Protocol Messages ### Listing Tools -To discover available tools, clients send a `tools/list` request. This operation supports [pagination]({{< ref "/specification/draft/server/utilities/pagination" >}}). +To discover available tools, clients send a `tools/list` request. This operation supports +[pagination]({{< ref "/specification/draft/server/utilities/pagination" >}}). **Request:** + ```json { "jsonrpc": "2.0", @@ -60,6 +69,7 @@ To discover available tools, clients send a `tools/list` request. This operation ``` **Response:** + ```json { "jsonrpc": "2.0", @@ -91,6 +101,7 @@ To discover available tools, clients send a `tools/list` request. This operation To invoke a tool, clients send a `tools/call` request: **Request:** + ```json { "jsonrpc": "2.0", @@ -106,15 +117,18 @@ To invoke a tool, clients send a `tools/call` request: ``` **Response:** + ```json { "jsonrpc": "2.0", "id": 2, "result": { - "content": [{ - "type": "text", - "text": "Current weather in New York:\nTemperature: 72°F\nConditions: Partly cloudy" - }], + "content": [ + { + "type": "text", + "text": "Current weather in New York:\nTemperature: 72°F\nConditions: Partly cloudy" + } + ], "isError": false } } @@ -122,7 +136,8 @@ To invoke a tool, clients send a `tools/call` request: ### List Changed Notification -When the list of available tools changes, servers that declared the `listChanged` capability **SHOULD** send a notification: +When the list of available tools changes, servers that declared the `listChanged` +capability **SHOULD** send a notification: ```json { @@ -172,6 +187,7 @@ A tool definition includes: Tool results can contain multiple content items of different types: #### Text Content + ```json { "type": "text", @@ -180,6 +196,7 @@ Tool results can contain multiple content items of different types: ``` #### Image Content + ```json { "type": "image", @@ -189,6 +206,7 @@ Tool results can contain multiple content items of different types: ``` #### Audio Content + ```json { "type": "audio", @@ -199,7 +217,9 @@ Tool results can contain multiple content items of different types: #### Embedded Resources -[Resources]({{< ref "/specification/draft/server/resources" >}}) **MAY** be embedded, to provide additional context or data, behind a URI that can be subscribed to or fetched again by the client later: +[Resources]({{< ref "/specification/draft/server/resources" >}}) **MAY** be embedded, to +provide additional context or data, behind a URI that can be subscribed to or fetched +again by the client later: ```json { @@ -217,6 +237,7 @@ Tool results can contain multiple content items of different types: Tools use two error reporting mechanisms: 1. **Protocol Errors**: Standard JSON-RPC errors for issues like: + - Unknown tools - Invalid arguments - Server errors @@ -227,6 +248,7 @@ Tools use two error reporting mechanisms: - Business logic errors Example protocol error: + ```json { "jsonrpc": "2.0", @@ -239,15 +261,18 @@ Example protocol error: ``` Example tool execution error: + ```json { "jsonrpc": "2.0", "id": 4, "result": { - "content": [{ - "type": "text", - "text": "Failed to fetch weather data: API rate limit exceeded" - }], + "content": [ + { + "type": "text", + "text": "Failed to fetch weather data: API rate limit exceeded" + } + ], "isError": true } } @@ -256,6 +281,7 @@ Example tool execution error: ## Security Considerations 1. Servers **MUST**: + - Validate all tool inputs - Implement proper access controls - Rate limit tool invocations @@ -263,7 +289,8 @@ Example tool execution error: 2. Clients **SHOULD**: - Prompt for user confirmation on sensitive operations - - Show tool inputs to the user before calling the server, to avoid malicious or accidental data exfiltration + - Show tool inputs to the user before calling the server, to avoid malicious or + accidental data exfiltration - Validate tool results before passing to LLM - Implement timeouts for tool calls - Log tool usage for audit purposes diff --git a/docs/specification/draft/server/utilities/_index.md b/docs/specification/draft/server/utilities/_index.md index 11536be..449223d 100644 --- a/docs/specification/draft/server/utilities/_index.md +++ b/docs/specification/draft/server/utilities/_index.md @@ -2,14 +2,10 @@ title: Utilities --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} These optional features can be used to enhance server functionality. -{{< cards >}} - {{< card link="completion" title="Completion" icon="at-symbol" >}} - {{< card link="logging" title="Logging" icon="terminal" >}} - {{< card link="pagination" title="Pagination" icon="collection" >}} -{{< /cards >}} +{{< cards >}} {{< card link="completion" title="Completion" icon="at-symbol" >}} +{{< card link="logging" title="Logging" icon="terminal" >}} +{{< card link="pagination" title="Pagination" icon="collection" >}} {{< /cards >}} diff --git a/docs/specification/draft/server/utilities/completion.md b/docs/specification/draft/server/utilities/completion.md index cab402d..073bed9 100644 --- a/docs/specification/draft/server/utilities/completion.md +++ b/docs/specification/draft/server/utilities/completion.md @@ -2,27 +2,34 @@ title: Completion --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} -The Model Context Protocol (MCP) provides a standardized way for servers to offer argument autocompletion suggestions for prompts and resource URIs. This enables rich, IDE-like experiences where users receive contextual suggestions while entering argument values. +The Model Context Protocol (MCP) provides a standardized way for servers to offer +argument autocompletion suggestions for prompts and resource URIs. This enables rich, +IDE-like experiences where users receive contextual suggestions while entering argument +values. ## User Interaction Model -Completion in MCP is designed to support interactive user experiences similar to IDE code completion. +Completion in MCP is designed to support interactive user experiences similar to IDE code +completion. -For example, applications may show completion suggestions in a dropdown or popup menu as users type, with the ability to filter and select from available options. +For example, applications may show completion suggestions in a dropdown or popup menu as +users type, with the ability to filter and select from available options. -However, implementations are free to expose completion through any interface pattern that suits their needs—the protocol itself does not mandate any specific user interaction model. +However, implementations are free to expose completion through any interface pattern that +suits their needs—the protocol itself does not mandate any specific user +interaction model. ## Protocol Messages ### Requesting Completions -To get completion suggestions, clients send a `completion/complete` request specifying what is being completed through a reference type: +To get completion suggestions, clients send a `completion/complete` request specifying +what is being completed through a reference type: **Request:** + ```json { "jsonrpc": "2.0", @@ -42,6 +49,7 @@ To get completion suggestions, clients send a `completion/complete` request spec ``` **Response:** + ```json { "jsonrpc": "2.0", @@ -60,10 +68,10 @@ To get completion suggestions, clients send a `completion/complete` request spec The protocol supports two types of completion references: -| Type | Description | Example | -|------|-------------|---------| -| `ref/prompt` | References a prompt by name | `{"type": "ref/prompt", "name": "code_review"}` | -| `ref/resource` | References a resource URI | `{"type": "ref/resource", "uri": "file:///{path}"}` | +| Type | Description | Example | +| -------------- | --------------------------- | --------------------------------------------------- | +| `ref/prompt` | References a prompt by name | `{"type": "ref/prompt", "name": "code_review"}` | +| `ref/resource` | References a resource URI | `{"type": "ref/resource", "uri": "file:///{path}"}` | ### Completion Results @@ -92,12 +100,14 @@ sequenceDiagram ## Data Types ### CompleteRequest + - `ref`: A `PromptReference` or `ResourceReference` - `argument`: Object containing: - `name`: Argument name - `value`: Current value ### CompleteResult + - `completion`: Object containing: - `values`: Array of suggestions (max 100) - `total`: Optional total matches @@ -106,6 +116,7 @@ sequenceDiagram ## Implementation Considerations 1. Servers **SHOULD**: + - Return suggestions sorted by relevance - Implement fuzzy matching where appropriate - Rate limit completion requests @@ -119,6 +130,7 @@ sequenceDiagram ## Security Implementations **MUST**: + - Validate all completion inputs - Implement appropriate rate limiting - Control access to sensitive suggestions diff --git a/docs/specification/draft/server/utilities/logging.md b/docs/specification/draft/server/utilities/logging.md index 159de10..8e9f168 100644 --- a/docs/specification/draft/server/utilities/logging.md +++ b/docs/specification/draft/server/utilities/logging.md @@ -2,15 +2,17 @@ title: Logging --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} -The Model Context Protocol (MCP) provides a standardized way for servers to send structured log messages to clients. Clients can control logging verbosity by setting minimum log levels, with servers sending notifications containing severity levels, optional logger names, and arbitrary JSON-serializable data. +The Model Context Protocol (MCP) provides a standardized way for servers to send +structured log messages to clients. Clients can control logging verbosity by setting +minimum log levels, with servers sending notifications containing severity levels, +optional logger names, and arbitrary JSON-serializable data. ## User Interaction Model -Implementations are free to expose logging through any interface pattern that suits their needs—the protocol itself does not mandate any specific user interaction model. +Implementations are free to expose logging through any interface pattern that suits their +needs—the protocol itself does not mandate any specific user interaction model. ## Capabilities @@ -26,18 +28,19 @@ Servers that emit log message notifications **MUST** declare the `logging` capab ## Log Levels -The protocol follows the standard syslog severity levels specified in [RFC 5424](https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1): +The protocol follows the standard syslog severity levels specified in +[RFC 5424](https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1): -| Level | Description | Example Use Case | -|------------|--------------------------------------|----------------------------------------| -| debug | Detailed debugging information | Function entry/exit points | -| info | General informational messages | Operation progress updates | -| notice | Normal but significant events | Configuration changes | -| warning | Warning conditions | Deprecated feature usage | -| error | Error conditions | Operation failures | -| critical | Critical conditions | System component failures | -| alert | Action must be taken immediately | Data corruption detected | -| emergency | System is unusable | Complete system failure | +| Level | Description | Example Use Case | +| --------- | -------------------------------- | -------------------------- | +| debug | Detailed debugging information | Function entry/exit points | +| info | General informational messages | Operation progress updates | +| notice | Normal but significant events | Configuration changes | +| warning | Warning conditions | Deprecated feature usage | +| error | Error conditions | Operation failures | +| critical | Critical conditions | System component failures | +| alert | Action must be taken immediately | Data corruption detected | +| emergency | System is unusable | Complete system failure | ## Protocol Messages @@ -46,6 +49,7 @@ The protocol follows the standard syslog severity levels specified in [RFC 5424] To configure the minimum log level, clients **MAY** send a `logging/setLevel` request: **Request:** + ```json { "jsonrpc": "2.0", @@ -111,6 +115,7 @@ Servers **SHOULD** return standard JSON-RPC errors for common failure cases: ## Implementation Considerations 1. Servers **SHOULD**: + - Rate limit log messages - Include relevant context in data field - Use consistent logger names @@ -125,6 +130,7 @@ Servers **SHOULD** return standard JSON-RPC errors for common failure cases: ## Security 1. Log messages **MUST NOT** contain: + - Credentials or secrets - Personal identifying information - Internal system details that could aid attacks diff --git a/docs/specification/draft/server/utilities/pagination.md b/docs/specification/draft/server/utilities/pagination.md index eeb5f0c..13efa23 100644 --- a/docs/specification/draft/server/utilities/pagination.md +++ b/docs/specification/draft/server/utilities/pagination.md @@ -1,24 +1,28 @@ --- title: Pagination --- -{{< callout type="info" >}} -**Protocol Revision**: draft -{{< /callout >}} -The Model Context Protocol (MCP) supports paginating list operations that may return large result sets. Pagination allows servers to yield results in smaller chunks rather than all at once. +{{< callout type="info" >}} **Protocol Revision**: draft {{< /callout >}} -Pagination is especially important when connecting to external services over the internet, but also useful for local integrations to avoid performance issues with large data sets. +The Model Context Protocol (MCP) supports paginating list operations that may return +large result sets. Pagination allows servers to yield results in smaller chunks rather +than all at once. + +Pagination is especially important when connecting to external services over the +internet, but also useful for local integrations to avoid performance issues with large +data sets. ## Pagination Model Pagination in MCP uses an opaque cursor-based approach, instead of numbered pages. -* The **cursor** is an opaque string token, representing a position in the result set -* **Page size** is determined by the server, and **MAY NOT** be fixed +- The **cursor** is an opaque string token, representing a position in the result set +- **Page size** is determined by the server, and **MAY NOT** be fixed ## Response Format Pagination starts when the server sends a **response** that includes: + - The current page of results - An optional `nextCursor` field if more results exist @@ -35,7 +39,8 @@ Pagination starts when the server sends a **response** that includes: ## Request Format -After receiving a cursor, the client can _continue_ paginating by issuing a request including that cursor: +After receiving a cursor, the client can _continue_ paginating by issuing a request +including that cursor: ```json { @@ -73,10 +78,12 @@ The following MCP operations support pagination: ## Implementation Guidelines 1. Servers **SHOULD**: + - Provide stable cursors - Handle invalid cursors gracefully 2. Clients **SHOULD**: + - Treat a missing `nextCursor` as the end of results - Support both paginated and non-paginated flows diff --git a/package-lock.json b/package-lock.json index 90bbc16..3995a2e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "glob": "^11.0.0", + "prettier": "^3.4.2", "tsx": "^4.19.1", "typescript": "^5.6.2", "typescript-json-schema": "^0.65.1" @@ -749,6 +750,22 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/prettier": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.4.2.tgz", + "integrity": "sha512-e9MewbtFo+Fevyuxn/4rrcDAaq0IYxPGLvObpQjiZBMAzB9IGmzlnG9RZy3FFas+eBMu2vA0CszMeduow5dIuQ==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", diff --git a/package.json b/package.json index 295a8f7..c8a146b 100644 --- a/package.json +++ b/package.json @@ -10,15 +10,29 @@ "engines": { "node": ">=20" }, + "prettier": { + "overrides": [ + { + "files": "*.md", + "options": { + "printWidth": 89, + "proseWrap": "always" + } + } + ] + }, "scripts": { "validate:schema": "tsc --noEmit schema/schema.ts schema/draft/schema.ts", "generate:json": "typescript-json-schema --defaultNumberType integer --required schema/schema.ts \"*\" -o schema/schema.json && typescript-json-schema --defaultNumberType integer --required schema/draft/schema.ts \"*\" -o schema/draft/schema.json", - "serve:docs": "hugo --source site/ server --logLevel debug --disableFastRender" + "serve:docs": "hugo --source site/ server --logLevel debug --disableFastRender", + "format": "prettier --write \"**/*.md\"", + "format:check": "prettier --check \"**/*.md\"" }, "devDependencies": { "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "glob": "^11.0.0", + "prettier": "^3.4.2", "tsx": "^4.19.1", "typescript": "^5.6.2", "typescript-json-schema": "^0.65.1"