This is page 5 of 5. Use http://codebase.md/stumason/coolify-mcp?lines=true&page={x} to view the full context. # Directory Structure ``` ├── .cursor │ └── rules │ ├── 000-cursor-rules.mdc │ ├── 801-feature-workflow.mdc │ ├── 802-coolify-mcp-workflow.mdc │ └── 803-npm-publish-workflow.mdc ├── .eslintrc.json ├── .github │ └── workflows │ └── ci.yml ├── .gitignore ├── .lintstagedrc.json ├── .markdownlint-cli2.jsonc ├── .prettierrc ├── .repomixignore ├── debug.js ├── docs │ ├── coolify-openapi.yaml │ ├── features │ │ ├── 001-core-server-setup.md │ │ ├── 002-server-info-resource.md │ │ ├── 003-project-management.md │ │ ├── 004-environment-management.md │ │ ├── 005-application-deployment.md │ │ ├── 006-database-management.md │ │ ├── 007-service-management.md │ │ ├── 008-mcp-resources-implementation.md │ │ ├── 009-mcp-prompts-implementation.md │ │ ├── 010-private-key-management.md │ │ ├── 011-team-management.md │ │ ├── 012-backup-management.md │ │ ├── 013-npx-config-fix.md │ │ └── future-adrs.md │ ├── mcp-example-clients.md │ ├── mcp-js-readme.md │ └── openapi-chunks │ ├── applications-api.yaml │ ├── databases-api.yaml │ ├── deployments-api.yaml │ ├── private-keys-api.yaml │ ├── projects-api.yaml │ ├── resources-api.yaml │ ├── schemas.yaml │ ├── servers-api.yaml │ ├── services-api.yaml │ ├── teams-api.yaml │ └── untagged-api.yaml ├── jest.config.js ├── package-lock.json ├── package.json ├── README.md ├── repomix-output.xml ├── src │ ├── __tests__ │ │ ├── coolify-client.test.ts │ │ └── resources │ │ ├── application-resources.test.ts │ │ ├── database-resources.test.ts │ │ ├── deployment-resources.test.ts │ │ └── service-resources.test.ts │ ├── index.ts │ ├── lib │ │ ├── coolify-client.ts │ │ ├── mcp-server.ts │ │ └── resource.ts │ ├── resources │ │ ├── application-resources.ts │ │ ├── database-resources.ts │ │ ├── deployment-resources.ts │ │ ├── index.ts │ │ └── service-resources.ts │ └── types │ └── coolify.ts └── tsconfig.json ``` # Files -------------------------------------------------------------------------------- /docs/mcp-example-clients.md: -------------------------------------------------------------------------------- ```markdown 1 | # Example Clients 2 | 3 | Source: https://modelcontextprotocol.io/clients 4 | 5 | A list of applications that support MCP integrations 6 | 7 | This page provides an overview of applications that support the Model Context Protocol (MCP). Each client may support different MCP features, allowing for varying levels of integration with MCP servers. 8 | 9 | ## Feature support matrix 10 | 11 | | Client | [Resources] | [Prompts] | [Tools] | [Sampling] | Roots | Notes | 12 | | ------------------------------------ | ----------- | --------- | ------- | ---------- | ----- | ------------------------------------------------------------------ | 13 | | [Claude Desktop App][Claude] | ✅ | ✅ | ✅ | ❌ | ❌ | Full support for all MCP features | 14 | | [5ire][5ire] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools. | 15 | | [BeeAI Framework][BeeAI Framework] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools in agentic workflows. | 16 | | [Cline][Cline] | ✅ | ❌ | ✅ | ❌ | ❌ | Supports tools and resources. | 17 | | [Continue][Continue] | ✅ | ✅ | ✅ | ❌ | ❌ | Full support for all MCP features | 18 | | [Cursor][Cursor] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools. | 19 | | [Emacs Mcp][Mcp.el] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools in Emacs. | 20 | | [Firebase Genkit][Genkit] | ⚠️ | ✅ | ✅ | ❌ | ❌ | Supports resource list and lookup through tools. | 21 | | [GenAIScript][GenAIScript] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools. | 22 | | [Goose][Goose] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools. | 23 | | [LibreChat][LibreChat] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools for Agents | 24 | | [mcp-agent][mcp-agent] | ❌ | ❌ | ✅ | ⚠️ | ❌ | Supports tools, server connection management, and agent workflows. | 25 | | [Roo Code][Roo Code] | ✅ | ❌ | ✅ | ❌ | ❌ | Supports tools and resources. | 26 | | [Sourcegraph Cody][Cody] | ✅ | ❌ | ❌ | ❌ | ❌ | Supports resources through OpenCTX | 27 | | [Superinterface][Superinterface] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools | 28 | | [TheiaAI/TheiaIDE][TheiaAI/TheiaIDE] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools for Agents in Theia AI and the AI-powered Theia IDE | 29 | | [Windsurf Editor][Windsurf] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools with AI Flow for collaborative development. | 30 | | [Zed][Zed] | ❌ | ✅ | ❌ | ❌ | ❌ | Prompts appear as slash commands | 31 | | \[OpenSumi]\[OpenSumi] | ❌ | ❌ | ✅ | ❌ | ❌ | Supports tools in OpenSumi | 32 | 33 | [Claude]: https://claude.ai/download 34 | [Cursor]: https://cursor.com 35 | [Zed]: https://zed.dev 36 | [Cody]: https://sourcegraph.com/cody 37 | [Genkit]: https://github.com/firebase/genkit 38 | [Continue]: https://github.com/continuedev/continue 39 | [GenAIScript]: https://microsoft.github.io/genaiscript/reference/scripts/mcp-tools/ 40 | [Cline]: https://github.com/cline/cline 41 | [LibreChat]: https://github.com/danny-avila/LibreChat 42 | [TheiaAI/TheiaIDE]: https://eclipsesource.com/blogs/2024/12/19/theia-ide-and-theia-ai-support-mcp/ 43 | [Superinterface]: https://superinterface.ai 44 | [5ire]: https://github.com/nanbingxyz/5ire 45 | [BeeAI Framework]: https://i-am-bee.github.io/beeai-framework 46 | [mcp-agent]: https://github.com/lastmile-ai/mcp-agent 47 | [Mcp.el]: https://github.com/lizqwerscott/mcp.el 48 | [Roo Code]: https://roocode.com 49 | [Goose]: https://block.github.io/goose/docs/goose-architecture/#interoperability-with-extensions 50 | [Windsurf]: https://codeium.com/windsurf 51 | [Resources]: https://modelcontextprotocol.io/docs/concepts/resources 52 | [Prompts]: https://modelcontextprotocol.io/docs/concepts/prompts 53 | [Tools]: https://modelcontextprotocol.io/docs/concepts/tools 54 | [Sampling]: https://modelcontextprotocol.io/docs/concepts/sampling 55 | 56 | ## Client details 57 | 58 | ### Claude Desktop App 59 | 60 | The Claude desktop application provides comprehensive support for MCP, enabling deep integration with local tools and data sources. 61 | 62 | **Key features:** 63 | 64 | - Full support for resources, allowing attachment of local files and data 65 | - Support for prompt templates 66 | - Tool integration for executing commands and scripts 67 | - Local server connections for enhanced privacy and security 68 | 69 | > ⓘ Note: The Claude.ai web application does not currently support MCP. MCP features are only available in the desktop application. 70 | 71 | ### 5ire 72 | 73 | [5ire](https://github.com/nanbingxyz/5ire) is an open source cross-platform desktop AI assistant that supports tools through MCP servers. 74 | 75 | **Key features:** 76 | 77 | - Built-in MCP servers can be quickly enabled and disabled. 78 | - Users can add more servers by modifying the configuration file. 79 | - It is open-source and user-friendly, suitable for beginners. 80 | - Future support for MCP will be continuously improved. 81 | 82 | ### BeeAI Framework 83 | 84 | [BeeAI Framework](https://i-am-bee.github.io/beeai-framework) is an open-source framework for building, deploying, and serving powerful agentic workflows at scale. The framework includes the **MCP Tool**, a native feature that simplifies the integration of MCP servers into agentic workflows. 85 | 86 | **Key features:** 87 | 88 | - Seamlessly incorporate MCP tools into agentic workflows. 89 | - Quickly instantiate framework-native tools from connected MCP client(s). 90 | - Planned future support for agentic MCP capabilities. 91 | 92 | **Learn more:** 93 | 94 | - [Example of using MCP tools in agentic workflow](https://i-am-bee.github.io/beeai-framework/#/typescript/tools?id=using-the-mcptool-class) 95 | 96 | ### Cline 97 | 98 | [Cline](https://github.com/cline/cline) is an autonomous coding agent in VS Code that edits files, runs commands, uses a browser, and more–with your permission at each step. 99 | 100 | **Key features:** 101 | 102 | - Create and add tools through natural language (e.g. "add a tool that searches the web") 103 | - Share custom MCP servers Cline creates with others via the `~/Documents/Cline/MCP` directory 104 | - Displays configured MCP servers along with their tools, resources, and any error logs 105 | 106 | ### Continue 107 | 108 | [Continue](https://github.com/continuedev/continue) is an open-source AI code assistant, with built-in support for all MCP features. 109 | 110 | **Key features** 111 | 112 | - Type "@" to mention MCP resources 113 | - Prompt templates surface as slash commands 114 | - Use both built-in and MCP tools directly in chat 115 | - Supports VS Code and JetBrains IDEs, with any LLM 116 | 117 | ### Cursor 118 | 119 | [Cursor](https://docs.cursor.com/advanced/model-context-protocol) is an AI code editor. 120 | 121 | **Key Features**: 122 | 123 | - Support for MCP tools in Cursor Composer 124 | - Support for both STDIO and SSE 125 | 126 | ### Emacs Mcp 127 | 128 | [Emacs Mcp](https://github.com/lizqwerscott/mcp.el) is an Emacs client designed to interface with MCP servers, enabling seamless connections and interactions. It provides MCP tool invocation support for AI plugins like [gptel](https://github.com/karthink/gptel) and [llm](https://github.com/ahyatt/llm), adhering to Emacs' standard tool invocation format. This integration enhances the functionality of AI tools within the Emacs ecosystem. 129 | 130 | **Key features:** 131 | 132 | - Provides MCP tool support for Emacs. 133 | 134 | ### Firebase Genkit 135 | 136 | [Genkit](https://github.com/firebase/genkit) is Firebase's SDK for building and integrating GenAI features into applications. The [genkitx-mcp](https://github.com/firebase/genkit/tree/main/js/plugins/mcp) plugin enables consuming MCP servers as a client or creating MCP servers from Genkit tools and prompts. 137 | 138 | **Key features:** 139 | 140 | - Client support for tools and prompts (resources partially supported) 141 | - Rich discovery with support in Genkit's Dev UI playground 142 | - Seamless interoperability with Genkit's existing tools and prompts 143 | - Works across a wide variety of GenAI models from top providers 144 | 145 | ### GenAIScript 146 | 147 | Programmatically assemble prompts for LLMs using [GenAIScript](https://microsoft.github.io/genaiscript/) (in JavaScript). Orchestrate LLMs, tools, and data in JavaScript. 148 | 149 | **Key features:** 150 | 151 | - JavaScript toolbox to work with prompts 152 | - Abstraction to make it easy and productive 153 | - Seamless Visual Studio Code integration 154 | 155 | ### Goose 156 | 157 | [Goose](https://github.com/block/goose) is an open source AI agent that supercharges your software development by automating coding tasks. 158 | 159 | **Key features:** 160 | 161 | - Expose MCP functionality to Goose through tools. 162 | - MCPs can be installed directly via the [extensions directory](https://block.github.io/goose/v1/extensions/), CLI, or UI. 163 | - Goose allows you to extend its functionality by [building your own MCP servers](https://block.github.io/goose/docs/tutorials/custom-extensions). 164 | - Includes built-in tools for development, web scraping, automation, memory, and integrations with JetBrains and Google Drive. 165 | 166 | ### LibreChat 167 | 168 | [LibreChat](https://github.com/danny-avila/LibreChat) is an open-source, customizable AI chat UI that supports multiple AI providers, now including MCP integration. 169 | 170 | **Key features:** 171 | 172 | - Extend current tool ecosystem, including [Code Interpreter](https://www.librechat.ai/docs/features/code_interpreter) and Image generation tools, through MCP servers 173 | - Add tools to customizable [Agents](https://www.librechat.ai/docs/features/agents), using a variety of LLMs from top providers 174 | - Open-source and self-hostable, with secure multi-user support 175 | - Future roadmap includes expanded MCP feature support 176 | 177 | ### mcp-agent 178 | 179 | [mcp-agent] is a simple, composable framework to build agents using Model Context Protocol. 180 | 181 | **Key features:** 182 | 183 | - Automatic connection management of MCP servers. 184 | - Expose tools from multiple servers to an LLM. 185 | - Implements every pattern defined in [Building Effective Agents](https://www.anthropic.com/research/building-effective-agents). 186 | - Supports workflow pause/resume signals, such as waiting for human feedback. 187 | 188 | ### Roo Code 189 | 190 | [Roo Code](https://roocode.com) enables AI coding assistance via MCP. 191 | 192 | **Key features:** 193 | 194 | - Support for MCP tools and resources 195 | - Integration with development workflows 196 | - Extensible AI capabilities 197 | 198 | ### Sourcegraph Cody 199 | 200 | [Cody](https://openctx.org/docs/providers/modelcontextprotocol) is Sourcegraph's AI coding assistant, which implements MCP through OpenCTX. 201 | 202 | **Key features:** 203 | 204 | - Support for MCP resources 205 | - Integration with Sourcegraph's code intelligence 206 | - Uses OpenCTX as an abstraction layer 207 | - Future support planned for additional MCP features 208 | 209 | ### Superinterface 210 | 211 | [Superinterface](https://superinterface.ai) is AI infrastructure and a developer platform to build in-app AI assistants with support for MCP, interactive components, client-side function calling and more. 212 | 213 | **Key features:** 214 | 215 | - Use tools from MCP servers in assistants embedded via React components or script tags 216 | - SSE transport support 217 | - Use any AI model from any AI provider (OpenAI, Anthropic, Ollama, others) 218 | 219 | ### TheiaAI/TheiaIDE 220 | 221 | [Theia AI](https://eclipsesource.com/blogs/2024/10/07/introducing-theia-ai/) is a framework for building AI-enhanced tools and IDEs. The [AI-powered Theia IDE](https://eclipsesource.com/blogs/2024/10/08/introducting-ai-theia-ide/) is an open and flexible development environment built on Theia AI. 222 | 223 | **Key features:** 224 | 225 | - **Tool Integration**: Theia AI enables AI agents, including those in the Theia IDE, to utilize MCP servers for seamless tool interaction. 226 | - **Customizable Prompts**: The Theia IDE allows users to define and adapt prompts, dynamically integrating MCP servers for tailored workflows. 227 | - **Custom agents**: The Theia IDE supports creating custom agents that leverage MCP capabilities, enabling users to design dedicated workflows on the fly. 228 | 229 | Theia AI and Theia IDE's MCP integration provide users with flexibility, making them powerful platforms for exploring and adapting MCP. 230 | 231 | **Learn more:** 232 | 233 | - [Theia IDE and Theia AI MCP Announcement](https://eclipsesource.com/blogs/2024/12/19/theia-ide-and-theia-ai-support-mcp/) 234 | - [Download the AI-powered Theia IDE](https://theia-ide.org/) 235 | 236 | ### Windsurf Editor 237 | 238 | [Windsurf Editor](https://codeium.com/windsurf) is an agentic IDE that combines AI assistance with developer workflows. It features an innovative AI Flow system that enables both collaborative and independent AI interactions while maintaining developer control. 239 | 240 | **Key features:** 241 | 242 | - Revolutionary AI Flow paradigm for human-AI collaboration 243 | - Intelligent code generation and understanding 244 | - Rich development tools with multi-model support 245 | 246 | ### Zed 247 | 248 | [Zed](https://zed.dev/docs/assistant/model-context-protocol) is a high-performance code editor with built-in MCP support, focusing on prompt templates and tool integration. 249 | 250 | **Key features:** 251 | 252 | - Prompt templates surface as slash commands in the editor 253 | - Tool integration for enhanced coding workflows 254 | - Tight integration with editor features and workspace context 255 | - Does not support MCP resources 256 | 257 | ### OpenSumi 258 | 259 | [OpenSumi](https://github.com/opensumi/core) is a framework helps you quickly build AI Native IDE products. 260 | 261 | **Key features:** 262 | 263 | - Supports MCP tools in OpenSumi 264 | - Supports built-in IDE MCP servers and custom MCP servers 265 | 266 | ## Adding MCP support to your application 267 | 268 | If you've added MCP support to your application, we encourage you to submit a pull request to add it to this list. MCP integration can provide your users with powerful contextual AI capabilities and make your application part of the growing MCP ecosystem. 269 | 270 | Benefits of adding MCP support: 271 | 272 | - Enable users to bring their own context and tools 273 | - Join a growing ecosystem of interoperable AI applications 274 | - Provide users with flexible integration options 275 | - Support local-first AI workflows 276 | 277 | To get started with implementing MCP in your application, check out our [Python](https://github.com/modelcontextprotocol/python-sdk) or [TypeScript SDK Documentation](https://github.com/modelcontextprotocol/typescript-sdk) 278 | 279 | ## Updates and corrections 280 | 281 | This list is maintained by the community. If you notice any inaccuracies or would like to update information about MCP support in your application, please submit a pull request or [open an issue in our documentation repository](https://github.com/modelcontextprotocol/docs/issues). 282 | 283 | # Contributing 284 | 285 | Source: https://modelcontextprotocol.io/development/contributing 286 | 287 | How to participate in Model Context Protocol development 288 | 289 | 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. 290 | 291 | All contributors must adhere to our [Code of Conduct](https://github.com/modelcontextprotocol/.github/blob/main/CODE_OF_CONDUCT.md). 292 | 293 | For questions and discussions, please use [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions). 294 | 295 | # Roadmap 296 | 297 | Source: https://modelcontextprotocol.io/development/roadmap 298 | 299 | Our plans for evolving Model Context Protocol (H1 2025) 300 | 301 | The Model Context Protocol is rapidly evolving. This page outlines our current thinking on key priorities and future direction for **the first half of 2025**, though these may change significantly as the project develops. 302 | 303 | <Note>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.</Note> 304 | 305 | We encourage community participation! Each section links to relevant discussions where you can learn more and contribute your thoughts. 306 | 307 | ## Remote MCP Support 308 | 309 | Our top priority is enabling [remote MCP connections](https://github.com/modelcontextprotocol/specification/discussions/102), allowing clients to securely connect to MCP servers over the internet. Key initiatives include: 310 | 311 | - [**Authentication & Authorization**](https://github.com/modelcontextprotocol/specification/discussions/64): Adding standardized auth capabilities, particularly focused on OAuth 2.0 support. 312 | 313 | - [**Service Discovery**](https://github.com/modelcontextprotocol/specification/discussions/69): Defining how clients can discover and connect to remote MCP servers. 314 | 315 | - [**Stateless Operations**](https://github.com/modelcontextprotocol/specification/discussions/102): Thinking about whether MCP could encompass serverless environments too, where they will need to be mostly stateless. 316 | 317 | ## Reference Implementations 318 | 319 | To help developers build with MCP, we want to offer documentation for: 320 | 321 | - **Client Examples**: Comprehensive reference client implementation(s), demonstrating all protocol features 322 | - **Protocol Drafting**: Streamlined process for proposing and incorporating new protocol features 323 | 324 | ## Distribution & Discovery 325 | 326 | Looking ahead, we're exploring ways to make MCP servers more accessible. Some areas we may investigate include: 327 | 328 | - **Package Management**: Standardized packaging format for MCP servers 329 | - **Installation Tools**: Simplified server installation across MCP clients 330 | - **Sandboxing**: Improved security through server isolation 331 | - **Server Registry**: A common directory for discovering available MCP servers 332 | 333 | ## Agent Support 334 | 335 | We're expanding MCP's capabilities for [complex agentic workflows](https://github.com/modelcontextprotocol/specification/discussions/111), particularly focusing on: 336 | 337 | - [**Hierarchical Agent Systems**](https://github.com/modelcontextprotocol/specification/discussions/94): Improved support for trees of agents through namespacing and topology awareness. 338 | 339 | - [**Interactive Workflows**](https://github.com/modelcontextprotocol/specification/issues/97): Better handling of user permissions and information requests across agent hierarchies, and ways to send output to users instead of models. 340 | 341 | - [**Streaming Results**](https://github.com/modelcontextprotocol/specification/issues/117): Real-time updates from long-running agent operations. 342 | 343 | ## Broader Ecosystem 344 | 345 | We're also invested in: 346 | 347 | - **Community-Led Standards Development**: Fostering a collaborative ecosystem where all AI providers can help shape MCP as an open standard through equal participation and shared governance, ensuring it meets the needs of diverse AI applications and use cases. 348 | - [**Additional Modalities**](https://github.com/modelcontextprotocol/specification/discussions/88): Expanding beyond text to support audio, video, and other formats. 349 | - \[**Standardization**] Considering standardization through a standardization body. 350 | 351 | ## Get Involved 352 | 353 | We welcome community participation in shaping MCP's future. Visit our [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions) to join the conversation and contribute your ideas. 354 | 355 | # What's New 356 | 357 | Source: https://modelcontextprotocol.io/development/updates 358 | 359 | The latest updates and improvements to MCP 360 | 361 | <Update label="2025-02-14" description="Java SDK released"> 362 | * We're excited to announce that the Java SDK developed by Spring AI at VMware Tanzu is now 363 | the official [Java SDK](https://github.com/modelcontextprotocol/java-sdk) for MCP. 364 | This joins our existing Kotlin SDK in our growing list of supported languages. 365 | The Spring AI team will maintain the SDK as an integral part of the Model Context Protocol 366 | organization. We're thrilled to welcome them to the MCP community! 367 | </Update> 368 | 369 | <Update label="2025-01-27" description="Python SDK 1.2.1"> 370 | * Version [1.2.1](https://github.com/modelcontextprotocol/python-sdk/releases/tag/v1.2.1) of the MCP Python SDK has been released, 371 | delivering important stability improvements and bug fixes. 372 | </Update> 373 | 374 | <Update label="2025-01-18" description="SDK and Server Improvements"> 375 | * Simplified, express-like API in the [TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) 376 | * Added 8 new clients to the [clients page](https://modelcontextprotocol.io/clients) 377 | </Update> 378 | 379 | <Update label="2025-01-03" description="SDK and Server Improvements"> 380 | * FastMCP API in the [Python SDK](https://github.com/modelcontextprotocol/python-sdk) 381 | * Dockerized MCP servers in the [servers repo](https://github.com/modelcontextprotocol/servers) 382 | </Update> 383 | 384 | <Update label="2024-12-21" description="Kotlin SDK released"> 385 | * Jetbrains released a Kotlin SDK for MCP! 386 | * For a sample MCP Kotlin server, check out [this repository](https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/kotlin-mcp-server) 387 | </Update> 388 | 389 | # Core architecture 390 | 391 | Source: https://modelcontextprotocol.io/docs/concepts/architecture 392 | 393 | Understand how MCP connects clients, servers, and LLMs 394 | 395 | 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. 396 | 397 | ## Overview 398 | 399 | MCP follows a client-server architecture where: 400 | 401 | - **Hosts** are LLM applications (like Claude Desktop or IDEs) that initiate connections 402 | - **Clients** maintain 1:1 connections with servers, inside the host application 403 | - **Servers** provide context, tools, and prompts to clients 404 | 405 | ```mermaid 406 | flowchart LR 407 | subgraph " Host " 408 | client1[MCP Client] 409 | client2[MCP Client] 410 | end 411 | subgraph "Server Process" 412 | server1[MCP Server] 413 | end 414 | subgraph "Server Process" 415 | server2[MCP Server] 416 | end 417 | 418 | client1 <-->|Transport Layer| server1 419 | client2 <-->|Transport Layer| server2 420 | ``` 421 | 422 | ## Core components 423 | 424 | ### Protocol layer 425 | 426 | The protocol layer handles message framing, request/response linking, and high-level communication patterns. 427 | 428 | <Tabs> 429 | <Tab title="TypeScript"> 430 | ```typescript 431 | class Protocol<Request, Notification, Result> { 432 | // Handle incoming requests 433 | setRequestHandler<T>(schema: T, handler: (request: T, extra: RequestHandlerExtra) => Promise<Result>): void 434 | 435 | // Handle incoming notifications 436 | setNotificationHandler<T>(schema: T, handler: (notification: T) => Promise<void>): void 437 | 438 | // Send requests and await responses 439 | request<T>(request: Request, schema: T, options?: RequestOptions): Promise<T> 440 | 441 | // Send one-way notifications 442 | notification(notification: Notification): Promise<void> 443 | } 444 | ``` 445 | 446 | </Tab> 447 | 448 | <Tab title="Python"> 449 | ```python 450 | class Session(BaseSession[RequestT, NotificationT, ResultT]): 451 | async def send_request( 452 | self, 453 | request: RequestT, 454 | result_type: type[Result] 455 | ) -> Result: 456 | """ 457 | Send request and wait for response. Raises McpError if response contains error. 458 | """ 459 | # Request handling implementation 460 | 461 | async def send_notification( 462 | self, 463 | notification: NotificationT 464 | ) -> None: 465 | """Send one-way notification that doesn't expect response.""" 466 | # Notification handling implementation 467 | 468 | async def _received_request( 469 | self, 470 | responder: RequestResponder[ReceiveRequestT, ResultT] 471 | ) -> None: 472 | """Handle incoming request from other side.""" 473 | # Request handling implementation 474 | 475 | async def _received_notification( 476 | self, 477 | notification: ReceiveNotificationT 478 | ) -> None: 479 | """Handle incoming notification from other side.""" 480 | # Notification handling implementation 481 | ``` 482 | 483 | </Tab> 484 | </Tabs> 485 | 486 | Key classes include: 487 | 488 | - `Protocol` 489 | - `Client` 490 | - `Server` 491 | 492 | ### Transport layer 493 | 494 | The transport layer handles the actual communication between clients and servers. MCP supports multiple transport mechanisms: 495 | 496 | 1. **Stdio transport** 497 | 498 | - Uses standard input/output for communication 499 | - Ideal for local processes 500 | 501 | 2. **HTTP with SSE transport** 502 | - Uses Server-Sent Events for server-to-client messages 503 | - HTTP POST for client-to-server messages 504 | 505 | 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. 506 | 507 | ### Message types 508 | 509 | MCP has these main types of messages: 510 | 511 | 1. **Requests** expect a response from the other side: 512 | 513 | ```typescript 514 | interface Request { 515 | method: string; 516 | params?: { ... }; 517 | } 518 | ``` 519 | 520 | 2. **Results** are successful responses to requests: 521 | 522 | ```typescript 523 | interface Result { 524 | [key: string]: unknown; 525 | } 526 | ``` 527 | 528 | 3. **Errors** indicate that a request failed: 529 | 530 | ```typescript 531 | interface Error { 532 | code: number; 533 | message: string; 534 | data?: unknown; 535 | } 536 | ``` 537 | 538 | 4. **Notifications** are one-way messages that don't expect a response: 539 | ```typescript 540 | interface Notification { 541 | method: string; 542 | params?: { ... }; 543 | } 544 | ``` 545 | 546 | ## Connection lifecycle 547 | 548 | ### 1. Initialization 549 | 550 | ```mermaid 551 | sequenceDiagram 552 | participant Client 553 | participant Server 554 | 555 | Client->>Server: initialize request 556 | Server->>Client: initialize response 557 | Client->>Server: initialized notification 558 | 559 | Note over Client,Server: Connection ready for use 560 | ``` 561 | 562 | 1. Client sends `initialize` request with protocol version and capabilities 563 | 2. Server responds with its protocol version and capabilities 564 | 3. Client sends `initialized` notification as acknowledgment 565 | 4. Normal message exchange begins 566 | 567 | ### 2. Message exchange 568 | 569 | After initialization, the following patterns are supported: 570 | 571 | - **Request-Response**: Client or server sends requests, the other responds 572 | - **Notifications**: Either party sends one-way messages 573 | 574 | ### 3. Termination 575 | 576 | Either party can terminate the connection: 577 | 578 | - Clean shutdown via `close()` 579 | - Transport disconnection 580 | - Error conditions 581 | 582 | ## Error handling 583 | 584 | MCP defines these standard error codes: 585 | 586 | ```typescript 587 | enum ErrorCode { 588 | // Standard JSON-RPC error codes 589 | ParseError = -32700, 590 | InvalidRequest = -32600, 591 | MethodNotFound = -32601, 592 | InvalidParams = -32602, 593 | InternalError = -32603, 594 | } 595 | ``` 596 | 597 | SDKs and applications can define their own error codes above -32000. 598 | 599 | Errors are propagated through: 600 | 601 | - Error responses to requests 602 | - Error events on transports 603 | - Protocol-level error handlers 604 | 605 | ## Implementation example 606 | 607 | Here's a basic example of implementing an MCP server: 608 | 609 | <Tabs> 610 | <Tab title="TypeScript"> 611 | ```typescript 612 | import { Server } from "@modelcontextprotocol/sdk/server/index.js"; 613 | import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; 614 | 615 | const server = new Server({ 616 | name: "example-server", 617 | version: "1.0.0" 618 | }, { 619 | capabilities: { 620 | resources: {} 621 | } 622 | }); 623 | 624 | // Handle requests 625 | server.setRequestHandler(ListResourcesRequestSchema, async () => { 626 | return { 627 | resources: [ 628 | { 629 | uri: "example://resource", 630 | name: "Example Resource" 631 | } 632 | ] 633 | }; 634 | }); 635 | 636 | // Connect transport 637 | const transport = new StdioServerTransport(); 638 | await server.connect(transport); 639 | ``` 640 | 641 | </Tab> 642 | 643 | <Tab title="Python"> 644 | ```python 645 | import asyncio 646 | import mcp.types as types 647 | from mcp.server import Server 648 | from mcp.server.stdio import stdio_server 649 | 650 | app = Server("example-server") 651 | 652 | @app.list_resources() 653 | async def list_resources() -> list[types.Resource]: 654 | return [ 655 | types.Resource( 656 | uri="example://resource", 657 | name="Example Resource" 658 | ) 659 | ] 660 | 661 | async def main(): 662 | async with stdio_server() as streams: 663 | await app.run( 664 | streams[0], 665 | streams[1], 666 | app.create_initialization_options() 667 | ) 668 | 669 | if __name__ == "__main__": 670 | asyncio.run(main) 671 | ``` 672 | 673 | </Tab> 674 | </Tabs> 675 | 676 | ## Best practices 677 | 678 | ### Transport selection 679 | 680 | 1. **Local communication** 681 | 682 | - Use stdio transport for local processes 683 | - Efficient for same-machine communication 684 | - Simple process management 685 | 686 | 2. **Remote communication** 687 | - Use SSE for scenarios requiring HTTP compatibility 688 | - Consider security implications including authentication and authorization 689 | 690 | ### Message handling 691 | 692 | 1. **Request processing** 693 | 694 | - Validate inputs thoroughly 695 | - Use type-safe schemas 696 | - Handle errors gracefully 697 | - Implement timeouts 698 | 699 | 2. **Progress reporting** 700 | 701 | - Use progress tokens for long operations 702 | - Report progress incrementally 703 | - Include total progress when known 704 | 705 | 3. **Error management** 706 | - Use appropriate error codes 707 | - Include helpful error messages 708 | - Clean up resources on errors 709 | 710 | ## Security considerations 711 | 712 | 1. **Transport security** 713 | 714 | - Use TLS for remote connections 715 | - Validate connection origins 716 | - Implement authentication when needed 717 | 718 | 2. **Message validation** 719 | 720 | - Validate all incoming messages 721 | - Sanitize inputs 722 | - Check message size limits 723 | - Verify JSON-RPC format 724 | 725 | 3. **Resource protection** 726 | 727 | - Implement access controls 728 | - Validate resource paths 729 | - Monitor resource usage 730 | - Rate limit requests 731 | 732 | 4. **Error handling** 733 | - Don't leak sensitive information 734 | - Log security-relevant errors 735 | - Implement proper cleanup 736 | - Handle DoS scenarios 737 | 738 | ## Debugging and monitoring 739 | 740 | 1. **Logging** 741 | 742 | - Log protocol events 743 | - Track message flow 744 | - Monitor performance 745 | - Record errors 746 | 747 | 2. **Diagnostics** 748 | 749 | - Implement health checks 750 | - Monitor connection state 751 | - Track resource usage 752 | - Profile performance 753 | 754 | 3. **Testing** 755 | - Test different transports 756 | - Verify error handling 757 | - Check edge cases 758 | - Load test servers 759 | 760 | # Prompts 761 | 762 | Source: https://modelcontextprotocol.io/docs/concepts/prompts 763 | 764 | Create reusable prompt templates and workflows 765 | 766 | 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. 767 | 768 | <Note> 769 | 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. 770 | </Note> 771 | 772 | ## Overview 773 | 774 | Prompts in MCP are predefined templates that can: 775 | 776 | - Accept dynamic arguments 777 | - Include context from resources 778 | - Chain multiple interactions 779 | - Guide specific workflows 780 | - Surface as UI elements (like slash commands) 781 | 782 | ## Prompt structure 783 | 784 | Each prompt is defined with: 785 | 786 | ```typescript 787 | { 788 | name: string; // Unique identifier for the prompt 789 | description?: string; // Human-readable description 790 | arguments?: [ // Optional list of arguments 791 | { 792 | name: string; // Argument identifier 793 | description?: string; // Argument description 794 | required?: boolean; // Whether argument is required 795 | } 796 | ] 797 | } 798 | ``` 799 | 800 | ## Discovering prompts 801 | 802 | Clients can discover available prompts through the `prompts/list` endpoint: 803 | 804 | ```typescript 805 | // Request 806 | { 807 | method: 'prompts/list'; 808 | } 809 | 810 | // Response 811 | { 812 | prompts: [ 813 | { 814 | name: 'analyze-code', 815 | description: 'Analyze code for potential improvements', 816 | arguments: [ 817 | { 818 | name: 'language', 819 | description: 'Programming language', 820 | required: true, 821 | }, 822 | ], 823 | }, 824 | ]; 825 | } 826 | ``` 827 | 828 | ## Using prompts 829 | 830 | To use a prompt, clients make a `prompts/get` request: 831 | 832 | ````typescript 833 | // Request 834 | { 835 | method: "prompts/get", 836 | params: { 837 | name: "analyze-code", 838 | arguments: { 839 | language: "python" 840 | } 841 | } 842 | } 843 | 844 | // Response 845 | { 846 | description: "Analyze Python code for potential improvements", 847 | messages: [ 848 | { 849 | role: "user", 850 | content: { 851 | type: "text", 852 | 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```" 853 | } 854 | } 855 | ] 856 | } 857 | ```` 858 | 859 | ## Dynamic prompts 860 | 861 | Prompts can be dynamic and include: 862 | 863 | ### Embedded resource context 864 | 865 | ```json 866 | { 867 | "name": "analyze-project", 868 | "description": "Analyze project logs and code", 869 | "arguments": [ 870 | { 871 | "name": "timeframe", 872 | "description": "Time period to analyze logs", 873 | "required": true 874 | }, 875 | { 876 | "name": "fileUri", 877 | "description": "URI of code file to review", 878 | "required": true 879 | } 880 | ] 881 | } 882 | ``` 883 | 884 | When handling the `prompts/get` request: 885 | 886 | ```json 887 | { 888 | "messages": [ 889 | { 890 | "role": "user", 891 | "content": { 892 | "type": "text", 893 | "text": "Analyze these system logs and the code file for any issues:" 894 | } 895 | }, 896 | { 897 | "role": "user", 898 | "content": { 899 | "type": "resource", 900 | "resource": { 901 | "uri": "logs://recent?timeframe=1h", 902 | "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", 903 | "mimeType": "text/plain" 904 | } 905 | } 906 | }, 907 | { 908 | "role": "user", 909 | "content": { 910 | "type": "resource", 911 | "resource": { 912 | "uri": "file:///path/to/code.py", 913 | "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", 914 | "mimeType": "text/x-python" 915 | } 916 | } 917 | } 918 | ] 919 | } 920 | ``` 921 | 922 | ### Multi-step workflows 923 | 924 | ```typescript 925 | const debugWorkflow = { 926 | name: 'debug-error', 927 | async getMessages(error: string) { 928 | return [ 929 | { 930 | role: 'user', 931 | content: { 932 | type: 'text', 933 | text: `Here's an error I'm seeing: ${error}`, 934 | }, 935 | }, 936 | { 937 | role: 'assistant', 938 | content: { 939 | type: 'text', 940 | text: "I'll help analyze this error. What have you tried so far?", 941 | }, 942 | }, 943 | { 944 | role: 'user', 945 | content: { 946 | type: 'text', 947 | text: "I've tried restarting the service, but the error persists.", 948 | }, 949 | }, 950 | ]; 951 | }, 952 | }; 953 | ``` 954 | 955 | ## Example implementation 956 | 957 | Here's a complete example of implementing prompts in an MCP server: 958 | 959 | <Tabs> 960 | <Tab title="TypeScript"> 961 | ```typescript 962 | import { Server } from "@modelcontextprotocol/sdk/server"; 963 | import { 964 | ListPromptsRequestSchema, 965 | GetPromptRequestSchema 966 | } from "@modelcontextprotocol/sdk/types"; 967 | 968 | const PROMPTS = { 969 | "git-commit": { 970 | name: "git-commit", 971 | description: "Generate a Git commit message", 972 | arguments: [ 973 | { 974 | name: "changes", 975 | description: "Git diff or description of changes", 976 | required: true 977 | } 978 | ] 979 | }, 980 | "explain-code": { 981 | name: "explain-code", 982 | description: "Explain how code works", 983 | arguments: [ 984 | { 985 | name: "code", 986 | description: "Code to explain", 987 | required: true 988 | }, 989 | { 990 | name: "language", 991 | description: "Programming language", 992 | required: false 993 | } 994 | ] 995 | } 996 | }; 997 | 998 | const server = new Server({ 999 | name: "example-prompts-server", 1000 | version: "1.0.0" 1001 | }, { 1002 | capabilities: { 1003 | prompts: {} 1004 | } 1005 | }); 1006 | 1007 | // List available prompts 1008 | server.setRequestHandler(ListPromptsRequestSchema, async () => { 1009 | return { 1010 | prompts: Object.values(PROMPTS) 1011 | }; 1012 | }); 1013 | 1014 | // Get specific prompt 1015 | server.setRequestHandler(GetPromptRequestSchema, async (request) => { 1016 | const prompt = PROMPTS[request.params.name]; 1017 | if (!prompt) { 1018 | throw new Error(`Prompt not found: ${request.params.name}`); 1019 | } 1020 | 1021 | if (request.params.name === "git-commit") { 1022 | return { 1023 | messages: [ 1024 | { 1025 | role: "user", 1026 | content: { 1027 | type: "text", 1028 | text: `Generate a concise but descriptive commit message for these changes:\n\n${request.params.arguments?.changes}` 1029 | } 1030 | } 1031 | ] 1032 | }; 1033 | } 1034 | 1035 | if (request.params.name === "explain-code") { 1036 | const language = request.params.arguments?.language || "Unknown"; 1037 | return { 1038 | messages: [ 1039 | { 1040 | role: "user", 1041 | content: { 1042 | type: "text", 1043 | text: `Explain how this ${language} code works:\n\n${request.params.arguments?.code}` 1044 | } 1045 | } 1046 | ] 1047 | }; 1048 | } 1049 | 1050 | throw new Error("Prompt implementation not found"); 1051 | }); 1052 | ``` 1053 | 1054 | </Tab> 1055 | 1056 | <Tab title="Python"> 1057 | ```python 1058 | from mcp.server import Server 1059 | import mcp.types as types 1060 | 1061 | # Define available prompts 1062 | PROMPTS = { 1063 | "git-commit": types.Prompt( 1064 | name="git-commit", 1065 | description="Generate a Git commit message", 1066 | arguments=[ 1067 | types.PromptArgument( 1068 | name="changes", 1069 | description="Git diff or description of changes", 1070 | required=True 1071 | ) 1072 | ], 1073 | ), 1074 | "explain-code": types.Prompt( 1075 | name="explain-code", 1076 | description="Explain how code works", 1077 | arguments=[ 1078 | types.PromptArgument( 1079 | name="code", 1080 | description="Code to explain", 1081 | required=True 1082 | ), 1083 | types.PromptArgument( 1084 | name="language", 1085 | description="Programming language", 1086 | required=False 1087 | ) 1088 | ], 1089 | ) 1090 | } 1091 | 1092 | # Initialize server 1093 | app = Server("example-prompts-server") 1094 | 1095 | @app.list_prompts() 1096 | async def list_prompts() -> list[types.Prompt]: 1097 | return list(PROMPTS.values()) 1098 | 1099 | @app.get_prompt() 1100 | async def get_prompt( 1101 | name: str, arguments: dict[str, str] | None = None 1102 | ) -> types.GetPromptResult: 1103 | if name not in PROMPTS: 1104 | raise ValueError(f"Prompt not found: {name}") 1105 | 1106 | if name == "git-commit": 1107 | changes = arguments.get("changes") if arguments else "" 1108 | return types.GetPromptResult( 1109 | messages=[ 1110 | types.PromptMessage( 1111 | role="user", 1112 | content=types.TextContent( 1113 | type="text", 1114 | text=f"Generate a concise but descriptive commit message " 1115 | f"for these changes:\n\n{changes}" 1116 | ) 1117 | ) 1118 | ] 1119 | ) 1120 | 1121 | if name == "explain-code": 1122 | code = arguments.get("code") if arguments else "" 1123 | language = arguments.get("language", "Unknown") if arguments else "Unknown" 1124 | return types.GetPromptResult( 1125 | messages=[ 1126 | types.PromptMessage( 1127 | role="user", 1128 | content=types.TextContent( 1129 | type="text", 1130 | text=f"Explain how this {language} code works:\n\n{code}" 1131 | ) 1132 | ) 1133 | ] 1134 | ) 1135 | 1136 | raise ValueError("Prompt implementation not found") 1137 | ``` 1138 | 1139 | </Tab> 1140 | </Tabs> 1141 | 1142 | ## Best practices 1143 | 1144 | When implementing prompts: 1145 | 1146 | 1. Use clear, descriptive prompt names 1147 | 2. Provide detailed descriptions for prompts and arguments 1148 | 3. Validate all required arguments 1149 | 4. Handle missing arguments gracefully 1150 | 5. Consider versioning for prompt templates 1151 | 6. Cache dynamic content when appropriate 1152 | 7. Implement error handling 1153 | 8. Document expected argument formats 1154 | 9. Consider prompt composability 1155 | 10. Test prompts with various inputs 1156 | 1157 | ## UI integration 1158 | 1159 | Prompts can be surfaced in client UIs as: 1160 | 1161 | - Slash commands 1162 | - Quick actions 1163 | - Context menu items 1164 | - Command palette entries 1165 | - Guided workflows 1166 | - Interactive forms 1167 | 1168 | ## Updates and changes 1169 | 1170 | Servers can notify clients about prompt changes: 1171 | 1172 | 1. Server capability: `prompts.listChanged` 1173 | 2. Notification: `notifications/prompts/list_changed` 1174 | 3. Client re-fetches prompt list 1175 | 1176 | ## Security considerations 1177 | 1178 | When implementing prompts: 1179 | 1180 | - Validate all arguments 1181 | - Sanitize user input 1182 | - Consider rate limiting 1183 | - Implement access controls 1184 | - Audit prompt usage 1185 | - Handle sensitive data appropriately 1186 | - Validate generated content 1187 | - Implement timeouts 1188 | - Consider prompt injection risks 1189 | - Document security requirements 1190 | 1191 | # Resources 1192 | 1193 | Source: https://modelcontextprotocol.io/docs/concepts/resources 1194 | 1195 | Expose data and content from your servers to LLMs 1196 | 1197 | 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. 1198 | 1199 | <Note> 1200 | Resources are designed to be **application-controlled**, meaning that the client application can decide how and when they should be used. 1201 | Different MCP clients may handle resources differently. For example: 1202 | 1203 | - Claude Desktop currently requires users to explicitly select resources before they can be used 1204 | - Other clients might automatically select resources based on heuristics 1205 | - Some implementations may even allow the AI model itself to determine which resources to use 1206 | 1207 | 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). 1208 | </Note> 1209 | 1210 | ## Overview 1211 | 1212 | Resources represent any kind of data that an MCP server wants to make available to clients. This can include: 1213 | 1214 | - File contents 1215 | - Database records 1216 | - API responses 1217 | - Live system data 1218 | - Screenshots and images 1219 | - Log files 1220 | - And more 1221 | 1222 | Each resource is identified by a unique URI and can contain either text or binary data. 1223 | 1224 | ## Resource URIs 1225 | 1226 | Resources are identified using URIs that follow this format: 1227 | 1228 | ``` 1229 | [protocol]://[host]/[path] 1230 | ``` 1231 | 1232 | For example: 1233 | 1234 | - `file:///home/user/documents/report.pdf` 1235 | - `postgres://database/customers/schema` 1236 | - `screen://localhost/display1` 1237 | 1238 | The protocol and path structure is defined by the MCP server implementation. Servers can define their own custom URI schemes. 1239 | 1240 | ## Resource types 1241 | 1242 | Resources can contain two types of content: 1243 | 1244 | ### Text resources 1245 | 1246 | Text resources contain UTF-8 encoded text data. These are suitable for: 1247 | 1248 | - Source code 1249 | - Configuration files 1250 | - Log files 1251 | - JSON/XML data 1252 | - Plain text 1253 | 1254 | ### Binary resources 1255 | 1256 | Binary resources contain raw binary data encoded in base64. These are suitable for: 1257 | 1258 | - Images 1259 | - PDFs 1260 | - Audio files 1261 | - Video files 1262 | - Other non-text formats 1263 | 1264 | ## Resource discovery 1265 | 1266 | Clients can discover available resources through two main methods: 1267 | 1268 | ### Direct resources 1269 | 1270 | Servers expose a list of concrete resources via the `resources/list` endpoint. Each resource includes: 1271 | 1272 | ```typescript 1273 | { 1274 | uri: string; // Unique identifier for the resource 1275 | name: string; // Human-readable name 1276 | description?: string; // Optional description 1277 | mimeType?: string; // Optional MIME type 1278 | } 1279 | ``` 1280 | 1281 | ### Resource templates 1282 | 1283 | For dynamic resources, servers can expose [URI templates](https://datatracker.ietf.org/doc/html/rfc6570) that clients can use to construct valid resource URIs: 1284 | 1285 | ```typescript 1286 | { 1287 | uriTemplate: string; // URI template following RFC 6570 1288 | name: string; // Human-readable name for this type 1289 | description?: string; // Optional description 1290 | mimeType?: string; // Optional MIME type for all matching resources 1291 | } 1292 | ``` 1293 | 1294 | ## Reading resources 1295 | 1296 | To read a resource, clients make a `resources/read` request with the resource URI. 1297 | 1298 | The server responds with a list of resource contents: 1299 | 1300 | ```typescript 1301 | { 1302 | contents: [ 1303 | { 1304 | uri: string; // The URI of the resource 1305 | mimeType?: string; // Optional MIME type 1306 | 1307 | // One of: 1308 | text?: string; // For text resources 1309 | blob?: string; // For binary resources (base64 encoded) 1310 | } 1311 | ] 1312 | } 1313 | ``` 1314 | 1315 | <Tip> 1316 | 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. 1317 | </Tip> 1318 | 1319 | ## Resource updates 1320 | 1321 | MCP supports real-time updates for resources through two mechanisms: 1322 | 1323 | ### List changes 1324 | 1325 | Servers can notify clients when their list of available resources changes via the `notifications/resources/list_changed` notification. 1326 | 1327 | ### Content changes 1328 | 1329 | Clients can subscribe to updates for specific resources: 1330 | 1331 | 1. Client sends `resources/subscribe` with resource URI 1332 | 2. Server sends `notifications/resources/updated` when the resource changes 1333 | 3. Client can fetch latest content with `resources/read` 1334 | 4. Client can unsubscribe with `resources/unsubscribe` 1335 | 1336 | ## Example implementation 1337 | 1338 | Here's a simple example of implementing resource support in an MCP server: 1339 | 1340 | <Tabs> 1341 | <Tab title="TypeScript"> 1342 | ```typescript 1343 | const server = new Server({ 1344 | name: "example-server", 1345 | version: "1.0.0" 1346 | }, { 1347 | capabilities: { 1348 | resources: {} 1349 | } 1350 | }); 1351 | 1352 | // List available resources 1353 | server.setRequestHandler(ListResourcesRequestSchema, async () => { 1354 | return { 1355 | resources: [ 1356 | { 1357 | uri: "file:///logs/app.log", 1358 | name: "Application Logs", 1359 | mimeType: "text/plain" 1360 | } 1361 | ] 1362 | }; 1363 | }); 1364 | 1365 | // Read resource contents 1366 | server.setRequestHandler(ReadResourceRequestSchema, async (request) => { 1367 | const uri = request.params.uri; 1368 | 1369 | if (uri === "file:///logs/app.log") { 1370 | const logContents = await readLogFile(); 1371 | return { 1372 | contents: [ 1373 | { 1374 | uri, 1375 | mimeType: "text/plain", 1376 | text: logContents 1377 | } 1378 | ] 1379 | }; 1380 | } 1381 | 1382 | throw new Error("Resource not found"); 1383 | }); 1384 | ``` 1385 | 1386 | </Tab> 1387 | 1388 | <Tab title="Python"> 1389 | ```python 1390 | app = Server("example-server") 1391 | 1392 | @app.list_resources() 1393 | async def list_resources() -> list[types.Resource]: 1394 | return [ 1395 | types.Resource( 1396 | uri="file:///logs/app.log", 1397 | name="Application Logs", 1398 | mimeType="text/plain" 1399 | ) 1400 | ] 1401 | 1402 | @app.read_resource() 1403 | async def read_resource(uri: AnyUrl) -> str: 1404 | if str(uri) == "file:///logs/app.log": 1405 | log_contents = await read_log_file() 1406 | return log_contents 1407 | 1408 | raise ValueError("Resource not found") 1409 | 1410 | # Start server 1411 | async with stdio_server() as streams: 1412 | await app.run( 1413 | streams[0], 1414 | streams[1], 1415 | app.create_initialization_options() 1416 | ) 1417 | ``` 1418 | 1419 | </Tab> 1420 | </Tabs> 1421 | 1422 | ## Best practices 1423 | 1424 | When implementing resource support: 1425 | 1426 | 1. Use clear, descriptive resource names and URIs 1427 | 2. Include helpful descriptions to guide LLM understanding 1428 | 3. Set appropriate MIME types when known 1429 | 4. Implement resource templates for dynamic content 1430 | 5. Use subscriptions for frequently changing resources 1431 | 6. Handle errors gracefully with clear error messages 1432 | 7. Consider pagination for large resource lists 1433 | 8. Cache resource contents when appropriate 1434 | 9. Validate URIs before processing 1435 | 10. Document your custom URI schemes 1436 | 1437 | ## Security considerations 1438 | 1439 | When exposing resources: 1440 | 1441 | - Validate all resource URIs 1442 | - Implement appropriate access controls 1443 | - Sanitize file paths to prevent directory traversal 1444 | - Be cautious with binary data handling 1445 | - Consider rate limiting for resource reads 1446 | - Audit resource access 1447 | - Encrypt sensitive data in transit 1448 | - Validate MIME types 1449 | - Implement timeouts for long-running reads 1450 | - Handle resource cleanup appropriately 1451 | 1452 | # Roots 1453 | 1454 | Source: https://modelcontextprotocol.io/docs/concepts/roots 1455 | 1456 | Understanding roots in MCP 1457 | 1458 | 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. 1459 | 1460 | ## What are Roots? 1461 | 1462 | 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. 1463 | 1464 | For example, roots could be: 1465 | 1466 | ``` 1467 | file:///home/user/projects/myapp 1468 | https://api.example.com/v1 1469 | ``` 1470 | 1471 | ## Why Use Roots? 1472 | 1473 | Roots serve several important purposes: 1474 | 1475 | 1. **Guidance**: They inform servers about relevant resources and locations 1476 | 2. **Clarity**: Roots make it clear which resources are part of your workspace 1477 | 3. **Organization**: Multiple roots let you work with different resources simultaneously 1478 | 1479 | ## How Roots Work 1480 | 1481 | When a client supports roots, it: 1482 | 1483 | 1. Declares the `roots` capability during connection 1484 | 2. Provides a list of suggested roots to the server 1485 | 3. Notifies the server when roots change (if supported) 1486 | 1487 | While roots are informational and not strictly enforcing, servers should: 1488 | 1489 | 1. Respect the provided roots 1490 | 2. Use root URIs to locate and access resources 1491 | 3. Prioritize operations within root boundaries 1492 | 1493 | ## Common Use Cases 1494 | 1495 | Roots are commonly used to define: 1496 | 1497 | - Project directories 1498 | - Repository locations 1499 | - API endpoints 1500 | - Configuration locations 1501 | - Resource boundaries 1502 | 1503 | ## Best Practices 1504 | 1505 | When working with roots: 1506 | 1507 | 1. Only suggest necessary resources 1508 | 2. Use clear, descriptive names for roots 1509 | 3. Monitor root accessibility 1510 | 4. Handle root changes gracefully 1511 | 1512 | ## Example 1513 | 1514 | Here's how a typical MCP client might expose roots: 1515 | 1516 | ```json 1517 | { 1518 | "roots": [ 1519 | { 1520 | "uri": "file:///home/user/projects/frontend", 1521 | "name": "Frontend Repository" 1522 | }, 1523 | { 1524 | "uri": "https://api.example.com/v1", 1525 | "name": "API Endpoint" 1526 | } 1527 | ] 1528 | } 1529 | ``` 1530 | 1531 | This configuration suggests the server focus on both a local repository and an API endpoint while keeping them logically separated. 1532 | 1533 | # Sampling 1534 | 1535 | Source: https://modelcontextprotocol.io/docs/concepts/sampling 1536 | 1537 | Let your servers request completions from LLMs 1538 | 1539 | 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. 1540 | 1541 | <Info> 1542 | This feature of MCP is not yet supported in the Claude Desktop client. 1543 | </Info> 1544 | 1545 | ## How sampling works 1546 | 1547 | The sampling flow follows these steps: 1548 | 1549 | 1. Server sends a `sampling/createMessage` request to the client 1550 | 2. Client reviews the request and can modify it 1551 | 3. Client samples from an LLM 1552 | 4. Client reviews the completion 1553 | 5. Client returns the result to the server 1554 | 1555 | This human-in-the-loop design ensures users maintain control over what the LLM sees and generates. 1556 | 1557 | ## Message format 1558 | 1559 | Sampling requests use a standardized message format: 1560 | 1561 | ```typescript 1562 | { 1563 | messages: [ 1564 | { 1565 | role: "user" | "assistant", 1566 | content: { 1567 | type: "text" | "image", 1568 | 1569 | // For text: 1570 | text?: string, 1571 | 1572 | // For images: 1573 | data?: string, // base64 encoded 1574 | mimeType?: string 1575 | } 1576 | } 1577 | ], 1578 | modelPreferences?: { 1579 | hints?: [{ 1580 | name?: string // Suggested model name/family 1581 | }], 1582 | costPriority?: number, // 0-1, importance of minimizing cost 1583 | speedPriority?: number, // 0-1, importance of low latency 1584 | intelligencePriority?: number // 0-1, importance of capabilities 1585 | }, 1586 | systemPrompt?: string, 1587 | includeContext?: "none" | "thisServer" | "allServers", 1588 | temperature?: number, 1589 | maxTokens: number, 1590 | stopSequences?: string[], 1591 | metadata?: Record<string, unknown> 1592 | } 1593 | ``` 1594 | 1595 | ## Request parameters 1596 | 1597 | ### Messages 1598 | 1599 | The `messages` array contains the conversation history to send to the LLM. Each message has: 1600 | 1601 | - `role`: Either "user" or "assistant" 1602 | - `content`: The message content, which can be: 1603 | - Text content with a `text` field 1604 | - Image content with `data` (base64) and `mimeType` fields 1605 | 1606 | ### Model preferences 1607 | 1608 | The `modelPreferences` object allows servers to specify their model selection preferences: 1609 | 1610 | - `hints`: Array of model name suggestions that clients can use to select an appropriate model: 1611 | 1612 | - `name`: String that can match full or partial model names (e.g. "claude-3", "sonnet") 1613 | - Clients may map hints to equivalent models from different providers 1614 | - Multiple hints are evaluated in preference order 1615 | 1616 | - Priority values (0-1 normalized): 1617 | - `costPriority`: Importance of minimizing costs 1618 | - `speedPriority`: Importance of low latency response 1619 | - `intelligencePriority`: Importance of advanced model capabilities 1620 | 1621 | Clients make the final model selection based on these preferences and their available models. 1622 | 1623 | ### System prompt 1624 | 1625 | An optional `systemPrompt` field allows servers to request a specific system prompt. The client may modify or ignore this. 1626 | 1627 | ### Context inclusion 1628 | 1629 | The `includeContext` parameter specifies what MCP context to include: 1630 | 1631 | - `"none"`: No additional context 1632 | - `"thisServer"`: Include context from the requesting server 1633 | - `"allServers"`: Include context from all connected MCP servers 1634 | 1635 | The client controls what context is actually included. 1636 | 1637 | ### Sampling parameters 1638 | 1639 | Fine-tune the LLM sampling with: 1640 | 1641 | - `temperature`: Controls randomness (0.0 to 1.0) 1642 | - `maxTokens`: Maximum tokens to generate 1643 | - `stopSequences`: Array of sequences that stop generation 1644 | - `metadata`: Additional provider-specific parameters 1645 | 1646 | ## Response format 1647 | 1648 | The client returns a completion result: 1649 | 1650 | ```typescript 1651 | { 1652 | model: string, // Name of the model used 1653 | stopReason?: "endTurn" | "stopSequence" | "maxTokens" | string, 1654 | role: "user" | "assistant", 1655 | content: { 1656 | type: "text" | "image", 1657 | text?: string, 1658 | data?: string, 1659 | mimeType?: string 1660 | } 1661 | } 1662 | ``` 1663 | 1664 | ## Example request 1665 | 1666 | Here's an example of requesting sampling from a client: 1667 | 1668 | ```json 1669 | { 1670 | "method": "sampling/createMessage", 1671 | "params": { 1672 | "messages": [ 1673 | { 1674 | "role": "user", 1675 | "content": { 1676 | "type": "text", 1677 | "text": "What files are in the current directory?" 1678 | } 1679 | } 1680 | ], 1681 | "systemPrompt": "You are a helpful file system assistant.", 1682 | "includeContext": "thisServer", 1683 | "maxTokens": 100 1684 | } 1685 | } 1686 | ``` 1687 | 1688 | ## Best practices 1689 | 1690 | When implementing sampling: 1691 | 1692 | 1. Always provide clear, well-structured prompts 1693 | 2. Handle both text and image content appropriately 1694 | 3. Set reasonable token limits 1695 | 4. Include relevant context through `includeContext` 1696 | 5. Validate responses before using them 1697 | 6. Handle errors gracefully 1698 | 7. Consider rate limiting sampling requests 1699 | 8. Document expected sampling behavior 1700 | 9. Test with various model parameters 1701 | 10. Monitor sampling costs 1702 | 1703 | ## Human in the loop controls 1704 | 1705 | Sampling is designed with human oversight in mind: 1706 | 1707 | ### For prompts 1708 | 1709 | - Clients should show users the proposed prompt 1710 | - Users should be able to modify or reject prompts 1711 | - System prompts can be filtered or modified 1712 | - Context inclusion is controlled by the client 1713 | 1714 | ### For completions 1715 | 1716 | - Clients should show users the completion 1717 | - Users should be able to modify or reject completions 1718 | - Clients can filter or modify completions 1719 | - Users control which model is used 1720 | 1721 | ## Security considerations 1722 | 1723 | When implementing sampling: 1724 | 1725 | - Validate all message content 1726 | - Sanitize sensitive information 1727 | - Implement appropriate rate limits 1728 | - Monitor sampling usage 1729 | - Encrypt data in transit 1730 | - Handle user data privacy 1731 | - Audit sampling requests 1732 | - Control cost exposure 1733 | - Implement timeouts 1734 | - Handle model errors gracefully 1735 | 1736 | ## Common patterns 1737 | 1738 | ### Agentic workflows 1739 | 1740 | Sampling enables agentic patterns like: 1741 | 1742 | - Reading and analyzing resources 1743 | - Making decisions based on context 1744 | - Generating structured data 1745 | - Handling multi-step tasks 1746 | - Providing interactive assistance 1747 | 1748 | ### Context management 1749 | 1750 | Best practices for context: 1751 | 1752 | - Request minimal necessary context 1753 | - Structure context clearly 1754 | - Handle context size limits 1755 | - Update context as needed 1756 | - Clean up stale context 1757 | 1758 | ### Error handling 1759 | 1760 | Robust error handling should: 1761 | 1762 | - Catch sampling failures 1763 | - Handle timeout errors 1764 | - Manage rate limits 1765 | - Validate responses 1766 | - Provide fallback behaviors 1767 | - Log errors appropriately 1768 | 1769 | ## Limitations 1770 | 1771 | Be aware of these limitations: 1772 | 1773 | - Sampling depends on client capabilities 1774 | - Users control sampling behavior 1775 | - Context size has limits 1776 | - Rate limits may apply 1777 | - Costs should be considered 1778 | - Model availability varies 1779 | - Response times vary 1780 | - Not all content types supported 1781 | 1782 | # Tools 1783 | 1784 | Source: https://modelcontextprotocol.io/docs/concepts/tools 1785 | 1786 | Enable LLMs to perform actions through your server 1787 | 1788 | 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. 1789 | 1790 | <Note> 1791 | 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). 1792 | </Note> 1793 | 1794 | ## Overview 1795 | 1796 | 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: 1797 | 1798 | - **Discovery**: Clients can list available tools through the `tools/list` endpoint 1799 | - **Invocation**: Tools are called using the `tools/call` endpoint, where servers perform the requested operation and return results 1800 | - **Flexibility**: Tools can range from simple calculations to complex API interactions 1801 | 1802 | 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. 1803 | 1804 | ## Tool definition structure 1805 | 1806 | Each tool is defined with the following structure: 1807 | 1808 | ```typescript 1809 | { 1810 | name: string; // Unique identifier for the tool 1811 | description?: string; // Human-readable description 1812 | inputSchema: { // JSON Schema for the tool's parameters 1813 | type: "object", 1814 | properties: { ... } // Tool-specific parameters 1815 | } 1816 | } 1817 | ``` 1818 | 1819 | ## Implementing tools 1820 | 1821 | Here's an example of implementing a basic tool in an MCP server: 1822 | 1823 | <Tabs> 1824 | <Tab title="TypeScript"> 1825 | ```typescript 1826 | const server = new Server({ 1827 | name: "example-server", 1828 | version: "1.0.0" 1829 | }, { 1830 | capabilities: { 1831 | tools: {} 1832 | } 1833 | }); 1834 | 1835 | // Define available tools 1836 | server.setRequestHandler(ListToolsRequestSchema, async () => { 1837 | return { 1838 | tools: [{ 1839 | name: "calculate_sum", 1840 | description: "Add two numbers together", 1841 | inputSchema: { 1842 | type: "object", 1843 | properties: { 1844 | a: { type: "number" }, 1845 | b: { type: "number" } 1846 | }, 1847 | required: ["a", "b"] 1848 | } 1849 | }] 1850 | }; 1851 | }); 1852 | 1853 | // Handle tool execution 1854 | server.setRequestHandler(CallToolRequestSchema, async (request) => { 1855 | if (request.params.name === "calculate_sum") { 1856 | const { a, b } = request.params.arguments; 1857 | return { 1858 | content: [ 1859 | { 1860 | type: "text", 1861 | text: String(a + b) 1862 | } 1863 | ] 1864 | }; 1865 | } 1866 | throw new Error("Tool not found"); 1867 | }); 1868 | ``` 1869 | 1870 | </Tab> 1871 | 1872 | <Tab title="Python"> 1873 | ```python 1874 | app = Server("example-server") 1875 | 1876 | @app.list_tools() 1877 | async def list_tools() -> list[types.Tool]: 1878 | return [ 1879 | types.Tool( 1880 | name="calculate_sum", 1881 | description="Add two numbers together", 1882 | inputSchema={ 1883 | "type": "object", 1884 | "properties": { 1885 | "a": {"type": "number"}, 1886 | "b": {"type": "number"} 1887 | }, 1888 | "required": ["a", "b"] 1889 | } 1890 | ) 1891 | ] 1892 | 1893 | @app.call_tool() 1894 | async def call_tool( 1895 | name: str, 1896 | arguments: dict 1897 | ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]: 1898 | if name == "calculate_sum": 1899 | a = arguments["a"] 1900 | b = arguments["b"] 1901 | result = a + b 1902 | return [types.TextContent(type="text", text=str(result))] 1903 | raise ValueError(f"Tool not found: {name}") 1904 | ``` 1905 | 1906 | </Tab> 1907 | </Tabs> 1908 | 1909 | ## Example tool patterns 1910 | 1911 | Here are some examples of types of tools that a server could provide: 1912 | 1913 | ### System operations 1914 | 1915 | Tools that interact with the local system: 1916 | 1917 | ```typescript 1918 | { 1919 | name: "execute_command", 1920 | description: "Run a shell command", 1921 | inputSchema: { 1922 | type: "object", 1923 | properties: { 1924 | command: { type: "string" }, 1925 | args: { type: "array", items: { type: "string" } } 1926 | } 1927 | } 1928 | } 1929 | ``` 1930 | 1931 | ### API integrations 1932 | 1933 | Tools that wrap external APIs: 1934 | 1935 | ```typescript 1936 | { 1937 | name: "github_create_issue", 1938 | description: "Create a GitHub issue", 1939 | inputSchema: { 1940 | type: "object", 1941 | properties: { 1942 | title: { type: "string" }, 1943 | body: { type: "string" }, 1944 | labels: { type: "array", items: { type: "string" } } 1945 | } 1946 | } 1947 | } 1948 | ``` 1949 | 1950 | ### Data processing 1951 | 1952 | Tools that transform or analyze data: 1953 | 1954 | ```typescript 1955 | { 1956 | name: "analyze_csv", 1957 | description: "Analyze a CSV file", 1958 | inputSchema: { 1959 | type: "object", 1960 | properties: { 1961 | filepath: { type: "string" }, 1962 | operations: { 1963 | type: "array", 1964 | items: { 1965 | enum: ["sum", "average", "count"] 1966 | } 1967 | } 1968 | } 1969 | } 1970 | } 1971 | ``` 1972 | 1973 | ## Best practices 1974 | 1975 | When implementing tools: 1976 | 1977 | 1. Provide clear, descriptive names and descriptions 1978 | 2. Use detailed JSON Schema definitions for parameters 1979 | 3. Include examples in tool descriptions to demonstrate how the model should use them 1980 | 4. Implement proper error handling and validation 1981 | 5. Use progress reporting for long operations 1982 | 6. Keep tool operations focused and atomic 1983 | 7. Document expected return value structures 1984 | 8. Implement proper timeouts 1985 | 9. Consider rate limiting for resource-intensive operations 1986 | 10. Log tool usage for debugging and monitoring 1987 | 1988 | ## Security considerations 1989 | 1990 | When exposing tools: 1991 | 1992 | ### Input validation 1993 | 1994 | - Validate all parameters against the schema 1995 | - Sanitize file paths and system commands 1996 | - Validate URLs and external identifiers 1997 | - Check parameter sizes and ranges 1998 | - Prevent command injection 1999 | 2000 | ### Access control 2001 | 2002 | - Implement authentication where needed 2003 | - Use appropriate authorization checks 2004 | - Audit tool usage 2005 | - Rate limit requests 2006 | - Monitor for abuse 2007 | 2008 | ### Error handling 2009 | 2010 | - Don't expose internal errors to clients 2011 | - Log security-relevant errors 2012 | - Handle timeouts appropriately 2013 | - Clean up resources after errors 2014 | - Validate return values 2015 | 2016 | ## Tool discovery and updates 2017 | 2018 | MCP supports dynamic tool discovery: 2019 | 2020 | 1. Clients can list available tools at any time 2021 | 2. Servers can notify clients when tools change using `notifications/tools/list_changed` 2022 | 3. Tools can be added or removed during runtime 2023 | 4. Tool definitions can be updated (though this should be done carefully) 2024 | 2025 | ## Error handling 2026 | 2027 | 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: 2028 | 2029 | 1. Set `isError` to `true` in the result 2030 | 2. Include error details in the `content` array 2031 | 2032 | Here's an example of proper error handling for tools: 2033 | 2034 | <Tabs> 2035 | <Tab title="TypeScript"> 2036 | ```typescript 2037 | try { 2038 | // Tool operation 2039 | const result = performOperation(); 2040 | return { 2041 | content: [ 2042 | { 2043 | type: "text", 2044 | text: `Operation successful: ${result}` 2045 | } 2046 | ] 2047 | }; 2048 | } catch (error) { 2049 | return { 2050 | isError: true, 2051 | content: [ 2052 | { 2053 | type: "text", 2054 | text: `Error: ${error.message}` 2055 | } 2056 | ] 2057 | }; 2058 | } 2059 | ``` 2060 | </Tab> 2061 | 2062 | <Tab title="Python"> 2063 | ```python 2064 | try: 2065 | # Tool operation 2066 | result = perform_operation() 2067 | return types.CallToolResult( 2068 | content=[ 2069 | types.TextContent( 2070 | type="text", 2071 | text=f"Operation successful: {result}" 2072 | ) 2073 | ] 2074 | ) 2075 | except Exception as error: 2076 | return types.CallToolResult( 2077 | isError=True, 2078 | content=[ 2079 | types.TextContent( 2080 | type="text", 2081 | text=f"Error: {str(error)}" 2082 | ) 2083 | ] 2084 | ) 2085 | ``` 2086 | </Tab> 2087 | </Tabs> 2088 | 2089 | This approach allows the LLM to see that an error occurred and potentially take corrective action or request human intervention. 2090 | 2091 | ## Testing tools 2092 | 2093 | A comprehensive testing strategy for MCP tools should cover: 2094 | 2095 | - **Functional testing**: Verify tools execute correctly with valid inputs and handle invalid inputs appropriately 2096 | - **Integration testing**: Test tool interaction with external systems using both real and mocked dependencies 2097 | - **Security testing**: Validate authentication, authorization, input sanitization, and rate limiting 2098 | - **Performance testing**: Check behavior under load, timeout handling, and resource cleanup 2099 | - **Error handling**: Ensure tools properly report errors through the MCP protocol and clean up resources 2100 | 2101 | # Transports 2102 | 2103 | Source: https://modelcontextprotocol.io/docs/concepts/transports 2104 | 2105 | Learn about MCP's communication mechanisms 2106 | 2107 | 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. 2108 | 2109 | ## Message Format 2110 | 2111 | 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. 2112 | 2113 | There are three types of JSON-RPC messages used: 2114 | 2115 | ### Requests 2116 | 2117 | ```typescript 2118 | { 2119 | jsonrpc: "2.0", 2120 | id: number | string, 2121 | method: string, 2122 | params?: object 2123 | } 2124 | ``` 2125 | 2126 | ### Responses 2127 | 2128 | ```typescript 2129 | { 2130 | jsonrpc: "2.0", 2131 | id: number | string, 2132 | result?: object, 2133 | error?: { 2134 | code: number, 2135 | message: string, 2136 | data?: unknown 2137 | } 2138 | } 2139 | ``` 2140 | 2141 | ### Notifications 2142 | 2143 | ```typescript 2144 | { 2145 | jsonrpc: "2.0", 2146 | method: string, 2147 | params?: object 2148 | } 2149 | ``` 2150 | 2151 | ## Built-in Transport Types 2152 | 2153 | MCP includes two standard transport implementations: 2154 | 2155 | ### Standard Input/Output (stdio) 2156 | 2157 | The stdio transport enables communication through standard input and output streams. This is particularly useful for local integrations and command-line tools. 2158 | 2159 | Use stdio when: 2160 | 2161 | - Building command-line tools 2162 | - Implementing local integrations 2163 | - Needing simple process communication 2164 | - Working with shell scripts 2165 | 2166 | <Tabs> 2167 | <Tab title="TypeScript (Server)"> 2168 | ```typescript 2169 | const server = new Server({ 2170 | name: "example-server", 2171 | version: "1.0.0" 2172 | }, { 2173 | capabilities: {} 2174 | }); 2175 | 2176 | const transport = new StdioServerTransport(); 2177 | await server.connect(transport); 2178 | ``` 2179 | 2180 | </Tab> 2181 | 2182 | <Tab title="TypeScript (Client)"> 2183 | ```typescript 2184 | const client = new Client({ 2185 | name: "example-client", 2186 | version: "1.0.0" 2187 | }, { 2188 | capabilities: {} 2189 | }); 2190 | 2191 | const transport = new StdioClientTransport({ 2192 | command: "./server", 2193 | args: ["--option", "value"] 2194 | }); 2195 | await client.connect(transport); 2196 | ``` 2197 | 2198 | </Tab> 2199 | 2200 | <Tab title="Python (Server)"> 2201 | ```python 2202 | app = Server("example-server") 2203 | 2204 | async with stdio_server() as streams: 2205 | await app.run( 2206 | streams[0], 2207 | streams[1], 2208 | app.create_initialization_options() 2209 | ) 2210 | ``` 2211 | 2212 | </Tab> 2213 | 2214 | <Tab title="Python (Client)"> 2215 | ```python 2216 | params = StdioServerParameters( 2217 | command="./server", 2218 | args=["--option", "value"] 2219 | ) 2220 | 2221 | async with stdio_client(params) as streams: 2222 | async with ClientSession(streams[0], streams[1]) as session: 2223 | await session.initialize() 2224 | ``` 2225 | 2226 | </Tab> 2227 | </Tabs> 2228 | 2229 | ### Server-Sent Events (SSE) 2230 | 2231 | SSE transport enables server-to-client streaming with HTTP POST requests for client-to-server communication. 2232 | 2233 | Use SSE when: 2234 | 2235 | - Only server-to-client streaming is needed 2236 | - Working with restricted networks 2237 | - Implementing simple updates 2238 | 2239 | <Tabs> 2240 | <Tab title="TypeScript (Server)"> 2241 | ```typescript 2242 | import express from "express"; 2243 | 2244 | const app = express(); 2245 | 2246 | const server = new Server({ 2247 | name: "example-server", 2248 | version: "1.0.0" 2249 | }, { 2250 | capabilities: {} 2251 | }); 2252 | 2253 | let transport: SSEServerTransport | null = null; 2254 | 2255 | app.get("/sse", (req, res) => { 2256 | transport = new SSEServerTransport("/messages", res); 2257 | server.connect(transport); 2258 | }); 2259 | 2260 | app.post("/messages", (req, res) => { 2261 | if (transport) { 2262 | transport.handlePostMessage(req, res); 2263 | } 2264 | }); 2265 | 2266 | app.listen(3000); 2267 | ``` 2268 | 2269 | </Tab> 2270 | 2271 | <Tab title="TypeScript (Client)"> 2272 | ```typescript 2273 | const client = new Client({ 2274 | name: "example-client", 2275 | version: "1.0.0" 2276 | }, { 2277 | capabilities: {} 2278 | }); 2279 | 2280 | const transport = new SSEClientTransport( 2281 | new URL("http://localhost:3000/sse") 2282 | ); 2283 | await client.connect(transport); 2284 | ``` 2285 | 2286 | </Tab> 2287 | 2288 | <Tab title="Python (Server)"> 2289 | ```python 2290 | from mcp.server.sse import SseServerTransport 2291 | from starlette.applications import Starlette 2292 | from starlette.routing import Route 2293 | 2294 | app = Server("example-server") 2295 | sse = SseServerTransport("/messages") 2296 | 2297 | async def handle_sse(scope, receive, send): 2298 | async with sse.connect_sse(scope, receive, send) as streams: 2299 | await app.run(streams[0], streams[1], app.create_initialization_options()) 2300 | 2301 | async def handle_messages(scope, receive, send): 2302 | await sse.handle_post_message(scope, receive, send) 2303 | 2304 | starlette_app = Starlette( 2305 | routes=[ 2306 | Route("/sse", endpoint=handle_sse), 2307 | Route("/messages", endpoint=handle_messages, methods=["POST"]), 2308 | ] 2309 | ) 2310 | ``` 2311 | 2312 | </Tab> 2313 | 2314 | <Tab title="Python (Client)"> 2315 | ```python 2316 | async with sse_client("http://localhost:8000/sse") as streams: 2317 | async with ClientSession(streams[0], streams[1]) as session: 2318 | await session.initialize() 2319 | ``` 2320 | </Tab> 2321 | </Tabs> 2322 | 2323 | ## Custom Transports 2324 | 2325 | MCP makes it easy to implement custom transports for specific needs. Any transport implementation just needs to conform to the Transport interface: 2326 | 2327 | You can implement custom transports for: 2328 | 2329 | - Custom network protocols 2330 | - Specialized communication channels 2331 | - Integration with existing systems 2332 | - Performance optimization 2333 | 2334 | <Tabs> 2335 | <Tab title="TypeScript"> 2336 | ```typescript 2337 | interface Transport { 2338 | // Start processing messages 2339 | start(): Promise<void>; 2340 | 2341 | // Send a JSON-RPC message 2342 | send(message: JSONRPCMessage): Promise<void>; 2343 | 2344 | // Close the connection 2345 | close(): Promise<void>; 2346 | 2347 | // Callbacks 2348 | onclose?: () => void; 2349 | onerror?: (error: Error) => void; 2350 | onmessage?: (message: JSONRPCMessage) => void; 2351 | } 2352 | ``` 2353 | 2354 | </Tab> 2355 | 2356 | <Tab title="Python"> 2357 | Note that while MCP Servers are often implemented with asyncio, we recommend 2358 | implementing low-level interfaces like transports with `anyio` for wider compatibility. 2359 | 2360 | ```python 2361 | @contextmanager 2362 | async def create_transport( 2363 | read_stream: MemoryObjectReceiveStream[JSONRPCMessage | Exception], 2364 | write_stream: MemoryObjectSendStream[JSONRPCMessage] 2365 | ): 2366 | """ 2367 | Transport interface for MCP. 2368 | 2369 | Args: 2370 | read_stream: Stream to read incoming messages from 2371 | write_stream: Stream to write outgoing messages to 2372 | """ 2373 | async with anyio.create_task_group() as tg: 2374 | try: 2375 | # Start processing messages 2376 | tg.start_soon(lambda: process_messages(read_stream)) 2377 | 2378 | # Send messages 2379 | async with write_stream: 2380 | yield write_stream 2381 | 2382 | except Exception as exc: 2383 | # Handle errors 2384 | raise exc 2385 | finally: 2386 | # Clean up 2387 | tg.cancel_scope.cancel() 2388 | await write_stream.aclose() 2389 | await read_stream.aclose() 2390 | ``` 2391 | 2392 | </Tab> 2393 | </Tabs> 2394 | 2395 | ## Error Handling 2396 | 2397 | Transport implementations should handle various error scenarios: 2398 | 2399 | 1. Connection errors 2400 | 2. Message parsing errors 2401 | 3. Protocol errors 2402 | 4. Network timeouts 2403 | 5. Resource cleanup 2404 | 2405 | Example error handling: 2406 | 2407 | <Tabs> 2408 | <Tab title="TypeScript"> 2409 | ```typescript 2410 | class ExampleTransport implements Transport { 2411 | async start() { 2412 | try { 2413 | // Connection logic 2414 | } catch (error) { 2415 | this.onerror?.(new Error(`Failed to connect: ${error}`)); 2416 | throw error; 2417 | } 2418 | } 2419 | 2420 | async send(message: JSONRPCMessage) { 2421 | try { 2422 | // Sending logic 2423 | } catch (error) { 2424 | this.onerror?.(new Error(`Failed to send message: ${error}`)); 2425 | throw error; 2426 | } 2427 | } 2428 | } 2429 | ``` 2430 | 2431 | </Tab> 2432 | 2433 | <Tab title="Python"> 2434 | Note that while MCP Servers are often implemented with asyncio, we recommend 2435 | implementing low-level interfaces like transports with `anyio` for wider compatibility. 2436 | 2437 | ```python 2438 | @contextmanager 2439 | async def example_transport(scope: Scope, receive: Receive, send: Send): 2440 | try: 2441 | # Create streams for bidirectional communication 2442 | read_stream_writer, read_stream = anyio.create_memory_object_stream(0) 2443 | write_stream, write_stream_reader = anyio.create_memory_object_stream(0) 2444 | 2445 | async def message_handler(): 2446 | try: 2447 | async with read_stream_writer: 2448 | # Message handling logic 2449 | pass 2450 | except Exception as exc: 2451 | logger.error(f"Failed to handle message: {exc}") 2452 | raise exc 2453 | 2454 | async with anyio.create_task_group() as tg: 2455 | tg.start_soon(message_handler) 2456 | try: 2457 | # Yield streams for communication 2458 | yield read_stream, write_stream 2459 | except Exception as exc: 2460 | logger.error(f"Transport error: {exc}") 2461 | raise exc 2462 | finally: 2463 | tg.cancel_scope.cancel() 2464 | await write_stream.aclose() 2465 | await read_stream.aclose() 2466 | except Exception as exc: 2467 | logger.error(f"Failed to initialize transport: {exc}") 2468 | raise exc 2469 | ``` 2470 | 2471 | </Tab> 2472 | </Tabs> 2473 | 2474 | ## Best Practices 2475 | 2476 | When implementing or using MCP transport: 2477 | 2478 | 1. Handle connection lifecycle properly 2479 | 2. Implement proper error handling 2480 | 3. Clean up resources on connection close 2481 | 4. Use appropriate timeouts 2482 | 5. Validate messages before sending 2483 | 6. Log transport events for debugging 2484 | 7. Implement reconnection logic when appropriate 2485 | 8. Handle backpressure in message queues 2486 | 9. Monitor connection health 2487 | 10. Implement proper security measures 2488 | 2489 | ## Security Considerations 2490 | 2491 | When implementing transport: 2492 | 2493 | ### Authentication and Authorization 2494 | 2495 | - Implement proper authentication mechanisms 2496 | - Validate client credentials 2497 | - Use secure token handling 2498 | - Implement authorization checks 2499 | 2500 | ### Data Security 2501 | 2502 | - Use TLS for network transport 2503 | - Encrypt sensitive data 2504 | - Validate message integrity 2505 | - Implement message size limits 2506 | - Sanitize input data 2507 | 2508 | ### Network Security 2509 | 2510 | - Implement rate limiting 2511 | - Use appropriate timeouts 2512 | - Handle denial of service scenarios 2513 | - Monitor for unusual patterns 2514 | - Implement proper firewall rules 2515 | 2516 | ## Debugging Transport 2517 | 2518 | Tips for debugging transport issues: 2519 | 2520 | 1. Enable debug logging 2521 | 2. Monitor message flow 2522 | 3. Check connection states 2523 | 4. Validate message formats 2524 | 5. Test error scenarios 2525 | 6. Use network analysis tools 2526 | 7. Implement health checks 2527 | 8. Monitor resource usage 2528 | 9. Test edge cases 2529 | 10. Use proper error tracking 2530 | 2531 | # Debugging 2532 | 2533 | Source: https://modelcontextprotocol.io/docs/tools/debugging 2534 | 2535 | A comprehensive guide to debugging Model Context Protocol (MCP) integrations 2536 | 2537 | 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. 2538 | 2539 | <Info> 2540 | This guide is for macOS. Guides for other platforms are coming soon. 2541 | </Info> 2542 | 2543 | ## Debugging tools overview 2544 | 2545 | MCP provides several tools for debugging at different levels: 2546 | 2547 | 1. **MCP Inspector** 2548 | 2549 | - Interactive debugging interface 2550 | - Direct server testing 2551 | - See the [Inspector guide](/docs/tools/inspector) for details 2552 | 2553 | 2. **Claude Desktop Developer Tools** 2554 | 2555 | - Integration testing 2556 | - Log collection 2557 | - Chrome DevTools integration 2558 | 2559 | 3. **Server Logging** 2560 | - Custom logging implementations 2561 | - Error tracking 2562 | - Performance monitoring 2563 | 2564 | ## Debugging in Claude Desktop 2565 | 2566 | ### Checking server status 2567 | 2568 | The Claude.app interface provides basic server status information: 2569 | 2570 | 1. Click the <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/claude-desktop-mcp-plug-icon.svg" style={{display: 'inline', margin: 0, height: '1.3em'}} /> icon to view: 2571 | 2572 | - Connected servers 2573 | - Available prompts and resources 2574 | 2575 | 2. Click the <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/claude-desktop-mcp-hammer-icon.svg" style={{display: 'inline', margin: 0, height: '1.3em'}} /> icon to view: 2576 | - Tools made available to the model 2577 | 2578 | ### Viewing logs 2579 | 2580 | Review detailed MCP logs from Claude Desktop: 2581 | 2582 | ```bash 2583 | # Follow logs in real-time 2584 | tail -n 20 -F ~/Library/Logs/Claude/mcp*.log 2585 | ``` 2586 | 2587 | The logs capture: 2588 | 2589 | - Server connection events 2590 | - Configuration issues 2591 | - Runtime errors 2592 | - Message exchanges 2593 | 2594 | ### Using Chrome DevTools 2595 | 2596 | Access Chrome's developer tools inside Claude Desktop to investigate client-side errors: 2597 | 2598 | 1. Create a `developer_settings.json` file with `allowDevTools` set to true: 2599 | 2600 | ```bash 2601 | echo '{"allowDevTools": true}' > ~/Library/Application\ Support/Claude/developer_settings.json 2602 | ``` 2603 | 2604 | 2. Open DevTools: `Command-Option-Shift-i` 2605 | 2606 | Note: You'll see two DevTools windows: 2607 | 2608 | - Main content window 2609 | - App title bar window 2610 | 2611 | Use the Console panel to inspect client-side errors. 2612 | 2613 | Use the Network panel to inspect: 2614 | 2615 | - Message payloads 2616 | - Connection timing 2617 | 2618 | ## Common issues 2619 | 2620 | ### Working directory 2621 | 2622 | When using MCP servers with Claude Desktop: 2623 | 2624 | - 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 2625 | - Always use absolute paths in your configuration and `.env` files to ensure reliable operation 2626 | - For testing servers directly via command line, the working directory will be where you run the command 2627 | 2628 | For example in `claude_desktop_config.json`, use: 2629 | 2630 | ```json 2631 | { 2632 | "command": "npx", 2633 | "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/username/data"] 2634 | } 2635 | ``` 2636 | 2637 | Instead of relative paths like `./data` 2638 | 2639 | ### Environment variables 2640 | 2641 | MCP servers inherit only a subset of environment variables automatically, like `USER`, `HOME`, and `PATH`. 2642 | 2643 | To override the default variables or provide your own, you can specify an `env` key in `claude_desktop_config.json`: 2644 | 2645 | ```json 2646 | { 2647 | "myserver": { 2648 | "command": "mcp-server-myapp", 2649 | "env": { 2650 | "MYAPP_API_KEY": "some_key" 2651 | } 2652 | } 2653 | } 2654 | ``` 2655 | 2656 | ### Server initialization 2657 | 2658 | Common initialization problems: 2659 | 2660 | 1. **Path Issues** 2661 | 2662 | - Incorrect server executable path 2663 | - Missing required files 2664 | - Permission problems 2665 | - Try using an absolute path for `command` 2666 | 2667 | 2. **Configuration Errors** 2668 | 2669 | - Invalid JSON syntax 2670 | - Missing required fields 2671 | - Type mismatches 2672 | 2673 | 3. **Environment Problems** 2674 | - Missing environment variables 2675 | - Incorrect variable values 2676 | - Permission restrictions 2677 | 2678 | ### Connection problems 2679 | 2680 | When servers fail to connect: 2681 | 2682 | 1. Check Claude Desktop logs 2683 | 2. Verify server process is running 2684 | 3. Test standalone with [Inspector](/docs/tools/inspector) 2685 | 4. Verify protocol compatibility 2686 | 2687 | ## Implementing logging 2688 | 2689 | ### Server-side logging 2690 | 2691 | 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. 2692 | 2693 | <Warning> 2694 | Local MCP servers should not log messages to stdout (standard out), as this will interfere with protocol operation. 2695 | </Warning> 2696 | 2697 | For all [transports](/docs/concepts/transports), you can also provide logging to the client by sending a log message notification: 2698 | 2699 | <Tabs> 2700 | <Tab title="Python"> 2701 | ```python 2702 | server.request_context.session.send_log_message( 2703 | level="info", 2704 | data="Server started successfully", 2705 | ) 2706 | ``` 2707 | </Tab> 2708 | 2709 | <Tab title="TypeScript"> 2710 | ```typescript 2711 | server.sendLoggingMessage({ 2712 | level: "info", 2713 | data: "Server started successfully", 2714 | }); 2715 | ``` 2716 | </Tab> 2717 | </Tabs> 2718 | 2719 | Important events to log: 2720 | 2721 | - Initialization steps 2722 | - Resource access 2723 | - Tool execution 2724 | - Error conditions 2725 | - Performance metrics 2726 | 2727 | ### Client-side logging 2728 | 2729 | In client applications: 2730 | 2731 | 1. Enable debug logging 2732 | 2. Monitor network traffic 2733 | 3. Track message exchanges 2734 | 4. Record error states 2735 | 2736 | ## Debugging workflow 2737 | 2738 | ### Development cycle 2739 | 2740 | 1. Initial Development 2741 | 2742 | - Use [Inspector](/docs/tools/inspector) for basic testing 2743 | - Implement core functionality 2744 | - Add logging points 2745 | 2746 | 2. Integration Testing 2747 | - Test in Claude Desktop 2748 | - Monitor logs 2749 | - Check error handling 2750 | 2751 | ### Testing changes 2752 | 2753 | To test changes efficiently: 2754 | 2755 | - **Configuration changes**: Restart Claude Desktop 2756 | - **Server code changes**: Use Command-R to reload 2757 | - **Quick iteration**: Use [Inspector](/docs/tools/inspector) during development 2758 | 2759 | ## Best practices 2760 | 2761 | ### Logging strategy 2762 | 2763 | 1. **Structured Logging** 2764 | 2765 | - Use consistent formats 2766 | - Include context 2767 | - Add timestamps 2768 | - Track request IDs 2769 | 2770 | 2. **Error Handling** 2771 | 2772 | - Log stack traces 2773 | - Include error context 2774 | - Track error patterns 2775 | - Monitor recovery 2776 | 2777 | 3. **Performance Tracking** 2778 | - Log operation timing 2779 | - Monitor resource usage 2780 | - Track message sizes 2781 | - Measure latency 2782 | 2783 | ### Security considerations 2784 | 2785 | When debugging: 2786 | 2787 | 1. **Sensitive Data** 2788 | 2789 | - Sanitize logs 2790 | - Protect credentials 2791 | - Mask personal information 2792 | 2793 | 2. **Access Control** 2794 | - Verify permissions 2795 | - Check authentication 2796 | - Monitor access patterns 2797 | 2798 | ## Getting help 2799 | 2800 | When encountering issues: 2801 | 2802 | 1. **First Steps** 2803 | 2804 | - Check server logs 2805 | - Test with [Inspector](/docs/tools/inspector) 2806 | - Review configuration 2807 | - Verify environment 2808 | 2809 | 2. **Support Channels** 2810 | 2811 | - GitHub issues 2812 | - GitHub discussions 2813 | 2814 | 3. **Providing Information** 2815 | - Log excerpts 2816 | - Configuration files 2817 | - Steps to reproduce 2818 | - Environment details 2819 | 2820 | ## Next steps 2821 | 2822 | <CardGroup cols={2}> 2823 | <Card title="MCP Inspector" icon="magnifying-glass" href="/docs/tools/inspector"> 2824 | Learn to use the MCP Inspector 2825 | </Card> 2826 | </CardGroup> 2827 | 2828 | # Inspector 2829 | 2830 | Source: https://modelcontextprotocol.io/docs/tools/inspector 2831 | 2832 | In-depth guide to using the MCP Inspector for testing and debugging Model Context Protocol servers 2833 | 2834 | 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. 2835 | 2836 | ## Getting started 2837 | 2838 | ### Installation and basic usage 2839 | 2840 | The Inspector runs directly through `npx` without requiring installation: 2841 | 2842 | ```bash 2843 | npx @modelcontextprotocol/inspector <command> 2844 | ``` 2845 | 2846 | ```bash 2847 | npx @modelcontextprotocol/inspector <command> <arg1> <arg2> 2848 | ``` 2849 | 2850 | #### Inspecting servers from NPM or PyPi 2851 | 2852 | A common way to start server packages from [NPM](https://npmjs.com) or [PyPi](https://pypi.com). 2853 | 2854 | <Tabs> 2855 | <Tab title="NPM package"> 2856 | ```bash 2857 | npx -y @modelcontextprotocol/inspector npx <package-name> <args> 2858 | # For example 2859 | npx -y @modelcontextprotocol/inspector npx server-postgres postgres://127.0.0.1/testdb 2860 | ``` 2861 | </Tab> 2862 | 2863 | <Tab title="PyPi package"> 2864 | ```bash 2865 | npx @modelcontextprotocol/inspector uvx <package-name> <args> 2866 | # For example 2867 | npx @modelcontextprotocol/inspector uvx mcp-server-git --repository ~/code/mcp/servers.git 2868 | ``` 2869 | </Tab> 2870 | </Tabs> 2871 | 2872 | #### Inspecting locally developed servers 2873 | 2874 | To inspect servers locally developed or downloaded as a repository, the most common 2875 | way is: 2876 | 2877 | <Tabs> 2878 | <Tab title="TypeScript"> 2879 | ```bash 2880 | npx @modelcontextprotocol/inspector node path/to/server/index.js args... 2881 | ``` 2882 | </Tab> 2883 | 2884 | <Tab title="Python"> 2885 | ```bash 2886 | npx @modelcontextprotocol/inspector \ 2887 | uv \ 2888 | --directory path/to/server \ 2889 | run \ 2890 | package-name \ 2891 | args... 2892 | ``` 2893 | </Tab> 2894 | </Tabs> 2895 | 2896 | Please carefully read any attached README for the most accurate instructions. 2897 | 2898 | ## Feature overview 2899 | 2900 | <Frame caption="The MCP Inspector interface"> 2901 | <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/mcp-inspector.png" /> 2902 | </Frame> 2903 | 2904 | The Inspector provides several features for interacting with your MCP server: 2905 | 2906 | ### Server connection pane 2907 | 2908 | - Allows selecting the [transport](/docs/concepts/transports) for connecting to the server 2909 | - For local servers, supports customizing the command-line arguments and environment 2910 | 2911 | ### Resources tab 2912 | 2913 | - Lists all available resources 2914 | - Shows resource metadata (MIME types, descriptions) 2915 | - Allows resource content inspection 2916 | - Supports subscription testing 2917 | 2918 | ### Prompts tab 2919 | 2920 | - Displays available prompt templates 2921 | - Shows prompt arguments and descriptions 2922 | - Enables prompt testing with custom arguments 2923 | - Previews generated messages 2924 | 2925 | ### Tools tab 2926 | 2927 | - Lists available tools 2928 | - Shows tool schemas and descriptions 2929 | - Enables tool testing with custom inputs 2930 | - Displays tool execution results 2931 | 2932 | ### Notifications pane 2933 | 2934 | - Presents all logs recorded from the server 2935 | - Shows notifications received from the server 2936 | 2937 | ## Best practices 2938 | 2939 | ### Development workflow 2940 | 2941 | 1. Start Development 2942 | 2943 | - Launch Inspector with your server 2944 | - Verify basic connectivity 2945 | - Check capability negotiation 2946 | 2947 | 2. Iterative testing 2948 | 2949 | - Make server changes 2950 | - Rebuild the server 2951 | - Reconnect the Inspector 2952 | - Test affected features 2953 | - Monitor messages 2954 | 2955 | 3. Test edge cases 2956 | - Invalid inputs 2957 | - Missing prompt arguments 2958 | - Concurrent operations 2959 | - Verify error handling and error responses 2960 | 2961 | ## Next steps 2962 | 2963 | <CardGroup cols={2}> 2964 | <Card title="Inspector Repository" icon="github" href="https://github.com/modelcontextprotocol/inspector"> 2965 | Check out the MCP Inspector source code 2966 | </Card> 2967 | 2968 | <Card title="Debugging Guide" icon="bug" href="/docs/tools/debugging"> 2969 | Learn about broader debugging strategies 2970 | </Card> 2971 | </CardGroup> 2972 | 2973 | # Example Servers 2974 | 2975 | Source: https://modelcontextprotocol.io/examples 2976 | 2977 | A list of example servers and implementations 2978 | 2979 | 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. 2980 | 2981 | ## Reference implementations 2982 | 2983 | These official reference servers demonstrate core MCP features and SDK usage: 2984 | 2985 | ### Data and file systems 2986 | 2987 | - **[Filesystem](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem)** - Secure file operations with configurable access controls 2988 | - **[PostgreSQL](https://github.com/modelcontextprotocol/servers/tree/main/src/postgres)** - Read-only database access with schema inspection capabilities 2989 | - **[SQLite](https://github.com/modelcontextprotocol/servers/tree/main/src/sqlite)** - Database interaction and business intelligence features 2990 | - **[Google Drive](https://github.com/modelcontextprotocol/servers/tree/main/src/gdrive)** - File access and search capabilities for Google Drive 2991 | 2992 | ### Development tools 2993 | 2994 | - **[Git](https://github.com/modelcontextprotocol/servers/tree/main/src/git)** - Tools to read, search, and manipulate Git repositories 2995 | - **[GitHub](https://github.com/modelcontextprotocol/servers/tree/main/src/github)** - Repository management, file operations, and GitHub API integration 2996 | - **[GitLab](https://github.com/modelcontextprotocol/servers/tree/main/src/gitlab)** - GitLab API integration enabling project management 2997 | - **[Sentry](https://github.com/modelcontextprotocol/servers/tree/main/src/sentry)** - Retrieving and analyzing issues from Sentry.io 2998 | 2999 | ### Web and browser automation 3000 | 3001 | - **[Brave Search](https://github.com/modelcontextprotocol/servers/tree/main/src/brave-search)** - Web and local search using Brave's Search API 3002 | - **[Fetch](https://github.com/modelcontextprotocol/servers/tree/main/src/fetch)** - Web content fetching and conversion optimized for LLM usage 3003 | - **[Puppeteer](https://github.com/modelcontextprotocol/servers/tree/main/src/puppeteer)** - Browser automation and web scraping capabilities 3004 | 3005 | ### Productivity and communication 3006 | 3007 | - **[Slack](https://github.com/modelcontextprotocol/servers/tree/main/src/slack)** - Channel management and messaging capabilities 3008 | - **[Google Maps](https://github.com/modelcontextprotocol/servers/tree/main/src/google-maps)** - Location services, directions, and place details 3009 | - **[Memory](https://github.com/modelcontextprotocol/servers/tree/main/src/memory)** - Knowledge graph-based persistent memory system 3010 | 3011 | ### AI and specialized tools 3012 | 3013 | - **[EverArt](https://github.com/modelcontextprotocol/servers/tree/main/src/everart)** - AI image generation using various models 3014 | - **[Sequential Thinking](https://github.com/modelcontextprotocol/servers/tree/main/src/sequentialthinking)** - Dynamic problem-solving through thought sequences 3015 | - **[AWS KB Retrieval](https://github.com/modelcontextprotocol/servers/tree/main/src/aws-kb-retrieval-server)** - Retrieval from AWS Knowledge Base using Bedrock Agent Runtime 3016 | 3017 | ## Official integrations 3018 | 3019 | These MCP servers are maintained by companies for their platforms: 3020 | 3021 | - **[Axiom](https://github.com/axiomhq/mcp-server-axiom)** - Query and analyze logs, traces, and event data using natural language 3022 | - **[Browserbase](https://github.com/browserbase/mcp-server-browserbase)** - Automate browser interactions in the cloud 3023 | - **[Cloudflare](https://github.com/cloudflare/mcp-server-cloudflare)** - Deploy and manage resources on the Cloudflare developer platform 3024 | - **[E2B](https://github.com/e2b-dev/mcp-server)** - Execute code in secure cloud sandboxes 3025 | - **[Neon](https://github.com/neondatabase/mcp-server-neon)** - Interact with the Neon serverless Postgres platform 3026 | - **[Obsidian Markdown Notes](https://github.com/calclavia/mcp-obsidian)** - Read and search through Markdown notes in Obsidian vaults 3027 | - **[Qdrant](https://github.com/qdrant/mcp-server-qdrant/)** - Implement semantic memory using the Qdrant vector search engine 3028 | - **[Raygun](https://github.com/MindscapeHQ/mcp-server-raygun)** - Access crash reporting and monitoring data 3029 | - **[Search1API](https://github.com/fatwang2/search1api-mcp)** - Unified API for search, crawling, and sitemaps 3030 | - **[Stripe](https://github.com/stripe/agent-toolkit)** - Interact with the Stripe API 3031 | - **[Tinybird](https://github.com/tinybirdco/mcp-tinybird)** - Interface with the Tinybird serverless ClickHouse platform 3032 | 3033 | ## Community highlights 3034 | 3035 | A growing ecosystem of community-developed servers extends MCP's capabilities: 3036 | 3037 | - **[Docker](https://github.com/ckreiling/mcp-server-docker)** - Manage containers, images, volumes, and networks 3038 | - **[Kubernetes](https://github.com/Flux159/mcp-server-kubernetes)** - Manage pods, deployments, and services 3039 | - **[Linear](https://github.com/jerhadf/linear-mcp-server)** - Project management and issue tracking 3040 | - **[Snowflake](https://github.com/datawiz168/mcp-snowflake-service)** - Interact with Snowflake databases 3041 | - **[Spotify](https://github.com/varunneal/spotify-mcp)** - Control Spotify playback and manage playlists 3042 | - **[Todoist](https://github.com/abhiz123/todoist-mcp-server)** - Task management integration 3043 | 3044 | > **Note:** Community servers are untested and should be used at your own risk. They are not affiliated with or endorsed by Anthropic. 3045 | 3046 | For a complete list of community servers, visit the [MCP Servers Repository](https://github.com/modelcontextprotocol/servers). 3047 | 3048 | ## Getting started 3049 | 3050 | ### Using reference servers 3051 | 3052 | TypeScript-based servers can be used directly with `npx`: 3053 | 3054 | ```bash 3055 | npx -y @modelcontextprotocol/server-memory 3056 | ``` 3057 | 3058 | Python-based servers can be used with `uvx` (recommended) or `pip`: 3059 | 3060 | ```bash 3061 | # Using uvx 3062 | uvx mcp-server-git 3063 | 3064 | # Using pip 3065 | pip install mcp-server-git 3066 | python -m mcp_server_git 3067 | ``` 3068 | 3069 | ### Configuring with Claude 3070 | 3071 | To use an MCP server with Claude, add it to your configuration: 3072 | 3073 | ```json 3074 | { 3075 | "mcpServers": { 3076 | "memory": { 3077 | "command": "npx", 3078 | "args": ["-y", "@modelcontextprotocol/server-memory"] 3079 | }, 3080 | "filesystem": { 3081 | "command": "npx", 3082 | "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"] 3083 | }, 3084 | "github": { 3085 | "command": "npx", 3086 | "args": ["-y", "@modelcontextprotocol/server-github"], 3087 | "env": { 3088 | "GITHUB_PERSONAL_ACCESS_TOKEN": "<YOUR_TOKEN>" 3089 | } 3090 | } 3091 | } 3092 | } 3093 | ``` 3094 | 3095 | ## Additional resources 3096 | 3097 | - [MCP Servers Repository](https://github.com/modelcontextprotocol/servers) - Complete collection of reference implementations and community servers 3098 | - [Awesome MCP Servers](https://github.com/punkpeye/awesome-mcp-servers) - Curated list of MCP servers 3099 | - [MCP CLI](https://github.com/wong2/mcp-cli) - Command-line inspector for testing MCP servers 3100 | - [MCP Get](https://mcp-get.com) - Tool for installing and managing MCP servers 3101 | - [Supergateway](https://github.com/supercorp-ai/supergateway) - Run MCP stdio servers over SSE 3102 | 3103 | Visit our [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions) to engage with the MCP community. 3104 | 3105 | # Introduction 3106 | 3107 | Source: https://modelcontextprotocol.io/introduction 3108 | 3109 | Get started with the Model Context Protocol (MCP) 3110 | 3111 | <Note>Java SDK released! Check out [what else is new.](/development/updates)</Note> 3112 | 3113 | 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. 3114 | 3115 | ## Why MCP? 3116 | 3117 | MCP helps you build agents and complex workflows on top of LLMs. LLMs frequently need to integrate with data and tools, and MCP provides: 3118 | 3119 | - A growing list of pre-built integrations that your LLM can directly plug into 3120 | - The flexibility to switch between LLM providers and vendors 3121 | - Best practices for securing your data within your infrastructure 3122 | 3123 | ### General architecture 3124 | 3125 | At its core, MCP follows a client-server architecture where a host application can connect to multiple servers: 3126 | 3127 | ```mermaid 3128 | flowchart LR 3129 | subgraph "Your Computer" 3130 | Host["Host with MCP Client\n(Claude, IDEs, Tools)"] 3131 | S1["MCP Server A"] 3132 | S2["MCP Server B"] 3133 | S3["MCP Server C"] 3134 | Host <-->|"MCP Protocol"| S1 3135 | Host <-->|"MCP Protocol"| S2 3136 | Host <-->|"MCP Protocol"| S3 3137 | S1 <--> D1[("Local\nData Source A")] 3138 | S2 <--> D2[("Local\nData Source B")] 3139 | end 3140 | subgraph "Internet" 3141 | S3 <-->|"Web APIs"| D3[("Remote\nService C")] 3142 | end 3143 | ``` 3144 | 3145 | - **MCP Hosts**: Programs like Claude Desktop, IDEs, or AI tools that want to access data through MCP 3146 | - **MCP Clients**: Protocol clients that maintain 1:1 connections with servers 3147 | - **MCP Servers**: Lightweight programs that each expose specific capabilities through the standardized Model Context Protocol 3148 | - **Local Data Sources**: Your computer's files, databases, and services that MCP servers can securely access 3149 | - **Remote Services**: External systems available over the internet (e.g., through APIs) that MCP servers can connect to 3150 | 3151 | ## Get started 3152 | 3153 | Choose the path that best fits your needs: 3154 | 3155 | #### Quick Starts 3156 | 3157 | <CardGroup cols={2}> 3158 | <Card title="For Server Developers" icon="bolt" href="/quickstart/server"> 3159 | Get started building your own server to use in Claude for Desktop and other clients 3160 | </Card> 3161 | 3162 | <Card title="For Client Developers" icon="bolt" href="/quickstart/client"> 3163 | Get started building your own client that can integrate with all MCP servers 3164 | </Card> 3165 | 3166 | <Card title="For Claude Desktop Users" icon="bolt" href="/quickstart/user"> 3167 | Get started using pre-built servers in Claude for Desktop 3168 | </Card> 3169 | </CardGroup> 3170 | 3171 | #### Examples 3172 | 3173 | <CardGroup cols={2}> 3174 | <Card title="Example Servers" icon="grid" href="/examples"> 3175 | Check out our gallery of official MCP servers and implementations 3176 | </Card> 3177 | 3178 | <Card title="Example Clients" icon="cubes" href="/clients"> 3179 | View the list of clients that support MCP integrations 3180 | </Card> 3181 | </CardGroup> 3182 | 3183 | ## Tutorials 3184 | 3185 | <CardGroup cols={2}> 3186 | <Card title="Building MCP with LLMs" icon="comments" href="/tutorials/building-mcp-with-llms"> 3187 | Learn how to use LLMs like Claude to speed up your MCP development 3188 | </Card> 3189 | 3190 | <Card title="Debugging Guide" icon="bug" href="/docs/tools/debugging"> 3191 | Learn how to effectively debug MCP servers and integrations 3192 | </Card> 3193 | 3194 | <Card title="MCP Inspector" icon="magnifying-glass" href="/docs/tools/inspector"> 3195 | Test and inspect your MCP servers with our interactive debugging tool 3196 | </Card> 3197 | </CardGroup> 3198 | 3199 | ## Explore MCP 3200 | 3201 | Dive deeper into MCP's core concepts and capabilities: 3202 | 3203 | <CardGroup cols={2}> 3204 | <Card title="Core architecture" icon="sitemap" href="/docs/concepts/architecture"> 3205 | Understand how MCP connects clients, servers, and LLMs 3206 | </Card> 3207 | 3208 | <Card title="Resources" icon="database" href="/docs/concepts/resources"> 3209 | Expose data and content from your servers to LLMs 3210 | </Card> 3211 | 3212 | <Card title="Prompts" icon="message" href="/docs/concepts/prompts"> 3213 | Create reusable prompt templates and workflows 3214 | </Card> 3215 | 3216 | <Card title="Tools" icon="wrench" href="/docs/concepts/tools"> 3217 | Enable LLMs to perform actions through your server 3218 | </Card> 3219 | 3220 | <Card title="Sampling" icon="robot" href="/docs/concepts/sampling"> 3221 | Let your servers request completions from LLMs 3222 | </Card> 3223 | 3224 | <Card title="Transports" icon="network-wired" href="/docs/concepts/transports"> 3225 | Learn about MCP's communication mechanism 3226 | </Card> 3227 | </CardGroup> 3228 | 3229 | ## Contributing 3230 | 3231 | Want to contribute? Check out our [Contributing Guide](/development/contributing) to learn how you can help improve MCP. 3232 | 3233 | ## Support and Feedback 3234 | 3235 | Here's how to get help or provide feedback: 3236 | 3237 | - 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) 3238 | - For discussions or Q\&A about the MCP specification, use the [specification discussions](https://github.com/modelcontextprotocol/specification/discussions) 3239 | - For discussions or Q\&A about other MCP open source components, use the [organization discussions](https://github.com/orgs/modelcontextprotocol/discussions) 3240 | - For bug reports, feature requests, and questions related to Claude.app and claude.ai's MCP integration, please email [[email protected]](mailto:[email protected]) 3241 | 3242 | # For Client Developers 3243 | 3244 | Source: https://modelcontextprotocol.io/quickstart/client 3245 | 3246 | Get started building your own client that can integrate with all MCP servers. 3247 | 3248 | In this tutorial, you'll learn how to build a LLM-powered chatbot client that connects to MCP servers. It helps to have gone through the [Server quickstart](/quickstart/server) that guides you through the basic of building your first server. 3249 | 3250 | <Tabs> 3251 | <Tab title="Python"> 3252 | [You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/mcp-client) 3253 | 3254 | ## System Requirements 3255 | 3256 | Before starting, ensure your system meets these requirements: 3257 | 3258 | * Mac or Windows computer 3259 | * Latest Python version installed 3260 | * Latest version of `uv` installed 3261 | 3262 | ## Setting Up Your Environment 3263 | 3264 | First, create a new Python project with `uv`: 3265 | 3266 | ```bash 3267 | # Create project directory 3268 | uv init mcp-client 3269 | cd mcp-client 3270 | 3271 | # Create virtual environment 3272 | uv venv 3273 | 3274 | # Activate virtual environment 3275 | # On Windows: 3276 | .venv\Scripts\activate 3277 | # On Unix or MacOS: 3278 | source .venv/bin/activate 3279 | 3280 | # Install required packages 3281 | uv add mcp anthropic python-dotenv 3282 | 3283 | # Remove boilerplate files 3284 | rm hello.py 3285 | 3286 | # Create our main file 3287 | touch client.py 3288 | ``` 3289 | 3290 | ## Setting Up Your API Key 3291 | 3292 | You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys). 3293 | 3294 | Create a `.env` file to store it: 3295 | 3296 | ```bash 3297 | # Create .env file 3298 | touch .env 3299 | ``` 3300 | 3301 | Add your key to the `.env` file: 3302 | 3303 | ```bash 3304 | ANTHROPIC_API_KEY=<your key here> 3305 | ``` 3306 | 3307 | Add `.env` to your `.gitignore`: 3308 | 3309 | ```bash 3310 | echo ".env" >> .gitignore 3311 | ``` 3312 | 3313 | <Warning> 3314 | Make sure you keep your `ANTHROPIC_API_KEY` secure! 3315 | </Warning> 3316 | 3317 | ## Creating the Client 3318 | 3319 | ### Basic Client Structure 3320 | 3321 | First, let's set up our imports and create the basic client class: 3322 | 3323 | ```python 3324 | import asyncio 3325 | from typing import Optional 3326 | from contextlib import AsyncExitStack 3327 | 3328 | from mcp import ClientSession, StdioServerParameters 3329 | from mcp.client.stdio import stdio_client 3330 | 3331 | from anthropic import Anthropic 3332 | from dotenv import load_dotenv 3333 | 3334 | load_dotenv() # load environment variables from .env 3335 | 3336 | class MCPClient: 3337 | def __init__(self): 3338 | # Initialize session and client objects 3339 | self.session: Optional[ClientSession] = None 3340 | self.exit_stack = AsyncExitStack() 3341 | self.anthropic = Anthropic() 3342 | # methods will go here 3343 | ``` 3344 | 3345 | ### Server Connection Management 3346 | 3347 | Next, we'll implement the method to connect to an MCP server: 3348 | 3349 | ```python 3350 | async def connect_to_server(self, server_script_path: str): 3351 | """Connect to an MCP server 3352 | 3353 | Args: 3354 | server_script_path: Path to the server script (.py or .js) 3355 | """ 3356 | is_python = server_script_path.endswith('.py') 3357 | is_js = server_script_path.endswith('.js') 3358 | if not (is_python or is_js): 3359 | raise ValueError("Server script must be a .py or .js file") 3360 | 3361 | command = "python" if is_python else "node" 3362 | server_params = StdioServerParameters( 3363 | command=command, 3364 | args=[server_script_path], 3365 | env=None 3366 | ) 3367 | 3368 | stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params)) 3369 | self.stdio, self.write = stdio_transport 3370 | self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write)) 3371 | 3372 | await self.session.initialize() 3373 | 3374 | # List available tools 3375 | response = await self.session.list_tools() 3376 | tools = response.tools 3377 | print("\nConnected to server with tools:", [tool.name for tool in tools]) 3378 | ``` 3379 | 3380 | ### Query Processing Logic 3381 | 3382 | Now let's add the core functionality for processing queries and handling tool calls: 3383 | 3384 | ```python 3385 | async def process_query(self, query: str) -> str: 3386 | """Process a query using Claude and available tools""" 3387 | messages = [ 3388 | { 3389 | "role": "user", 3390 | "content": query 3391 | } 3392 | ] 3393 | 3394 | response = await self.session.list_tools() 3395 | available_tools = [{ 3396 | "name": tool.name, 3397 | "description": tool.description, 3398 | "input_schema": tool.inputSchema 3399 | } for tool in response.tools] 3400 | 3401 | # Initial Claude API call 3402 | response = self.anthropic.messages.create( 3403 | model="claude-3-5-sonnet-20241022", 3404 | max_tokens=1000, 3405 | messages=messages, 3406 | tools=available_tools 3407 | ) 3408 | 3409 | # Process response and handle tool calls 3410 | tool_results = [] 3411 | final_text = [] 3412 | 3413 | assistant_message_content = [] 3414 | for content in response.content: 3415 | if content.type == 'text': 3416 | final_text.append(content.text) 3417 | assistant_message_content.append(content) 3418 | elif content.type == 'tool_use': 3419 | tool_name = content.name 3420 | tool_args = content.input 3421 | 3422 | # Execute tool call 3423 | result = await self.session.call_tool(tool_name, tool_args) 3424 | tool_results.append({"call": tool_name, "result": result}) 3425 | final_text.append(f"[Calling tool {tool_name} with args {tool_args}]") 3426 | 3427 | assistant_message_content.append(content) 3428 | messages.append({ 3429 | "role": "assistant", 3430 | "content": assistant_message_content 3431 | }) 3432 | messages.append({ 3433 | "role": "user", 3434 | "content": [ 3435 | { 3436 | "type": "tool_result", 3437 | "tool_use_id": content.id, 3438 | "content": result.content 3439 | } 3440 | ] 3441 | }) 3442 | 3443 | # Get next response from Claude 3444 | response = self.anthropic.messages.create( 3445 | model="claude-3-5-sonnet-20241022", 3446 | max_tokens=1000, 3447 | messages=messages, 3448 | tools=available_tools 3449 | ) 3450 | 3451 | final_text.append(response.content[0].text) 3452 | 3453 | return "\n".join(final_text) 3454 | ``` 3455 | 3456 | ### Interactive Chat Interface 3457 | 3458 | Now we'll add the chat loop and cleanup functionality: 3459 | 3460 | ```python 3461 | async def chat_loop(self): 3462 | """Run an interactive chat loop""" 3463 | print("\nMCP Client Started!") 3464 | print("Type your queries or 'quit' to exit.") 3465 | 3466 | while True: 3467 | try: 3468 | query = input("\nQuery: ").strip() 3469 | 3470 | if query.lower() == 'quit': 3471 | break 3472 | 3473 | response = await self.process_query(query) 3474 | print("\n" + response) 3475 | 3476 | except Exception as e: 3477 | print(f"\nError: {str(e)}") 3478 | 3479 | async def cleanup(self): 3480 | """Clean up resources""" 3481 | await self.exit_stack.aclose() 3482 | ``` 3483 | 3484 | ### Main Entry Point 3485 | 3486 | Finally, we'll add the main execution logic: 3487 | 3488 | ```python 3489 | async def main(): 3490 | if len(sys.argv) < 2: 3491 | print("Usage: python client.py <path_to_server_script>") 3492 | sys.exit(1) 3493 | 3494 | client = MCPClient() 3495 | try: 3496 | await client.connect_to_server(sys.argv[1]) 3497 | await client.chat_loop() 3498 | finally: 3499 | await client.cleanup() 3500 | 3501 | if __name__ == "__main__": 3502 | import sys 3503 | asyncio.run(main()) 3504 | ``` 3505 | 3506 | You can find the complete `client.py` file [here.](https://gist.github.com/zckly/f3f28ea731e096e53b39b47bf0a2d4b1) 3507 | 3508 | ## Key Components Explained 3509 | 3510 | ### 1. Client Initialization 3511 | 3512 | * The `MCPClient` class initializes with session management and API clients 3513 | * Uses `AsyncExitStack` for proper resource management 3514 | * Configures the Anthropic client for Claude interactions 3515 | 3516 | ### 2. Server Connection 3517 | 3518 | * Supports both Python and Node.js servers 3519 | * Validates server script type 3520 | * Sets up proper communication channels 3521 | * Initializes the session and lists available tools 3522 | 3523 | ### 3. Query Processing 3524 | 3525 | * Maintains conversation context 3526 | * Handles Claude's responses and tool calls 3527 | * Manages the message flow between Claude and tools 3528 | * Combines results into a coherent response 3529 | 3530 | ### 4. Interactive Interface 3531 | 3532 | * Provides a simple command-line interface 3533 | * Handles user input and displays responses 3534 | * Includes basic error handling 3535 | * Allows graceful exit 3536 | 3537 | ### 5. Resource Management 3538 | 3539 | * Proper cleanup of resources 3540 | * Error handling for connection issues 3541 | * Graceful shutdown procedures 3542 | 3543 | ## Common Customization Points 3544 | 3545 | 1. **Tool Handling** 3546 | * Modify `process_query()` to handle specific tool types 3547 | * Add custom error handling for tool calls 3548 | * Implement tool-specific response formatting 3549 | 3550 | 2. **Response Processing** 3551 | * Customize how tool results are formatted 3552 | * Add response filtering or transformation 3553 | * Implement custom logging 3554 | 3555 | 3. **User Interface** 3556 | * Add a GUI or web interface 3557 | * Implement rich console output 3558 | * Add command history or auto-completion 3559 | 3560 | ## Running the Client 3561 | 3562 | To run your client with any MCP server: 3563 | 3564 | ```bash 3565 | uv run client.py path/to/server.py # python server 3566 | uv run client.py path/to/build/index.js # node server 3567 | ``` 3568 | 3569 | <Note> 3570 | If you're continuing the weather tutorial from the server quickstart, your command might look something like this: `python client.py .../weather/src/weather/server.py` 3571 | </Note> 3572 | 3573 | The client will: 3574 | 3575 | 1. Connect to the specified server 3576 | 2. List available tools 3577 | 3. Start an interactive chat session where you can: 3578 | * Enter queries 3579 | * See tool executions 3580 | * Get responses from Claude 3581 | 3582 | Here's an example of what it should look like if connected to the weather server from the server quickstart: 3583 | 3584 | <Frame> 3585 | <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/client-claude-cli-python.png" /> 3586 | </Frame> 3587 | 3588 | ## How It Works 3589 | 3590 | When you submit a query: 3591 | 3592 | 1. The client gets the list of available tools from the server 3593 | 2. Your query is sent to Claude along with tool descriptions 3594 | 3. Claude decides which tools (if any) to use 3595 | 4. The client executes any requested tool calls through the server 3596 | 5. Results are sent back to Claude 3597 | 6. Claude provides a natural language response 3598 | 7. The response is displayed to you 3599 | 3600 | ## Best practices 3601 | 3602 | 1. **Error Handling** 3603 | * Always wrap tool calls in try-catch blocks 3604 | * Provide meaningful error messages 3605 | * Gracefully handle connection issues 3606 | 3607 | 2. **Resource Management** 3608 | * Use `AsyncExitStack` for proper cleanup 3609 | * Close connections when done 3610 | * Handle server disconnections 3611 | 3612 | 3. **Security** 3613 | * Store API keys securely in `.env` 3614 | * Validate server responses 3615 | * Be cautious with tool permissions 3616 | 3617 | ## Troubleshooting 3618 | 3619 | ### Server Path Issues 3620 | 3621 | * Double-check the path to your server script is correct 3622 | * Use the absolute path if the relative path isn't working 3623 | * For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path 3624 | * Verify the server file has the correct extension (.py for Python or .js for Node.js) 3625 | 3626 | Example of correct path usage: 3627 | 3628 | ```bash 3629 | # Relative path 3630 | uv run client.py ./server/weather.py 3631 | 3632 | # Absolute path 3633 | uv run client.py /Users/username/projects/mcp-server/weather.py 3634 | 3635 | # Windows path (either format works) 3636 | uv run client.py C:/projects/mcp-server/weather.py 3637 | uv run client.py C:\\projects\\mcp-server\\weather.py 3638 | ``` 3639 | 3640 | ### Response Timing 3641 | 3642 | * The first response might take up to 30 seconds to return 3643 | * This is normal and happens while: 3644 | * The server initializes 3645 | * Claude processes the query 3646 | * Tools are being executed 3647 | * Subsequent responses are typically faster 3648 | * Don't interrupt the process during this initial waiting period 3649 | 3650 | ### Common Error Messages 3651 | 3652 | If you see: 3653 | 3654 | * `FileNotFoundError`: Check your server path 3655 | * `Connection refused`: Ensure the server is running and the path is correct 3656 | * `Tool execution failed`: Verify the tool's required environment variables are set 3657 | * `Timeout error`: Consider increasing the timeout in your client configuration 3658 | 3659 | </Tab> 3660 | 3661 | <Tab title="Java"> 3662 | <Note> 3663 | This is a quickstart demo based on Spring AI MCP auto-configuration and boot starters. 3664 | To learn how to create sync and async MCP Clients manually, consult the [Java SDK Client](/sdk/java/mcp-client) documentation 3665 | </Note> 3666 | 3667 | This example demonstrates how to build an interactive chatbot that combines Spring AI's Model Context Protocol (MCP) with the [Brave Search MCP Server](https://github.com/modelcontextprotocol/servers/tree/main/src/brave-search). The application creates a conversational interface powered by Anthropic's Claude AI model that can perform internet searches through Brave Search, enabling natural language interactions with real-time web data. 3668 | [You can find the complete code for this tutorial here.](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/web-search/brave-chatbot) 3669 | 3670 | ## System Requirements 3671 | 3672 | Before starting, ensure your system meets these requirements: 3673 | 3674 | * Java 17 or higher 3675 | * Maven 3.6+ 3676 | * npx package manager 3677 | * Anthropic API key (Claude) 3678 | * Brave Search API key 3679 | 3680 | ## Setting Up Your Environment 3681 | 3682 | 1. Install npx (Node Package eXecute): 3683 | First, make sure to install [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) 3684 | and then run: 3685 | ```bash 3686 | npm install -g npx 3687 | ``` 3688 | 3689 | 2. Clone the repository: 3690 | ```bash 3691 | git clone https://github.com/spring-projects/spring-ai-examples.git 3692 | cd model-context-protocol/brave-chatbot 3693 | ``` 3694 | 3695 | 3. Set up your API keys: 3696 | ```bash 3697 | export ANTHROPIC_API_KEY='your-anthropic-api-key-here' 3698 | export BRAVE_API_KEY='your-brave-api-key-here' 3699 | ``` 3700 | 3701 | 4. Build the application: 3702 | ```bash 3703 | ./mvnw clean install 3704 | ``` 3705 | 3706 | 5. Run the application using Maven: 3707 | ```bash 3708 | ./mvnw spring-boot:run 3709 | ``` 3710 | 3711 | <Warning> 3712 | Make sure you keep your `ANTHROPIC_API_KEY` and `BRAVE_API_KEY` keys secure! 3713 | </Warning> 3714 | 3715 | ## How it Works 3716 | 3717 | The application integrates Spring AI with the Brave Search MCP server through several components: 3718 | 3719 | ### MCP Client Configuration 3720 | 3721 | 1. Required dependencies in pom.xml: 3722 | 3723 | ```xml 3724 | <dependency> 3725 | <groupId>org.springframework.ai</groupId> 3726 | <artifactId>spring-ai-mcp-client-spring-boot-starter</artifactId> 3727 | </dependency> 3728 | <dependency> 3729 | <groupId>org.springframework.ai</groupId> 3730 | <artifactId>spring-ai-anthropic-spring-boot-starter</artifactId> 3731 | </dependency> 3732 | ``` 3733 | 3734 | 2. Application properties (application.yml): 3735 | 3736 | ```yml 3737 | spring: 3738 | ai: 3739 | mcp: 3740 | client: 3741 | enabled: true 3742 | name: brave-search-client 3743 | version: 1.0.0 3744 | type: SYNC 3745 | request-timeout: 20s 3746 | stdio: 3747 | root-change-notification: true 3748 | servers-configuration: classpath:/mcp-servers-config.json 3749 | anthropic: 3750 | api-key: ${ANTHROPIC_API_KEY} 3751 | ``` 3752 | 3753 | This activates the `spring-ai-mcp-client-spring-boot-starter` to create one or more `McpClient`s based on the provided server configuration. 3754 | 3755 | 3. MCP Server Configuration (`mcp-servers-config.json`): 3756 | 3757 | ```json 3758 | { 3759 | "mcpServers": { 3760 | "brave-search": { 3761 | "command": "npx", 3762 | "args": [ 3763 | "-y", 3764 | "@modelcontextprotocol/server-brave-search" 3765 | ], 3766 | "env": { 3767 | "BRAVE_API_KEY": "<PUT YOUR BRAVE API KEY>" 3768 | } 3769 | } 3770 | } 3771 | } 3772 | ``` 3773 | 3774 | ### Chat Implementation 3775 | 3776 | The chatbot is implemented using Spring AI's ChatClient with MCP tool integration: 3777 | 3778 | ```java 3779 | var chatClient = chatClientBuilder 3780 | .defaultSystem("You are useful assistant, expert in AI and Java.") 3781 | .defaultTools((Object[]) mcpToolAdapter.toolCallbacks()) 3782 | .defaultAdvisors(new MessageChatMemoryAdvisor(new InMemoryChatMemory())) 3783 | .build(); 3784 | ``` 3785 | 3786 | Key features: 3787 | 3788 | * Uses Claude AI model for natural language understanding 3789 | * Integrates Brave Search through MCP for real-time web search capabilities 3790 | * Maintains conversation memory using InMemoryChatMemory 3791 | * Runs as an interactive command-line application 3792 | 3793 | ### Build and run 3794 | 3795 | ```bash 3796 | ./mvnw clean install 3797 | java -jar ./target/ai-mcp-brave-chatbot-0.0.1-SNAPSHOT.jar 3798 | ``` 3799 | 3800 | or 3801 | 3802 | ```bash 3803 | ./mvnw spring-boot:run 3804 | ``` 3805 | 3806 | The application will start an interactive chat session where you can ask questions. The chatbot will use Brave Search when it needs to find information from the internet to answer your queries. 3807 | 3808 | The chatbot can: 3809 | 3810 | * Answer questions using its built-in knowledge 3811 | * Perform web searches when needed using Brave Search 3812 | * Remember context from previous messages in the conversation 3813 | * Combine information from multiple sources to provide comprehensive answers 3814 | 3815 | ### Advanced Configuration 3816 | 3817 | The MCP client supports additional configuration options: 3818 | 3819 | * Client customization through `McpSyncClientCustomizer` or `McpAsyncClientCustomizer` 3820 | * Multiple clients with multiple transport types: `STDIO` and `SSE` (Server-Sent Events) 3821 | * Integration with Spring AI's tool execution framework 3822 | * Automatic client initialization and lifecycle management 3823 | 3824 | For WebFlux-based applications, you can use the WebFlux starter instead: 3825 | 3826 | ```xml 3827 | <dependency> 3828 | <groupId>org.springframework.ai</groupId> 3829 | <artifactId>spring-ai-mcp-client-webflux-spring-boot-starter</artifactId> 3830 | </dependency> 3831 | ``` 3832 | 3833 | This provides similar functionality but uses a WebFlux-based SSE transport implementation, recommended for production deployments. 3834 | 3835 | </Tab> 3836 | </Tabs> 3837 | 3838 | ## Next steps 3839 | 3840 | <CardGroup cols={2}> 3841 | <Card title="Example servers" icon="grid" href="/examples"> 3842 | Check out our gallery of official MCP servers and implementations 3843 | </Card> 3844 | 3845 | <Card title="Clients" icon="cubes" href="/clients"> 3846 | View the list of clients that support MCP integrations 3847 | </Card> 3848 | 3849 | <Card title="Building MCP with LLMs" icon="comments" href="/building-mcp-with-llms"> 3850 | Learn how to use LLMs like Claude to speed up your MCP development 3851 | </Card> 3852 | 3853 | <Card title="Core architecture" icon="sitemap" href="/docs/concepts/architecture"> 3854 | Understand how MCP connects clients, servers, and LLMs 3855 | </Card> 3856 | </CardGroup> 3857 | 3858 | # For Server Developers 3859 | 3860 | Source: https://modelcontextprotocol.io/quickstart/server 3861 | 3862 | Get started building your own server to use in Claude for Desktop and other clients. 3863 | 3864 | In this tutorial, we'll build a simple MCP weather server and connect it to a host, Claude for Desktop. We'll start with a basic setup, and then progress to more complex use cases. 3865 | 3866 | ### What we'll be building 3867 | 3868 | Many LLMs (including Claude) do not currently have the ability to fetch the forecast and severe weather alerts. Let's use MCP to solve that! 3869 | 3870 | We'll build a server that exposes two tools: `get-alerts` and `get-forecast`. Then we'll connect the server to an MCP host (in this case, Claude for Desktop): 3871 | 3872 | <Frame> 3873 | <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/weather-alerts.png" /> 3874 | </Frame> 3875 | 3876 | <Frame> 3877 | <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/current-weather.png" /> 3878 | </Frame> 3879 | 3880 | <Note> 3881 | Servers can connect to any client. We've chosen Claude for Desktop here for simplicity, but we also have guides on [building your own client](/quickstart/client) as well as a [list of other clients here](/clients). 3882 | </Note> 3883 | 3884 | <Accordion title="Why Claude for Desktop and not Claude.ai?"> 3885 | Because servers are locally run, MCP currently only supports desktop hosts. Remote hosts are in active development. 3886 | </Accordion> 3887 | 3888 | ### Core MCP Concepts 3889 | 3890 | MCP servers can provide three main types of capabilities: 3891 | 3892 | 1. **Resources**: File-like data that can be read by clients (like API responses or file contents) 3893 | 2. **Tools**: Functions that can be called by the LLM (with user approval) 3894 | 3. **Prompts**: Pre-written templates that help users accomplish specific tasks 3895 | 3896 | This tutorial will primarily focus on tools. 3897 | 3898 | <Tabs> 3899 | <Tab title="Python"> 3900 | Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-python) 3901 | 3902 | ### Prerequisite knowledge 3903 | 3904 | This quickstart assumes you have familiarity with: 3905 | 3906 | * Python 3907 | * LLMs like Claude 3908 | 3909 | ### System requirements 3910 | 3911 | * Python 3.10 or higher installed. 3912 | * You must use the Python MCP SDK 1.2.0 or higher. 3913 | 3914 | ### Set up your environment 3915 | 3916 | First, let's install `uv` and set up our Python project and environment: 3917 | 3918 | <CodeGroup> 3919 | ```bash MacOS/Linux 3920 | curl -LsSf https://astral.sh/uv/install.sh | sh 3921 | ``` 3922 | 3923 | ```powershell Windows 3924 | powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" 3925 | ``` 3926 | </CodeGroup> 3927 | 3928 | Make sure to restart your terminal afterwards to ensure that the `uv` command gets picked up. 3929 | 3930 | Now, let's create and set up our project: 3931 | 3932 | <CodeGroup> 3933 | ```bash MacOS/Linux 3934 | # Create a new directory for our project 3935 | uv init weather 3936 | cd weather 3937 | 3938 | # Create virtual environment and activate it 3939 | uv venv 3940 | source .venv/bin/activate 3941 | 3942 | # Install dependencies 3943 | uv add "mcp[cli]" httpx 3944 | 3945 | # Create our server file 3946 | touch weather.py 3947 | ``` 3948 | 3949 | ```powershell Windows 3950 | # Create a new directory for our project 3951 | uv init weather 3952 | cd weather 3953 | 3954 | # Create virtual environment and activate it 3955 | uv venv 3956 | .venv\Scripts\activate 3957 | 3958 | # Install dependencies 3959 | uv add mcp[cli] httpx 3960 | 3961 | # Create our server file 3962 | new-item weather.py 3963 | ``` 3964 | </CodeGroup> 3965 | 3966 | Now let's dive into building your server. 3967 | 3968 | ## Building your server 3969 | 3970 | ### Importing packages and setting up the instance 3971 | 3972 | Add these to the top of your `weather.py`: 3973 | 3974 | ```python 3975 | from typing import Any 3976 | import httpx 3977 | from mcp.server.fastmcp import FastMCP 3978 | 3979 | # Initialize FastMCP server 3980 | mcp = FastMCP("weather") 3981 | 3982 | # Constants 3983 | NWS_API_BASE = "https://api.weather.gov" 3984 | USER_AGENT = "weather-app/1.0" 3985 | ``` 3986 | 3987 | The FastMCP class uses Python type hints and docstrings to automatically generate tool definitions, making it easy to create and maintain MCP tools. 3988 | 3989 | ### Helper functions 3990 | 3991 | Next, let's add our helper functions for querying and formatting the data from the National Weather Service API: 3992 | 3993 | ```python 3994 | async def make_nws_request(url: str) -> dict[str, Any] | None: 3995 | """Make a request to the NWS API with proper error handling.""" 3996 | headers = { 3997 | "User-Agent": USER_AGENT, 3998 | "Accept": "application/geo+json" 3999 | } 4000 | async with httpx.AsyncClient() as client: 4001 | try: 4002 | response = await client.get(url, headers=headers, timeout=30.0) 4003 | response.raise_for_status() 4004 | return response.json() 4005 | except Exception: 4006 | return None 4007 | 4008 | def format_alert(feature: dict) -> str: 4009 | """Format an alert feature into a readable string.""" 4010 | props = feature["properties"] 4011 | return f""" 4012 | Event: {props.get('event', 'Unknown')} 4013 | Area: {props.get('areaDesc', 'Unknown')} 4014 | Severity: {props.get('severity', 'Unknown')} 4015 | Description: {props.get('description', 'No description available')} 4016 | Instructions: {props.get('instruction', 'No specific instructions provided')} 4017 | """ 4018 | ``` 4019 | 4020 | ### Implementing tool execution 4021 | 4022 | The tool execution handler is responsible for actually executing the logic of each tool. Let's add it: 4023 | 4024 | ```python 4025 | @mcp.tool() 4026 | async def get_alerts(state: str) -> str: 4027 | """Get weather alerts for a US state. 4028 | 4029 | Args: 4030 | state: Two-letter US state code (e.g. CA, NY) 4031 | """ 4032 | url = f"{NWS_API_BASE}/alerts/active/area/{state}" 4033 | data = await make_nws_request(url) 4034 | 4035 | if not data or "features" not in data: 4036 | return "Unable to fetch alerts or no alerts found." 4037 | 4038 | if not data["features"]: 4039 | return "No active alerts for this state." 4040 | 4041 | alerts = [format_alert(feature) for feature in data["features"]] 4042 | return "\n---\n".join(alerts) 4043 | 4044 | @mcp.tool() 4045 | async def get_forecast(latitude: float, longitude: float) -> str: 4046 | """Get weather forecast for a location. 4047 | 4048 | Args: 4049 | latitude: Latitude of the location 4050 | longitude: Longitude of the location 4051 | """ 4052 | # First get the forecast grid endpoint 4053 | points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}" 4054 | points_data = await make_nws_request(points_url) 4055 | 4056 | if not points_data: 4057 | return "Unable to fetch forecast data for this location." 4058 | 4059 | # Get the forecast URL from the points response 4060 | forecast_url = points_data["properties"]["forecast"] 4061 | forecast_data = await make_nws_request(forecast_url) 4062 | 4063 | if not forecast_data: 4064 | return "Unable to fetch detailed forecast." 4065 | 4066 | # Format the periods into a readable forecast 4067 | periods = forecast_data["properties"]["periods"] 4068 | forecasts = [] 4069 | for period in periods[:5]: # Only show next 5 periods 4070 | forecast = f""" 4071 | {period['name']}: 4072 | Temperature: {period['temperature']}°{period['temperatureUnit']} 4073 | Wind: {period['windSpeed']} {period['windDirection']} 4074 | Forecast: {period['detailedForecast']} 4075 | """ 4076 | forecasts.append(forecast) 4077 | 4078 | return "\n---\n".join(forecasts) 4079 | ``` 4080 | 4081 | ### Running the server 4082 | 4083 | Finally, let's initialize and run the server: 4084 | 4085 | ```python 4086 | if __name__ == "__main__": 4087 | # Initialize and run the server 4088 | mcp.run(transport='stdio') 4089 | ``` 4090 | 4091 | Your server is complete! Run `uv run weather.py` to confirm that everything's working. 4092 | 4093 | Let's now test your server from an existing MCP host, Claude for Desktop. 4094 | 4095 | ## Testing your server with Claude for Desktop 4096 | 4097 | <Note> 4098 | Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/quickstart/client) tutorial to build an MCP client that connects to the server we just built. 4099 | </Note> 4100 | 4101 | First, make sure you have Claude for Desktop installed. [You can install the latest version 4102 | here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.** 4103 | 4104 | We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist. 4105 | 4106 | For example, if you have [VS Code](https://code.visualstudio.com/) installed: 4107 | 4108 | <Tabs> 4109 | <Tab title="MacOS/Linux"> 4110 | ```bash 4111 | code ~/Library/Application\ Support/Claude/claude_desktop_config.json 4112 | ``` 4113 | </Tab> 4114 | 4115 | <Tab title="Windows"> 4116 | ```powershell 4117 | code $env:AppData\Claude\claude_desktop_config.json 4118 | ``` 4119 | </Tab> 4120 | </Tabs> 4121 | 4122 | You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured. 4123 | 4124 | In this case, we'll add our single weather server like so: 4125 | 4126 | <Tabs> 4127 | <Tab title="MacOS/Linux"> 4128 | ```json Python 4129 | { 4130 | "mcpServers": { 4131 | "weather": { 4132 | "command": "uv", 4133 | "args": [ 4134 | "--directory", 4135 | "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather", 4136 | "run", 4137 | "weather.py" 4138 | ] 4139 | } 4140 | } 4141 | } 4142 | ``` 4143 | </Tab> 4144 | 4145 | <Tab title="Windows"> 4146 | ```json Python 4147 | { 4148 | "mcpServers": { 4149 | "weather": { 4150 | "command": "uv", 4151 | "args": [ 4152 | "--directory", 4153 | "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather", 4154 | "run", 4155 | "weather.py" 4156 | ] 4157 | } 4158 | } 4159 | } 4160 | ``` 4161 | </Tab> 4162 | </Tabs> 4163 | 4164 | <Warning> 4165 | You may need to put the full path to the `uv` executable in the `command` field. You can get this by running `which uv` on MacOS/Linux or `where uv` on Windows. 4166 | </Warning> 4167 | 4168 | <Note> 4169 | Make sure you pass in the absolute path to your server. 4170 | </Note> 4171 | 4172 | This tells Claude for Desktop: 4173 | 4174 | 1. There's an MCP server named "weather" 4175 | 2. To launch it by running `uv --directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather run weather` 4176 | 4177 | Save the file, and restart **Claude for Desktop**. 4178 | 4179 | </Tab> 4180 | 4181 | <Tab title="Node"> 4182 | Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/quickstart-resources/tree/main/weather-server-typescript) 4183 | 4184 | ### Prerequisite knowledge 4185 | 4186 | This quickstart assumes you have familiarity with: 4187 | 4188 | * TypeScript 4189 | * LLMs like Claude 4190 | 4191 | ### System requirements 4192 | 4193 | For TypeScript, make sure you have the latest version of Node installed. 4194 | 4195 | ### Set up your environment 4196 | 4197 | First, let's install Node.js and npm if you haven't already. You can download them from [nodejs.org](https://nodejs.org/). 4198 | Verify your Node.js installation: 4199 | 4200 | ```bash 4201 | node --version 4202 | npm --version 4203 | ``` 4204 | 4205 | For this tutorial, you'll need Node.js version 16 or higher. 4206 | 4207 | Now, let's create and set up our project: 4208 | 4209 | <CodeGroup> 4210 | ```bash MacOS/Linux 4211 | # Create a new directory for our project 4212 | mkdir weather 4213 | cd weather 4214 | 4215 | # Initialize a new npm project 4216 | npm init -y 4217 | 4218 | # Install dependencies 4219 | npm install @modelcontextprotocol/sdk zod 4220 | npm install -D @types/node typescript 4221 | 4222 | # Create our files 4223 | mkdir src 4224 | touch src/index.ts 4225 | ``` 4226 | 4227 | ```powershell Windows 4228 | # Create a new directory for our project 4229 | md weather 4230 | cd weather 4231 | 4232 | # Initialize a new npm project 4233 | npm init -y 4234 | 4235 | # Install dependencies 4236 | npm install @modelcontextprotocol/sdk zod 4237 | npm install -D @types/node typescript 4238 | 4239 | # Create our files 4240 | md src 4241 | new-item src\index.ts 4242 | ``` 4243 | </CodeGroup> 4244 | 4245 | Update your package.json to add type: "module" and a build script: 4246 | 4247 | ```json package.json 4248 | { 4249 | "type": "module", 4250 | "bin": { 4251 | "weather": "./build/index.js" 4252 | }, 4253 | "scripts": { 4254 | "build": "tsc && node -e \"require('fs').chmodSync('build/index.js', '755')\"", 4255 | }, 4256 | "files": [ 4257 | "build" 4258 | ], 4259 | } 4260 | ``` 4261 | 4262 | Create a `tsconfig.json` in the root of your project: 4263 | 4264 | ```json tsconfig.json 4265 | { 4266 | "compilerOptions": { 4267 | "target": "ES2022", 4268 | "module": "Node16", 4269 | "moduleResolution": "Node16", 4270 | "outDir": "./build", 4271 | "rootDir": "./src", 4272 | "strict": true, 4273 | "esModuleInterop": true, 4274 | "skipLibCheck": true, 4275 | "forceConsistentCasingInFileNames": true 4276 | }, 4277 | "include": ["src/**/*"], 4278 | "exclude": ["node_modules"] 4279 | } 4280 | ``` 4281 | 4282 | Now let's dive into building your server. 4283 | 4284 | ## Building your server 4285 | 4286 | ### Importing packages and setting up the instance 4287 | 4288 | Add these to the top of your `src/index.ts`: 4289 | 4290 | ```typescript 4291 | import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; 4292 | import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; 4293 | import { z } from "zod"; 4294 | 4295 | const NWS_API_BASE = "https://api.weather.gov"; 4296 | const USER_AGENT = "weather-app/1.0"; 4297 | 4298 | // Create server instance 4299 | const server = new McpServer({ 4300 | name: "weather", 4301 | version: "1.0.0", 4302 | }); 4303 | ``` 4304 | 4305 | ### Helper functions 4306 | 4307 | Next, let's add our helper functions for querying and formatting the data from the National Weather Service API: 4308 | 4309 | ```typescript 4310 | // Helper function for making NWS API requests 4311 | async function makeNWSRequest<T>(url: string): Promise<T | null> { 4312 | const headers = { 4313 | "User-Agent": USER_AGENT, 4314 | Accept: "application/geo+json", 4315 | }; 4316 | 4317 | try { 4318 | const response = await fetch(url, { headers }); 4319 | if (!response.ok) { 4320 | throw new Error(`HTTP error! status: ${response.status}`); 4321 | } 4322 | return (await response.json()) as T; 4323 | } catch (error) { 4324 | console.error("Error making NWS request:", error); 4325 | return null; 4326 | } 4327 | } 4328 | 4329 | interface AlertFeature { 4330 | properties: { 4331 | event?: string; 4332 | areaDesc?: string; 4333 | severity?: string; 4334 | status?: string; 4335 | headline?: string; 4336 | }; 4337 | } 4338 | 4339 | // Format alert data 4340 | function formatAlert(feature: AlertFeature): string { 4341 | const props = feature.properties; 4342 | return [ 4343 | `Event: ${props.event || "Unknown"}`, 4344 | `Area: ${props.areaDesc || "Unknown"}`, 4345 | `Severity: ${props.severity || "Unknown"}`, 4346 | `Status: ${props.status || "Unknown"}`, 4347 | `Headline: ${props.headline || "No headline"}`, 4348 | "---", 4349 | ].join("\n"); 4350 | } 4351 | 4352 | interface ForecastPeriod { 4353 | name?: string; 4354 | temperature?: number; 4355 | temperatureUnit?: string; 4356 | windSpeed?: string; 4357 | windDirection?: string; 4358 | shortForecast?: string; 4359 | } 4360 | 4361 | interface AlertsResponse { 4362 | features: AlertFeature[]; 4363 | } 4364 | 4365 | interface PointsResponse { 4366 | properties: { 4367 | forecast?: string; 4368 | }; 4369 | } 4370 | 4371 | interface ForecastResponse { 4372 | properties: { 4373 | periods: ForecastPeriod[]; 4374 | }; 4375 | } 4376 | ``` 4377 | 4378 | ### Implementing tool execution 4379 | 4380 | The tool execution handler is responsible for actually executing the logic of each tool. Let's add it: 4381 | 4382 | ```typescript 4383 | // Register weather tools 4384 | server.tool( 4385 | "get-alerts", 4386 | "Get weather alerts for a state", 4387 | { 4388 | state: z.string().length(2).describe("Two-letter state code (e.g. CA, NY)"), 4389 | }, 4390 | async ({ state }) => { 4391 | const stateCode = state.toUpperCase(); 4392 | const alertsUrl = `${NWS_API_BASE}/alerts?area=${stateCode}`; 4393 | const alertsData = await makeNWSRequest<AlertsResponse>(alertsUrl); 4394 | 4395 | if (!alertsData) { 4396 | return { 4397 | content: [ 4398 | { 4399 | type: "text", 4400 | text: "Failed to retrieve alerts data", 4401 | }, 4402 | ], 4403 | }; 4404 | } 4405 | 4406 | const features = alertsData.features || []; 4407 | if (features.length === 0) { 4408 | return { 4409 | content: [ 4410 | { 4411 | type: "text", 4412 | text: `No active alerts for ${stateCode}`, 4413 | }, 4414 | ], 4415 | }; 4416 | } 4417 | 4418 | const formattedAlerts = features.map(formatAlert); 4419 | const alertsText = `Active alerts for ${stateCode}:\n\n${formattedAlerts.join("\n")}`; 4420 | 4421 | return { 4422 | content: [ 4423 | { 4424 | type: "text", 4425 | text: alertsText, 4426 | }, 4427 | ], 4428 | }; 4429 | }, 4430 | ); 4431 | 4432 | server.tool( 4433 | "get-forecast", 4434 | "Get weather forecast for a location", 4435 | { 4436 | latitude: z.number().min(-90).max(90).describe("Latitude of the location"), 4437 | longitude: z.number().min(-180).max(180).describe("Longitude of the location"), 4438 | }, 4439 | async ({ latitude, longitude }) => { 4440 | // Get grid point data 4441 | const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(4)},${longitude.toFixed(4)}`; 4442 | const pointsData = await makeNWSRequest<PointsResponse>(pointsUrl); 4443 | 4444 | if (!pointsData) { 4445 | return { 4446 | content: [ 4447 | { 4448 | type: "text", 4449 | text: `Failed to retrieve grid point data for coordinates: ${latitude}, ${longitude}. This location may not be supported by the NWS API (only US locations are supported).`, 4450 | }, 4451 | ], 4452 | }; 4453 | } 4454 | 4455 | const forecastUrl = pointsData.properties?.forecast; 4456 | if (!forecastUrl) { 4457 | return { 4458 | content: [ 4459 | { 4460 | type: "text", 4461 | text: "Failed to get forecast URL from grid point data", 4462 | }, 4463 | ], 4464 | }; 4465 | } 4466 | 4467 | // Get forecast data 4468 | const forecastData = await makeNWSRequest<ForecastResponse>(forecastUrl); 4469 | if (!forecastData) { 4470 | return { 4471 | content: [ 4472 | { 4473 | type: "text", 4474 | text: "Failed to retrieve forecast data", 4475 | }, 4476 | ], 4477 | }; 4478 | } 4479 | 4480 | const periods = forecastData.properties?.periods || []; 4481 | if (periods.length === 0) { 4482 | return { 4483 | content: [ 4484 | { 4485 | type: "text", 4486 | text: "No forecast periods available", 4487 | }, 4488 | ], 4489 | }; 4490 | } 4491 | 4492 | // Format forecast periods 4493 | const formattedForecast = periods.map((period: ForecastPeriod) => 4494 | [ 4495 | `${period.name || "Unknown"}:`, 4496 | `Temperature: ${period.temperature || "Unknown"}°${period.temperatureUnit || "F"}`, 4497 | `Wind: ${period.windSpeed || "Unknown"} ${period.windDirection || ""}`, 4498 | `${period.shortForecast || "No forecast available"}`, 4499 | "---", 4500 | ].join("\n"), 4501 | ); 4502 | 4503 | const forecastText = `Forecast for ${latitude}, ${longitude}:\n\n${formattedForecast.join("\n")}`; 4504 | 4505 | return { 4506 | content: [ 4507 | { 4508 | type: "text", 4509 | text: forecastText, 4510 | }, 4511 | ], 4512 | }; 4513 | }, 4514 | ); 4515 | ``` 4516 | 4517 | ### Running the server 4518 | 4519 | Finally, implement the main function to run the server: 4520 | 4521 | ```typescript 4522 | async function main() { 4523 | const transport = new StdioServerTransport(); 4524 | await server.connect(transport); 4525 | console.error("Weather MCP Server running on stdio"); 4526 | } 4527 | 4528 | main().catch((error) => { 4529 | console.error("Fatal error in main():", error); 4530 | process.exit(1); 4531 | }); 4532 | ``` 4533 | 4534 | Make sure to run `npm run build` to build your server! This is a very important step in getting your server to connect. 4535 | 4536 | Let's now test your server from an existing MCP host, Claude for Desktop. 4537 | 4538 | ## Testing your server with Claude for Desktop 4539 | 4540 | <Note> 4541 | Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/quickstart/client) tutorial to build an MCP client that connects to the server we just built. 4542 | </Note> 4543 | 4544 | First, make sure you have Claude for Desktop installed. [You can install the latest version 4545 | here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.** 4546 | 4547 | We'll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. Make sure to create the file if it doesn't exist. 4548 | 4549 | For example, if you have [VS Code](https://code.visualstudio.com/) installed: 4550 | 4551 | <Tabs> 4552 | <Tab title="MacOS/Linux"> 4553 | ```bash 4554 | code ~/Library/Application\ Support/Claude/claude_desktop_config.json 4555 | ``` 4556 | </Tab> 4557 | 4558 | <Tab title="Windows"> 4559 | ```powershell 4560 | code $env:AppData\Claude\claude_desktop_config.json 4561 | ``` 4562 | </Tab> 4563 | </Tabs> 4564 | 4565 | You'll then add your servers in the `mcpServers` key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured. 4566 | 4567 | In this case, we'll add our single weather server like so: 4568 | 4569 | <Tabs> 4570 | <Tab title="MacOS/Linux"> 4571 | <CodeGroup> 4572 | ```json Node 4573 | { 4574 | "mcpServers": { 4575 | "weather": { 4576 | "command": "node", 4577 | "args": [ 4578 | "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js" 4579 | ] 4580 | } 4581 | } 4582 | } 4583 | ``` 4584 | </CodeGroup> 4585 | </Tab> 4586 | 4587 | <Tab title="Windows"> 4588 | <CodeGroup> 4589 | ```json Node 4590 | { 4591 | "mcpServers": { 4592 | "weather": { 4593 | "command": "node", 4594 | "args": [ 4595 | "C:\\PATH\\TO\\PARENT\\FOLDER\\weather\\build\\index.js" 4596 | ] 4597 | } 4598 | } 4599 | } 4600 | ``` 4601 | </CodeGroup> 4602 | </Tab> 4603 | </Tabs> 4604 | 4605 | This tells Claude for Desktop: 4606 | 4607 | 1. There's an MCP server named "weather" 4608 | 2. Launch it by running `node /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js` 4609 | 4610 | Save the file, and restart **Claude for Desktop**. 4611 | 4612 | </Tab> 4613 | 4614 | <Tab title="Java"> 4615 | <Note> 4616 | This is a quickstart demo based on Spring AI MCP auto-configuraiton and boot starters. 4617 | To learn how to create sync and async MCP Servers, manually, consult the [Java SDK Server](/sdk/java/mcp-server) documentation. 4618 | </Note> 4619 | 4620 | Let's get started with building our weather server! 4621 | [You can find the complete code for what we'll be building here.](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/weather/starter-stdio-server) 4622 | 4623 | For more information, see the [MCP Server Boot Starter](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html) reference documentation. 4624 | For manual MCP Server implementation, refer to the [MCP Server Java SDK documentation](/sdk/java/mcp-server). 4625 | 4626 | ### System requirements 4627 | 4628 | * Java 17 or higher installed. 4629 | * [Spring Boot 3.3.x](https://docs.spring.io/spring-boot/installing.html) or higher 4630 | 4631 | ### Set up your environment 4632 | 4633 | Use the [Spring Initizer](https://start.spring.io/) to bootstrat the project. 4634 | 4635 | You will need to add the following dependencies: 4636 | 4637 | <Tabs> 4638 | <Tab title="Maven"> 4639 | ```xml 4640 | <dependencies> 4641 | <dependency> 4642 | <groupId>org.springframework.ai</groupId> 4643 | <artifactId>spring-ai-mcp-server-spring-boot-starter</artifactId> 4644 | </dependency> 4645 | 4646 | <dependency> 4647 | <groupId>org.springframework</groupId> 4648 | <artifactId>spring-web</artifactId> 4649 | </dependency> 4650 | </dependencies> 4651 | ``` 4652 | </Tab> 4653 | 4654 | <Tab title="Gradle"> 4655 | ```groovy 4656 | dependencies { 4657 | implementation platform("org.springframework.ai:spring-ai-mcp-server-spring-boot-starter") 4658 | implementation platform("org.springframework:spring-web") 4659 | } 4660 | ``` 4661 | </Tab> 4662 | </Tabs> 4663 | 4664 | Then configure your application by setting the applicaiton properties: 4665 | 4666 | <CodeGroup> 4667 | ```bash application.properties 4668 | spring.main.bannerMode=off 4669 | logging.pattern.console= 4670 | ``` 4671 | 4672 | ```yaml application.yml 4673 | logging: 4674 | pattern: 4675 | console: 4676 | spring: 4677 | main: 4678 | banner-mode: off 4679 | ``` 4680 | </CodeGroup> 4681 | 4682 | The [Server Configuration Properties](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-starter-docs.html#_configuration_properties) documents all available properties. 4683 | 4684 | Now let's dive into building your server. 4685 | 4686 | ## Building your server 4687 | 4688 | ### Weather Service 4689 | 4690 | Let's implement a [WeatheService.java](https://github.com/spring-projects/spring-ai-examples/blob/main/model-context-protocol/weather/starter-stdio-server/src/main/java/org/springframework/ai/mcp/sample/server/WeatherService.java) that uses a REST client to query the data from the National Weather Service API: 4691 | 4692 | ```java 4693 | @Service 4694 | public class WeatherService { 4695 | 4696 | private final RestClient restClient; 4697 | 4698 | public WeatherService() { 4699 | this.restClient = RestClient.builder() 4700 | .baseUrl("https://api.weather.gov") 4701 | .defaultHeader("Accept", "application/geo+json") 4702 | .defaultHeader("User-Agent", "WeatherApiClient/1.0 ([email protected])") 4703 | .build(); 4704 | } 4705 | 4706 | @Tool(description = "Get weather forecast for a specific latitude/longitude") 4707 | public String getWeatherForecastByLocation( 4708 | double latitude, // Latitude coordinate 4709 | double longitude // Longitude coordinate 4710 | ) { 4711 | // Returns detailed forecast including: 4712 | // - Temperature and unit 4713 | // - Wind speed and direction 4714 | // - Detailed forecast description 4715 | } 4716 | 4717 | @Tool(description = "Get weather alerts for a US state") 4718 | public String getAlerts( 4719 | @ToolParam(description = "Two-letter US state code (e.g. CA, NY") String state) 4720 | ) { 4721 | // Returns active alerts including: 4722 | // - Event type 4723 | // - Affected area 4724 | // - Severity 4725 | // - Description 4726 | // - Safety instructions 4727 | } 4728 | 4729 | // ...... 4730 | } 4731 | ``` 4732 | 4733 | The `@Service` annotation with auto-register the service in your applicaiton context. 4734 | The Spring AI `@Tool` annotation, making it easy to create and maintain MCP tools. 4735 | 4736 | The auto-configuration will automatically register these tools with the MCP server. 4737 | 4738 | ### Create your Boot Applicaiton 4739 | 4740 | ```java 4741 | @SpringBootApplication 4742 | public class McpServerApplication { 4743 | 4744 | public static void main(String[] args) { 4745 | SpringApplication.run(McpServerApplication.class, args); 4746 | } 4747 | 4748 | @Bean 4749 | public ToolCallbackProvider weatherTools(WeatherService weatherService) { 4750 | return MethodToolCallbackProvider.builder().toolObjects(weatherService).build(); 4751 | } 4752 | } 4753 | ``` 4754 | 4755 | Uses the the `MethodToolCallbackProvider` utils to convert the `@Tools` into actionalble callbackes used by the MCP server. 4756 | 4757 | ### Running the server 4758 | 4759 | Finally, let's build the server: 4760 | 4761 | ```bash 4762 | ./mvnw clean install 4763 | ``` 4764 | 4765 | This will generate a `mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar` file within the `target` folder. 4766 | 4767 | Let's now test your server from an existing MCP host, Claude for Desktop. 4768 | 4769 | ## Testing your server with Claude for Desktop 4770 | 4771 | <Note> 4772 | Claude for Desktop is not yet available on Linux. 4773 | </Note> 4774 | 4775 | First, make sure you have Claude for Desktop installed. 4776 | [You can install the latest version here.](https://claude.ai/download) If you already have Claude for Desktop, **make sure it's updated to the latest version.** 4777 | 4778 | We'll need to configure Claude for Desktop for whichever MCP servers you want to use. 4779 | To do this, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor. 4780 | Make sure to create the file if it doesn't exist. 4781 | 4782 | For example, if you have [VS Code](https://code.visualstudio.com/) installed: 4783 | 4784 | <Tabs> 4785 | <Tab title="MacOS/Linux"> 4786 | ```bash 4787 | code ~/Library/Application\ Support/Claude/claude_desktop_config.json 4788 | ``` 4789 | </Tab> 4790 | 4791 | <Tab title="Windows"> 4792 | ```powershell 4793 | code $env:AppData\Claude\claude_desktop_config.json 4794 | ``` 4795 | </Tab> 4796 | </Tabs> 4797 | 4798 | You'll then add your servers in the `mcpServers` key. 4799 | The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured. 4800 | 4801 | In this case, we'll add our single weather server like so: 4802 | 4803 | <Tabs> 4804 | <Tab title="MacOS/Linux"> 4805 | ```json java 4806 | { 4807 | "mcpServers": { 4808 | "spring-ai-mcp-weather": { 4809 | "command": "java", 4810 | "args": [ 4811 | "-Dspring.ai.mcp.server.stdio=true", 4812 | "-jar", 4813 | "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar" 4814 | ] 4815 | } 4816 | } 4817 | } 4818 | ``` 4819 | </Tab> 4820 | 4821 | <Tab title="Windows"> 4822 | ```json java 4823 | { 4824 | "mcpServers": { 4825 | "spring-ai-mcp-weather": { 4826 | "command": "java", 4827 | "args": [ 4828 | "-Dspring.ai.mcp.server.transport=STDIO", 4829 | "-jar", 4830 | "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\weather\\mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar" 4831 | ] 4832 | } 4833 | } 4834 | } 4835 | ``` 4836 | </Tab> 4837 | </Tabs> 4838 | 4839 | <Note> 4840 | Make sure you pass in the absolute path to your server. 4841 | </Note> 4842 | 4843 | This tells Claude for Desktop: 4844 | 4845 | 1. There's an MCP server named "my-weather-server" 4846 | 2. To launch it by running `java -jar /ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar` 4847 | 4848 | Save the file, and restart **Claude for Desktop**. 4849 | 4850 | ## Testing your server with Java client 4851 | 4852 | ### Create a MCP Client manually 4853 | 4854 | Use the `McpClient` to connect to the server: 4855 | 4856 | ```java 4857 | var stdioParams = ServerParameters.builder("java") 4858 | .args("-jar", "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-weather-stdio-server-0.0.1-SNAPSHOT.jar") 4859 | .build(); 4860 | 4861 | var stdioTransport = new StdioClientTransport(stdioParams); 4862 | 4863 | var mcpClient = McpClient.sync(stdioTransport).build(); 4864 | 4865 | mcpClient.initialize(); 4866 | 4867 | ListToolsResult toolsList = mcpClient.listTools(); 4868 | 4869 | CallToolResult weather = mcpClient.callTool( 4870 | new CallToolRequest("getWeatherForecastByLocation", 4871 | Map.of("latitude", "47.6062", "longitude", "-122.3321"))); 4872 | 4873 | CallToolResult alert = mcpClient.callTool( 4874 | new CallToolRequest("getAlerts", Map.of("state", "NY"))); 4875 | 4876 | mcpClient.closeGracefully(); 4877 | ``` 4878 | 4879 | ### Use MCP Client Boot Starter 4880 | 4881 | Create a new boot starter applicaiton using the `spring-ai-mcp-client-spring-boot-starter` dependency: 4882 | 4883 | ```xml 4884 | <dependency> 4885 | <groupId>org.springframework.ai</groupId> 4886 | <artifactId>spring-ai-mcp-client-spring-boot-starter</artifactId> 4887 | </dependency> 4888 | ``` 4889 | 4890 | and set the `spring.ai.mcp.client.stdio.servers-configuration` property to point to your `claude_desktop_config.json`. 4891 | You can re-use the existing Anthropic Destop configuration: 4892 | 4893 | ```properties 4894 | spring.ai.mcp.client.stdio.servers-configuration=file:PATH/TO/claude_desktop_config.json 4895 | ``` 4896 | 4897 | When you stasrt your client applicaiton, the auto-configuration will create, automatically MCP clients from the claude\_desktop\_config.json. 4898 | 4899 | For more information, see the [MCP Client Boot Starters](https://docs.spring.io/spring-ai/reference/api/mcp/mcp-server-boot-client-docs.html) reference documentation. 4900 | 4901 | ## More Java MCP Server examples 4902 | 4903 | The [starter-webflux-server](https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol/weather/starter-webflux-server) demonstrates how to create a MCP server using SSE transport. 4904 | It showcases how to define and register MCP Tools, Resources, and Prompts, using the Spring Boot's auto-configuration capabilities. 4905 | 4906 | </Tab> 4907 | </Tabs> 4908 | 4909 | ### Test with commands 4910 | 4911 | Let's make sure Claude for Desktop is picking up the two tools we've exposed in our `weather` server. You can do this by looking for the hammer <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/claude-desktop-mcp-hammer-icon.svg" style={{display: 'inline', margin: 0, height: '1.3em'}} /> icon: 4912 | 4913 | <Frame> 4914 | <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/visual-indicator-mcp-tools.png" /> 4915 | </Frame> 4916 | 4917 | After clicking on the hammer icon, you should see two tools listed: 4918 | 4919 | <Frame> 4920 | <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/available-mcp-tools.png" /> 4921 | </Frame> 4922 | 4923 | If your server isn't being picked up by Claude for Desktop, proceed to the [Troubleshooting](#troubleshooting) section for debugging tips. 4924 | 4925 | If the hammer icon has shown up, you can now test your server by running the following commands in Claude for Desktop: 4926 | 4927 | - What's the weather in Sacramento? 4928 | - What are the active weather alerts in Texas? 4929 | 4930 | <Frame> 4931 | <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/current-weather.png" /> 4932 | </Frame> 4933 | 4934 | <Frame> 4935 | <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/weather-alerts.png" /> 4936 | </Frame> 4937 | 4938 | <Note> 4939 | Since this is the US National Weather service, the queries will only work for US locations. 4940 | </Note> 4941 | 4942 | ## What's happening under the hood 4943 | 4944 | When you ask a question: 4945 | 4946 | 1. The client sends your question to Claude 4947 | 2. Claude analyzes the available tools and decides which one(s) to use 4948 | 3. The client executes the chosen tool(s) through the MCP server 4949 | 4. The results are sent back to Claude 4950 | 5. Claude formulates a natural language response 4951 | 6. The response is displayed to you! 4952 | 4953 | ## Troubleshooting 4954 | 4955 | <AccordionGroup> 4956 | <Accordion title="Claude for Desktop Integration Issues"> 4957 | **Getting logs from Claude for Desktop** 4958 | 4959 | Claude.app logging related to MCP is written to log files in `~/Library/Logs/Claude`: 4960 | 4961 | * `mcp.log` will contain general logging about MCP connections and connection failures. 4962 | * Files named `mcp-server-SERVERNAME.log` will contain error (stderr) logging from the named server. 4963 | 4964 | You can run the following command to list recent logs and follow along with any new ones: 4965 | 4966 | ```bash 4967 | # Check Claude's logs for errors 4968 | tail -n 20 -f ~/Library/Logs/Claude/mcp*.log 4969 | ``` 4970 | 4971 | **Server not showing up in Claude** 4972 | 4973 | 1. Check your `claude_desktop_config.json` file syntax 4974 | 2. Make sure the path to your project is absolute and not relative 4975 | 3. Restart Claude for Desktop completely 4976 | 4977 | **Tool calls failing silently** 4978 | 4979 | If Claude attempts to use the tools but they fail: 4980 | 4981 | 1. Check Claude's logs for errors 4982 | 2. Verify your server builds and runs without errors 4983 | 3. Try restarting Claude for Desktop 4984 | 4985 | **None of this is working. What do I do?** 4986 | 4987 | Please refer to our [debugging guide](/docs/tools/debugging) for better debugging tools and more detailed guidance. 4988 | 4989 | </Accordion> 4990 | 4991 | <Accordion title="Weather API Issues"> 4992 | **Error: Failed to retrieve grid point data** 4993 | 4994 | This usually means either: 4995 | 4996 | 1. The coordinates are outside the US 4997 | 2. The NWS API is having issues 4998 | 3. You're being rate limited 4999 | 5000 | Fix: 5001 | 5002 | * Verify you're using US coordinates 5003 | * Add a small delay between requests 5004 | * Check the NWS API status page 5005 | 5006 | **Error: No active alerts for \[STATE]** 5007 | 5008 | This isn't an error - it just means there are no current weather alerts for that state. Try a different state or check during severe weather. 5009 | 5010 | </Accordion> 5011 | </AccordionGroup> 5012 | 5013 | <Note> 5014 | For more advanced troubleshooting, check out our guide on [Debugging MCP](/docs/tools/debugging) 5015 | </Note> 5016 | 5017 | ## Next steps 5018 | 5019 | <CardGroup cols={2}> 5020 | <Card title="Building a client" icon="outlet" href="/quickstart/client"> 5021 | Learn how to build your own MCP client that can connect to your server 5022 | </Card> 5023 | 5024 | <Card title="Example servers" icon="grid" href="/examples"> 5025 | Check out our gallery of official MCP servers and implementations 5026 | </Card> 5027 | 5028 | <Card title="Debugging Guide" icon="bug" href="/docs/tools/debugging"> 5029 | Learn how to effectively debug MCP servers and integrations 5030 | </Card> 5031 | 5032 | <Card title="Building MCP with LLMs" icon="comments" href="/building-mcp-with-llms"> 5033 | Learn how to use LLMs like Claude to speed up your MCP development 5034 | </Card> 5035 | </CardGroup> 5036 | 5037 | # For Claude Desktop Users 5038 | 5039 | Source: https://modelcontextprotocol.io/quickstart/user 5040 | 5041 | Get started using pre-built servers in Claude for Desktop. 5042 | 5043 | 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. 5044 | 5045 | <Frame> 5046 | <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-filesystem.png" /> 5047 | </Frame> 5048 | 5049 | Don't worry — it will ask you for your permission before executing these actions! 5050 | 5051 | ## 1. Download Claude for Desktop 5052 | 5053 | Start by downloading [Claude for Desktop](https://claude.ai/download), choosing either macOS or Windows. (Linux is not yet supported for Claude for Desktop.) 5054 | 5055 | Follow the installation instructions. 5056 | 5057 | 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..." 5058 | 5059 | <Accordion title="Why Claude for Desktop and not Claude.ai?"> 5060 | Because servers are locally run, MCP currently only supports desktop hosts. Remote hosts are in active development. 5061 | </Accordion> 5062 | 5063 | ## 2. Add the Filesystem MCP Server 5064 | 5065 | 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. 5066 | 5067 | 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. 5068 | 5069 | This is what it should look like on a Mac: 5070 | 5071 | <Frame style={{ textAlign: 'center' }}> 5072 | <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-menu.png" width="400" /> 5073 | </Frame> 5074 | 5075 | Click on "Developer" in the lefthand bar of the Settings pane, and then click on "Edit Config": 5076 | 5077 | <Frame> 5078 | <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-developer.png" /> 5079 | </Frame> 5080 | 5081 | This will create a configuration file at: 5082 | 5083 | - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json` 5084 | - Windows: `%APPDATA%\Claude\claude_desktop_config.json` 5085 | 5086 | if you don't already have one, and will display the file in your file system. 5087 | 5088 | Open up the configuration file in any text editor. Replace the file contents with this: 5089 | 5090 | <Tabs> 5091 | <Tab title="MacOS/Linux"> 5092 | ```json 5093 | { 5094 | "mcpServers": { 5095 | "filesystem": { 5096 | "command": "npx", 5097 | "args": [ 5098 | "-y", 5099 | "@modelcontextprotocol/server-filesystem", 5100 | "/Users/username/Desktop", 5101 | "/Users/username/Downloads" 5102 | ] 5103 | } 5104 | } 5105 | } 5106 | ``` 5107 | </Tab> 5108 | 5109 | <Tab title="Windows"> 5110 | ```json 5111 | { 5112 | "mcpServers": { 5113 | "filesystem": { 5114 | "command": "npx", 5115 | "args": [ 5116 | "-y", 5117 | "@modelcontextprotocol/server-filesystem", 5118 | "C:\\Users\\username\\Desktop", 5119 | "C:\\Users\\username\\Downloads" 5120 | ] 5121 | } 5122 | } 5123 | } 5124 | ``` 5125 | </Tab> 5126 | </Tabs> 5127 | 5128 | 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. 5129 | 5130 | 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. 5131 | 5132 | - On macOS, open the Terminal from your Applications folder 5133 | - On Windows, press Windows + R, type "cmd", and press Enter 5134 | 5135 | Once in the command line, verify you have Node installed by entering in the following command: 5136 | 5137 | ```bash 5138 | node --version 5139 | ``` 5140 | 5141 | If you get an error saying "command not found" or "node is not recognized", download Node from [nodejs.org](https://nodejs.org/). 5142 | 5143 | <Tip> 5144 | **How does the configuration file work?** 5145 | 5146 | 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. 5147 | </Tip> 5148 | 5149 | <Warning> 5150 | **Command Privileges** 5151 | 5152 | 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. 5153 | </Warning> 5154 | 5155 | ## 3. Restart Claude 5156 | 5157 | After updating your configuration file, you need to restart Claude for Desktop. 5158 | 5159 | Upon restarting, you should see a hammer <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/claude-desktop-mcp-hammer-icon.svg" style={{display: 'inline', margin: 0, height: '1.3em'}} /> icon in the bottom right corner of the input box: 5160 | 5161 | <Frame> 5162 | <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-hammer.png" /> 5163 | </Frame> 5164 | 5165 | After clicking on the hammer icon, you should see the tools that come with the Filesystem MCP Server: 5166 | 5167 | <Frame style={{ textAlign: 'center' }}> 5168 | <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-tools.png" width="400" /> 5169 | </Frame> 5170 | 5171 | If your server isn't being picked up by Claude for Desktop, proceed to the [Troubleshooting](#troubleshooting) section for debugging tips. 5172 | 5173 | ## 4. Try it out! 5174 | 5175 | You can now talk to Claude and ask it about your filesystem. It should know when to call the relevant tools. 5176 | 5177 | Things you might try asking Claude: 5178 | 5179 | - Can you write a poem and save it to my desktop? 5180 | - What are some work-related files in my downloads folder? 5181 | - Can you take all the images on my desktop and move them to a new folder called "Images"? 5182 | 5183 | As needed, Claude will call the relevant tools and seek your approval before taking an action: 5184 | 5185 | <Frame style={{ textAlign: 'center' }}> 5186 | <img src="https://mintlify.s3.us-west-1.amazonaws.com/mcp/images/quickstart-approve.png" width="500" /> 5187 | </Frame> 5188 | 5189 | ## Troubleshooting 5190 | 5191 | <AccordionGroup> 5192 | <Accordion title="Server not showing up in Claude / hammer icon missing"> 5193 | 1. Restart Claude for Desktop completely 5194 | 2. Check your `claude_desktop_config.json` file syntax 5195 | 3. Make sure the file paths included in `claude_desktop_config.json` are valid and that they are absolute and not relative 5196 | 4. Look at [logs](#getting-logs-from-claude-for-desktop) to see why the server is not connecting 5197 | 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: 5198 | 5199 | <Tabs> 5200 | <Tab title="MacOS/Linux"> 5201 | ```bash 5202 | npx -y @modelcontextprotocol/server-filesystem /Users/username/Desktop /Users/username/Downloads 5203 | ``` 5204 | </Tab> 5205 | 5206 | <Tab title="Windows"> 5207 | ```bash 5208 | npx -y @modelcontextprotocol/server-filesystem C:\Users\username\Desktop C:\Users\username\Downloads 5209 | ``` 5210 | </Tab> 5211 | </Tabs> 5212 | 5213 | </Accordion> 5214 | 5215 | <Accordion title="Getting logs from Claude for Desktop"> 5216 | Claude.app logging related to MCP is written to log files in: 5217 | 5218 | * macOS: `~/Library/Logs/Claude` 5219 | 5220 | * Windows: `%APPDATA%\Claude\logs` 5221 | 5222 | * `mcp.log` will contain general logging about MCP connections and connection failures. 5223 | 5224 | * Files named `mcp-server-SERVERNAME.log` will contain error (stderr) logging from the named server. 5225 | 5226 | 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): 5227 | 5228 | <Tabs> 5229 | <Tab title="MacOS/Linux"> 5230 | ```bash 5231 | # Check Claude's logs for errors 5232 | tail -n 20 -f ~/Library/Logs/Claude/mcp*.log 5233 | ``` 5234 | </Tab> 5235 | 5236 | <Tab title="Windows"> 5237 | ```bash 5238 | type "%APPDATA%\Claude\logs\mcp*.log" 5239 | ``` 5240 | </Tab> 5241 | </Tabs> 5242 | 5243 | </Accordion> 5244 | 5245 | <Accordion title="Tool calls failing silently"> 5246 | If Claude attempts to use the tools but they fail: 5247 | 5248 | 1. Check Claude's logs for errors 5249 | 2. Verify your server builds and runs without errors 5250 | 3. Try restarting Claude for Desktop 5251 | 5252 | </Accordion> 5253 | 5254 | <Accordion title="None of this is working. What do I do?"> 5255 | Please refer to our [debugging guide](/docs/tools/debugging) for better debugging tools and more detailed guidance. 5256 | </Accordion> 5257 | 5258 | <Accordion title="ENOENT error and `${APPDATA}` in paths on Windows"> 5259 | 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`: 5260 | 5261 | ```json 5262 | { 5263 | "brave-search": { 5264 | "command": "npx", 5265 | "args": ["-y", "@modelcontextprotocol/server-brave-search"], 5266 | "env": { 5267 | "APPDATA": "C:\\Users\\user\\AppData\\Roaming\\", 5268 | "BRAVE_API_KEY": "..." 5269 | } 5270 | } 5271 | } 5272 | ``` 5273 | 5274 | With this change in place, launch Claude Desktop once again. 5275 | 5276 | <Warning> 5277 | **NPM should be installed globally** 5278 | 5279 | 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: 5280 | 5281 | ```bash 5282 | npm install -g npm 5283 | ``` 5284 | </Warning> 5285 | 5286 | </Accordion> 5287 | </AccordionGroup> 5288 | 5289 | ## Next steps 5290 | 5291 | <CardGroup cols={2}> 5292 | <Card title="Explore other servers" icon="grid" href="/examples"> 5293 | Check out our gallery of official MCP servers and implementations 5294 | </Card> 5295 | 5296 | <Card title="Build your own server" icon="code" href="/quickstart/server"> 5297 | Now build your own custom server to use in Claude for Desktop and other clients 5298 | </Card> 5299 | </CardGroup> 5300 | 5301 | # MCP Client 5302 | 5303 | Source: https://modelcontextprotocol.io/sdk/java/mcp-client 5304 | 5305 | Learn how to use the Model Context Protocol (MCP) client to interact with MCP servers 5306 | 5307 | # Model Context Protocol Client 5308 | 5309 | 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: 5310 | 5311 | - Protocol version negotiation to ensure compatibility with servers 5312 | - Capability negotiation to determine available features 5313 | - Message transport and JSON-RPC communication 5314 | - Tool discovery and execution 5315 | - Resource access and management 5316 | - Prompt system interactions 5317 | - Optional features like roots management and sampling support 5318 | 5319 | The client provides both synchronous and asynchronous APIs for flexibility in different application contexts. 5320 | 5321 | <Tabs> 5322 | <Tab title="Sync API"> 5323 | ```java 5324 | // Create a sync client with custom configuration 5325 | McpSyncClient client = McpClient.sync(transport) 5326 | .requestTimeout(Duration.ofSeconds(10)) 5327 | .capabilities(ClientCapabilities.builder() 5328 | .roots(true) // Enable roots capability 5329 | .sampling() // Enable sampling capability 5330 | .build()) 5331 | .sampling(request -> new CreateMessageResult(response)) 5332 | .build(); 5333 | 5334 | // Initialize connection 5335 | client.initialize(); 5336 | 5337 | // List available tools 5338 | ListToolsResult tools = client.listTools(); 5339 | 5340 | // Call a tool 5341 | CallToolResult result = client.callTool( 5342 | new CallToolRequest("calculator", 5343 | Map.of("operation", "add", "a", 2, "b", 3)) 5344 | ); 5345 | 5346 | // List and read resources 5347 | ListResourcesResult resources = client.listResources(); 5348 | ReadResourceResult resource = client.readResource( 5349 | new ReadResourceRequest("resource://uri") 5350 | ); 5351 | 5352 | // List and use prompts 5353 | ListPromptsResult prompts = client.listPrompts(); 5354 | GetPromptResult prompt = client.getPrompt( 5355 | new GetPromptRequest("greeting", Map.of("name", "Spring")) 5356 | ); 5357 | 5358 | // Add/remove roots 5359 | client.addRoot(new Root("file:///path", "description")); 5360 | client.removeRoot("file:///path"); 5361 | 5362 | // Close client 5363 | client.closeGracefully(); 5364 | ``` 5365 | 5366 | </Tab> 5367 | 5368 | <Tab title="Async API"> 5369 | ```java 5370 | // Create an async client with custom configuration 5371 | McpAsyncClient client = McpClient.async(transport) 5372 | .requestTimeout(Duration.ofSeconds(10)) 5373 | .capabilities(ClientCapabilities.builder() 5374 | .roots(true) // Enable roots capability 5375 | .sampling() // Enable sampling capability 5376 | .build()) 5377 | .sampling(request -> Mono.just(new CreateMessageResult(response))) 5378 | .toolsChangeConsumer(tools -> Mono.fromRunnable(() -> { 5379 | logger.info("Tools updated: {}", tools); 5380 | })) 5381 | .resourcesChangeConsumer(resources -> Mono.fromRunnable(() -> { 5382 | logger.info("Resources updated: {}", resources); 5383 | })) 5384 | .promptsChangeConsumer(prompts -> Mono.fromRunnable(() -> { 5385 | logger.info("Prompts updated: {}", prompts); 5386 | })) 5387 | .build(); 5388 | 5389 | // Initialize connection and use features 5390 | client.initialize() 5391 | .flatMap(initResult -> client.listTools()) 5392 | .flatMap(tools -> { 5393 | return client.callTool(new CallToolRequest( 5394 | "calculator", 5395 | Map.of("operation", "add", "a", 2, "b", 3) 5396 | )); 5397 | }) 5398 | .flatMap(result -> { 5399 | return client.listResources() 5400 | .flatMap(resources -> 5401 | client.readResource(new ReadResourceRequest("resource://uri")) 5402 | ); 5403 | }) 5404 | .flatMap(resource -> { 5405 | return client.listPrompts() 5406 | .flatMap(prompts -> 5407 | client.getPrompt(new GetPromptRequest( 5408 | "greeting", 5409 | Map.of("name", "Spring") 5410 | )) 5411 | ); 5412 | }) 5413 | .flatMap(prompt -> { 5414 | return client.addRoot(new Root("file:///path", "description")) 5415 | .then(client.removeRoot("file:///path")); 5416 | }) 5417 | .doFinally(signalType -> { 5418 | client.closeGracefully().subscribe(); 5419 | }) 5420 | .subscribe(); 5421 | ``` 5422 | 5423 | </Tab> 5424 | </Tabs> 5425 | 5426 | ## Client Transport 5427 | 5428 | 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. 5429 | 5430 | <Tabs> 5431 | <Tab title="STDIO"> 5432 | Creates transport for in-process based communication 5433 | 5434 | ```java 5435 | ServerParameters params = ServerParameters.builder("npx") 5436 | .args("-y", "@modelcontextprotocol/server-everything", "dir") 5437 | .build(); 5438 | McpTransport transport = new StdioClientTransport(params); 5439 | ``` 5440 | 5441 | </Tab> 5442 | 5443 | <Tab title="SSE (HttpClient)"> 5444 | Creates a framework agnostic (pure Java API) SSE client transport. Included in the core mcp module. 5445 | 5446 | ```java 5447 | McpTransport transport = new HttpClientSseClientTransport("http://your-mcp-server"); 5448 | ``` 5449 | 5450 | </Tab> 5451 | 5452 | <Tab title="SSE (WebFlux)"> 5453 | Creates WebFlux-based SSE client transport. Requires the mcp-webflux-sse-transport dependency. 5454 | 5455 | ```java 5456 | WebClient.Builder webClientBuilder = WebClient.builder() 5457 | .baseUrl("http://your-mcp-server"); 5458 | McpTransport transport = new WebFluxSseClientTransport(webClientBuilder); 5459 | ``` 5460 | 5461 | </Tab> 5462 | </Tabs> 5463 | 5464 | ## Client Capabilities 5465 | 5466 | The client can be configured with various capabilities: 5467 | 5468 | ```java 5469 | var capabilities = ClientCapabilities.builder() 5470 | .roots(true) // Enable filesystem roots support with list changes notifications 5471 | .sampling() // Enable LLM sampling support 5472 | .build(); 5473 | ``` 5474 | 5475 | ### Roots Support 5476 | 5477 | Roots define the boundaries of where servers can operate within the filesystem: 5478 | 5479 | ```java 5480 | // Add a root dynamically 5481 | client.addRoot(new Root("file:///path", "description")); 5482 | 5483 | // Remove a root 5484 | client.removeRoot("file:///path"); 5485 | 5486 | // Notify server of roots changes 5487 | client.rootsListChangedNotification(); 5488 | ``` 5489 | 5490 | The roots capability allows servers to: 5491 | 5492 | - Request the list of accessible filesystem roots 5493 | - Receive notifications when the roots list changes 5494 | - Understand which directories and files they have access to 5495 | 5496 | ### Sampling Support 5497 | 5498 | Sampling enables servers to request LLM interactions ("completions" or "generations") through the client: 5499 | 5500 | ```java 5501 | // Configure sampling handler 5502 | Function<CreateMessageRequest, CreateMessageResult> samplingHandler = request -> { 5503 | // Sampling implementation that interfaces with LLM 5504 | return new CreateMessageResult(response); 5505 | }; 5506 | 5507 | // Create client with sampling support 5508 | var client = McpClient.sync(transport) 5509 | .capabilities(ClientCapabilities.builder() 5510 | .sampling() 5511 | .build()) 5512 | .sampling(samplingHandler) 5513 | .build(); 5514 | ``` 5515 | 5516 | This capability allows: 5517 | 5518 | - Servers to leverage AI capabilities without requiring API keys 5519 | - Clients to maintain control over model access and permissions 5520 | - Support for both text and image-based interactions 5521 | - Optional inclusion of MCP server context in prompts 5522 | 5523 | ## Using MCP Clients 5524 | 5525 | ### Tool Execution 5526 | 5527 | 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. 5528 | 5529 | <Tabs> 5530 | <Tab title="Sync API"> 5531 | ```java 5532 | // List available tools and their names 5533 | var tools = client.listTools(); 5534 | tools.forEach(tool -> System.out.println(tool.getName())); 5535 | 5536 | // Execute a tool with parameters 5537 | var result = client.callTool("calculator", Map.of( 5538 | "operation", "add", 5539 | "a", 1, 5540 | "b", 2 5541 | )); 5542 | ``` 5543 | 5544 | </Tab> 5545 | 5546 | <Tab title="Async API"> 5547 | ```java 5548 | // List available tools asynchronously 5549 | client.listTools() 5550 | .doOnNext(tools -> tools.forEach(tool -> 5551 | System.out.println(tool.getName()))) 5552 | .subscribe(); 5553 | 5554 | // Execute a tool asynchronously 5555 | client.callTool("calculator", Map.of( 5556 | "operation", "add", 5557 | "a", 1, 5558 | "b", 2 5559 | )) 5560 | .subscribe(); 5561 | ``` 5562 | 5563 | </Tab> 5564 | </Tabs> 5565 | 5566 | ### Resource Access 5567 | 5568 | 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. 5569 | 5570 | <Tabs> 5571 | <Tab title="Sync API"> 5572 | ```java 5573 | // List available resources and their names 5574 | var resources = client.listResources(); 5575 | resources.forEach(resource -> System.out.println(resource.getName())); 5576 | 5577 | // Retrieve resource content using a URI template 5578 | var content = client.getResource("file", Map.of( 5579 | "path", "/path/to/file.txt" 5580 | )); 5581 | ``` 5582 | 5583 | </Tab> 5584 | 5585 | <Tab title="Async API"> 5586 | ```java 5587 | // List available resources asynchronously 5588 | client.listResources() 5589 | .doOnNext(resources -> resources.forEach(resource -> 5590 | System.out.println(resource.getName()))) 5591 | .subscribe(); 5592 | 5593 | // Retrieve resource content asynchronously 5594 | client.getResource("file", Map.of( 5595 | "path", "/path/to/file.txt" 5596 | )) 5597 | .subscribe(); 5598 | ``` 5599 | 5600 | </Tab> 5601 | </Tabs> 5602 | 5603 | ### Prompt System 5604 | 5605 | 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. 5606 | 5607 | <Tabs> 5608 | <Tab title="Sync API"> 5609 | ```java 5610 | // List available prompt templates 5611 | var prompts = client.listPrompts(); 5612 | prompts.forEach(prompt -> System.out.println(prompt.getName())); 5613 | 5614 | // Execute a prompt template with parameters 5615 | var response = client.executePrompt("echo", Map.of( 5616 | "text", "Hello, World!" 5617 | )); 5618 | ``` 5619 | 5620 | </Tab> 5621 | 5622 | <Tab title="Async API"> 5623 | ```java 5624 | // List available prompt templates asynchronously 5625 | client.listPrompts() 5626 | .doOnNext(prompts -> prompts.forEach(prompt -> 5627 | System.out.println(prompt.getName()))) 5628 | .subscribe(); 5629 | 5630 | // Execute a prompt template asynchronously 5631 | client.executePrompt("echo", Map.of( 5632 | "text", "Hello, World!" 5633 | )) 5634 | .subscribe(); 5635 | ``` 5636 | 5637 | </Tab> 5638 | </Tabs> 5639 | 5640 | # Overview 5641 | 5642 | Source: https://modelcontextprotocol.io/sdk/java/mcp-overview 5643 | 5644 | Introduction to the Model Context Protocol (MCP) Java SDK 5645 | 5646 | Java SDK for the [Model Context Protocol](https://modelcontextprotocol.org/docs/concepts/architecture) 5647 | enables standardized integration between AI models and tools. 5648 | 5649 | ## Features 5650 | 5651 | - MCP Client and MCP Server implementations supporting: 5652 | - Protocol [version compatibility negotiation](https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization) 5653 | - [Tool](https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/) discovery, execution, list change notifications 5654 | - [Resource](https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/) management with URI templates 5655 | - [Roots](https://spec.modelcontextprotocol.io/specification/2024-11-05/client/roots/) list management and notifications 5656 | - [Prompt](https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/) handling and management 5657 | - [Sampling](https://spec.modelcontextprotocol.io/specification/2024-11-05/client/sampling/) support for AI model interactions 5658 | - Multiple transport implementations: 5659 | - Default transports: 5660 | - Stdio-based transport for process-based communication 5661 | - Java HttpClient-based SSE client transport for HTTP SSE Client-side streaming 5662 | - Servlet-based SSE server transport for HTTP SSE Server streaming 5663 | - Spring-based transports: 5664 | - WebFlux SSE client and server transports for reactive HTTP streaming 5665 | - WebMVC SSE transport for servlet-based HTTP streaming 5666 | - Supports Synchronous and Asynchronous programming paradigms 5667 | 5668 | ## Architecture 5669 | 5670 | The SDK follows a layered architecture with clear separation of concerns: 5671 | 5672 |  5673 | 5674 | - **Client/Server Layer (McpClient/McpServer)**: Both use McpSession for sync/async operations, 5675 | with McpClient handling client-side protocol operations and McpServer managing server-side protocol operations. 5676 | - **Session Layer (McpSession)**: Manages communication patterns and state using DefaultMcpSession implementation. 5677 | - **Transport Layer (McpTransport)**: Handles JSON-RPC message serialization/deserialization via: 5678 | - StdioTransport (stdin/stdout) in the core module 5679 | - HTTP SSE transports in dedicated transport modules (Java HttpClient, Spring WebFlux, Spring WebMVC) 5680 | 5681 | The MCP Client is a key component in the Model Context Protocol (MCP) architecture, responsible for establishing and managing connections with MCP servers. 5682 | It implements the client-side of the protocol. 5683 | 5684 |  5685 | 5686 | The MCP Server is a foundational component in the Model Context Protocol (MCP) architecture that provides tools, resources, and capabilities to clients. 5687 | It implements the server-side of the protocol. 5688 | 5689 |  5690 | 5691 | Key Interactions: 5692 | 5693 | - **Client/Server Initialization**: Transport setup, protocol compatibility check, capability negotiation, and implementation details exchange. 5694 | - **Message Flow**: JSON-RPC message handling with validation, type-safe response processing, and error handling. 5695 | - **Resource Management**: Resource discovery, URI template-based access, subscription system, and content retrieval. 5696 | 5697 | ## Dependencies 5698 | 5699 | Add the following Maven dependency to your project: 5700 | 5701 | <Tabs> 5702 | <Tab title="Maven"> 5703 | The core MCP functionality: 5704 | 5705 | ```xml 5706 | <dependency> 5707 | <groupId>io.modelcontextprotocol.sdk</groupId> 5708 | <artifactId>mcp</artifactId> 5709 | </dependency> 5710 | ``` 5711 | 5712 | For HTTP SSE transport implementations, add one of the following dependencies: 5713 | 5714 | ```xml 5715 | <!-- Spring WebFlux-based SSE client and server transport --> 5716 | <dependency> 5717 | <groupId>io.modelcontextprotocol.sdk</groupId> 5718 | <artifactId>mcp-spring-webflux</artifactId> 5719 | </dependency> 5720 | 5721 | <!-- Spring WebMVC-based SSE server transport --> 5722 | <dependency> 5723 | <groupId>io.modelcontextprotocol.sdk</groupId> 5724 | <artifactId>mcp-spring-webmvc</artifactId> 5725 | </dependency> 5726 | ``` 5727 | 5728 | </Tab> 5729 | 5730 | <Tab title="Gradle"> 5731 | The core MCP functionality: 5732 | 5733 | ```groovy 5734 | dependencies { 5735 | implementation platform("io.modelcontextprotocol.sdk:mcp") 5736 | //... 5737 | } 5738 | ``` 5739 | 5740 | For HTTP SSE transport implementations, add one of the following dependencies: 5741 | 5742 | ```groovy 5743 | // Spring WebFlux-based SSE client and server transport 5744 | dependencies { 5745 | implementation platform("io.modelcontextprotocol.sdk:mcp-spring-webflux") 5746 | } 5747 | 5748 | // Spring WebMVC-based SSE server transport 5749 | dependencies { 5750 | implementation platform("io.modelcontextprotocol.sdk:mcp-spring-webmvc") 5751 | } 5752 | ``` 5753 | 5754 | </Tab> 5755 | </Tabs> 5756 | 5757 | ### Bill of Materials (BOM) 5758 | 5759 | The Bill of Materials (BOM) declares the recommended versions of all the dependencies used by a given release. 5760 | Using the BOM from your application's build script avoids the need for you to specify and maintain the dependency versions yourself. 5761 | Instead, the version of the BOM you're using determines the utilized dependency versions. 5762 | It also ensures that you're using supported and tested versions of the dependencies by default, unless you choose to override them. 5763 | 5764 | Add the BOM to your project: 5765 | 5766 | <Tabs> 5767 | <Tab title="Maven"> 5768 | ```xml 5769 | <dependencyManagement> 5770 | <dependencies> 5771 | <dependency> 5772 | <groupId>io.modelcontextprotocol.sdk</groupId> 5773 | <artifactId>mcp-bom</artifactId> 5774 | <version>0.7.0</version> 5775 | <type>pom</type> 5776 | <scope>import</scope> 5777 | </dependency> 5778 | </dependencies> 5779 | </dependencyManagement> 5780 | ``` 5781 | </Tab> 5782 | 5783 | <Tab title="Gradle"> 5784 | ```groovy 5785 | dependencies { 5786 | implementation platform("io.modelcontextprotocol.sdk:mcp-bom:0.7.0") 5787 | //... 5788 | } 5789 | ``` 5790 | 5791 | 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. 5792 | This is implemented by adding a 'platform' dependency handler method to the dependencies section of your Gradle build script. 5793 | 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. 5794 | 5795 | </Tab> 5796 | </Tabs> 5797 | 5798 | Replace the version number with the version of the BOM you want to use. 5799 | 5800 | ### Available Dependencies 5801 | 5802 | The following dependencies are available and managed by the BOM: 5803 | 5804 | - Core Dependencies 5805 | - `io.modelcontextprotocol.sdk:mcp` - Core MCP library providing the base functionality and APIs for Model Context Protocol implementation. 5806 | - Transport Dependencies 5807 | - `io.modelcontextprotocol.sdk:mcp-spring-webflux` - WebFlux-based Server-Sent Events (SSE) transport implementation for reactive applications. 5808 | - `io.modelcontextprotocol.sdk:mcp-spring-webmvc` - WebMVC-based Server-Sent Events (SSE) transport implementation for servlet-based applications. 5809 | - Testing Dependencies 5810 | - `io.modelcontextprotocol.sdk:mcp-test` - Testing utilities and support for MCP-based applications. 5811 | 5812 | # MCP Server 5813 | 5814 | Source: https://modelcontextprotocol.io/sdk/java/mcp-server 5815 | 5816 | Learn how to implement and configure a Model Context Protocol (MCP) server 5817 | 5818 | ## Overview 5819 | 5820 | The MCP Server is a foundational component in the Model Context Protocol (MCP) architecture that provides tools, resources, and capabilities to clients. It implements the server-side of the protocol, responsible for: 5821 | 5822 | - Exposing tools that clients can discover and execute 5823 | - Managing resources with URI-based access patterns 5824 | - Providing prompt templates and handling prompt requests 5825 | - Supporting capability negotiation with clients 5826 | - Implementing server-side protocol operations 5827 | - Managing concurrent client connections 5828 | - Providing structured logging and notifications 5829 | 5830 | The server supports both synchronous and asynchronous APIs, allowing for flexible integration in different application contexts. 5831 | 5832 | <Tabs> 5833 | <Tab title="Sync API"> 5834 | ```java 5835 | // Create a server with custom configuration 5836 | McpSyncServer syncServer = McpServer.sync(transport) 5837 | .serverInfo("my-server", "1.0.0") 5838 | .capabilities(ServerCapabilities.builder() 5839 | .resources(true) // Enable resource support 5840 | .tools(true) // Enable tool support 5841 | .prompts(true) // Enable prompt support 5842 | .logging() // Enable logging support 5843 | .build()) 5844 | .build(); 5845 | 5846 | // Register tools, resources, and prompts 5847 | syncServer.addTool(syncToolRegistration); 5848 | syncServer.addResource(syncResourceRegistration); 5849 | syncServer.addPrompt(syncPromptRegistration); 5850 | 5851 | // Send logging notifications 5852 | syncServer.loggingNotification(LoggingMessageNotification.builder() 5853 | .level(LoggingLevel.INFO) 5854 | .logger("custom-logger") 5855 | .data("Server initialized") 5856 | .build()); 5857 | 5858 | // Close the server when done 5859 | syncServer.close(); 5860 | ``` 5861 | 5862 | </Tab> 5863 | 5864 | <Tab title="Async API"> 5865 | ```java 5866 | // Create an async server with custom configuration 5867 | McpAsyncServer asyncServer = McpServer.async(transport) 5868 | .serverInfo("my-server", "1.0.0") 5869 | .capabilities(ServerCapabilities.builder() 5870 | .resources(true) // Enable resource support 5871 | .tools(true) // Enable tool support 5872 | .prompts(true) // Enable prompt support 5873 | .logging() // Enable logging support 5874 | .build()) 5875 | .build(); 5876 | 5877 | // Register tools, resources, and prompts 5878 | asyncServer.addTool(asyncToolRegistration) 5879 | .doOnSuccess(v -> logger.info("Tool registered")) 5880 | .subscribe(); 5881 | 5882 | asyncServer.addResource(asyncResourceRegistration) 5883 | .doOnSuccess(v -> logger.info("Resource registered")) 5884 | .subscribe(); 5885 | 5886 | asyncServer.addPrompt(asyncPromptRegistration) 5887 | .doOnSuccess(v -> logger.info("Prompt registered")) 5888 | .subscribe(); 5889 | 5890 | // Send logging notifications 5891 | asyncServer.loggingNotification(LoggingMessageNotification.builder() 5892 | .level(LoggingLevel.INFO) 5893 | .logger("custom-logger") 5894 | .data("Server initialized") 5895 | .build()); 5896 | 5897 | // Close the server when done 5898 | asyncServer.close() 5899 | .doOnSuccess(v -> logger.info("Server closed")) 5900 | .subscribe(); 5901 | ``` 5902 | 5903 | </Tab> 5904 | </Tabs> 5905 | 5906 | ## Server Transport 5907 | 5908 | The transport layer in the MCP SDK is responsible for handling the communication between clients and servers. It provides different implementations to support various communication protocols and patterns. The SDK includes several built-in transport implementations: 5909 | 5910 | <Tabs> 5911 | <Tab title="STDIO"> 5912 | <> 5913 | Create in-process based transport: 5914 | 5915 | ```java 5916 | StdioServerTransport transport = new StdioServerTransport(new ObjectMapper()); 5917 | ``` 5918 | 5919 | Provides bidirectional JSON-RPC message handling over standard input/output streams with non-blocking message processing, serialization/deserialization, and graceful shutdown support. 5920 | 5921 | Key features: 5922 | 5923 | <ul> 5924 | <li>Bidirectional communication through stdin/stdout</li> 5925 | <li>Process-based integration support</li> 5926 | <li>Simple setup and configuration</li> 5927 | <li>Lightweight implementation</li> 5928 | </ul> 5929 | </> 5930 | 5931 | </Tab> 5932 | 5933 | <Tab title="SSE (WebFlux)"> 5934 | <> 5935 | <p>Creates WebFlux-based SSE server transport.<br />Requires the <code>mcp-spring-webflux</code> dependency.</p> 5936 | 5937 | ```java 5938 | @Configuration 5939 | class McpConfig { 5940 | @Bean 5941 | WebFluxSseServerTransport webFluxSseServerTransport(ObjectMapper mapper) { 5942 | return new WebFluxSseServerTransport(mapper, "/mcp/message"); 5943 | } 5944 | 5945 | @Bean 5946 | RouterFunction<?> mcpRouterFunction(WebFluxSseServerTransport transport) { 5947 | return transport.getRouterFunction(); 5948 | } 5949 | } 5950 | ``` 5951 | 5952 | <p>Implements the MCP HTTP with SSE transport specification, providing:</p> 5953 | 5954 | <ul> 5955 | <li>Reactive HTTP streaming with WebFlux</li> 5956 | <li>Concurrent client connections through SSE endpoints</li> 5957 | <li>Message routing and session management</li> 5958 | <li>Graceful shutdown capabilities</li> 5959 | </ul> 5960 | </> 5961 | 5962 | </Tab> 5963 | 5964 | <Tab title="SSE (WebMvc)"> 5965 | <> 5966 | <p>Creates WebMvc-based SSE server transport.<br />Requires the <code>mcp-spring-webmvc</code> dependency.</p> 5967 | 5968 | ```java 5969 | @Configuration 5970 | @EnableWebMvc 5971 | class McpConfig { 5972 | @Bean 5973 | WebMvcSseServerTransport webMvcSseServerTransport(ObjectMapper mapper) { 5974 | return new WebMvcSseServerTransport(mapper, "/mcp/message"); 5975 | } 5976 | 5977 | @Bean 5978 | RouterFunction<ServerResponse> mcpRouterFunction(WebMvcSseServerTransport transport) { 5979 | return transport.getRouterFunction(); 5980 | } 5981 | } 5982 | ``` 5983 | 5984 | <p>Implements the MCP HTTP with SSE transport specification, providing:</p> 5985 | 5986 | <ul> 5987 | <li>Server-side event streaming</li> 5988 | <li>Integration with Spring WebMVC</li> 5989 | <li>Support for traditional web applications</li> 5990 | <li>Synchronous operation handling</li> 5991 | </ul> 5992 | </> 5993 | 5994 | </Tab> 5995 | 5996 | <Tab title="SSE (Servlet)"> 5997 | <> 5998 | <p> 5999 | Creates a Servlet-based SSE server transport. It is included in the core <code>mcp</code> module.<br /> 6000 | The <code>HttpServletSseServerTransport</code> can be used with any Servlet container.<br /> 6001 | To use it with a Spring Web application, you can register it as a Servlet bean: 6002 | </p> 6003 | 6004 | ```java 6005 | @Configuration 6006 | @EnableWebMvc 6007 | public class McpServerConfig implements WebMvcConfigurer { 6008 | 6009 | @Bean 6010 | public HttpServletSseServerTransport servletSseServerTransport() { 6011 | return new HttpServletSseServerTransport(new ObjectMapper(), "/mcp/message"); 6012 | } 6013 | 6014 | @Bean 6015 | public ServletRegistrationBean customServletBean(HttpServletSseServerTransport servlet) { 6016 | return new ServletRegistrationBean(servlet); 6017 | } 6018 | } 6019 | ``` 6020 | 6021 | <p> 6022 | Implements the MCP HTTP with SSE transport specification using the traditional Servlet API, providing: 6023 | </p> 6024 | 6025 | <ul> 6026 | <li>Asynchronous message handling using Servlet 6.0 async support</li> 6027 | <li>Session management for multiple client connections</li> 6028 | 6029 | <li> 6030 | Two types of endpoints: 6031 | 6032 | <ul> 6033 | <li>SSE endpoint (<code>/sse</code>) for server-to-client events</li> 6034 | <li>Message endpoint (configurable) for client-to-server requests</li> 6035 | </ul> 6036 | </li> 6037 | 6038 | <li>Error handling and response formatting</li> 6039 | <li>Graceful shutdown support</li> 6040 | </ul> 6041 | </> 6042 | 6043 | </Tab> 6044 | </Tabs> 6045 | 6046 | ## Server Capabilities 6047 | 6048 | The server can be configured with various capabilities: 6049 | 6050 | ```java 6051 | var capabilities = ServerCapabilities.builder() 6052 | .resources(false, true) // Resource support with list changes notifications 6053 | .tools(true) // Tool support with list changes notifications 6054 | .prompts(true) // Prompt support with list changes notifications 6055 | .logging() // Enable logging support (enabled by default with loging level INFO) 6056 | .build(); 6057 | ``` 6058 | 6059 | ### Logging Support 6060 | 6061 | The server provides structured logging capabilities that allow sending log messages to clients with different severity levels: 6062 | 6063 | ```java 6064 | // Send a log message to clients 6065 | server.loggingNotification(LoggingMessageNotification.builder() 6066 | .level(LoggingLevel.INFO) 6067 | .logger("custom-logger") 6068 | .data("Custom log message") 6069 | .build()); 6070 | ``` 6071 | 6072 | Clients can control the minimum logging level they receive through the `mcpClient.setLoggingLevel(level)` request. Messages below the set level will be filtered out. 6073 | Supported logging levels (in order of increasing severity): DEBUG (0), INFO (1), NOTICE (2), WARNING (3), ERROR (4), CRITICAL (5), ALERT (6), EMERGENCY (7) 6074 | 6075 | ### Tool Registration 6076 | 6077 | <Tabs> 6078 | <Tab title="Sync"> 6079 | ```java 6080 | // Sync tool registration 6081 | var syncToolRegistration = new McpServerFeatures.SyncToolRegistration( 6082 | new Tool("calculator", "Basic calculator", Map.of( 6083 | "operation", "string", 6084 | "a", "number", 6085 | "b", "number" 6086 | )), 6087 | arguments -> { 6088 | // Tool implementation 6089 | return new CallToolResult(result, false); 6090 | } 6091 | ); 6092 | ``` 6093 | </Tab> 6094 | 6095 | <Tab title="Async"> 6096 | ```java 6097 | // Async tool registration 6098 | var asyncToolRegistration = new McpServerFeatures.AsyncToolRegistration( 6099 | new Tool("calculator", "Basic calculator", Map.of( 6100 | "operation", "string", 6101 | "a", "number", 6102 | "b", "number" 6103 | )), 6104 | arguments -> { 6105 | // Tool implementation 6106 | return Mono.just(new CallToolResult(result, false)); 6107 | } 6108 | ); 6109 | ``` 6110 | </Tab> 6111 | </Tabs> 6112 | 6113 | ### Resource Registration 6114 | 6115 | <Tabs> 6116 | <Tab title="Sync"> 6117 | ```java 6118 | // Sync resource registration 6119 | var syncResourceRegistration = new McpServerFeatures.SyncResourceRegistration( 6120 | new Resource("custom://resource", "name", "description", "mime-type", null), 6121 | request -> { 6122 | // Resource read implementation 6123 | return new ReadResourceResult(contents); 6124 | } 6125 | ); 6126 | ``` 6127 | </Tab> 6128 | 6129 | <Tab title="Async"> 6130 | ```java 6131 | // Async resource registration 6132 | var asyncResourceRegistration = new McpServerFeatures.AsyncResourceRegistration( 6133 | new Resource("custom://resource", "name", "description", "mime-type", null), 6134 | request -> { 6135 | // Resource read implementation 6136 | return Mono.just(new ReadResourceResult(contents)); 6137 | } 6138 | ); 6139 | ``` 6140 | </Tab> 6141 | </Tabs> 6142 | 6143 | ### Prompt Registration 6144 | 6145 | <Tabs> 6146 | <Tab title="Sync"> 6147 | ```java 6148 | // Sync prompt registration 6149 | var syncPromptRegistration = new McpServerFeatures.SyncPromptRegistration( 6150 | new Prompt("greeting", "description", List.of( 6151 | new PromptArgument("name", "description", true) 6152 | )), 6153 | request -> { 6154 | // Prompt implementation 6155 | return new GetPromptResult(description, messages); 6156 | } 6157 | ); 6158 | ``` 6159 | </Tab> 6160 | 6161 | <Tab title="Async"> 6162 | ```java 6163 | // Async prompt registration 6164 | var asyncPromptRegistration = new McpServerFeatures.AsyncPromptRegistration( 6165 | new Prompt("greeting", "description", List.of( 6166 | new PromptArgument("name", "description", true) 6167 | )), 6168 | request -> { 6169 | // Prompt implementation 6170 | return Mono.just(new GetPromptResult(description, messages)); 6171 | } 6172 | ); 6173 | ``` 6174 | </Tab> 6175 | </Tabs> 6176 | 6177 | ## Error Handling 6178 | 6179 | The SDK provides comprehensive error handling through the McpError class, covering protocol compatibility, transport communication, JSON-RPC messaging, tool execution, resource management, prompt handling, timeouts, and connection issues. This unified error handling approach ensures consistent and reliable error management across both synchronous and asynchronous operations. 6180 | 6181 | # Building MCP with LLMs 6182 | 6183 | Source: https://modelcontextprotocol.io/tutorials/building-mcp-with-llms 6184 | 6185 | Speed up your MCP development using LLMs such as Claude! 6186 | 6187 | 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. 6188 | 6189 | ## Preparing the documentation 6190 | 6191 | Before starting, gather the necessary documentation to help Claude understand MCP: 6192 | 6193 | 1. Visit [https://modelcontextprotocol.io/llms-full.txt](https://modelcontextprotocol.io/llms-full.txt) and copy the full documentation text 6194 | 2. Navigate to either the [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) or [Python SDK repository](https://github.com/modelcontextprotocol/python-sdk) 6195 | 3. Copy the README files and other relevant documentation 6196 | 4. Paste these documents into your conversation with Claude 6197 | 6198 | ## Describing your server 6199 | 6200 | Once you've provided the documentation, clearly describe to Claude what kind of server you want to build. Be specific about: 6201 | 6202 | - What resources your server will expose 6203 | - What tools it will provide 6204 | - Any prompts it should offer 6205 | - What external systems it needs to interact with 6206 | 6207 | For example: 6208 | 6209 | ``` 6210 | Build an MCP server that: 6211 | - Connects to my company's PostgreSQL database 6212 | - Exposes table schemas as resources 6213 | - Provides tools for running read-only SQL queries 6214 | - Includes prompts for common data analysis tasks 6215 | ``` 6216 | 6217 | ## Working with Claude 6218 | 6219 | When working with Claude on MCP servers: 6220 | 6221 | 1. Start with the core functionality first, then iterate to add more features 6222 | 2. Ask Claude to explain any parts of the code you don't understand 6223 | 3. Request modifications or improvements as needed 6224 | 4. Have Claude help you test the server and handle edge cases 6225 | 6226 | Claude can help implement all the key MCP features: 6227 | 6228 | - Resource management and exposure 6229 | - Tool definitions and implementations 6230 | - Prompt templates and handlers 6231 | - Error handling and logging 6232 | - Connection and transport setup 6233 | 6234 | ## Best practices 6235 | 6236 | When building MCP servers with Claude: 6237 | 6238 | - Break down complex servers into smaller pieces 6239 | - Test each component thoroughly before moving on 6240 | - Keep security in mind - validate inputs and limit access appropriately 6241 | - Document your code well for future maintenance 6242 | - Follow MCP protocol specifications carefully 6243 | 6244 | ## Next steps 6245 | 6246 | After Claude helps you build your server: 6247 | 6248 | 1. Review the generated code carefully 6249 | 2. Test the server with the MCP Inspector tool 6250 | 3. Connect it to Claude.app or other MCP clients 6251 | 4. Iterate based on real usage and feedback 6252 | 6253 | Remember that Claude can help you modify and improve your server as requirements change over time. 6254 | 6255 | Need more guidance? Just ask Claude specific questions about implementing MCP features or troubleshooting issues that arise. 6256 | ```