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