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