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