├── .prettierignore ├── logo ├── dark.png ├── light.png └── dark.svg ├── sdk └── java │ ├── .DS_Store │ ├── mcp-overview.mdx │ └── mcp-client.mdx ├── images ├── og-image.png ├── current-weather.png ├── mcp-inspector.png ├── quickstart-menu.png ├── weather-alerts.png ├── quickstart-hammer.png ├── quickstart-tools.png ├── available-mcp-tools.png ├── quickstart-approve.png ├── quickstart-developer.png ├── quickstart-filesystem.png ├── quickstart-screenshot.png ├── client-claude-cli-python.png ├── quickstart-dotnet-client.png ├── visual-indicator-mcp-tools.png ├── java │ ├── java-mcp-client-architecture.jpg │ ├── java-mcp-server-architecture.jpg │ └── class-diagrams.puml ├── claude-desktop-mcp-hammer-icon.svg ├── claude-desktop-mcp-plug-icon.svg ├── hero-light.svg └── hero-dark.svg ├── README.md ├── snippets └── snippet-intro.mdx ├── development ├── contributing.mdx ├── updates.mdx └── roadmap.mdx ├── favicon.svg ├── LICENSE ├── CLAUDE.md ├── CONTRIBUTING.md ├── docs ├── concepts │ ├── roots.mdx │ ├── sampling.mdx │ ├── resources.mdx │ ├── tools.mdx │ ├── architecture.mdx │ ├── transports.mdx │ └── prompts.mdx └── tools │ ├── inspector.mdx │ └── debugging.mdx ├── tutorials ├── building-mcp-with-llms.mdx └── building-a-client-node.mdx ├── docs.json ├── CODE_OF_CONDUCT.md ├── introduction.mdx ├── examples.mdx └── quickstart └── user.mdx /.prettierignore: -------------------------------------------------------------------------------- 1 | *.mdx -------------------------------------------------------------------------------- /logo/dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/logo/dark.png -------------------------------------------------------------------------------- /logo/light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/logo/light.png -------------------------------------------------------------------------------- /sdk/java/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/sdk/java/.DS_Store -------------------------------------------------------------------------------- /images/og-image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/images/og-image.png -------------------------------------------------------------------------------- /images/current-weather.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/images/current-weather.png -------------------------------------------------------------------------------- /images/mcp-inspector.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/images/mcp-inspector.png -------------------------------------------------------------------------------- /images/quickstart-menu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/images/quickstart-menu.png -------------------------------------------------------------------------------- /images/weather-alerts.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/images/weather-alerts.png -------------------------------------------------------------------------------- /images/quickstart-hammer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/images/quickstart-hammer.png -------------------------------------------------------------------------------- /images/quickstart-tools.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/images/quickstart-tools.png -------------------------------------------------------------------------------- /images/available-mcp-tools.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/images/available-mcp-tools.png -------------------------------------------------------------------------------- /images/quickstart-approve.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/images/quickstart-approve.png -------------------------------------------------------------------------------- /images/quickstart-developer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/images/quickstart-developer.png -------------------------------------------------------------------------------- /images/quickstart-filesystem.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/images/quickstart-filesystem.png -------------------------------------------------------------------------------- /images/quickstart-screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/images/quickstart-screenshot.png -------------------------------------------------------------------------------- /images/client-claude-cli-python.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/images/client-claude-cli-python.png -------------------------------------------------------------------------------- /images/quickstart-dotnet-client.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/images/quickstart-dotnet-client.png -------------------------------------------------------------------------------- /images/visual-indicator-mcp-tools.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/images/visual-indicator-mcp-tools.png -------------------------------------------------------------------------------- /images/java/java-mcp-client-architecture.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/images/java/java-mcp-client-architecture.jpg -------------------------------------------------------------------------------- /images/java/java-mcp-server-architecture.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/modelcontextprotocol/docs/HEAD/images/java/java-mcp-server-architecture.jpg -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Model Context Protocol documentation 2 | 3 | **This documentation has moved to [modelcontextprotocol/modelcontextprotocol](https://github.com/modelcontextprotocol/modelcontextprotocol/tree/main/docs).** 4 | 5 | Please file issues and pull requests for documentation changes there. 6 | -------------------------------------------------------------------------------- /snippets/snippet-intro.mdx: -------------------------------------------------------------------------------- 1 | One of the core principles of software development is DRY (Don't Repeat 2 | Yourself). This is a principle that apply to documentation as 3 | well. If you find yourself repeating the same content in multiple places, you 4 | should consider creating a custom snippet to keep your content in sync. 5 | -------------------------------------------------------------------------------- /development/contributing.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Contributing 3 | description: How to participate in Model Context Protocol development 4 | --- 5 | 6 | We welcome contributions from the community! Please review our [contributing guidelines](https://github.com/modelcontextprotocol/.github/blob/main/CONTRIBUTING.md) for details on how to submit changes. 7 | 8 | All contributors must adhere to our [Code of Conduct](https://github.com/modelcontextprotocol/.github/blob/main/CODE_OF_CONDUCT.md). 9 | 10 | For questions and discussions, please use [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions). 11 | -------------------------------------------------------------------------------- /favicon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024–2025 Anthropic, PBC and contributors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /CLAUDE.md: -------------------------------------------------------------------------------- 1 | # MCP Documentation Guidelines 2 | 3 | ## Build Commands 4 | - Preview changes locally: `mintlify dev` 5 | - Deploy: Automatic after PR merge to main branch 6 | 7 | ## Style Guidelines 8 | - Follow existing MDX formatting and components 9 | - Keep content clear, concise, and technically accurate 10 | - Include practical code examples where appropriate 11 | - Test all links and code samples before submitting 12 | - Maintain consistent structure with existing documentation 13 | - When documenting CLI commands, use two-line format with the prompt on a separate line: `$ claude` followed by `> /command` 14 | - Use appropriate headings: "When to use", "Steps", and "Tips" for tutorials 15 | - Branch naming convention: prefix with "ashwin/" (e.g., "ashwin/add-mcp-cli-docs") 16 | 17 | ## File Organization 18 | - Place new pages in appropriate sections (concepts, tutorials, etc.) 19 | - Update docs.json when adding new pages 20 | - Follow existing file naming conventions (kebab-case.mdx) 21 | - Include proper frontmatter in MDX files 22 | 23 | ## Documentation Standards 24 | - Prioritize user understanding over technical completeness 25 | - Document both basic syntax and concrete examples 26 | - Structure command documentation with clear formatting 27 | - For image analysis examples, use quotes: `$ claude "Analyze this image: /path/to/image.png"` -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to MCP Documentation 2 | 3 | Thank you for your interest in contributing to the Model Context Protocol (MCP) documentation! This guide will help you get started with contributing. 4 | 5 | ## Getting Started 6 | 7 | 1. Install the required tools: 8 | - Node.js 9 | - Git 10 | - [Mintlify CLI](https://www.npmjs.com/package/mintlify): `npm i -g mintlify` 11 | 2. Fork and clone the repository 12 | 3. Create a new branch for your changes 13 | 4. Run `mintlify dev` to preview changes locally 14 | 15 | ## Documentation Guidelines 16 | 17 | - Keep content clear, concise, and technically accurate 18 | - Follow the existing file structure and naming conventions 19 | - Include code examples where appropriate 20 | - Use proper MDX formatting and components 21 | - Test all links and code samples 22 | 23 | ## Content Types 24 | 25 | You can contribute to: 26 | 27 | - Conceptual guides 28 | - API reference documentation 29 | - Tutorials and quickstarts 30 | - Best practices and examples 31 | - Troubleshooting guides 32 | 33 | ## Pull Request Process 34 | 35 | 1. Ensure your changes follow our documentation guidelines 36 | 2. Update the relevant table of contents if needed 37 | 3. Test your changes locally using `mintlify dev` 38 | 4. Submit a pull request with a clear description of your changes 39 | 5. Wait for review and address any feedback 40 | 41 | ## Need Help? 42 | 43 | - Check existing documentation at [modelcontextprotocol.io](https://modelcontextprotocol.io) 44 | - [Open an issue](https://github.com/modelcontextprotocol/docs/issues) for bugs or concerns 45 | - Join our [community discussions](https://github.com/modelcontextprotocol/docs/discussions) 46 | 47 | ## Code of Conduct 48 | 49 | Please note that this project follows our [Code of Conduct](CODE_OF_CONDUCT.md). By participating, you agree to uphold these guidelines. 50 | -------------------------------------------------------------------------------- /images/claude-desktop-mcp-hammer-icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /docs/concepts/roots.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Roots" 3 | description: "Understanding roots in MCP" 4 | --- 5 | 6 | Roots are a concept in MCP that define the boundaries where servers can operate. They provide a way for clients to inform servers about relevant resources and their locations. 7 | 8 | ## What are Roots? 9 | 10 | A root is a URI that a client suggests a server should focus on. When a client connects to a server, it declares which roots the server should work with. While primarily used for filesystem paths, roots can be any valid URI including HTTP URLs. 11 | 12 | For example, roots could be: 13 | 14 | ``` 15 | file:///home/user/projects/myapp 16 | https://api.example.com/v1 17 | ``` 18 | 19 | ## Why Use Roots? 20 | 21 | Roots serve several important purposes: 22 | 23 | 1. **Guidance**: They inform servers about relevant resources and locations 24 | 2. **Clarity**: Roots make it clear which resources are part of your workspace 25 | 3. **Organization**: Multiple roots let you work with different resources simultaneously 26 | 27 | ## How Roots Work 28 | 29 | When a client supports roots, it: 30 | 31 | 1. Declares the `roots` capability during connection 32 | 2. Provides a list of suggested roots to the server 33 | 3. Notifies the server when roots change (if supported) 34 | 35 | While roots are informational and not strictly enforcing, servers should: 36 | 37 | 1. Respect the provided roots 38 | 2. Use root URIs to locate and access resources 39 | 3. Prioritize operations within root boundaries 40 | 41 | ## Common Use Cases 42 | 43 | Roots are commonly used to define: 44 | 45 | - Project directories 46 | - Repository locations 47 | - API endpoints 48 | - Configuration locations 49 | - Resource boundaries 50 | 51 | ## Best Practices 52 | 53 | When working with roots: 54 | 55 | 1. Only suggest necessary resources 56 | 2. Use clear, descriptive names for roots 57 | 3. Monitor root accessibility 58 | 4. Handle root changes gracefully 59 | 60 | ## Example 61 | 62 | Here's how a typical MCP client might expose roots: 63 | 64 | ```json 65 | { 66 | "roots": [ 67 | { 68 | "uri": "file:///home/user/projects/frontend", 69 | "name": "Frontend Repository" 70 | }, 71 | { 72 | "uri": "https://api.example.com/v1", 73 | "name": "API Endpoint" 74 | } 75 | ] 76 | } 77 | ``` 78 | 79 | This configuration suggests the server focus on both a local repository and an API endpoint while keeping them logically separated. -------------------------------------------------------------------------------- /tutorials/building-mcp-with-llms.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Building MCP with LLMs" 3 | description: "Speed up your MCP development using LLMs such as Claude!" 4 | --- 5 | 6 | This guide will help you use LLMs to help you build custom Model Context Protocol (MCP) servers and clients. We'll be focusing on Claude for this tutorial, but you can do this with any frontier LLM. 7 | 8 | ## Preparing the documentation 9 | 10 | Before starting, gather the necessary documentation to help Claude understand MCP: 11 | 12 | 1. Visit https://modelcontextprotocol.io/llms-full.txt and copy the full documentation text 13 | 2. Navigate to either the [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) or [Python SDK repository](https://github.com/modelcontextprotocol/python-sdk) 14 | 3. Copy the README files and other relevant documentation 15 | 4. Paste these documents into your conversation with Claude 16 | 17 | ## Describing your server 18 | 19 | Once you've provided the documentation, clearly describe to Claude what kind of server you want to build. Be specific about: 20 | 21 | - What resources your server will expose 22 | - What tools it will provide 23 | - Any prompts it should offer 24 | - What external systems it needs to interact with 25 | 26 | For example: 27 | ``` 28 | Build an MCP server that: 29 | - Connects to my company's PostgreSQL database 30 | - Exposes table schemas as resources 31 | - Provides tools for running read-only SQL queries 32 | - Includes prompts for common data analysis tasks 33 | ``` 34 | 35 | ## Working with Claude 36 | 37 | When working with Claude on MCP servers: 38 | 39 | 1. Start with the core functionality first, then iterate to add more features 40 | 2. Ask Claude to explain any parts of the code you don't understand 41 | 3. Request modifications or improvements as needed 42 | 4. Have Claude help you test the server and handle edge cases 43 | 44 | Claude can help implement all the key MCP features: 45 | 46 | - Resource management and exposure 47 | - Tool definitions and implementations 48 | - Prompt templates and handlers 49 | - Error handling and logging 50 | - Connection and transport setup 51 | 52 | ## Best practices 53 | 54 | When building MCP servers with Claude: 55 | 56 | - Break down complex servers into smaller pieces 57 | - Test each component thoroughly before moving on 58 | - Keep security in mind - validate inputs and limit access appropriately 59 | - Document your code well for future maintenance 60 | - Follow MCP protocol specifications carefully 61 | 62 | ## Next steps 63 | 64 | After Claude helps you build your server: 65 | 66 | 1. Review the generated code carefully 67 | 2. Test the server with the MCP Inspector tool 68 | 3. Connect it to Claude.app or other MCP clients 69 | 4. Iterate based on real usage and feedback 70 | 71 | Remember that Claude can help you modify and improve your server as requirements change over time. 72 | 73 | Need more guidance? Just ask Claude specific questions about implementing MCP features or troubleshooting issues that arise. -------------------------------------------------------------------------------- /development/updates.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "What's New" 3 | description: 'The latest updates and improvements to MCP' 4 | --- 5 | 6 | 7 | - Fix issues and cleanup API 8 | - Added binary compatibility tracking to avoid breaking changes 9 | - Drop jdk requirements to JDK8 10 | - Added Claude Desktop integration with sample 11 | - The full changelog can be found here: https://github.com/modelcontextprotocol/kotlin-sdk/releases/tag/0.4.0 12 | 13 | 14 | 15 | - Version [0.8.1](https://github.com/modelcontextprotocol/java-sdk/releases/tag/v0.8.1) of the MCP Java SDK has been released, 16 | providing important bug fixes. 17 | 18 | 19 | - We are exited to announce the availability of the MCP 20 | [C# SDK](https://github.com/modelcontextprotocol/csharp-sdk/) developed by 21 | [Peder Holdgaard Pedersen](http://github.com/PederHP) and Microsoft. This joins our growing 22 | list of supported languages. The C# SDK is also available as 23 | [NuGet package](https://www.nuget.org/packages/ModelContextProtocol) 24 | - Python SDK 1.5.0 was released with multiple fixes and improvements. 25 | 26 | 27 | - Version [0.8.0](https://github.com/modelcontextprotocol/java-sdk/releases/tag/v0.8.0) of the MCP Java SDK has been released, 28 | delivering important session management improvements and bug fixes. 29 | 30 | 31 | - Typescript SDK 1.7.0 was released with multiple fixes and improvements. 32 | 33 | 34 | - We're excited to announce that the Java SDK developed by Spring AI at VMware Tanzu is now 35 | the official [Java SDK](https://github.com/modelcontextprotocol/java-sdk) for MCP. 36 | This joins our existing Kotlin SDK in our growing list of supported languages. 37 | The Spring AI team will maintain the SDK as an integral part of the Model Context Protocol 38 | organization. We're thrilled to welcome them to the MCP community! 39 | 40 | 41 | 42 | - Version [1.2.1](https://github.com/modelcontextprotocol/python-sdk/releases/tag/v1.2.1) of the MCP Python SDK has been released, 43 | delivering important stability improvements and bug fixes. 44 | 45 | 46 | - Simplified, express-like API in the [TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) 47 | - Added 8 new clients to the [clients page](https://modelcontextprotocol.io/clients) 48 | 49 | 50 | 51 | - FastMCP API in the [Python SDK](https://github.com/modelcontextprotocol/python-sdk) 52 | - Dockerized MCP servers in the [servers repo](https://github.com/modelcontextprotocol/servers) 53 | 54 | 55 | 56 | - Jetbrains released a Kotlin SDK for MCP! 57 | - For a sample MCP Kotlin server, check out [this repository](https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/kotlin-mcp-server) 58 | 59 | -------------------------------------------------------------------------------- /development/roadmap.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Roadmap 3 | description: Our plans for evolving Model Context Protocol 4 | --- 5 | 6 | Last updated: **2025-03-27** 7 | 8 | The Model Context Protocol is rapidly evolving. This page outlines our current thinking on key priorities and direction for approximately **the next six months**, though these may change significantly as the project develops. To see what's changed recently, check out the **[specification changelog](https://spec.modelcontextprotocol.io/specification/2025-03-26/changelog/)**. 9 | 10 | The ideas presented here are not commitments—we may solve these challenges differently than described, or some may not materialize at all. This is also not an _exhaustive_ list; we may incorporate work that isn't mentioned here. 11 | 12 | We value community participation! Each section links to relevant discussions where you can learn more and contribute your thoughts. 13 | 14 | For a technical view of our standardization process, visit the [Standards Track](https://github.com/orgs/modelcontextprotocol/projects/2/views/2) on GitHub, which tracks how proposals progress toward inclusion in the official [MCP specification](https://spec.modelcontextprotocol.io). 15 | 16 | ## Validation 17 | 18 | To foster a robust developer ecosystem, we plan to invest in: 19 | 20 | - **Reference Client Implementations**: demonstrating protocol features with high-quality AI applications 21 | - **Compliance Test Suites**: automated verification that clients, servers, and SDKs properly implement the specification 22 | 23 | These tools will help developers confidently implement MCP while ensuring consistent behavior across the ecosystem. 24 | 25 | ## Registry 26 | 27 | For MCP to reach its full potential, we need streamlined ways to distribute and discover MCP servers. 28 | 29 | We plan to develop an [**MCP Registry**](https://github.com/orgs/modelcontextprotocol/discussions/159) that will enable centralized server discovery and metadata. This registry will primarily function as an API layer that third-party marketplaces and discovery services can build upon. 30 | 31 | ## Agents 32 | 33 | As MCP increasingly becomes part of agentic workflows, we're exploring [improvements](https://github.com/modelcontextprotocol/specification/discussions/111) such as: 34 | 35 | - **[Agent Graphs](https://github.com/modelcontextprotocol/specification/discussions/94)**: enabling complex agent topologies through namespacing and graph-aware communication patterns 36 | - **Interactive Workflows**: improving human-in-the-loop experiences with granular permissioning, standardized interaction patterns, and [ways to directly communicate](https://github.com/modelcontextprotocol/specification/issues/97) with the end user 37 | 38 | ## Multimodality 39 | 40 | Supporting the full spectrum of AI capabilities in MCP, including: 41 | 42 | - **Additional Modalities**: video and other media types 43 | - **[Streaming](https://github.com/modelcontextprotocol/specification/issues/117)**: multipart, chunked messages, and bidirectional communication for interactive experiences 44 | 45 | ## Governance 46 | 47 | We're implementing governance structures that prioritize: 48 | 49 | - **Community-Led Development**: fostering a collaborative ecosystem where community members and AI developers can all participate in MCP's evolution, ensuring it serves diverse applications and use cases 50 | - **Transparent Standardization**: establishing clear processes for contributing to the specification, while exploring formal standardization via industry bodies 51 | 52 | ## Get Involved 53 | 54 | We welcome your contributions to MCP's future! Join our [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions) to share ideas, provide feedback, or participate in the development process. 55 | -------------------------------------------------------------------------------- /images/claude-desktop-mcp-plug-icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /docs.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://mintlify.com/docs.json", 3 | "theme": "willow", 4 | "name": "Model Context Protocol", 5 | "colors": { 6 | "primary": "#09090b", 7 | "light": "#FAFAFA", 8 | "dark": "#09090b" 9 | }, 10 | "favicon": "/favicon.svg", 11 | "navigation": { 12 | "tabs": [ 13 | { 14 | "tab": "Documentation", 15 | "groups": [ 16 | { 17 | "group": "Get Started", 18 | "pages": [ 19 | "introduction", 20 | { 21 | "group": "Quickstart", 22 | "pages": [ 23 | "quickstart/server", 24 | "quickstart/client", 25 | "quickstart/user" 26 | ] 27 | }, 28 | "examples", 29 | "clients" 30 | ] 31 | }, 32 | { 33 | "group": "Tutorials", 34 | "pages": [ 35 | "tutorials/building-mcp-with-llms", 36 | "docs/tools/debugging", 37 | "docs/tools/inspector" 38 | ] 39 | }, 40 | { 41 | "group": "Concepts", 42 | "pages": [ 43 | "docs/concepts/architecture", 44 | "docs/concepts/resources", 45 | "docs/concepts/prompts", 46 | "docs/concepts/tools", 47 | "docs/concepts/sampling", 48 | "docs/concepts/roots", 49 | "docs/concepts/transports" 50 | ] 51 | }, 52 | { 53 | "group": "Development", 54 | "pages": [ 55 | "development/updates", 56 | "development/roadmap", 57 | "development/contributing" 58 | ] 59 | } 60 | ] 61 | }, 62 | { 63 | "tab": "SDKs", 64 | "icon": "book-open", 65 | "groups": [ 66 | { 67 | "group": "Java", 68 | "pages": [ 69 | "sdk/java/mcp-overview", 70 | "sdk/java/mcp-client", 71 | "sdk/java/mcp-server" 72 | ] 73 | } 74 | ] 75 | } 76 | ], 77 | "global": { 78 | "anchors": [ 79 | { 80 | "anchor": "Python SDK", 81 | "href": "https://github.com/modelcontextprotocol/python-sdk", 82 | "icon": "python" 83 | }, 84 | { 85 | "anchor": "TypeScript SDK", 86 | "href": "https://github.com/modelcontextprotocol/typescript-sdk", 87 | "icon": "square-js" 88 | }, 89 | { 90 | "anchor": "Java SDK", 91 | "href": "https://github.com/modelcontextprotocol/java-sdk", 92 | "icon": "java" 93 | }, 94 | { 95 | "anchor": "Kotlin SDK", 96 | "href": "https://github.com/modelcontextprotocol/kotlin-sdk", 97 | "icon": "square-k" 98 | }, 99 | { 100 | "anchor": "C# SDK", 101 | "href": "https://github.com/modelcontextprotocol/csharp-sdk", 102 | "icon": "square-c" 103 | }, 104 | { 105 | "anchor": "Specification", 106 | "href": "https://spec.modelcontextprotocol.io", 107 | "icon": "book" 108 | } 109 | ] 110 | } 111 | }, 112 | "logo": { 113 | "light": "/logo/light.svg", 114 | "dark": "/logo/dark.svg" 115 | }, 116 | "navbar": { 117 | "links": [], 118 | "primary": { 119 | "type": "button", 120 | "label": "GitHub", 121 | "href": "https://github.com/modelcontextprotocol" 122 | } 123 | }, 124 | "seo": { 125 | "metatags": { 126 | "og:image": "https://raw.githubusercontent.com/modelcontextprotocol/docs/2eb6171ddbfeefde349dc3b8d5e2b87414c26250/images/og-image.png" 127 | }, 128 | "indexing": "navigable" 129 | }, 130 | "footer": { 131 | "socials": { 132 | "github": "https://github.com/modelcontextprotocol" 133 | } 134 | }, 135 | "redirects": [ 136 | { 137 | "source": "/tutorials/building-a-client", 138 | "destination": "/quickstart/client" 139 | }, 140 | { 141 | "source": "/quickstart", 142 | "destination": "/quickstart/server" 143 | } 144 | ] 145 | } 146 | -------------------------------------------------------------------------------- /docs/tools/inspector.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Inspector 3 | description: In-depth guide to using the MCP Inspector for testing and debugging Model Context Protocol servers 4 | --- 5 | 6 | The [MCP Inspector](https://github.com/modelcontextprotocol/inspector) is an interactive developer tool for testing and debugging MCP servers. While the [Debugging Guide](/docs/tools/debugging) covers the Inspector as part of the overall debugging toolkit, this document provides a detailed exploration of the Inspector's features and capabilities. 7 | 8 | ## Getting started 9 | 10 | ### Installation and basic usage 11 | 12 | The Inspector runs directly through `npx` without requiring installation: 13 | 14 | 15 | ```bash 16 | npx @modelcontextprotocol/inspector 17 | ``` 18 | 19 | ```bash 20 | npx @modelcontextprotocol/inspector 21 | ``` 22 | 23 | #### Inspecting servers from NPM or PyPi 24 | 25 | A common way to start server packages from [NPM](https://npmjs.com) or [PyPi](https://pypi.com). 26 | 27 | 28 | 29 | 30 | ```bash 31 | npx -y @modelcontextprotocol/inspector npx 32 | # For example 33 | npx -y @modelcontextprotocol/inspector npx server-postgres postgres://127.0.0.1/testdb 34 | ``` 35 | 36 | 37 | 38 | ```bash 39 | npx @modelcontextprotocol/inspector uvx 40 | # For example 41 | npx @modelcontextprotocol/inspector uvx mcp-server-git --repository ~/code/mcp/servers.git 42 | ``` 43 | 44 | 45 | 46 | #### Inspecting locally developed servers 47 | 48 | To inspect servers locally developed or downloaded as a repository, the most common 49 | way is: 50 | 51 | 52 | 53 | ```bash 54 | npx @modelcontextprotocol/inspector node path/to/server/index.js args... 55 | ``` 56 | 57 | 58 | ```bash 59 | npx @modelcontextprotocol/inspector \ 60 | uv \ 61 | --directory path/to/server \ 62 | run \ 63 | package-name \ 64 | args... 65 | ``` 66 | 67 | 68 | 69 | Please carefully read any attached README for the most accurate instructions. 70 | 71 | ## Feature overview 72 | 73 | 74 | 75 | 76 | 77 | The Inspector provides several features for interacting with your MCP server: 78 | 79 | ### Server connection pane 80 | - Allows selecting the [transport](/docs/concepts/transports) for connecting to the server 81 | - For local servers, supports customizing the command-line arguments and environment 82 | 83 | ### Resources tab 84 | - Lists all available resources 85 | - Shows resource metadata (MIME types, descriptions) 86 | - Allows resource content inspection 87 | - Supports subscription testing 88 | 89 | ### Prompts tab 90 | - Displays available prompt templates 91 | - Shows prompt arguments and descriptions 92 | - Enables prompt testing with custom arguments 93 | - Previews generated messages 94 | 95 | ### Tools tab 96 | - Lists available tools 97 | - Shows tool schemas and descriptions 98 | - Enables tool testing with custom inputs 99 | - Displays tool execution results 100 | 101 | ### Notifications pane 102 | - Presents all logs recorded from the server 103 | - Shows notifications received from the server 104 | 105 | ## Best practices 106 | 107 | ### Development workflow 108 | 109 | 1. Start Development 110 | - Launch Inspector with your server 111 | - Verify basic connectivity 112 | - Check capability negotiation 113 | 114 | 2. Iterative testing 115 | - Make server changes 116 | - Rebuild the server 117 | - Reconnect the Inspector 118 | - Test affected features 119 | - Monitor messages 120 | 121 | 3. Test edge cases 122 | - Invalid inputs 123 | - Missing prompt arguments 124 | - Concurrent operations 125 | - Verify error handling and error responses 126 | 127 | ## Next steps 128 | 129 | 130 | 135 | Check out the MCP Inspector source code 136 | 137 | 138 | 143 | Learn about broader debugging strategies 144 | 145 | 146 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | mcp-coc@anthropic.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /introduction.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Introduction 3 | description: 'Get started with the Model Context Protocol (MCP)' 4 | --- 5 | 6 | C# SDK released! Check out [what else is new.](/development/updates) 7 | 8 | MCP is an open protocol that standardizes how applications provide context to LLMs. Think of MCP like a USB-C port for AI applications. Just as USB-C provides a standardized way to connect your devices to various peripherals and accessories, MCP provides a standardized way to connect AI models to different data sources and tools. 9 | 10 | ## Why MCP? 11 | 12 | MCP helps you build agents and complex workflows on top of LLMs. LLMs frequently need to integrate with data and tools, and MCP provides: 13 | - A growing list of pre-built integrations that your LLM can directly plug into 14 | - The flexibility to switch between LLM providers and vendors 15 | - Best practices for securing your data within your infrastructure 16 | 17 | ### General architecture 18 | 19 | At its core, MCP follows a client-server architecture where a host application can connect to multiple servers: 20 | 21 | ```mermaid 22 | flowchart LR 23 | subgraph "Your Computer" 24 | Host["Host with MCP Client\n(Claude, IDEs, Tools)"] 25 | S1["MCP Server A"] 26 | S2["MCP Server B"] 27 | S3["MCP Server C"] 28 | Host <-->|"MCP Protocol"| S1 29 | Host <-->|"MCP Protocol"| S2 30 | Host <-->|"MCP Protocol"| S3 31 | S1 <--> D1[("Local\nData Source A")] 32 | S2 <--> D2[("Local\nData Source B")] 33 | end 34 | subgraph "Internet" 35 | S3 <-->|"Web APIs"| D3[("Remote\nService C")] 36 | end 37 | ``` 38 | 39 | - **MCP Hosts**: Programs like Claude Desktop, IDEs, or AI tools that want to access data through MCP 40 | - **MCP Clients**: Protocol clients that maintain 1:1 connections with servers 41 | - **MCP Servers**: Lightweight programs that each expose specific capabilities through the standardized Model Context Protocol 42 | - **Local Data Sources**: Your computer's files, databases, and services that MCP servers can securely access 43 | - **Remote Services**: External systems available over the internet (e.g., through APIs) that MCP servers can connect to 44 | 45 | ## Get started 46 | 47 | Choose the path that best fits your needs: 48 | 49 | #### Quick Starts 50 | 51 | 56 | Get started building your own server to use in Claude for Desktop and other clients 57 | 58 | 63 | Get started building your own client that can integrate with all MCP servers 64 | 65 | 70 | Get started using pre-built servers in Claude for Desktop 71 | 72 | 73 | 74 | #### Examples 75 | 76 | 81 | Check out our gallery of official MCP servers and implementations 82 | 83 | 88 | View the list of clients that support MCP integrations 89 | 90 | 91 | 92 | ## Tutorials 93 | 94 | 95 | 100 | Learn how to use LLMs like Claude to speed up your MCP development 101 | 102 | 106 | Learn how to effectively debug MCP servers and integrations 107 | 108 | 113 | Test and inspect your MCP servers with our interactive debugging tool 114 | 115 | 120 | 121 | 122 | 123 | 124 | ## Explore MCP 125 | 126 | Dive deeper into MCP's core concepts and capabilities: 127 | 128 | 129 | 134 | Understand how MCP connects clients, servers, and LLMs 135 | 136 | 141 | Expose data and content from your servers to LLMs 142 | 143 | 148 | Create reusable prompt templates and workflows 149 | 150 | 155 | Enable LLMs to perform actions through your server 156 | 157 | 162 | Let your servers request completions from LLMs 163 | 164 | 169 | Learn about MCP's communication mechanism 170 | 171 | 172 | 173 | ## Contributing 174 | 175 | Want to contribute? Check out our [Contributing Guide](/development/contributing) to learn how you can help improve MCP. 176 | 177 | ## Support and Feedback 178 | 179 | Here's how to get help or provide feedback: 180 | 181 | - For bug reports and feature requests related to the MCP specification, SDKs, or documentation (open source), please [create a GitHub issue](https://github.com/modelcontextprotocol) 182 | - For discussions or Q&A about the MCP specification, use the [specification discussions](https://github.com/modelcontextprotocol/specification/discussions) 183 | - For discussions or Q&A about other MCP open source components, use the [organization discussions](https://github.com/orgs/modelcontextprotocol/discussions) 184 | - For bug reports, feature requests, and questions related to Claude.app and claude.ai's MCP integration, please see Anthropic's guide on [How to Get Support](https://support.anthropic.com/en/articles/9015913-how-to-get-support) 185 | -------------------------------------------------------------------------------- /docs/concepts/sampling.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Sampling" 3 | description: "Let your servers request completions from LLMs" 4 | --- 5 | 6 | Sampling is a powerful MCP feature that allows servers to request LLM completions through the client, enabling sophisticated agentic behaviors while maintaining security and privacy. 7 | 8 | 9 | This feature of MCP is not yet supported in the Claude Desktop client. 10 | 11 | 12 | ## How sampling works 13 | 14 | The sampling flow follows these steps: 15 | 16 | 1. Server sends a `sampling/createMessage` request to the client 17 | 2. Client reviews the request and can modify it 18 | 3. Client samples from an LLM 19 | 4. Client reviews the completion 20 | 5. Client returns the result to the server 21 | 22 | This human-in-the-loop design ensures users maintain control over what the LLM sees and generates. 23 | 24 | ## Message format 25 | 26 | Sampling requests use a standardized message format: 27 | 28 | ```typescript 29 | { 30 | messages: [ 31 | { 32 | role: "user" | "assistant", 33 | content: { 34 | type: "text" | "image", 35 | 36 | // For text: 37 | text?: string, 38 | 39 | // For images: 40 | data?: string, // base64 encoded 41 | mimeType?: string 42 | } 43 | } 44 | ], 45 | modelPreferences?: { 46 | hints?: [{ 47 | name?: string // Suggested model name/family 48 | }], 49 | costPriority?: number, // 0-1, importance of minimizing cost 50 | speedPriority?: number, // 0-1, importance of low latency 51 | intelligencePriority?: number // 0-1, importance of capabilities 52 | }, 53 | systemPrompt?: string, 54 | includeContext?: "none" | "thisServer" | "allServers", 55 | temperature?: number, 56 | maxTokens: number, 57 | stopSequences?: string[], 58 | metadata?: Record 59 | } 60 | ``` 61 | 62 | ## Request parameters 63 | 64 | ### Messages 65 | 66 | The `messages` array contains the conversation history to send to the LLM. Each message has: 67 | 68 | - `role`: Either "user" or "assistant" 69 | - `content`: The message content, which can be: 70 | - Text content with a `text` field 71 | - Image content with `data` (base64) and `mimeType` fields 72 | 73 | ### Model preferences 74 | 75 | The `modelPreferences` object allows servers to specify their model selection preferences: 76 | 77 | - `hints`: Array of model name suggestions that clients can use to select an appropriate model: 78 | - `name`: String that can match full or partial model names (e.g. "claude-3", "sonnet") 79 | - Clients may map hints to equivalent models from different providers 80 | - Multiple hints are evaluated in preference order 81 | 82 | - Priority values (0-1 normalized): 83 | - `costPriority`: Importance of minimizing costs 84 | - `speedPriority`: Importance of low latency response 85 | - `intelligencePriority`: Importance of advanced model capabilities 86 | 87 | Clients make the final model selection based on these preferences and their available models. 88 | 89 | ### System prompt 90 | 91 | An optional `systemPrompt` field allows servers to request a specific system prompt. The client may modify or ignore this. 92 | 93 | ### Context inclusion 94 | 95 | The `includeContext` parameter specifies what MCP context to include: 96 | 97 | - `"none"`: No additional context 98 | - `"thisServer"`: Include context from the requesting server 99 | - `"allServers"`: Include context from all connected MCP servers 100 | 101 | The client controls what context is actually included. 102 | 103 | ### Sampling parameters 104 | 105 | Fine-tune the LLM sampling with: 106 | 107 | - `temperature`: Controls randomness (0.0 to 1.0) 108 | - `maxTokens`: Maximum tokens to generate 109 | - `stopSequences`: Array of sequences that stop generation 110 | - `metadata`: Additional provider-specific parameters 111 | 112 | ## Response format 113 | 114 | The client returns a completion result: 115 | 116 | ```typescript 117 | { 118 | model: string, // Name of the model used 119 | stopReason?: "endTurn" | "stopSequence" | "maxTokens" | string, 120 | role: "user" | "assistant", 121 | content: { 122 | type: "text" | "image", 123 | text?: string, 124 | data?: string, 125 | mimeType?: string 126 | } 127 | } 128 | ``` 129 | 130 | ## Example request 131 | 132 | Here's an example of requesting sampling from a client: 133 | ```json 134 | { 135 | "method": "sampling/createMessage", 136 | "params": { 137 | "messages": [ 138 | { 139 | "role": "user", 140 | "content": { 141 | "type": "text", 142 | "text": "What files are in the current directory?" 143 | } 144 | } 145 | ], 146 | "systemPrompt": "You are a helpful file system assistant.", 147 | "includeContext": "thisServer", 148 | "maxTokens": 100 149 | } 150 | } 151 | ``` 152 | 153 | ## Best practices 154 | 155 | When implementing sampling: 156 | 157 | 1. Always provide clear, well-structured prompts 158 | 2. Handle both text and image content appropriately 159 | 3. Set reasonable token limits 160 | 4. Include relevant context through `includeContext` 161 | 5. Validate responses before using them 162 | 6. Handle errors gracefully 163 | 7. Consider rate limiting sampling requests 164 | 8. Document expected sampling behavior 165 | 9. Test with various model parameters 166 | 10. Monitor sampling costs 167 | 168 | ## Human in the loop controls 169 | 170 | Sampling is designed with human oversight in mind: 171 | 172 | ### For prompts 173 | 174 | - Clients should show users the proposed prompt 175 | - Users should be able to modify or reject prompts 176 | - System prompts can be filtered or modified 177 | - Context inclusion is controlled by the client 178 | 179 | ### For completions 180 | 181 | - Clients should show users the completion 182 | - Users should be able to modify or reject completions 183 | - Clients can filter or modify completions 184 | - Users control which model is used 185 | 186 | ## Security considerations 187 | 188 | When implementing sampling: 189 | 190 | - Validate all message content 191 | - Sanitize sensitive information 192 | - Implement appropriate rate limits 193 | - Monitor sampling usage 194 | - Encrypt data in transit 195 | - Handle user data privacy 196 | - Audit sampling requests 197 | - Control cost exposure 198 | - Implement timeouts 199 | - Handle model errors gracefully 200 | 201 | ## Common patterns 202 | 203 | ### Agentic workflows 204 | 205 | Sampling enables agentic patterns like: 206 | 207 | - Reading and analyzing resources 208 | - Making decisions based on context 209 | - Generating structured data 210 | - Handling multi-step tasks 211 | - Providing interactive assistance 212 | 213 | ### Context management 214 | 215 | Best practices for context: 216 | 217 | - Request minimal necessary context 218 | - Structure context clearly 219 | - Handle context size limits 220 | - Update context as needed 221 | - Clean up stale context 222 | 223 | ### Error handling 224 | 225 | Robust error handling should: 226 | 227 | - Catch sampling failures 228 | - Handle timeout errors 229 | - Manage rate limits 230 | - Validate responses 231 | - Provide fallback behaviors 232 | - Log errors appropriately 233 | 234 | ## Limitations 235 | 236 | Be aware of these limitations: 237 | 238 | - Sampling depends on client capabilities 239 | - Users control sampling behavior 240 | - Context size has limits 241 | - Rate limits may apply 242 | - Costs should be considered 243 | - Model availability varies 244 | - Response times vary 245 | - Not all content types supported 246 | -------------------------------------------------------------------------------- /examples.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Example Servers 3 | description: 'A list of example servers and implementations' 4 | --- 5 | 6 | This page showcases various Model Context Protocol (MCP) servers that demonstrate the protocol's capabilities and versatility. These servers enable Large Language Models (LLMs) to securely access tools and data sources. 7 | 8 | ## Reference implementations 9 | 10 | These official reference servers demonstrate core MCP features and SDK usage: 11 | 12 | ### Data and file systems 13 | - **[Filesystem](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem)** - Secure file operations with configurable access controls 14 | - **[PostgreSQL](https://github.com/modelcontextprotocol/servers/tree/main/src/postgres)** - Read-only database access with schema inspection capabilities 15 | - **[SQLite](https://github.com/modelcontextprotocol/servers/tree/main/src/sqlite)** - Database interaction and business intelligence features 16 | - **[Google Drive](https://github.com/modelcontextprotocol/servers/tree/main/src/gdrive)** - File access and search capabilities for Google Drive 17 | 18 | ### Development tools 19 | - **[Git](https://github.com/modelcontextprotocol/servers/tree/main/src/git)** - Tools to read, search, and manipulate Git repositories 20 | - **[GitHub](https://github.com/modelcontextprotocol/servers/tree/main/src/github)** - Repository management, file operations, and GitHub API integration 21 | - **[GitLab](https://github.com/modelcontextprotocol/servers/tree/main/src/gitlab)** - GitLab API integration enabling project management 22 | - **[Sentry](https://github.com/modelcontextprotocol/servers/tree/main/src/sentry)** - Retrieving and analyzing issues from Sentry.io 23 | 24 | ### Web and browser automation 25 | - **[Brave Search](https://github.com/modelcontextprotocol/servers/tree/main/src/brave-search)** - Web and local search using Brave's Search API 26 | - **[Fetch](https://github.com/modelcontextprotocol/servers/tree/main/src/fetch)** - Web content fetching and conversion optimized for LLM usage 27 | - **[Puppeteer](https://github.com/modelcontextprotocol/servers/tree/main/src/puppeteer)** - Browser automation and web scraping capabilities 28 | 29 | ### Productivity and communication 30 | - **[Slack](https://github.com/modelcontextprotocol/servers/tree/main/src/slack)** - Channel management and messaging capabilities 31 | - **[Google Maps](https://github.com/modelcontextprotocol/servers/tree/main/src/google-maps)** - Location services, directions, and place details 32 | - **[Memory](https://github.com/modelcontextprotocol/servers/tree/main/src/memory)** - Knowledge graph-based persistent memory system 33 | 34 | ### AI and specialized tools 35 | - **[EverArt](https://github.com/modelcontextprotocol/servers/tree/main/src/everart)** - AI image generation using various models 36 | - **[Sequential Thinking](https://github.com/modelcontextprotocol/servers/tree/main/src/sequentialthinking)** - Dynamic problem-solving through thought sequences 37 | - **[AWS KB Retrieval](https://github.com/modelcontextprotocol/servers/tree/main/src/aws-kb-retrieval-server)** - Retrieval from AWS Knowledge Base using Bedrock Agent Runtime 38 | 39 | ## Official integrations 40 | 41 | These MCP servers are maintained by companies for their platforms: 42 | 43 | - **[Axiom](https://github.com/axiomhq/mcp-server-axiom)** - Query and analyze logs, traces, and event data using natural language 44 | - **[Browserbase](https://github.com/browserbase/mcp-server-browserbase)** - Automate browser interactions in the cloud 45 | - **[Cloudflare](https://github.com/cloudflare/mcp-server-cloudflare)** - Deploy and manage resources on the Cloudflare developer platform 46 | - **[E2B](https://github.com/e2b-dev/mcp-server)** - Execute code in secure cloud sandboxes 47 | - **[Neon](https://github.com/neondatabase/mcp-server-neon)** - Interact with the Neon serverless Postgres platform 48 | - **[Obsidian Markdown Notes](https://github.com/calclavia/mcp-obsidian)** - Read and search through Markdown notes in Obsidian vaults 49 | - **[Qdrant](https://github.com/qdrant/mcp-server-qdrant/)** - Implement semantic memory using the Qdrant vector search engine 50 | - **[Raygun](https://github.com/MindscapeHQ/mcp-server-raygun)** - Access crash reporting and monitoring data 51 | - **[Search1API](https://github.com/fatwang2/search1api-mcp)** - Unified API for search, crawling, and sitemaps 52 | - **[Stripe](https://github.com/stripe/agent-toolkit)** - Interact with the Stripe API 53 | - **[Tinybird](https://github.com/tinybirdco/mcp-tinybird)** - Interface with the Tinybird serverless ClickHouse platform 54 | - **[Weaviate](https://github.com/weaviate/mcp-server-weaviate)** - Enable Agentic RAG through your Weaviate collection(s) 55 | 56 | ## Community highlights 57 | 58 | A growing ecosystem of community-developed servers extends MCP's capabilities: 59 | 60 | - **[Docker](https://github.com/ckreiling/mcp-server-docker)** - Manage containers, images, volumes, and networks 61 | - **[Kubernetes](https://github.com/Flux159/mcp-server-kubernetes)** - Manage pods, deployments, and services 62 | - **[Linear](https://github.com/jerhadf/linear-mcp-server)** - Project management and issue tracking 63 | - **[Snowflake](https://github.com/datawiz168/mcp-snowflake-service)** - Interact with Snowflake databases 64 | - **[Spotify](https://github.com/varunneal/spotify-mcp)** - Control Spotify playback and manage playlists 65 | - **[Todoist](https://github.com/abhiz123/todoist-mcp-server)** - Task management integration 66 | 67 | > **Note:** Community servers are untested and should be used at your own risk. They are not affiliated with or endorsed by Anthropic. 68 | 69 | For a complete list of community servers, visit the [MCP Servers Repository](https://github.com/modelcontextprotocol/servers). 70 | 71 | ## Getting started 72 | 73 | ### Using reference servers 74 | 75 | TypeScript-based servers can be used directly with `npx`: 76 | 77 | ```bash 78 | npx -y @modelcontextprotocol/server-memory 79 | ``` 80 | 81 | Python-based servers can be used with `uvx` (recommended) or `pip`: 82 | 83 | ```bash 84 | # Using uvx 85 | uvx mcp-server-git 86 | 87 | # Using pip 88 | pip install mcp-server-git 89 | python -m mcp_server_git 90 | ``` 91 | 92 | ### Configuring with Claude 93 | 94 | To use an MCP server with Claude, add it to your configuration: 95 | 96 | ```json 97 | { 98 | "mcpServers": { 99 | "memory": { 100 | "command": "npx", 101 | "args": ["-y", "@modelcontextprotocol/server-memory"] 102 | }, 103 | "filesystem": { 104 | "command": "npx", 105 | "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"] 106 | }, 107 | "github": { 108 | "command": "npx", 109 | "args": ["-y", "@modelcontextprotocol/server-github"], 110 | "env": { 111 | "GITHUB_PERSONAL_ACCESS_TOKEN": "" 112 | } 113 | } 114 | } 115 | } 116 | ``` 117 | 118 | ## Additional resources 119 | 120 | - [MCP Servers Repository](https://github.com/modelcontextprotocol/servers) - Complete collection of reference implementations and community servers 121 | - [Awesome MCP Servers](https://github.com/punkpeye/awesome-mcp-servers) - Curated list of MCP servers 122 | - [MCP CLI](https://github.com/wong2/mcp-cli) - Command-line inspector for testing MCP servers 123 | - [MCP Get](https://mcp-get.com) - Tool for installing and managing MCP servers 124 | - [Supergateway](https://github.com/supercorp-ai/supergateway) - Run MCP stdio servers over SSE 125 | - [Zapier MCP](https://zapier.com/mcp) - MCP Server with over 7,000+ apps and 30,000+ actions 126 | 127 | Visit our [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions) to engage with the MCP community. 128 | -------------------------------------------------------------------------------- /docs/tools/debugging.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Debugging 3 | description: A comprehensive guide to debugging Model Context Protocol (MCP) integrations 4 | --- 5 | 6 | Effective debugging is essential when developing MCP servers or integrating them with applications. This guide covers the debugging tools and approaches available in the MCP ecosystem. 7 | 8 | 9 | This guide is for macOS. Guides for other platforms are coming soon. 10 | 11 | 12 | ## Debugging tools overview 13 | 14 | MCP provides several tools for debugging at different levels: 15 | 16 | 1. **MCP Inspector** 17 | - Interactive debugging interface 18 | - Direct server testing 19 | - See the [Inspector guide](/docs/tools/inspector) for details 20 | 21 | 2. **Claude Desktop Developer Tools** 22 | - Integration testing 23 | - Log collection 24 | - Chrome DevTools integration 25 | 26 | 3. **Server Logging** 27 | - Custom logging implementations 28 | - Error tracking 29 | - Performance monitoring 30 | 31 | ## Debugging in Claude Desktop 32 | 33 | ### Checking server status 34 | 35 | The Claude.app interface provides basic server status information: 36 | 37 | 1. Click the icon to view: 38 | - Connected servers 39 | - Available prompts and resources 40 | 41 | 2. Click the icon to view: 42 | - Tools made available to the model 43 | 44 | ### Viewing logs 45 | 46 | Review detailed MCP logs from Claude Desktop: 47 | 48 | ```bash 49 | # Follow logs in real-time 50 | tail -n 20 -F ~/Library/Logs/Claude/mcp*.log 51 | ``` 52 | 53 | The logs capture: 54 | - Server connection events 55 | - Configuration issues 56 | - Runtime errors 57 | - Message exchanges 58 | 59 | ### Using Chrome DevTools 60 | 61 | Access Chrome's developer tools inside Claude Desktop to investigate client-side errors: 62 | 63 | 1. Create a `developer_settings.json` file with `allowDevTools` set to true: 64 | 65 | ```bash 66 | echo '{"allowDevTools": true}' > ~/Library/Application\ Support/Claude/developer_settings.json 67 | ``` 68 | 69 | 2. Open DevTools: `Command-Option-Shift-i` 70 | 71 | Note: You'll see two DevTools windows: 72 | - Main content window 73 | - App title bar window 74 | 75 | Use the Console panel to inspect client-side errors. 76 | 77 | Use the Network panel to inspect: 78 | - Message payloads 79 | - Connection timing 80 | 81 | ## Common issues 82 | 83 | ### Working directory 84 | 85 | When using MCP servers with Claude Desktop: 86 | 87 | - The working directory for servers launched via `claude_desktop_config.json` may be undefined (like `/` on macOS) since Claude Desktop could be started from anywhere 88 | - Always use absolute paths in your configuration and `.env` files to ensure reliable operation 89 | - For testing servers directly via command line, the working directory will be where you run the command 90 | 91 | For example in `claude_desktop_config.json`, use: 92 | ```json 93 | { 94 | "command": "npx", 95 | "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/username/data"] 96 | } 97 | ``` 98 | Instead of relative paths like `./data` 99 | 100 | ### Environment variables 101 | 102 | MCP servers inherit only a subset of environment variables automatically, like `USER`, `HOME`, and `PATH`. 103 | 104 | To override the default variables or provide your own, you can specify an `env` key in `claude_desktop_config.json`: 105 | 106 | ```json 107 | { 108 | "myserver": { 109 | "command": "mcp-server-myapp", 110 | "env": { 111 | "MYAPP_API_KEY": "some_key", 112 | } 113 | } 114 | } 115 | ``` 116 | 117 | ### Server initialization 118 | 119 | Common initialization problems: 120 | 121 | 1. **Path Issues** 122 | - Incorrect server executable path 123 | - Missing required files 124 | - Permission problems 125 | - Try using an absolute path for `command` 126 | 127 | 2. **Configuration Errors** 128 | - Invalid JSON syntax 129 | - Missing required fields 130 | - Type mismatches 131 | 132 | 3. **Environment Problems** 133 | - Missing environment variables 134 | - Incorrect variable values 135 | - Permission restrictions 136 | 137 | ### Connection problems 138 | 139 | When servers fail to connect: 140 | 141 | 1. Check Claude Desktop logs 142 | 2. Verify server process is running 143 | 3. Test standalone with [Inspector](/docs/tools/inspector) 144 | 4. Verify protocol compatibility 145 | 146 | ## Implementing logging 147 | 148 | ### Server-side logging 149 | 150 | When building a server that uses the local stdio [transport](/docs/concepts/transports), all messages logged to stderr (standard error) will be captured by the host application (e.g., Claude Desktop) automatically. 151 | 152 | 153 | Local MCP servers should not log messages to stdout (standard out), as this will interfere with protocol operation. 154 | 155 | 156 | For all [transports](/docs/concepts/transports), you can also provide logging to the client by sending a log message notification: 157 | 158 | 159 | 160 | ```python 161 | server.request_context.session.send_log_message( 162 | level="info", 163 | data="Server started successfully", 164 | ) 165 | ``` 166 | 167 | 168 | ```typescript 169 | server.sendLoggingMessage({ 170 | level: "info", 171 | data: "Server started successfully", 172 | }); 173 | ``` 174 | 175 | 176 | 177 | Important events to log: 178 | - Initialization steps 179 | - Resource access 180 | - Tool execution 181 | - Error conditions 182 | - Performance metrics 183 | 184 | ### Client-side logging 185 | 186 | In client applications: 187 | 188 | 1. Enable debug logging 189 | 2. Monitor network traffic 190 | 3. Track message exchanges 191 | 4. Record error states 192 | 193 | ## Debugging workflow 194 | 195 | ### Development cycle 196 | 197 | 1. Initial Development 198 | - Use [Inspector](/docs/tools/inspector) for basic testing 199 | - Implement core functionality 200 | - Add logging points 201 | 202 | 2. Integration Testing 203 | - Test in Claude Desktop 204 | - Monitor logs 205 | - Check error handling 206 | 207 | ### Testing changes 208 | 209 | To test changes efficiently: 210 | 211 | - **Configuration changes**: Restart Claude Desktop 212 | - **Server code changes**: Use Command-R to reload 213 | - **Quick iteration**: Use [Inspector](/docs/tools/inspector) during development 214 | 215 | ## Best practices 216 | 217 | ### Logging strategy 218 | 219 | 1. **Structured Logging** 220 | - Use consistent formats 221 | - Include context 222 | - Add timestamps 223 | - Track request IDs 224 | 225 | 2. **Error Handling** 226 | - Log stack traces 227 | - Include error context 228 | - Track error patterns 229 | - Monitor recovery 230 | 231 | 3. **Performance Tracking** 232 | - Log operation timing 233 | - Monitor resource usage 234 | - Track message sizes 235 | - Measure latency 236 | 237 | ### Security considerations 238 | 239 | When debugging: 240 | 241 | 1. **Sensitive Data** 242 | - Sanitize logs 243 | - Protect credentials 244 | - Mask personal information 245 | 246 | 2. **Access Control** 247 | - Verify permissions 248 | - Check authentication 249 | - Monitor access patterns 250 | 251 | ## Getting help 252 | 253 | When encountering issues: 254 | 255 | 1. **First Steps** 256 | - Check server logs 257 | - Test with [Inspector](/docs/tools/inspector) 258 | - Review configuration 259 | - Verify environment 260 | 261 | 2. **Support Channels** 262 | - GitHub issues 263 | - GitHub discussions 264 | 265 | 3. **Providing Information** 266 | - Log excerpts 267 | - Configuration files 268 | - Steps to reproduce 269 | - Environment details 270 | 271 | ## Next steps 272 | 273 | 274 | 279 | Learn to use the MCP Inspector 280 | 281 | 282 | -------------------------------------------------------------------------------- /docs/concepts/resources.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Resources" 3 | description: "Expose data and content from your servers to LLMs" 4 | --- 5 | 6 | Resources are a core primitive in the Model Context Protocol (MCP) that allow servers to expose data and content that can be read by clients and used as context for LLM interactions. 7 | 8 | 9 | Resources are designed to be **application-controlled**, meaning that the client application can decide how and when they should be used. 10 | Different MCP clients may handle resources differently. For example: 11 | - Claude Desktop currently requires users to explicitly select resources before they can be used 12 | - Other clients might automatically select resources based on heuristics 13 | - Some implementations may even allow the AI model itself to determine which resources to use 14 | 15 | Server authors should be prepared to handle any of these interaction patterns when implementing resource support. In order to expose data to models automatically, server authors should use a **model-controlled** primitive such as [Tools](./tools). 16 | 17 | 18 | ## Overview 19 | 20 | Resources represent any kind of data that an MCP server wants to make available to clients. This can include: 21 | 22 | - File contents 23 | - Database records 24 | - API responses 25 | - Live system data 26 | - Screenshots and images 27 | - Log files 28 | - And more 29 | 30 | Each resource is identified by a unique URI and can contain either text or binary data. 31 | 32 | ## Resource URIs 33 | 34 | Resources are identified using URIs that follow this format: 35 | 36 | ``` 37 | [protocol]://[host]/[path] 38 | ``` 39 | 40 | For example: 41 | - `file:///home/user/documents/report.pdf` 42 | - `postgres://database/customers/schema` 43 | - `screen://localhost/display1` 44 | 45 | The protocol and path structure is defined by the MCP server implementation. Servers can define their own custom URI schemes. 46 | 47 | ## Resource types 48 | 49 | Resources can contain two types of content: 50 | 51 | ### Text resources 52 | 53 | Text resources contain UTF-8 encoded text data. These are suitable for: 54 | - Source code 55 | - Configuration files 56 | - Log files 57 | - JSON/XML data 58 | - Plain text 59 | 60 | ### Binary resources 61 | 62 | Binary resources contain raw binary data encoded in base64. These are suitable for: 63 | - Images 64 | - PDFs 65 | - Audio files 66 | - Video files 67 | - Other non-text formats 68 | 69 | ## Resource discovery 70 | 71 | Clients can discover available resources through two main methods: 72 | 73 | ### Direct resources 74 | 75 | Servers expose a list of concrete resources via the `resources/list` endpoint. Each resource includes: 76 | 77 | ```typescript 78 | { 79 | uri: string; // Unique identifier for the resource 80 | name: string; // Human-readable name 81 | description?: string; // Optional description 82 | mimeType?: string; // Optional MIME type 83 | } 84 | ``` 85 | 86 | ### Resource templates 87 | 88 | For dynamic resources, servers can expose [URI templates](https://datatracker.ietf.org/doc/html/rfc6570) that clients can use to construct valid resource URIs: 89 | 90 | ```typescript 91 | { 92 | uriTemplate: string; // URI template following RFC 6570 93 | name: string; // Human-readable name for this type 94 | description?: string; // Optional description 95 | mimeType?: string; // Optional MIME type for all matching resources 96 | } 97 | ``` 98 | 99 | ## Reading resources 100 | 101 | To read a resource, clients make a `resources/read` request with the resource URI. 102 | 103 | The server responds with a list of resource contents: 104 | 105 | ```typescript 106 | { 107 | contents: [ 108 | { 109 | uri: string; // The URI of the resource 110 | mimeType?: string; // Optional MIME type 111 | 112 | // One of: 113 | text?: string; // For text resources 114 | blob?: string; // For binary resources (base64 encoded) 115 | } 116 | ] 117 | } 118 | ``` 119 | 120 | 121 | Servers may return multiple resources in response to one `resources/read` request. This could be used, for example, to return a list of files inside a directory when the directory is read. 122 | 123 | 124 | ## Resource updates 125 | 126 | MCP supports real-time updates for resources through two mechanisms: 127 | 128 | ### List changes 129 | 130 | Servers can notify clients when their list of available resources changes via the `notifications/resources/list_changed` notification. 131 | 132 | ### Content changes 133 | 134 | Clients can subscribe to updates for specific resources: 135 | 136 | 1. Client sends `resources/subscribe` with resource URI 137 | 2. Server sends `notifications/resources/updated` when the resource changes 138 | 3. Client can fetch latest content with `resources/read` 139 | 4. Client can unsubscribe with `resources/unsubscribe` 140 | 141 | ## Example implementation 142 | 143 | Here's a simple example of implementing resource support in an MCP server: 144 | 145 | 146 | 147 | ```typescript 148 | const server = new Server({ 149 | name: "example-server", 150 | version: "1.0.0" 151 | }, { 152 | capabilities: { 153 | resources: {} 154 | } 155 | }); 156 | 157 | // List available resources 158 | server.setRequestHandler(ListResourcesRequestSchema, async () => { 159 | return { 160 | resources: [ 161 | { 162 | uri: "file:///logs/app.log", 163 | name: "Application Logs", 164 | mimeType: "text/plain" 165 | } 166 | ] 167 | }; 168 | }); 169 | 170 | // Read resource contents 171 | server.setRequestHandler(ReadResourceRequestSchema, async (request) => { 172 | const uri = request.params.uri; 173 | 174 | if (uri === "file:///logs/app.log") { 175 | const logContents = await readLogFile(); 176 | return { 177 | contents: [ 178 | { 179 | uri, 180 | mimeType: "text/plain", 181 | text: logContents 182 | } 183 | ] 184 | }; 185 | } 186 | 187 | throw new Error("Resource not found"); 188 | }); 189 | ``` 190 | 191 | 192 | ```python 193 | app = Server("example-server") 194 | 195 | @app.list_resources() 196 | async def list_resources() -> list[types.Resource]: 197 | return [ 198 | types.Resource( 199 | uri="file:///logs/app.log", 200 | name="Application Logs", 201 | mimeType="text/plain" 202 | ) 203 | ] 204 | 205 | @app.read_resource() 206 | async def read_resource(uri: AnyUrl) -> str: 207 | if str(uri) == "file:///logs/app.log": 208 | log_contents = await read_log_file() 209 | return log_contents 210 | 211 | raise ValueError("Resource not found") 212 | 213 | # Start server 214 | async with stdio_server() as streams: 215 | await app.run( 216 | streams[0], 217 | streams[1], 218 | app.create_initialization_options() 219 | ) 220 | ``` 221 | 222 | 223 | 224 | ## Best practices 225 | 226 | When implementing resource support: 227 | 228 | 1. Use clear, descriptive resource names and URIs 229 | 2. Include helpful descriptions to guide LLM understanding 230 | 3. Set appropriate MIME types when known 231 | 4. Implement resource templates for dynamic content 232 | 5. Use subscriptions for frequently changing resources 233 | 6. Handle errors gracefully with clear error messages 234 | 7. Consider pagination for large resource lists 235 | 8. Cache resource contents when appropriate 236 | 9. Validate URIs before processing 237 | 10. Document your custom URI schemes 238 | 239 | ## Security considerations 240 | 241 | When exposing resources: 242 | 243 | - Validate all resource URIs 244 | - Implement appropriate access controls 245 | - Sanitize file paths to prevent directory traversal 246 | - Be cautious with binary data handling 247 | - Consider rate limiting for resource reads 248 | - Audit resource access 249 | - Encrypt sensitive data in transit 250 | - Validate MIME types 251 | - Implement timeouts for long-running reads 252 | - Handle resource cleanup appropriately 253 | -------------------------------------------------------------------------------- /images/java/class-diagrams.puml: -------------------------------------------------------------------------------- 1 | @startuml Core Components 2 | 3 | ' Core Interfaces 4 | interface McpTransport { 5 | +Mono connect(Function, Mono> handler) 6 | +Mono sendMessage(JSONRPCMessage message) 7 | +void close() 8 | +Mono closeGracefully() 9 | + T unmarshalFrom(Object data, TypeReference typeRef) 10 | } 11 | 12 | interface McpSession { 13 | + Mono sendRequest(String method, Object requestParams, TypeReference typeRef) 14 | +Mono sendNotification(String method, Map params) 15 | +Mono closeGracefully() 16 | +void close() 17 | } 18 | 19 | ' Core Implementation Classes 20 | class DefaultMcpSession { 21 | +interface RequestHandler 22 | +interface NotificationHandler 23 | } 24 | 25 | ' Client Classes 26 | class McpClient { 27 | +{static} Builder using(ClientMcpTransport transport) 28 | } 29 | 30 | class McpAsyncClient { 31 | +Mono initialize() 32 | +ServerCapabilities getServerCapabilities() 33 | +Implementation getServerInfo() 34 | +ClientCapabilities getClientCapabilities() 35 | +Implementation getClientInfo() 36 | +void close() 37 | +Mono closeGracefully() 38 | +Mono ping() 39 | +Mono addRoot(Root root) 40 | +Mono removeRoot(String rootUri) 41 | +Mono rootsListChangedNotification() 42 | +Mono callTool(CallToolRequest request) 43 | +Mono listTools() 44 | +Mono listResources() 45 | +Mono readResource(ReadResourceRequest request) 46 | +Mono listResourceTemplates() 47 | +Mono subscribeResource(SubscribeRequest request) 48 | +Mono unsubscribeResource(UnsubscribeRequest request) 49 | +Mono listPrompts() 50 | +Mono getPrompt(GetPromptRequest request) 51 | +Mono setLoggingLevel(LoggingLevel level) 52 | } 53 | 54 | class McpSyncClient { 55 | +InitializeResult initialize() 56 | +ServerCapabilities getServerCapabilities() 57 | +Implementation getServerInfo() 58 | +ClientCapabilities getClientCapabilities() 59 | +Implementation getClientInfo() 60 | +void close() 61 | +boolean closeGracefully() 62 | +Object ping() 63 | +void addRoot(Root root) 64 | +void removeRoot(String rootUri) 65 | +void rootsListChangedNotification() 66 | +CallToolResult callTool(CallToolRequest request) 67 | +ListToolsResult listTools() 68 | +ListResourcesResult listResources() 69 | +ReadResourceResult readResource(ReadResourceRequest request) 70 | +ListResourceTemplatesResult listResourceTemplates() 71 | +void subscribeResource(SubscribeRequest request) 72 | +void unsubscribeResource(UnsubscribeRequest request) 73 | +ListPromptsResult listPrompts() 74 | +GetPromptResult getPrompt(GetPromptRequest request) 75 | +void setLoggingLevel(LoggingLevel level) 76 | } 77 | 78 | ' Server Classes 79 | class McpServer { 80 | +{static} Builder using(ServerMcpTransport transport) 81 | } 82 | 83 | class McpAsyncServer { 84 | 85 | +ServerCapabilities getServerCapabilities() 86 | +Implementation getServerInfo() 87 | +ClientCapabilities getClientCapabilities() 88 | +Implementation getClientInfo() 89 | +void close() 90 | +Mono closeGracefully() 91 | 92 | ' Tool Management 93 | +Mono addTool(ToolRegistration toolRegistration) 94 | +Mono removeTool(String toolName) 95 | +Mono notifyToolsListChanged() 96 | 97 | ' Resource Management 98 | +Mono addResource(ResourceRegistration resourceHandler) 99 | +Mono removeResource(String resourceUri) 100 | +Mono notifyResourcesListChanged() 101 | 102 | ' Prompt Management 103 | +Mono addPrompt(PromptRegistration promptRegistration) 104 | +Mono removePrompt(String promptName) 105 | +Mono notifyPromptsListChanged() 106 | 107 | ' Logging 108 | +Mono loggingNotification(LoggingMessageNotification notification) 109 | 110 | ' Sampling 111 | +Mono createMessage(CreateMessageRequest request) 112 | } 113 | 114 | class McpSyncServer { 115 | +McpAsyncServer getAsyncServer() 116 | 117 | +ServerCapabilities getServerCapabilities() 118 | +Implementation getServerInfo() 119 | +ClientCapabilities getClientCapabilities() 120 | +Implementation getClientInfo() 121 | +void close() 122 | +void closeGracefully() 123 | 124 | ' Tool Management 125 | +void addTool(ToolRegistration toolHandler) 126 | +void removeTool(String toolName) 127 | +void notifyToolsListChanged() 128 | 129 | ' Resource Management 130 | +void addResource(ResourceRegistration resourceHandler) 131 | +void removeResource(String resourceUri) 132 | +void notifyResourcesListChanged() 133 | 134 | ' Prompt Management 135 | +void addPrompt(PromptRegistration promptRegistration) 136 | +void removePrompt(String promptName) 137 | +void notifyPromptsListChanged() 138 | 139 | ' Logging 140 | +void loggingNotification(LoggingMessageNotification notification) 141 | 142 | ' Sampling 143 | +CreateMessageResult createMessage(CreateMessageRequest request) 144 | } 145 | 146 | ' Transport Implementations 147 | class StdioClientTransport implements ClientMcpTransport { 148 | +void setErrorHandler(Consumer errorHandler) 149 | +Sinks.Many getErrorSink() 150 | } 151 | 152 | class StdioServerTransport implements ServerMcpTransport { 153 | } 154 | 155 | 156 | class HttpServletSseServerTransport implements ServerMcpTransport { 157 | } 158 | 159 | 160 | class HttpClientSseClientTransport implements ClientMcpTransport { 161 | } 162 | 163 | 164 | class WebFluxSseClientTransport implements ClientMcpTransport { 165 | } 166 | 167 | 168 | class WebFluxSseServerTransport implements ServerMcpTransport { 169 | +RouterFunction getRouterFunction() 170 | } 171 | 172 | class WebMvcSseServerTransport implements ServerMcpTransport { 173 | +RouterFunction getRouterFunction() 174 | } 175 | 176 | 177 | ' Schema and Error Classes 178 | class McpSchema { 179 | +class ErrorCodes 180 | +interface Request 181 | +interface JSONRPCMessage 182 | +interface ResourceContents 183 | +interface Content 184 | +interface ServerCapabilities 185 | +{static} JSONRPCMessage deserializeJsonRpcMessage() 186 | } 187 | 188 | class McpError { 189 | } 190 | 191 | ' Relationships 192 | McpTransport <|.. ClientMcpTransport 193 | McpTransport <|.. ServerMcpTransport 194 | 195 | McpSession <|.. DefaultMcpSession 196 | DefaultMcpSession --o McpAsyncClient 197 | DefaultMcpSession --o McpAsyncServer 198 | 199 | McpClient ..> McpAsyncClient : creates 200 | McpClient ..> McpSyncClient : creates 201 | McpSyncClient --> McpAsyncClient : delegates to 202 | 203 | McpServer ..> McpAsyncServer : creates 204 | McpServer ..> McpSyncServer : creates 205 | McpSyncServer o-- McpAsyncServer 206 | 207 | DefaultMcpSession o-- McpTransport 208 | McpSchema <.. McpSession : uses 209 | McpError ..> McpSession : throws 210 | 211 | @enduml 212 | 213 | @startuml Message Flow 214 | 215 | package "MCP Schema" { 216 | interface JSONRPCMessage { 217 | +String jsonrpc() 218 | } 219 | 220 | interface Request { 221 | } 222 | 223 | class InitializeRequest 224 | class CallToolRequest 225 | class ListToolsRequest 226 | class ListResourcesRequest 227 | class ReadResourceRequest 228 | class ListResourceTemplatesRequest 229 | class ListPromptsRequest 230 | class GetPromptRequest 231 | } 232 | 233 | package "Resource Types" { 234 | interface ResourceContents { 235 | +String uri() 236 | +String mimeType() 237 | } 238 | 239 | class TextResourceContents 240 | class BlobResourceContents 241 | 242 | interface Content { 243 | +String type() 244 | } 245 | 246 | class TextContent 247 | class ImageContent 248 | class EmbeddedResource 249 | 250 | interface Annotated { 251 | +Annotations annotations() 252 | } 253 | 254 | interface PromptOrResourceReference { 255 | +String type() 256 | } 257 | 258 | class PromptReference 259 | class ResourceReference 260 | } 261 | 262 | JSONRPCMessage <|.. Request 263 | Request <|.. InitializeRequest 264 | Request <|.. CallToolRequest 265 | Request <|.. ListToolsRequest 266 | Request <|.. ListResourcesRequest 267 | Request <|.. ReadResourceRequest 268 | Request <|.. ListResourceTemplatesRequest 269 | Request <|.. ListPromptsRequest 270 | Request <|.. GetPromptRequest 271 | 272 | ResourceContents <|.. TextResourceContents 273 | ResourceContents <|.. BlobResourceContents 274 | 275 | Content <|.. TextContent 276 | Content <|.. ImageContent 277 | Content <|.. EmbeddedResource 278 | 279 | PromptOrResourceReference <|.. PromptReference 280 | PromptOrResourceReference <|.. ResourceReference 281 | 282 | @enduml 283 | -------------------------------------------------------------------------------- /sdk/java/mcp-overview.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: Overview 3 | description: Introduction to the Model Context Protocol (MCP) Java SDK 4 | --- 5 | 6 | Java SDK for the [Model Context Protocol](https://modelcontextprotocol.org/docs/concepts/architecture) 7 | enables standardized integration between AI models and tools. 8 | 9 | 10 | ### Breaking Changes in 0.8.x ⚠️ 11 | **Note:** Version 0.8.x introduces several breaking changes including a new session-based architecture. 12 | If you're upgrading from 0.7.0, please refer to the [Migration Guide](https://github.com/modelcontextprotocol/java-sdk/blob/main/migration-0.8.0.md) for detailed instructions. 13 | 14 | 15 | ## Features 16 | 17 | - MCP Client and MCP Server implementations supporting: 18 | - Protocol [version compatibility negotiation](https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization) 19 | - [Tool](https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/) discovery, execution, list change notifications 20 | - [Resource](https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/) management with URI templates 21 | - [Roots](https://spec.modelcontextprotocol.io/specification/2024-11-05/client/roots/) list management and notifications 22 | - [Prompt](https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/) handling and management 23 | - [Sampling](https://spec.modelcontextprotocol.io/specification/2024-11-05/client/sampling/) support for AI model interactions 24 | - Multiple transport implementations: 25 | - Default transports (included in core `mcp` module, no external web frameworks required): 26 | - Stdio-based transport for process-based communication 27 | - Java HttpClient-based SSE client transport for HTTP SSE Client-side streaming 28 | - Servlet-based SSE server transport for HTTP SSE Server streaming 29 | - Optional Spring-based transports (convenience if using Spring Framework): 30 | - WebFlux SSE client and server transports for reactive HTTP streaming 31 | - WebMVC SSE transport for servlet-based HTTP streaming 32 | - Supports Synchronous and Asynchronous programming paradigms 33 | 34 | 35 | The core `io.modelcontextprotocol.sdk:mcp` module provides default STDIO and SSE client and server transport implementations without requiring external web frameworks. 36 | 37 | Spring-specific transports are available as optional dependencies for convenience when using the [Spring Framework](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-client-boot-starter-docs.html). 38 | 39 | 40 | ## Architecture 41 | 42 | The SDK follows a layered architecture with clear separation of concerns: 43 | 44 | ![MCP Stack Architecture](/images/java/mcp-stack.svg) 45 | 46 | - **Client/Server Layer (McpClient/McpServer)**: Both use McpSession for sync/async operations, 47 | with McpClient handling client-side protocol operations and McpServer managing server-side protocol operations. 48 | - **Session Layer (McpSession)**: Manages communication patterns and state using DefaultMcpSession implementation. 49 | - **Transport Layer (McpTransport)**: Handles JSON-RPC message serialization/deserialization via: 50 | - StdioTransport (stdin/stdout) in the core module 51 | - HTTP SSE transports in dedicated transport modules (Java HttpClient, Spring WebFlux, Spring WebMVC) 52 | 53 | 54 | The MCP Client is a key component in the Model Context Protocol (MCP) architecture, responsible for establishing and managing connections with MCP servers. 55 | It implements the client-side of the protocol. 56 | 57 | ![Java MCP Client Architecture](/images/java/java-mcp-client-architecture.jpg) 58 | 59 | The MCP Server is a foundational component in the Model Context Protocol (MCP) architecture that provides tools, resources, and capabilities to clients. 60 | It implements the server-side of the protocol. 61 | 62 | ![Java MCP Server Architecture](/images/java/java-mcp-server-architecture.jpg) 63 | 64 | Key Interactions: 65 | 66 | - **Client/Server Initialization**: Transport setup, protocol compatibility check, capability negotiation, and implementation details exchange. 67 | - **Message Flow**: JSON-RPC message handling with validation, type-safe response processing, and error handling. 68 | - **Resource Management**: Resource discovery, URI template-based access, subscription system, and content retrieval. 69 | 70 | ## Dependencies 71 | 72 | Add the following Maven dependency to your project: 73 | 74 | 75 | 76 | The core MCP functionality: 77 | 78 | ```xml 79 | 80 | io.modelcontextprotocol.sdk 81 | mcp 82 | 83 | ``` 84 | 85 | The core `mcp` module already includes default STDIO and SSE transport implementations and doesn't require external web frameworks. 86 | 87 | If you're using the Spring Framework and want to use Spring-specific transport implementations, add one of the following optional dependencies: 88 | 89 | ```xml 90 | 91 | 92 | io.modelcontextprotocol.sdk 93 | mcp-spring-webflux 94 | 95 | 96 | 97 | 98 | io.modelcontextprotocol.sdk 99 | mcp-spring-webmvc 100 | 101 | ``` 102 | 103 | 104 | The core MCP functionality: 105 | 106 | ```groovy 107 | dependencies { 108 | implementation platform("io.modelcontextprotocol.sdk:mcp") 109 | //... 110 | } 111 | ``` 112 | 113 | The core `mcp` module already includes default STDIO and SSE transport implementations and doesn't require external web frameworks. 114 | 115 | If you're using the Spring Framework and want to use Spring-specific transport implementations, add one of the following optional dependencies: 116 | 117 | ```groovy 118 | // Optional: Spring WebFlux-based SSE client and server transport 119 | dependencies { 120 | implementation platform("io.modelcontextprotocol.sdk:mcp-spring-webflux") 121 | } 122 | 123 | // Optional: Spring WebMVC-based SSE server transport 124 | dependencies { 125 | implementation platform("io.modelcontextprotocol.sdk:mcp-spring-webmvc") 126 | } 127 | ``` 128 | 129 | 130 | 131 | ### Bill of Materials (BOM) 132 | 133 | The Bill of Materials (BOM) declares the recommended versions of all the dependencies used by a given release. 134 | Using the BOM from your application's build script avoids the need for you to specify and maintain the dependency versions yourself. 135 | Instead, the version of the BOM you're using determines the utilized dependency versions. 136 | It also ensures that you're using supported and tested versions of the dependencies by default, unless you choose to override them. 137 | 138 | Add the BOM to your project: 139 | 140 | 141 | 142 | ```xml 143 | 144 | 145 | 146 | io.modelcontextprotocol.sdk 147 | mcp-bom 148 | 0.8.1 149 | pom 150 | import 151 | 152 | 153 | 154 | ``` 155 | 156 | 157 | 158 | ```groovy 159 | dependencies { 160 | implementation platform("io.modelcontextprotocol.sdk:mcp-bom:0.8.1") 161 | //... 162 | } 163 | ``` 164 | 165 | Gradle users can also use the Spring AI MCP BOM by leveraging Gradle (5.0+) native support for declaring dependency constraints using a Maven BOM. 166 | This is implemented by adding a 'platform' dependency handler method to the dependencies section of your Gradle build script. 167 | As shown in the snippet above this can then be followed by version-less declarations of the Starter Dependencies for the one or more spring-ai modules you wish to use, e.g. spring-ai-openai. 168 | 169 | 170 | 171 | Replace the version number with the version of the BOM you want to use. 172 | 173 | ### Available Dependencies 174 | 175 | The following dependencies are available and managed by the BOM: 176 | 177 | - Core Dependencies 178 | - `io.modelcontextprotocol.sdk:mcp` - Core MCP library providing the base functionality and APIs for Model Context Protocol implementation, including default STDIO and SSE client and server transport implementations. No external web frameworks required. 179 | - Optional Transport Dependencies (convenience if using Spring Framework) 180 | - `io.modelcontextprotocol.sdk:mcp-spring-webflux` - WebFlux-based Server-Sent Events (SSE) transport implementation for reactive applications. 181 | - `io.modelcontextprotocol.sdk:mcp-spring-webmvc` - WebMVC-based Server-Sent Events (SSE) transport implementation for servlet-based applications. 182 | - Testing Dependencies 183 | - `io.modelcontextprotocol.sdk:mcp-test` - Testing utilities and support for MCP-based applications. 184 | -------------------------------------------------------------------------------- /quickstart/user.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "For Claude Desktop Users" 3 | description: "Get started using pre-built servers in Claude for Desktop." 4 | --- 5 | 6 | In this tutorial, you will extend [Claude for Desktop](https://claude.ai/download) so that it can read from your computer's file system, write new files, move files, and even search files. 7 | 8 | 9 | 10 | 11 | 12 | Don't worry — it will ask you for your permission before executing these actions! 13 | 14 | ## 1. Download Claude for Desktop 15 | 16 | Start by downloading [Claude for Desktop](https://claude.ai/download), choosing either macOS or Windows. (Linux is not yet supported for Claude for Desktop.) 17 | 18 | Follow the installation instructions. 19 | 20 | If you already have Claude for Desktop, make sure it's on the latest version by clicking on the Claude menu on your computer and selecting "Check for Updates..." 21 | 22 | 23 | Because servers are locally run, MCP currently only supports desktop hosts. Remote hosts are in active development. 24 | 25 | 26 | ## 2. Add the Filesystem MCP Server 27 | 28 | To add this filesystem functionality, we will be installing a pre-built [Filesystem MCP Server](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem) to Claude for Desktop. This is one of dozens of [servers](https://github.com/modelcontextprotocol/servers/tree/main) created by Anthropic and the community. 29 | 30 | Get started by opening up the Claude menu on your computer and select "Settings..." Please note that these are not the Claude Account Settings found in the app window itself. 31 | 32 | This is what it should look like on a Mac: 33 | 34 | 35 | 36 | 37 | Click on "Developer" in the left-hand bar of the Settings pane, and then click on "Edit Config": 38 | 39 | 40 | 41 | 42 | This will create a configuration file at: 43 | - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json` 44 | - Windows: `%APPDATA%\Claude\claude_desktop_config.json` 45 | 46 | if you don't already have one, and will display the file in your file system. 47 | 48 | Open up the configuration file in any text editor. Replace the file contents with this: 49 | 50 | 51 | ```json 52 | { 53 | "mcpServers": { 54 | "filesystem": { 55 | "command": "npx", 56 | "args": [ 57 | "-y", 58 | "@modelcontextprotocol/server-filesystem", 59 | "/Users/username/Desktop", 60 | "/Users/username/Downloads" 61 | ] 62 | } 63 | } 64 | } 65 | ``` 66 | 67 | 68 | ```json 69 | { 70 | "mcpServers": { 71 | "filesystem": { 72 | "command": "npx", 73 | "args": [ 74 | "-y", 75 | "@modelcontextprotocol/server-filesystem", 76 | "C:\\Users\\username\\Desktop", 77 | "C:\\Users\\username\\Downloads" 78 | ] 79 | } 80 | } 81 | } 82 | ``` 83 | 84 | 85 | 86 | Make sure to replace `username` with your computer's username. The paths should point to valid directories that you want Claude to be able to access and modify. It's set up to work for Desktop and Downloads, but you can add more paths as well. 87 | 88 | You will also need [Node.js](https://nodejs.org) on your computer for this to run properly. To verify you have Node installed, open the command line on your computer. 89 | - On macOS, open the Terminal from your Applications folder 90 | - On Windows, press Windows + R, type "cmd", and press Enter 91 | 92 | Once in the command line, verify you have Node installed by entering in the following command: 93 | ```bash 94 | node --version 95 | ``` 96 | If you get an error saying "command not found" or "node is not recognized", download Node from [nodejs.org](https://nodejs.org/). 97 | 98 | 99 | **How does the configuration file work?** 100 | 101 | This configuration file tells Claude for Desktop which MCP servers to start up every time you start the application. In this case, we have added one server called "filesystem" that will use the Node `npx` command to install and run `@modelcontextprotocol/server-filesystem`. This server, described [here](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem), will let you access your file system in Claude for Desktop. 102 | 103 | 104 | 105 | **Command Privileges** 106 | 107 | Claude for Desktop will run the commands in the configuration file with the permissions of your user account, and access to your local files. Only add commands if you understand and trust the source. 108 | 109 | 110 | ## 3. Restart Claude 111 | 112 | After updating your configuration file, you need to restart Claude for Desktop. 113 | 114 | Upon restarting, you should see a hammer icon in the bottom right corner of the input box: 115 | 116 | 117 | 118 | 119 | 120 | After clicking on the hammer icon, you should see the tools that come with the Filesystem MCP Server: 121 | 122 | 123 | 124 | 125 | 126 | If your server isn't being picked up by Claude for Desktop, proceed to the [Troubleshooting](#troubleshooting) section for debugging tips. 127 | 128 | ## 4. Try it out! 129 | 130 | You can now talk to Claude and ask it about your filesystem. It should know when to call the relevant tools. 131 | 132 | Things you might try asking Claude: 133 | - Can you write a poem and save it to my desktop? 134 | - What are some work-related files in my downloads folder? 135 | - Can you take all the images on my desktop and move them to a new folder called "Images"? 136 | 137 | As needed, Claude will call the relevant tools and seek your approval before taking an action: 138 | 139 | 140 | 141 | 142 | ## Troubleshooting 143 | 144 | 145 | 146 | 1. Restart Claude for Desktop completely 147 | 2. Check your `claude_desktop_config.json` file syntax 148 | 3. Make sure the file paths included in `claude_desktop_config.json` are valid and that they are absolute and not relative 149 | 4. Look at [logs](#getting-logs-from-claude-for-desktop) to see why the server is not connecting 150 | 5. In your command line, try manually running the server (replacing `username` as you did in `claude_desktop_config.json`) to see if you get any errors: 151 | 152 | 153 | ```bash 154 | npx -y @modelcontextprotocol/server-filesystem /Users/username/Desktop /Users/username/Downloads 155 | ``` 156 | 157 | 158 | ```bash 159 | npx -y @modelcontextprotocol/server-filesystem C:\Users\username\Desktop C:\Users\username\Downloads 160 | ``` 161 | 162 | 163 | 164 | 165 | Claude.app logging related to MCP is written to log files in: 166 | - macOS: `~/Library/Logs/Claude` 167 | - Windows: `%APPDATA%\Claude\logs` 168 | 169 | - `mcp.log` will contain general logging about MCP connections and connection failures. 170 | - Files named `mcp-server-SERVERNAME.log` will contain error (stderr) logging from the named server. 171 | 172 | You can run the following command to list recent logs and follow along with any new ones (on Windows, it will only show recent logs): 173 | 174 | 175 | ```bash 176 | # Check Claude's logs for errors 177 | tail -n 20 -f ~/Library/Logs/Claude/mcp*.log 178 | ``` 179 | 180 | 181 | ```bash 182 | type "%APPDATA%\Claude\logs\mcp*.log" 183 | ``` 184 | 185 | 186 | 187 | 188 | If Claude attempts to use the tools but they fail: 189 | 190 | 1. Check Claude's logs for errors 191 | 2. Verify your server builds and runs without errors 192 | 3. Try restarting Claude for Desktop 193 | 194 | 195 | Please refer to our [debugging guide](/docs/tools/debugging) for better debugging tools and more detailed guidance. 196 | 197 | 198 | If your configured server fails to load, and you see within its logs an error referring to `${APPDATA}` within a path, you may need to add the expanded value of `%APPDATA%` to your `env` key in `claude_desktop_config.json`: 199 | 200 | ```json 201 | { 202 | "brave-search": { 203 | "command": "npx", 204 | "args": ["-y", "@modelcontextprotocol/server-brave-search"], 205 | "env": { 206 | "APPDATA": "C:\\Users\\user\\AppData\\Roaming\\", 207 | "BRAVE_API_KEY": "..." 208 | } 209 | } 210 | } 211 | ``` 212 | 213 | With this change in place, launch Claude Desktop once again. 214 | 215 | 216 | **NPM should be installed globally** 217 | 218 | The `npx` command may continue to fail if you have not installed NPM globally. If NPM is already installed globally, you will find `%APPDATA%\npm` exists on your system. If not, you can install NPM globally by running the following command: 219 | 220 | ```bash 221 | npm install -g npm 222 | ``` 223 | 224 | 225 | 226 | 227 | 228 | ## Next steps 229 | 230 | 235 | Check out our gallery of official MCP servers and implementations 236 | 237 | 242 | Now build your own custom server to use in Claude for Desktop and other clients 243 | 244 | 245 | -------------------------------------------------------------------------------- /docs/concepts/tools.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Tools" 3 | description: "Enable LLMs to perform actions through your server" 4 | --- 5 | 6 | Tools are a powerful primitive in the Model Context Protocol (MCP) that enable servers to expose executable functionality to clients. Through tools, LLMs can interact with external systems, perform computations, and take actions in the real world. 7 | 8 | 9 | Tools are designed to be **model-controlled**, meaning that tools are exposed from servers to clients with the intention of the AI model being able to automatically invoke them (with a human in the loop to grant approval). 10 | 11 | 12 | ## Overview 13 | 14 | Tools in MCP allow servers to expose executable functions that can be invoked by clients and used by LLMs to perform actions. Key aspects of tools include: 15 | 16 | - **Discovery**: Clients can list available tools through the `tools/list` endpoint 17 | - **Invocation**: Tools are called using the `tools/call` endpoint, where servers perform the requested operation and return results 18 | - **Flexibility**: Tools can range from simple calculations to complex API interactions 19 | 20 | Like [resources](/docs/concepts/resources), tools are identified by unique names and can include descriptions to guide their usage. However, unlike resources, tools represent dynamic operations that can modify state or interact with external systems. 21 | 22 | ## Tool definition structure 23 | 24 | Each tool is defined with the following structure: 25 | 26 | ```typescript 27 | { 28 | name: string; // Unique identifier for the tool 29 | description?: string; // Human-readable description 30 | inputSchema: { // JSON Schema for the tool's parameters 31 | type: "object", 32 | properties: { ... } // Tool-specific parameters 33 | } 34 | } 35 | ``` 36 | 37 | ## Implementing tools 38 | 39 | Here's an example of implementing a basic tool in an MCP server: 40 | 41 | 42 | 43 | ```typescript 44 | const server = new Server({ 45 | name: "example-server", 46 | version: "1.0.0" 47 | }, { 48 | capabilities: { 49 | tools: {} 50 | } 51 | }); 52 | 53 | // Define available tools 54 | server.setRequestHandler(ListToolsRequestSchema, async () => { 55 | return { 56 | tools: [{ 57 | name: "calculate_sum", 58 | description: "Add two numbers together", 59 | inputSchema: { 60 | type: "object", 61 | properties: { 62 | a: { type: "number" }, 63 | b: { type: "number" } 64 | }, 65 | required: ["a", "b"] 66 | } 67 | }] 68 | }; 69 | }); 70 | 71 | // Handle tool execution 72 | server.setRequestHandler(CallToolRequestSchema, async (request) => { 73 | if (request.params.name === "calculate_sum") { 74 | const { a, b } = request.params.arguments; 75 | return { 76 | content: [ 77 | { 78 | type: "text", 79 | text: String(a + b) 80 | } 81 | ] 82 | }; 83 | } 84 | throw new Error("Tool not found"); 85 | }); 86 | ``` 87 | 88 | 89 | ```python 90 | app = Server("example-server") 91 | 92 | @app.list_tools() 93 | async def list_tools() -> list[types.Tool]: 94 | return [ 95 | types.Tool( 96 | name="calculate_sum", 97 | description="Add two numbers together", 98 | inputSchema={ 99 | "type": "object", 100 | "properties": { 101 | "a": {"type": "number"}, 102 | "b": {"type": "number"} 103 | }, 104 | "required": ["a", "b"] 105 | } 106 | ) 107 | ] 108 | 109 | @app.call_tool() 110 | async def call_tool( 111 | name: str, 112 | arguments: dict 113 | ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]: 114 | if name == "calculate_sum": 115 | a = arguments["a"] 116 | b = arguments["b"] 117 | result = a + b 118 | return [types.TextContent(type="text", text=str(result))] 119 | raise ValueError(f"Tool not found: {name}") 120 | ``` 121 | 122 | 123 | 124 | ## Example tool patterns 125 | 126 | Here are some examples of types of tools that a server could provide: 127 | 128 | ### System operations 129 | 130 | Tools that interact with the local system: 131 | 132 | ```typescript 133 | { 134 | name: "execute_command", 135 | description: "Run a shell command", 136 | inputSchema: { 137 | type: "object", 138 | properties: { 139 | command: { type: "string" }, 140 | args: { type: "array", items: { type: "string" } } 141 | } 142 | } 143 | } 144 | ``` 145 | 146 | ### API integrations 147 | 148 | Tools that wrap external APIs: 149 | 150 | ```typescript 151 | { 152 | name: "github_create_issue", 153 | description: "Create a GitHub issue", 154 | inputSchema: { 155 | type: "object", 156 | properties: { 157 | title: { type: "string" }, 158 | body: { type: "string" }, 159 | labels: { type: "array", items: { type: "string" } } 160 | } 161 | } 162 | } 163 | ``` 164 | 165 | ### Data processing 166 | 167 | Tools that transform or analyze data: 168 | 169 | ```typescript 170 | { 171 | name: "analyze_csv", 172 | description: "Analyze a CSV file", 173 | inputSchema: { 174 | type: "object", 175 | properties: { 176 | filepath: { type: "string" }, 177 | operations: { 178 | type: "array", 179 | items: { 180 | enum: ["sum", "average", "count"] 181 | } 182 | } 183 | } 184 | } 185 | } 186 | ``` 187 | 188 | ## Best practices 189 | 190 | When implementing tools: 191 | 192 | 1. Provide clear, descriptive names and descriptions 193 | 2. Use detailed JSON Schema definitions for parameters 194 | 3. Include examples in tool descriptions to demonstrate how the model should use them 195 | 4. Implement proper error handling and validation 196 | 5. Use progress reporting for long operations 197 | 6. Keep tool operations focused and atomic 198 | 7. Document expected return value structures 199 | 8. Implement proper timeouts 200 | 9. Consider rate limiting for resource-intensive operations 201 | 10. Log tool usage for debugging and monitoring 202 | 203 | ## Security considerations 204 | 205 | When exposing tools: 206 | 207 | ### Input validation 208 | 209 | - Validate all parameters against the schema 210 | - Sanitize file paths and system commands 211 | - Validate URLs and external identifiers 212 | - Check parameter sizes and ranges 213 | - Prevent command injection 214 | 215 | ### Access control 216 | 217 | - Implement authentication where needed 218 | - Use appropriate authorization checks 219 | - Audit tool usage 220 | - Rate limit requests 221 | - Monitor for abuse 222 | 223 | ### Error handling 224 | 225 | - Don't expose internal errors to clients 226 | - Log security-relevant errors 227 | - Handle timeouts appropriately 228 | - Clean up resources after errors 229 | - Validate return values 230 | 231 | ## Tool discovery and updates 232 | 233 | MCP supports dynamic tool discovery: 234 | 235 | 1. Clients can list available tools at any time 236 | 2. Servers can notify clients when tools change using `notifications/tools/list_changed` 237 | 3. Tools can be added or removed during runtime 238 | 4. Tool definitions can be updated (though this should be done carefully) 239 | 240 | ## Error handling 241 | 242 | Tool errors should be reported within the result object, not as MCP protocol-level errors. This allows the LLM to see and potentially handle the error. When a tool encounters an error: 243 | 244 | 1. Set `isError` to `true` in the result 245 | 2. Include error details in the `content` array 246 | 247 | Here's an example of proper error handling for tools: 248 | 249 | 250 | 251 | ```typescript 252 | try { 253 | // Tool operation 254 | const result = performOperation(); 255 | return { 256 | content: [ 257 | { 258 | type: "text", 259 | text: `Operation successful: ${result}` 260 | } 261 | ] 262 | }; 263 | } catch (error) { 264 | return { 265 | isError: true, 266 | content: [ 267 | { 268 | type: "text", 269 | text: `Error: ${error.message}` 270 | } 271 | ] 272 | }; 273 | } 274 | ``` 275 | 276 | 277 | ```python 278 | try: 279 | # Tool operation 280 | result = perform_operation() 281 | return types.CallToolResult( 282 | content=[ 283 | types.TextContent( 284 | type="text", 285 | text=f"Operation successful: {result}" 286 | ) 287 | ] 288 | ) 289 | except Exception as error: 290 | return types.CallToolResult( 291 | isError=True, 292 | content=[ 293 | types.TextContent( 294 | type="text", 295 | text=f"Error: {str(error)}" 296 | ) 297 | ] 298 | ) 299 | ``` 300 | 301 | 302 | 303 | This approach allows the LLM to see that an error occurred and potentially take corrective action or request human intervention. 304 | 305 | ## Testing tools 306 | 307 | A comprehensive testing strategy for MCP tools should cover: 308 | 309 | - **Functional testing**: Verify tools execute correctly with valid inputs and handle invalid inputs appropriately 310 | - **Integration testing**: Test tool interaction with external systems using both real and mocked dependencies 311 | - **Security testing**: Validate authentication, authorization, input sanitization, and rate limiting 312 | - **Performance testing**: Check behavior under load, timeout handling, and resource cleanup 313 | - **Error handling**: Ensure tools properly report errors through the MCP protocol and clean up resources 314 | -------------------------------------------------------------------------------- /docs/concepts/architecture.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Core architecture" 3 | description: "Understand how MCP connects clients, servers, and LLMs" 4 | --- 5 | 6 | The Model Context Protocol (MCP) is built on a flexible, extensible architecture that enables seamless communication between LLM applications and integrations. This document covers the core architectural components and concepts. 7 | 8 | ## Overview 9 | 10 | MCP follows a client-server architecture where: 11 | 12 | - **Hosts** are LLM applications (like Claude Desktop or IDEs) that initiate connections 13 | - **Clients** maintain 1:1 connections with servers, inside the host application 14 | - **Servers** provide context, tools, and prompts to clients 15 | 16 | ```mermaid 17 | flowchart LR 18 | subgraph "Host" 19 | client1[MCP Client] 20 | client2[MCP Client] 21 | end 22 | subgraph "Server Process" 23 | server1[MCP Server] 24 | end 25 | subgraph "Server Process" 26 | server2[MCP Server] 27 | end 28 | 29 | client1 <-->|Transport Layer| server1 30 | client2 <-->|Transport Layer| server2 31 | ``` 32 | 33 | ## Core components 34 | 35 | ### Protocol layer 36 | 37 | The protocol layer handles message framing, request/response linking, and high-level communication patterns. 38 | 39 | 40 | 41 | ```typescript 42 | class Protocol { 43 | // Handle incoming requests 44 | setRequestHandler(schema: T, handler: (request: T, extra: RequestHandlerExtra) => Promise): void 45 | 46 | // Handle incoming notifications 47 | setNotificationHandler(schema: T, handler: (notification: T) => Promise): void 48 | 49 | // Send requests and await responses 50 | request(request: Request, schema: T, options?: RequestOptions): Promise 51 | 52 | // Send one-way notifications 53 | notification(notification: Notification): Promise 54 | } 55 | ``` 56 | 57 | 58 | ```python 59 | class Session(BaseSession[RequestT, NotificationT, ResultT]): 60 | async def send_request( 61 | self, 62 | request: RequestT, 63 | result_type: type[Result] 64 | ) -> Result: 65 | """ 66 | Send request and wait for response. Raises McpError if response contains error. 67 | """ 68 | # Request handling implementation 69 | 70 | async def send_notification( 71 | self, 72 | notification: NotificationT 73 | ) -> None: 74 | """Send one-way notification that doesn't expect response.""" 75 | # Notification handling implementation 76 | 77 | async def _received_request( 78 | self, 79 | responder: RequestResponder[ReceiveRequestT, ResultT] 80 | ) -> None: 81 | """Handle incoming request from other side.""" 82 | # Request handling implementation 83 | 84 | async def _received_notification( 85 | self, 86 | notification: ReceiveNotificationT 87 | ) -> None: 88 | """Handle incoming notification from other side.""" 89 | # Notification handling implementation 90 | ``` 91 | 92 | 93 | 94 | Key classes include: 95 | 96 | * `Protocol` 97 | * `Client` 98 | * `Server` 99 | 100 | ### Transport layer 101 | 102 | The transport layer handles the actual communication between clients and servers. MCP supports multiple transport mechanisms: 103 | 104 | 1. **Stdio transport** 105 | - Uses standard input/output for communication 106 | - Ideal for local processes 107 | 108 | 2. **HTTP with SSE transport** 109 | - Uses Server-Sent Events for server-to-client messages 110 | - HTTP POST for client-to-server messages 111 | 112 | All transports use [JSON-RPC](https://www.jsonrpc.org/) 2.0 to exchange messages. See the [specification](https://spec.modelcontextprotocol.io) for detailed information about the Model Context Protocol message format. 113 | 114 | ### Message types 115 | 116 | MCP has these main types of messages: 117 | 118 | 1. **Requests** expect a response from the other side: 119 | ```typescript 120 | interface Request { 121 | method: string; 122 | params?: { ... }; 123 | } 124 | ``` 125 | 126 | 2. **Results** are successful responses to requests: 127 | ```typescript 128 | interface Result { 129 | [key: string]: unknown; 130 | } 131 | ``` 132 | 133 | 3. **Errors** indicate that a request failed: 134 | ```typescript 135 | interface Error { 136 | code: number; 137 | message: string; 138 | data?: unknown; 139 | } 140 | ``` 141 | 142 | 4. **Notifications** are one-way messages that don't expect a response: 143 | ```typescript 144 | interface Notification { 145 | method: string; 146 | params?: { ... }; 147 | } 148 | ``` 149 | 150 | ## Connection lifecycle 151 | 152 | ### 1. Initialization 153 | 154 | ```mermaid 155 | sequenceDiagram 156 | participant Client 157 | participant Server 158 | 159 | Client->>Server: initialize request 160 | Server->>Client: initialize response 161 | Client->>Server: initialized notification 162 | 163 | Note over Client,Server: Connection ready for use 164 | ``` 165 | 166 | 1. Client sends `initialize` request with protocol version and capabilities 167 | 2. Server responds with its protocol version and capabilities 168 | 3. Client sends `initialized` notification as acknowledgment 169 | 4. Normal message exchange begins 170 | 171 | ### 2. Message exchange 172 | 173 | After initialization, the following patterns are supported: 174 | 175 | - **Request-Response**: Client or server sends requests, the other responds 176 | - **Notifications**: Either party sends one-way messages 177 | 178 | ### 3. Termination 179 | 180 | Either party can terminate the connection: 181 | - Clean shutdown via `close()` 182 | - Transport disconnection 183 | - Error conditions 184 | 185 | ## Error handling 186 | 187 | MCP defines these standard error codes: 188 | 189 | ```typescript 190 | enum ErrorCode { 191 | // Standard JSON-RPC error codes 192 | ParseError = -32700, 193 | InvalidRequest = -32600, 194 | MethodNotFound = -32601, 195 | InvalidParams = -32602, 196 | InternalError = -32603 197 | } 198 | ``` 199 | 200 | SDKs and applications can define their own error codes above -32000. 201 | 202 | Errors are propagated through: 203 | - Error responses to requests 204 | - Error events on transports 205 | - Protocol-level error handlers 206 | 207 | ## Implementation example 208 | 209 | Here's a basic example of implementing an MCP server: 210 | 211 | 212 | 213 | ```typescript 214 | import { Server } from "@modelcontextprotocol/sdk/server/index.js"; 215 | import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; 216 | 217 | const server = new Server({ 218 | name: "example-server", 219 | version: "1.0.0" 220 | }, { 221 | capabilities: { 222 | resources: {} 223 | } 224 | }); 225 | 226 | // Handle requests 227 | server.setRequestHandler(ListResourcesRequestSchema, async () => { 228 | return { 229 | resources: [ 230 | { 231 | uri: "example://resource", 232 | name: "Example Resource" 233 | } 234 | ] 235 | }; 236 | }); 237 | 238 | // Connect transport 239 | const transport = new StdioServerTransport(); 240 | await server.connect(transport); 241 | ``` 242 | 243 | 244 | ```python 245 | import asyncio 246 | import mcp.types as types 247 | from mcp.server import Server 248 | from mcp.server.stdio import stdio_server 249 | 250 | app = Server("example-server") 251 | 252 | @app.list_resources() 253 | async def list_resources() -> list[types.Resource]: 254 | return [ 255 | types.Resource( 256 | uri="example://resource", 257 | name="Example Resource" 258 | ) 259 | ] 260 | 261 | async def main(): 262 | async with stdio_server() as streams: 263 | await app.run( 264 | streams[0], 265 | streams[1], 266 | app.create_initialization_options() 267 | ) 268 | 269 | if __name__ == "__main__": 270 | asyncio.run(main()) 271 | ``` 272 | 273 | 274 | 275 | ## Best practices 276 | 277 | ### Transport selection 278 | 279 | 1. **Local communication** 280 | - Use stdio transport for local processes 281 | - Efficient for same-machine communication 282 | - Simple process management 283 | 284 | 2. **Remote communication** 285 | - Use SSE for scenarios requiring HTTP compatibility 286 | - Consider security implications including authentication and authorization 287 | 288 | ### Message handling 289 | 290 | 1. **Request processing** 291 | - Validate inputs thoroughly 292 | - Use type-safe schemas 293 | - Handle errors gracefully 294 | - Implement timeouts 295 | 296 | 2. **Progress reporting** 297 | - Use progress tokens for long operations 298 | - Report progress incrementally 299 | - Include total progress when known 300 | 301 | 3. **Error management** 302 | - Use appropriate error codes 303 | - Include helpful error messages 304 | - Clean up resources on errors 305 | 306 | ## Security considerations 307 | 308 | 1. **Transport security** 309 | - Use TLS for remote connections 310 | - Validate connection origins 311 | - Implement authentication when needed 312 | 313 | 2. **Message validation** 314 | - Validate all incoming messages 315 | - Sanitize inputs 316 | - Check message size limits 317 | - Verify JSON-RPC format 318 | 319 | 3. **Resource protection** 320 | - Implement access controls 321 | - Validate resource paths 322 | - Monitor resource usage 323 | - Rate limit requests 324 | 325 | 4. **Error handling** 326 | - Don't leak sensitive information 327 | - Log security-relevant errors 328 | - Implement proper cleanup 329 | - Handle DoS scenarios 330 | 331 | ## Debugging and monitoring 332 | 333 | 1. **Logging** 334 | - Log protocol events 335 | - Track message flow 336 | - Monitor performance 337 | - Record errors 338 | 339 | 2. **Diagnostics** 340 | - Implement health checks 341 | - Monitor connection state 342 | - Track resource usage 343 | - Profile performance 344 | 345 | 3. **Testing** 346 | - Test different transports 347 | - Verify error handling 348 | - Check edge cases 349 | - Load test servers 350 | -------------------------------------------------------------------------------- /images/hero-light.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | -------------------------------------------------------------------------------- /sdk/java/mcp-client.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: MCP Client 3 | description: Learn how to use the Model Context Protocol (MCP) client to interact with MCP servers 4 | --- 5 | 6 | # Model Context Protocol Client 7 | 8 | The MCP Client is a key component in the Model Context Protocol (MCP) architecture, responsible for establishing and managing connections with MCP servers. It implements the client-side of the protocol, handling: 9 | 10 | - Protocol version negotiation to ensure compatibility with servers 11 | - Capability negotiation to determine available features 12 | - Message transport and JSON-RPC communication 13 | - Tool discovery and execution 14 | - Resource access and management 15 | - Prompt system interactions 16 | - Optional features like roots management and sampling support 17 | 18 | 19 | The core `io.modelcontextprotocol.sdk:mcp` module provides STDIO and SSE client transport implementations without requiring external web frameworks. 20 | 21 | Spring-specific transport implementations are available as an **optional** dependency `io.modelcontextprotocol.sdk:mcp-spring-webflux` for [Spring Framework](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-client-boot-starter-docs.html) users. 22 | 23 | 24 | The client provides both synchronous and asynchronous APIs for flexibility in different application contexts. 25 | 26 | 27 | 28 | ```java 29 | // Create a sync client with custom configuration 30 | McpSyncClient client = McpClient.sync(transport) 31 | .requestTimeout(Duration.ofSeconds(10)) 32 | .capabilities(ClientCapabilities.builder() 33 | .roots(true) // Enable roots capability 34 | .sampling() // Enable sampling capability 35 | .build()) 36 | .sampling(request -> new CreateMessageResult(response)) 37 | .build(); 38 | 39 | // Initialize connection 40 | client.initialize(); 41 | 42 | // List available tools 43 | ListToolsResult tools = client.listTools(); 44 | 45 | // Call a tool 46 | CallToolResult result = client.callTool( 47 | new CallToolRequest("calculator", 48 | Map.of("operation", "add", "a", 2, "b", 3)) 49 | ); 50 | 51 | // List and read resources 52 | ListResourcesResult resources = client.listResources(); 53 | ReadResourceResult resource = client.readResource( 54 | new ReadResourceRequest("resource://uri") 55 | ); 56 | 57 | // List and use prompts 58 | ListPromptsResult prompts = client.listPrompts(); 59 | GetPromptResult prompt = client.getPrompt( 60 | new GetPromptRequest("greeting", Map.of("name", "Spring")) 61 | ); 62 | 63 | // Add/remove roots 64 | client.addRoot(new Root("file:///path", "description")); 65 | client.removeRoot("file:///path"); 66 | 67 | // Close client 68 | client.closeGracefully(); 69 | ``` 70 | 71 | 72 | 73 | ```java 74 | // Create an async client with custom configuration 75 | McpAsyncClient client = McpClient.async(transport) 76 | .requestTimeout(Duration.ofSeconds(10)) 77 | .capabilities(ClientCapabilities.builder() 78 | .roots(true) // Enable roots capability 79 | .sampling() // Enable sampling capability 80 | .build()) 81 | .sampling(request -> Mono.just(new CreateMessageResult(response))) 82 | .toolsChangeConsumer(tools -> Mono.fromRunnable(() -> { 83 | logger.info("Tools updated: {}", tools); 84 | })) 85 | .resourcesChangeConsumer(resources -> Mono.fromRunnable(() -> { 86 | logger.info("Resources updated: {}", resources); 87 | })) 88 | .promptsChangeConsumer(prompts -> Mono.fromRunnable(() -> { 89 | logger.info("Prompts updated: {}", prompts); 90 | })) 91 | .build(); 92 | 93 | // Initialize connection and use features 94 | client.initialize() 95 | .flatMap(initResult -> client.listTools()) 96 | .flatMap(tools -> { 97 | return client.callTool(new CallToolRequest( 98 | "calculator", 99 | Map.of("operation", "add", "a", 2, "b", 3) 100 | )); 101 | }) 102 | .flatMap(result -> { 103 | return client.listResources() 104 | .flatMap(resources -> 105 | client.readResource(new ReadResourceRequest("resource://uri")) 106 | ); 107 | }) 108 | .flatMap(resource -> { 109 | return client.listPrompts() 110 | .flatMap(prompts -> 111 | client.getPrompt(new GetPromptRequest( 112 | "greeting", 113 | Map.of("name", "Spring") 114 | )) 115 | ); 116 | }) 117 | .flatMap(prompt -> { 118 | return client.addRoot(new Root("file:///path", "description")) 119 | .then(client.removeRoot("file:///path")); 120 | }) 121 | .doFinally(signalType -> { 122 | client.closeGracefully().subscribe(); 123 | }) 124 | .subscribe(); 125 | ``` 126 | 127 | 128 | 129 | ## Client Transport 130 | 131 | The transport layer handles the communication between MCP clients and servers, providing different implementations for various use cases. The client transport manages message serialization, connection establishment, and protocol-specific communication patterns. 132 | 133 | 134 | 135 | Creates transport for in-process based communication 136 | ```java 137 | ServerParameters params = ServerParameters.builder("npx") 138 | .args("-y", "@modelcontextprotocol/server-everything", "dir") 139 | .build(); 140 | McpTransport transport = new StdioClientTransport(params); 141 | ``` 142 | 143 | 144 | Creates a framework agnostic (pure Java API) SSE client transport. Included in the core mcp module. 145 | ```java 146 | McpTransport transport = new HttpClientSseClientTransport("http://your-mcp-server"); 147 | ``` 148 | 149 | 150 | Creates WebFlux-based SSE client transport. Requires the mcp-webflux-sse-transport dependency. 151 | ```java 152 | WebClient.Builder webClientBuilder = WebClient.builder() 153 | .baseUrl("http://your-mcp-server"); 154 | McpTransport transport = new WebFluxSseClientTransport(webClientBuilder); 155 | ``` 156 | 157 | 158 | 159 | ## Client Capabilities 160 | 161 | The client can be configured with various capabilities: 162 | 163 | ```java 164 | var capabilities = ClientCapabilities.builder() 165 | .roots(true) // Enable filesystem roots support with list changes notifications 166 | .sampling() // Enable LLM sampling support 167 | .build(); 168 | ``` 169 | 170 | ### Roots Support 171 | 172 | Roots define the boundaries of where servers can operate within the filesystem: 173 | 174 | ```java 175 | // Add a root dynamically 176 | client.addRoot(new Root("file:///path", "description")); 177 | 178 | // Remove a root 179 | client.removeRoot("file:///path"); 180 | 181 | // Notify server of roots changes 182 | client.rootsListChangedNotification(); 183 | ``` 184 | 185 | The roots capability allows servers to: 186 | 187 | - Request the list of accessible filesystem roots 188 | - Receive notifications when the roots list changes 189 | - Understand which directories and files they have access to 190 | 191 | ### Sampling Support 192 | 193 | Sampling enables servers to request LLM interactions ("completions" or "generations") through the client: 194 | 195 | ```java 196 | // Configure sampling handler 197 | Function samplingHandler = request -> { 198 | // Sampling implementation that interfaces with LLM 199 | return new CreateMessageResult(response); 200 | }; 201 | 202 | // Create client with sampling support 203 | var client = McpClient.sync(transport) 204 | .capabilities(ClientCapabilities.builder() 205 | .sampling() 206 | .build()) 207 | .sampling(samplingHandler) 208 | .build(); 209 | ``` 210 | 211 | This capability allows: 212 | - Servers to leverage AI capabilities without requiring API keys 213 | - Clients to maintain control over model access and permissions 214 | - Support for both text and image-based interactions 215 | - Optional inclusion of MCP server context in prompts 216 | 217 | ## Using MCP Clients 218 | 219 | ### Tool Execution 220 | 221 | Tools are server-side functions that clients can discover and execute. The MCP client provides methods to list available tools and execute them with specific parameters. Each tool has a unique name and accepts a map of parameters. 222 | 223 | 224 | 225 | ```java 226 | // List available tools and their names 227 | var tools = client.listTools(); 228 | tools.forEach(tool -> System.out.println(tool.getName())); 229 | 230 | // Execute a tool with parameters 231 | var result = client.callTool("calculator", Map.of( 232 | "operation", "add", 233 | "a", 1, 234 | "b", 2 235 | )); 236 | ``` 237 | 238 | 239 | 240 | ```java 241 | // List available tools asynchronously 242 | client.listTools() 243 | .doOnNext(tools -> tools.forEach(tool -> 244 | System.out.println(tool.getName()))) 245 | .subscribe(); 246 | 247 | // Execute a tool asynchronously 248 | client.callTool("calculator", Map.of( 249 | "operation", "add", 250 | "a", 1, 251 | "b", 2 252 | )) 253 | .subscribe(); 254 | ``` 255 | 256 | 257 | 258 | ### Resource Access 259 | 260 | Resources represent server-side data sources that clients can access using URI templates. The MCP client provides methods to discover available resources and retrieve their contents through a standardized interface. 261 | 262 | 263 | 264 | ```java 265 | // List available resources and their names 266 | var resources = client.listResources(); 267 | resources.forEach(resource -> System.out.println(resource.getName())); 268 | 269 | // Retrieve resource content using a URI template 270 | var content = client.getResource("file", Map.of( 271 | "path", "/path/to/file.txt" 272 | )); 273 | ``` 274 | 275 | 276 | 277 | ```java 278 | // List available resources asynchronously 279 | client.listResources() 280 | .doOnNext(resources -> resources.forEach(resource -> 281 | System.out.println(resource.getName()))) 282 | .subscribe(); 283 | 284 | // Retrieve resource content asynchronously 285 | client.getResource("file", Map.of( 286 | "path", "/path/to/file.txt" 287 | )) 288 | .subscribe(); 289 | ``` 290 | 291 | 292 | 293 | ### Prompt System 294 | 295 | The prompt system enables interaction with server-side prompt templates. These templates can be discovered and executed with custom parameters, allowing for dynamic text generation based on predefined patterns. 296 | 297 | 298 | 299 | ```java 300 | // List available prompt templates 301 | var prompts = client.listPrompts(); 302 | prompts.forEach(prompt -> System.out.println(prompt.getName())); 303 | 304 | // Execute a prompt template with parameters 305 | var response = client.executePrompt("echo", Map.of( 306 | "text", "Hello, World!" 307 | )); 308 | ``` 309 | 310 | 311 | 312 | ```java 313 | // List available prompt templates asynchronously 314 | client.listPrompts() 315 | .doOnNext(prompts -> prompts.forEach(prompt -> 316 | System.out.println(prompt.getName()))) 317 | .subscribe(); 318 | 319 | // Execute a prompt template asynchronously 320 | client.executePrompt("echo", Map.of( 321 | "text", "Hello, World!" 322 | )) 323 | .subscribe(); 324 | ``` 325 | 326 | 327 | 328 | -------------------------------------------------------------------------------- /docs/concepts/transports.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Transports" 3 | description: "Learn about MCP's communication mechanisms" 4 | --- 5 | 6 | Transports in the Model Context Protocol (MCP) provide the foundation for communication between clients and servers. A transport handles the underlying mechanics of how messages are sent and received. 7 | 8 | ## Message Format 9 | 10 | MCP uses [JSON-RPC](https://www.jsonrpc.org/) 2.0 as its wire format. The transport layer is responsible for converting MCP protocol messages into JSON-RPC format for transmission and converting received JSON-RPC messages back into MCP protocol messages. 11 | 12 | There are three types of JSON-RPC messages used: 13 | 14 | ### Requests 15 | ```typescript 16 | { 17 | jsonrpc: "2.0", 18 | id: number | string, 19 | method: string, 20 | params?: object 21 | } 22 | ``` 23 | 24 | ### Responses 25 | ```typescript 26 | { 27 | jsonrpc: "2.0", 28 | id: number | string, 29 | result?: object, 30 | error?: { 31 | code: number, 32 | message: string, 33 | data?: unknown 34 | } 35 | } 36 | ``` 37 | 38 | ### Notifications 39 | ```typescript 40 | { 41 | jsonrpc: "2.0", 42 | method: string, 43 | params?: object 44 | } 45 | ``` 46 | 47 | ## Built-in Transport Types 48 | 49 | MCP includes two standard transport implementations: 50 | 51 | ### Standard Input/Output (stdio) 52 | 53 | The stdio transport enables communication through standard input and output streams. This is particularly useful for local integrations and command-line tools. 54 | 55 | Use stdio when: 56 | - Building command-line tools 57 | - Implementing local integrations 58 | - Needing simple process communication 59 | - Working with shell scripts 60 | 61 | 62 | 63 | ```typescript 64 | const server = new Server({ 65 | name: "example-server", 66 | version: "1.0.0" 67 | }, { 68 | capabilities: {} 69 | }); 70 | 71 | const transport = new StdioServerTransport(); 72 | await server.connect(transport); 73 | ``` 74 | 75 | 76 | ```typescript 77 | const client = new Client({ 78 | name: "example-client", 79 | version: "1.0.0" 80 | }, { 81 | capabilities: {} 82 | }); 83 | 84 | const transport = new StdioClientTransport({ 85 | command: "./server", 86 | args: ["--option", "value"] 87 | }); 88 | await client.connect(transport); 89 | ``` 90 | 91 | 92 | ```python 93 | app = Server("example-server") 94 | 95 | async with stdio_server() as streams: 96 | await app.run( 97 | streams[0], 98 | streams[1], 99 | app.create_initialization_options() 100 | ) 101 | ``` 102 | 103 | 104 | ```python 105 | params = StdioServerParameters( 106 | command="./server", 107 | args=["--option", "value"] 108 | ) 109 | 110 | async with stdio_client(params) as streams: 111 | async with ClientSession(streams[0], streams[1]) as session: 112 | await session.initialize() 113 | ``` 114 | 115 | 116 | 117 | ### Server-Sent Events (SSE) 118 | 119 | SSE transport enables server-to-client streaming with HTTP POST requests for client-to-server communication. 120 | 121 | Use SSE when: 122 | - Only server-to-client streaming is needed 123 | - Working with restricted networks 124 | - Implementing simple updates 125 | 126 | 127 | 128 | ```typescript 129 | import express from "express"; 130 | 131 | const app = express(); 132 | 133 | const server = new Server({ 134 | name: "example-server", 135 | version: "1.0.0" 136 | }, { 137 | capabilities: {} 138 | }); 139 | 140 | let transport: SSEServerTransport | null = null; 141 | 142 | app.get("/sse", (req, res) => { 143 | transport = new SSEServerTransport("/messages", res); 144 | server.connect(transport); 145 | }); 146 | 147 | app.post("/messages", (req, res) => { 148 | if (transport) { 149 | transport.handlePostMessage(req, res); 150 | } 151 | }); 152 | 153 | app.listen(3000); 154 | ``` 155 | 156 | 157 | ```typescript 158 | const client = new Client({ 159 | name: "example-client", 160 | version: "1.0.0" 161 | }, { 162 | capabilities: {} 163 | }); 164 | 165 | const transport = new SSEClientTransport( 166 | new URL("http://localhost:3000/sse") 167 | ); 168 | await client.connect(transport); 169 | ``` 170 | 171 | 172 | ```python 173 | from mcp.server.sse import SseServerTransport 174 | from starlette.applications import Starlette 175 | from starlette.routing import Route 176 | 177 | app = Server("example-server") 178 | sse = SseServerTransport("/messages") 179 | 180 | async def handle_sse(scope, receive, send): 181 | async with sse.connect_sse(scope, receive, send) as streams: 182 | await app.run(streams[0], streams[1], app.create_initialization_options()) 183 | 184 | async def handle_messages(scope, receive, send): 185 | await sse.handle_post_message(scope, receive, send) 186 | 187 | starlette_app = Starlette( 188 | routes=[ 189 | Route("/sse", endpoint=handle_sse), 190 | Route("/messages", endpoint=handle_messages, methods=["POST"]), 191 | ] 192 | ) 193 | ``` 194 | 195 | 196 | ```python 197 | async with sse_client("http://localhost:8000/sse") as streams: 198 | async with ClientSession(streams[0], streams[1]) as session: 199 | await session.initialize() 200 | ``` 201 | 202 | 203 | 204 | ## Custom Transports 205 | 206 | MCP makes it easy to implement custom transports for specific needs. Any transport implementation just needs to conform to the Transport interface: 207 | 208 | You can implement custom transports for: 209 | - Custom network protocols 210 | - Specialized communication channels 211 | - Integration with existing systems 212 | - Performance optimization 213 | 214 | 215 | 216 | ```typescript 217 | interface Transport { 218 | // Start processing messages 219 | start(): Promise; 220 | 221 | // Send a JSON-RPC message 222 | send(message: JSONRPCMessage): Promise; 223 | 224 | // Close the connection 225 | close(): Promise; 226 | 227 | // Callbacks 228 | onclose?: () => void; 229 | onerror?: (error: Error) => void; 230 | onmessage?: (message: JSONRPCMessage) => void; 231 | } 232 | ``` 233 | 234 | 235 | Note that while MCP Servers are often implemented with asyncio, we recommend 236 | implementing low-level interfaces like transports with `anyio` for wider compatibility. 237 | ```python 238 | @contextmanager 239 | async def create_transport( 240 | read_stream: MemoryObjectReceiveStream[JSONRPCMessage | Exception], 241 | write_stream: MemoryObjectSendStream[JSONRPCMessage] 242 | ): 243 | """ 244 | Transport interface for MCP. 245 | 246 | Args: 247 | read_stream: Stream to read incoming messages from 248 | write_stream: Stream to write outgoing messages to 249 | """ 250 | async with anyio.create_task_group() as tg: 251 | try: 252 | # Start processing messages 253 | tg.start_soon(lambda: process_messages(read_stream)) 254 | 255 | # Send messages 256 | async with write_stream: 257 | yield write_stream 258 | 259 | except Exception as exc: 260 | # Handle errors 261 | raise exc 262 | finally: 263 | # Clean up 264 | tg.cancel_scope.cancel() 265 | await write_stream.aclose() 266 | await read_stream.aclose() 267 | ``` 268 | 269 | 270 | 271 | ## Error Handling 272 | 273 | Transport implementations should handle various error scenarios: 274 | 275 | 1. Connection errors 276 | 2. Message parsing errors 277 | 3. Protocol errors 278 | 4. Network timeouts 279 | 5. Resource cleanup 280 | 281 | Example error handling: 282 | 283 | 284 | 285 | ```typescript 286 | class ExampleTransport implements Transport { 287 | async start() { 288 | try { 289 | // Connection logic 290 | } catch (error) { 291 | this.onerror?.(new Error(`Failed to connect: ${error}`)); 292 | throw error; 293 | } 294 | } 295 | 296 | async send(message: JSONRPCMessage) { 297 | try { 298 | // Sending logic 299 | } catch (error) { 300 | this.onerror?.(new Error(`Failed to send message: ${error}`)); 301 | throw error; 302 | } 303 | } 304 | } 305 | ``` 306 | 307 | 308 | Note that while MCP Servers are often implemented with asyncio, we recommend 309 | implementing low-level interfaces like transports with `anyio` for wider compatibility. 310 | ```python 311 | @contextmanager 312 | async def example_transport(scope: Scope, receive: Receive, send: Send): 313 | try: 314 | # Create streams for bidirectional communication 315 | read_stream_writer, read_stream = anyio.create_memory_object_stream(0) 316 | write_stream, write_stream_reader = anyio.create_memory_object_stream(0) 317 | 318 | async def message_handler(): 319 | try: 320 | async with read_stream_writer: 321 | # Message handling logic 322 | pass 323 | except Exception as exc: 324 | logger.error(f"Failed to handle message: {exc}") 325 | raise exc 326 | 327 | async with anyio.create_task_group() as tg: 328 | tg.start_soon(message_handler) 329 | try: 330 | # Yield streams for communication 331 | yield read_stream, write_stream 332 | except Exception as exc: 333 | logger.error(f"Transport error: {exc}") 334 | raise exc 335 | finally: 336 | tg.cancel_scope.cancel() 337 | await write_stream.aclose() 338 | await read_stream.aclose() 339 | except Exception as exc: 340 | logger.error(f"Failed to initialize transport: {exc}") 341 | raise exc 342 | ``` 343 | 344 | 345 | 346 | ## Best Practices 347 | 348 | When implementing or using MCP transport: 349 | 350 | 1. Handle connection lifecycle properly 351 | 2. Implement proper error handling 352 | 3. Clean up resources on connection close 353 | 4. Use appropriate timeouts 354 | 5. Validate messages before sending 355 | 6. Log transport events for debugging 356 | 7. Implement reconnection logic when appropriate 357 | 8. Handle backpressure in message queues 358 | 9. Monitor connection health 359 | 10. Implement proper security measures 360 | 361 | ## Security Considerations 362 | 363 | When implementing transport: 364 | 365 | ### Authentication and Authorization 366 | - Implement proper authentication mechanisms 367 | - Validate client credentials 368 | - Use secure token handling 369 | - Implement authorization checks 370 | 371 | ### Data Security 372 | - Use TLS for network transport 373 | - Encrypt sensitive data 374 | - Validate message integrity 375 | - Implement message size limits 376 | - Sanitize input data 377 | 378 | ### Network Security 379 | - Implement rate limiting 380 | - Use appropriate timeouts 381 | - Handle denial of service scenarios 382 | - Monitor for unusual patterns 383 | - Implement proper firewall rules 384 | 385 | ## Debugging Transport 386 | 387 | Tips for debugging transport issues: 388 | 389 | 1. Enable debug logging 390 | 2. Monitor message flow 391 | 3. Check connection states 392 | 4. Validate message formats 393 | 5. Test error scenarios 394 | 6. Use network analysis tools 395 | 7. Implement health checks 396 | 8. Monitor resource usage 397 | 9. Test edge cases 398 | 10. Use proper error tracking 399 | -------------------------------------------------------------------------------- /images/hero-dark.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | -------------------------------------------------------------------------------- /docs/concepts/prompts.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Prompts" 3 | description: "Create reusable prompt templates and workflows" 4 | --- 5 | 6 | Prompts enable servers to define reusable prompt templates and workflows that clients can easily surface to users and LLMs. They provide a powerful way to standardize and share common LLM interactions. 7 | 8 | 9 | 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. 10 | 11 | 12 | ## Overview 13 | 14 | Prompts in MCP are predefined templates that can: 15 | - Accept dynamic arguments 16 | - Include context from resources 17 | - Chain multiple interactions 18 | - Guide specific workflows 19 | - Surface as UI elements (like slash commands) 20 | 21 | ## Prompt structure 22 | 23 | Each prompt is defined with: 24 | 25 | ```typescript 26 | { 27 | name: string; // Unique identifier for the prompt 28 | description?: string; // Human-readable description 29 | arguments?: [ // Optional list of arguments 30 | { 31 | name: string; // Argument identifier 32 | description?: string; // Argument description 33 | required?: boolean; // Whether argument is required 34 | } 35 | ] 36 | } 37 | ``` 38 | 39 | ## Discovering prompts 40 | 41 | Clients can discover available prompts through the `prompts/list` endpoint: 42 | 43 | ```typescript 44 | // Request 45 | { 46 | method: "prompts/list" 47 | } 48 | 49 | // Response 50 | { 51 | prompts: [ 52 | { 53 | name: "analyze-code", 54 | description: "Analyze code for potential improvements", 55 | arguments: [ 56 | { 57 | name: "language", 58 | description: "Programming language", 59 | required: true 60 | } 61 | ] 62 | } 63 | ] 64 | } 65 | ``` 66 | 67 | ## Using prompts 68 | 69 | To use a prompt, clients make a `prompts/get` request: 70 | 71 | ```typescript 72 | // Request 73 | { 74 | method: "prompts/get", 75 | params: { 76 | name: "analyze-code", 77 | arguments: { 78 | language: "python" 79 | } 80 | } 81 | } 82 | 83 | // Response 84 | { 85 | description: "Analyze Python code for potential improvements", 86 | messages: [ 87 | { 88 | role: "user", 89 | content: { 90 | type: "text", 91 | text: "Please analyze the following Python code for potential improvements:\n\n```python\ndef calculate_sum(numbers):\n total = 0\n for num in numbers:\n total = total + num\n return total\n\nresult = calculate_sum([1, 2, 3, 4, 5])\nprint(result)\n```" 92 | } 93 | } 94 | ] 95 | } 96 | ``` 97 | 98 | ## Dynamic prompts 99 | 100 | Prompts can be dynamic and include: 101 | 102 | ### Embedded resource context 103 | 104 | ```json 105 | { 106 | "name": "analyze-project", 107 | "description": "Analyze project logs and code", 108 | "arguments": [ 109 | { 110 | "name": "timeframe", 111 | "description": "Time period to analyze logs", 112 | "required": true 113 | }, 114 | { 115 | "name": "fileUri", 116 | "description": "URI of code file to review", 117 | "required": true 118 | } 119 | ] 120 | } 121 | ``` 122 | 123 | When handling the `prompts/get` request: 124 | 125 | ```json 126 | { 127 | "messages": [ 128 | { 129 | "role": "user", 130 | "content": { 131 | "type": "text", 132 | "text": "Analyze these system logs and the code file for any issues:" 133 | } 134 | }, 135 | { 136 | "role": "user", 137 | "content": { 138 | "type": "resource", 139 | "resource": { 140 | "uri": "logs://recent?timeframe=1h", 141 | "text": "[2024-03-14 15:32:11] ERROR: Connection timeout in network.py:127\n[2024-03-14 15:32:15] WARN: Retrying connection (attempt 2/3)\n[2024-03-14 15:32:20] ERROR: Max retries exceeded", 142 | "mimeType": "text/plain" 143 | } 144 | } 145 | }, 146 | { 147 | "role": "user", 148 | "content": { 149 | "type": "resource", 150 | "resource": { 151 | "uri": "file:///path/to/code.py", 152 | "text": "def connect_to_service(timeout=30):\n retries = 3\n for attempt in range(retries):\n try:\n return establish_connection(timeout)\n except TimeoutError:\n if attempt == retries - 1:\n raise\n time.sleep(5)\n\ndef establish_connection(timeout):\n # Connection implementation\n pass", 153 | "mimeType": "text/x-python" 154 | } 155 | } 156 | } 157 | ] 158 | } 159 | ``` 160 | 161 | ### Multi-step workflows 162 | 163 | ```typescript 164 | const debugWorkflow = { 165 | name: "debug-error", 166 | async getMessages(error: string) { 167 | return [ 168 | { 169 | role: "user", 170 | content: { 171 | type: "text", 172 | text: `Here's an error I'm seeing: ${error}` 173 | } 174 | }, 175 | { 176 | role: "assistant", 177 | content: { 178 | type: "text", 179 | text: "I'll help analyze this error. What have you tried so far?" 180 | } 181 | }, 182 | { 183 | role: "user", 184 | content: { 185 | type: "text", 186 | text: "I've tried restarting the service, but the error persists." 187 | } 188 | } 189 | ]; 190 | } 191 | }; 192 | ``` 193 | 194 | ## Example implementation 195 | 196 | Here's a complete example of implementing prompts in an MCP server: 197 | 198 | 199 | 200 | ```typescript 201 | import { Server } from "@modelcontextprotocol/sdk/server"; 202 | import { 203 | ListPromptsRequestSchema, 204 | GetPromptRequestSchema 205 | } from "@modelcontextprotocol/sdk/types"; 206 | 207 | const PROMPTS = { 208 | "git-commit": { 209 | name: "git-commit", 210 | description: "Generate a Git commit message", 211 | arguments: [ 212 | { 213 | name: "changes", 214 | description: "Git diff or description of changes", 215 | required: true 216 | } 217 | ] 218 | }, 219 | "explain-code": { 220 | name: "explain-code", 221 | description: "Explain how code works", 222 | arguments: [ 223 | { 224 | name: "code", 225 | description: "Code to explain", 226 | required: true 227 | }, 228 | { 229 | name: "language", 230 | description: "Programming language", 231 | required: false 232 | } 233 | ] 234 | } 235 | }; 236 | 237 | const server = new Server({ 238 | name: "example-prompts-server", 239 | version: "1.0.0" 240 | }, { 241 | capabilities: { 242 | prompts: {} 243 | } 244 | }); 245 | 246 | // List available prompts 247 | server.setRequestHandler(ListPromptsRequestSchema, async () => { 248 | return { 249 | prompts: Object.values(PROMPTS) 250 | }; 251 | }); 252 | 253 | // Get specific prompt 254 | server.setRequestHandler(GetPromptRequestSchema, async (request) => { 255 | const prompt = PROMPTS[request.params.name]; 256 | if (!prompt) { 257 | throw new Error(`Prompt not found: ${request.params.name}`); 258 | } 259 | 260 | if (request.params.name === "git-commit") { 261 | return { 262 | messages: [ 263 | { 264 | role: "user", 265 | content: { 266 | type: "text", 267 | text: `Generate a concise but descriptive commit message for these changes:\n\n${request.params.arguments?.changes}` 268 | } 269 | } 270 | ] 271 | }; 272 | } 273 | 274 | if (request.params.name === "explain-code") { 275 | const language = request.params.arguments?.language || "Unknown"; 276 | return { 277 | messages: [ 278 | { 279 | role: "user", 280 | content: { 281 | type: "text", 282 | text: `Explain how this ${language} code works:\n\n${request.params.arguments?.code}` 283 | } 284 | } 285 | ] 286 | }; 287 | } 288 | 289 | throw new Error("Prompt implementation not found"); 290 | }); 291 | ``` 292 | 293 | 294 | ```python 295 | from mcp.server import Server 296 | import mcp.types as types 297 | 298 | # Define available prompts 299 | PROMPTS = { 300 | "git-commit": types.Prompt( 301 | name="git-commit", 302 | description="Generate a Git commit message", 303 | arguments=[ 304 | types.PromptArgument( 305 | name="changes", 306 | description="Git diff or description of changes", 307 | required=True 308 | ) 309 | ], 310 | ), 311 | "explain-code": types.Prompt( 312 | name="explain-code", 313 | description="Explain how code works", 314 | arguments=[ 315 | types.PromptArgument( 316 | name="code", 317 | description="Code to explain", 318 | required=True 319 | ), 320 | types.PromptArgument( 321 | name="language", 322 | description="Programming language", 323 | required=False 324 | ) 325 | ], 326 | ) 327 | } 328 | 329 | # Initialize server 330 | app = Server("example-prompts-server") 331 | 332 | @app.list_prompts() 333 | async def list_prompts() -> list[types.Prompt]: 334 | return list(PROMPTS.values()) 335 | 336 | @app.get_prompt() 337 | async def get_prompt( 338 | name: str, arguments: dict[str, str] | None = None 339 | ) -> types.GetPromptResult: 340 | if name not in PROMPTS: 341 | raise ValueError(f"Prompt not found: {name}") 342 | 343 | if name == "git-commit": 344 | changes = arguments.get("changes") if arguments else "" 345 | return types.GetPromptResult( 346 | messages=[ 347 | types.PromptMessage( 348 | role="user", 349 | content=types.TextContent( 350 | type="text", 351 | text=f"Generate a concise but descriptive commit message " 352 | f"for these changes:\n\n{changes}" 353 | ) 354 | ) 355 | ] 356 | ) 357 | 358 | if name == "explain-code": 359 | code = arguments.get("code") if arguments else "" 360 | language = arguments.get("language", "Unknown") if arguments else "Unknown" 361 | return types.GetPromptResult( 362 | messages=[ 363 | types.PromptMessage( 364 | role="user", 365 | content=types.TextContent( 366 | type="text", 367 | text=f"Explain how this {language} code works:\n\n{code}" 368 | ) 369 | ) 370 | ] 371 | ) 372 | 373 | raise ValueError("Prompt implementation not found") 374 | ``` 375 | 376 | 377 | 378 | ## Best practices 379 | 380 | When implementing prompts: 381 | 382 | 1. Use clear, descriptive prompt names 383 | 2. Provide detailed descriptions for prompts and arguments 384 | 3. Validate all required arguments 385 | 4. Handle missing arguments gracefully 386 | 5. Consider versioning for prompt templates 387 | 6. Cache dynamic content when appropriate 388 | 7. Implement error handling 389 | 8. Document expected argument formats 390 | 9. Consider prompt composability 391 | 10. Test prompts with various inputs 392 | 393 | ## UI integration 394 | 395 | Prompts can be surfaced in client UIs as: 396 | 397 | - Slash commands 398 | - Quick actions 399 | - Context menu items 400 | - Command palette entries 401 | - Guided workflows 402 | - Interactive forms 403 | 404 | ## Updates and changes 405 | 406 | Servers can notify clients about prompt changes: 407 | 408 | 1. Server capability: `prompts.listChanged` 409 | 2. Notification: `notifications/prompts/list_changed` 410 | 3. Client re-fetches prompt list 411 | 412 | ## Security considerations 413 | 414 | When implementing prompts: 415 | 416 | - Validate all arguments 417 | - Sanitize user input 418 | - Consider rate limiting 419 | - Implement access controls 420 | - Audit prompt usage 421 | - Handle sensitive data appropriately 422 | - Validate generated content 423 | - Implement timeouts 424 | - Consider prompt injection risks 425 | - Document security requirements 426 | -------------------------------------------------------------------------------- /tutorials/building-a-client-node.mdx: -------------------------------------------------------------------------------- 1 | 2 | ## System Requirements 3 | 4 | Before starting, ensure your system meets these requirements: 5 | - Mac or Windows computer 6 | - Node.js version 16 or higher installed 7 | - npm (comes with Node.js) 8 | 9 | ## Setting Up Your Environment 10 | 11 | First, create a new Node.js project: 12 | 13 | ```bash 14 | # Create project directory 15 | mkdir mcp-client 16 | cd mcp-client 17 | 18 | # Initialize npm project 19 | npm init -y 20 | 21 | # Install dependencies 22 | npm install @modelcontextprotocol/sdk @anthropic-ai/sdk dotenv 23 | npm install -D typescript @types/node 24 | 25 | # Create TypeScript config 26 | npx tsc --init 27 | 28 | # Create necessary files 29 | mkdir src 30 | touch src/client.ts 31 | touch .env 32 | ``` 33 | 34 | Update your `package.json` to add necessary configuration: 35 | 36 | ```json 37 | { 38 | "type": "module", 39 | "scripts": { 40 | "build": "tsc", 41 | "start": "node build/client.js" 42 | } 43 | } 44 | ``` 45 | 46 | Update your `tsconfig.json` with appropriate settings: 47 | 48 | ```json 49 | { 50 | "compilerOptions": { 51 | "target": "ES2022", 52 | "module": "Node16", 53 | "moduleResolution": "Node16", 54 | "outDir": "./build", 55 | "rootDir": "./src", 56 | "strict": true, 57 | "esModuleInterop": true, 58 | "skipLibCheck": true, 59 | "forceConsistentCasingInFileNames": true 60 | }, 61 | "include": ["src/**/*"] 62 | } 63 | ``` 64 | 65 | ## Setting Up Your API Key 66 | 67 | You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys). 68 | 69 | Create a `.env` file: 70 | ```bash 71 | ANTHROPIC_API_KEY=your_key_here 72 | ``` 73 | 74 | Add `.env` to your `.gitignore`: 75 | ```bash 76 | echo ".env" >> .gitignore 77 | ``` 78 | 79 | ## Creating the Client 80 | 81 | First, let's set up our imports and create the basic client class in `src/client.ts`: 82 | 83 | ```typescript 84 | import { Client } from "@modelcontextprotocol/sdk/client/index.js"; 85 | import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; 86 | import Anthropic from "@anthropic-ai/sdk"; 87 | import dotenv from "dotenv"; 88 | import { 89 | CallToolResultSchema, 90 | ListToolsResultSchema, 91 | } from "@modelcontextprotocol/sdk/types.js"; 92 | import * as readline from "node:readline"; 93 | 94 | dotenv.config(); 95 | 96 | interface MCPClientConfig { 97 | name?: string; 98 | version?: string; 99 | } 100 | 101 | class MCPClient { 102 | private client: Client | null = null; 103 | private anthropic: Anthropic; 104 | private transport: StdioClientTransport | null = null; 105 | 106 | constructor(config: MCPClientConfig = {}) { 107 | this.anthropic = new Anthropic(); 108 | } 109 | 110 | // Methods will go here 111 | } 112 | ``` 113 | 114 | ## Server Connection Management 115 | 116 | Next, implement the method to connect to an MCP server: 117 | 118 | ```typescript 119 | async connectToServer(serverScriptPath: string): Promise { 120 | const isPython = serverScriptPath.endsWith(".py"); 121 | const isJs = serverScriptPath.endsWith(".js"); 122 | 123 | if (!isPython && !isJs) { 124 | throw new Error("Server script must be a .py or .js file"); 125 | } 126 | 127 | const command = isPython ? "python" : "node"; 128 | 129 | this.transport = new StdioClientTransport({ 130 | command, 131 | args: [serverScriptPath], 132 | }); 133 | 134 | this.client = new Client( 135 | { 136 | name: "mcp-client", 137 | version: "1.0.0", 138 | }, 139 | { 140 | capabilities: {}, 141 | } 142 | ); 143 | 144 | await this.client.connect(this.transport); 145 | 146 | // List available tools 147 | const response = await this.client.request( 148 | { method: "tools/list" }, 149 | ListToolsResultSchema 150 | ); 151 | 152 | console.log( 153 | "\nConnected to server with tools:", 154 | response.tools.map((tool: any) => tool.name) 155 | ); 156 | } 157 | ``` 158 | 159 | ## Query Processing Logic 160 | 161 | Now add the core functionality for processing queries and handling tool calls: 162 | 163 | ```typescript 164 | async processQuery(query: string): Promise { 165 | if (!this.client) { 166 | throw new Error("Client not connected"); 167 | } 168 | 169 | // Initialize messages array with user query 170 | let messages: Anthropic.MessageParam[] = [ 171 | { 172 | role: "user", 173 | content: query, 174 | }, 175 | ]; 176 | 177 | // Get available tools 178 | const toolsResponse = await this.client.request( 179 | { method: "tools/list" }, 180 | ListToolsResultSchema 181 | ); 182 | 183 | const availableTools = toolsResponse.tools.map((tool: any) => ({ 184 | name: tool.name, 185 | description: tool.description, 186 | input_schema: tool.inputSchema, 187 | })); 188 | 189 | const finalText: string[] = []; 190 | let currentResponse = await this.anthropic.messages.create({ 191 | model: "claude-3-5-sonnet-20241022", 192 | max_tokens: 1000, 193 | messages, 194 | tools: availableTools, 195 | }); 196 | 197 | // Process the response and any tool calls 198 | while (true) { 199 | // Add Claude's response to final text and messages 200 | for (const content of currentResponse.content) { 201 | if (content.type === "text") { 202 | finalText.push(content.text); 203 | } else if (content.type === "tool_use") { 204 | const toolName = content.name; 205 | const toolArgs = content.input; 206 | 207 | // Execute tool call 208 | const result = await this.client.request( 209 | { 210 | method: "tools/call", 211 | params: { 212 | name: toolName, 213 | arguments: toolArgs, 214 | }, 215 | }, 216 | CallToolResultSchema 217 | ); 218 | 219 | finalText.push( 220 | `[Calling tool ${toolName} with args ${JSON.stringify(toolArgs)}]` 221 | ); 222 | 223 | // Add Claude's response (including tool use) to messages 224 | messages.push({ 225 | role: "assistant", 226 | content: currentResponse.content, 227 | }); 228 | 229 | // Add tool result to messages 230 | messages.push({ 231 | role: "user", 232 | content: [ 233 | { 234 | type: "tool_result", 235 | tool_use_id: content.id, 236 | content: [ 237 | { type: "text", text: JSON.stringify(result.content) }, 238 | ], 239 | }, 240 | ], 241 | }); 242 | 243 | // Get next response from Claude with tool results 244 | currentResponse = await this.anthropic.messages.create({ 245 | model: "claude-3-5-sonnet-20241022", 246 | max_tokens: 1000, 247 | messages, 248 | tools: availableTools, 249 | }); 250 | 251 | // Add Claude's interpretation of the tool results to final text 252 | if (currentResponse.content[0]?.type === "text") { 253 | finalText.push(currentResponse.content[0].text); 254 | } 255 | 256 | // Continue the loop to process any additional tool calls 257 | continue; 258 | } 259 | } 260 | 261 | // If we reach here, there were no tool calls in the response 262 | break; 263 | } 264 | 265 | return finalText.join("\n"); 266 | } 267 | 268 | ``` 269 | 270 | ## Interactive Chat Interface 271 | 272 | Add the chat loop and cleanup functionality: 273 | 274 | ```typescript 275 | async chatLoop(): Promise { 276 | console.log("\nMCP Client Started!"); 277 | console.log("Type your queries or 'quit' to exit."); 278 | 279 | // Using Node's readline for console input 280 | const rl = readline.createInterface({ 281 | input: process.stdin, 282 | output: process.stdout, 283 | }); 284 | 285 | const askQuestion = () => { 286 | rl.question("\nQuery: ", async (query: string) => { 287 | try { 288 | if (query.toLowerCase() === "quit") { 289 | await this.cleanup(); 290 | rl.close(); 291 | return; 292 | } 293 | 294 | const response = await this.processQuery(query); 295 | console.log("\n" + response); 296 | askQuestion(); 297 | } catch (error) { 298 | console.error("\nError:", error); 299 | askQuestion(); 300 | } 301 | }); 302 | }; 303 | 304 | askQuestion(); 305 | } 306 | 307 | async cleanup(): Promise { 308 | if (this.transport) { 309 | await this.transport.close(); 310 | } 311 | } 312 | ``` 313 | 314 | ## Main Entry Point 315 | 316 | Finally, add the main execution logic outside the class: 317 | 318 | ```typescript 319 | // Main execution 320 | async function main() { 321 | if (process.argv.length < 3) { 322 | console.log("Usage: ts-node client.ts "); 323 | process.exit(1); 324 | } 325 | 326 | const client = new MCPClient(); 327 | try { 328 | await client.connectToServer(process.argv[2]); 329 | await client.chatLoop(); 330 | } catch (error) { 331 | console.error("Error:", error); 332 | await client.cleanup(); 333 | process.exit(1); 334 | } 335 | } 336 | 337 | // Run main if this is the main module 338 | if (import.meta.url === new URL(process.argv[1], "file:").href) { 339 | main(); 340 | } 341 | 342 | export default MCPClient; 343 | ``` 344 | 345 | ## Running the Client 346 | 347 | To run your client with any MCP server: 348 | 349 | ```bash 350 | # Build the TypeScript code. Make sure to rerun this every time you update `client.ts`! 351 | npm run build 352 | 353 | # Run the client 354 | node build/client.js path/to/server.py # for Python servers 355 | node build/client.js path/to/server.js # for Node.js servers 356 | ``` 357 | 358 | The client will: 359 | 1. Connect to the specified server 360 | 2. List available tools 361 | 3. Start an interactive chat session where you can: 362 | - Enter queries 363 | - See tool executions 364 | - Get responses from Claude 365 | 366 | ## Key Components Explained 367 | 368 | #### 1. Client Initialization 369 | - The `MCPClient` class initializes with session management and API clients 370 | - Sets up the MCP client with basic capabilities 371 | - Configures the Anthropic client for Claude interactions 372 | 373 | #### 2. Server Connection 374 | - Supports both Python and Node.js servers 375 | - Validates server script type 376 | - Sets up proper communication channels 377 | - Lists available tools on connection 378 | 379 | #### 3. Query Processing 380 | - Maintains conversation context 381 | - Handles Claude's responses and tool calls 382 | - Manages the message flow between Claude and tools 383 | - Combines results into a coherent response 384 | 385 | #### 4. Interactive Interface 386 | - Provides a simple command-line interface 387 | - Handles user input and displays responses 388 | - Includes basic error handling 389 | - Allows graceful exit 390 | 391 | #### 5. Resource Management 392 | - Proper cleanup of resources 393 | - Error handling for connection issues 394 | - Graceful shutdown procedures 395 | 396 | ### Common Customization Points 397 | 398 | 1. **Tool Handling** 399 | - Modify `processQuery()` to handle specific tool types 400 | - Add custom error handling for tool calls 401 | - Implement tool-specific response formatting 402 | 403 | 2. **Response Processing** 404 | - Customize how tool results are formatted 405 | - Add response filtering or transformation 406 | - Implement custom logging 407 | 408 | 3. **User Interface** 409 | - Add a GUI or web interface 410 | - Implement rich console output 411 | - Add command history or auto-completion 412 | 413 | ### Best Practices 414 | 415 | 1. **Error Handling** 416 | - Always wrap tool calls in try-catch blocks 417 | - Provide meaningful error messages 418 | - Gracefully handle connection issues 419 | 420 | 2. **Resource Management** 421 | - Use proper cleanup methods 422 | - Close connections when done 423 | - Handle server disconnections 424 | 425 | 3. **Security** 426 | - Store API keys securely in `.env` 427 | - Validate server responses 428 | - Be cautious with tool permissions 429 | 430 | ### Troubleshooting 431 | 432 | #### Server Path Issues 433 | - Double-check the path to your server script 434 | - Use absolute paths if relative paths aren't working 435 | - For Windows users, use forward slashes (/) or escaped backslashes (\\) 436 | - Verify the server file has the correct extension (.py or .js) 437 | 438 | Example of correct path usage: 439 | ```bash 440 | # Relative path 441 | node build/client.js ./server/weather.js 442 | 443 | # Absolute path 444 | node build/client.js /Users/username/projects/mcp-server/weather.js 445 | 446 | # Windows path (either format works) 447 | node build/client.js C:/projects/mcp-server/weather.js 448 | node build/client.js C:\\projects\\mcp-server\\weather.js 449 | ``` 450 | 451 | #### Connection Issues 452 | - Verify the server script exists and has correct permissions 453 | - Check that the server script is executable 454 | - Ensure the server script's dependencies are installed 455 | - Try running the server script directly to check for errors 456 | 457 | #### Tool Execution Issues 458 | - Check server logs for error messages 459 | - Verify tool input arguments match the schema 460 | - Ensure tool dependencies are available 461 | - Add debug logging to track execution flow 462 | -------------------------------------------------------------------------------- /logo/dark.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | --------------------------------------------------------------------------------