├── .DS_Store ├── .gitignore ├── .prettierignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── clients.mdx ├── development ├── contributing.mdx ├── roadmap.mdx └── updates.mdx ├── docs.json ├── docs ├── concepts │ ├── architecture.mdx │ ├── prompts.mdx │ ├── resources.mdx │ ├── roots.mdx │ ├── sampling.mdx │ ├── tools.mdx │ └── transports.mdx └── tools │ ├── debugging.mdx │ └── inspector.mdx ├── examples.mdx ├── ext ├── .DS_Store ├── ad │ ├── myact.jpg │ └── 灯塔红白间.jpg ├── article.mdx └── me.mdx ├── favicon.svg ├── images ├── available-mcp-tools.png ├── claude-desktop-mcp-hammer-icon.svg ├── claude-desktop-mcp-plug-icon.svg ├── client-claude-cli-python.png ├── current-weather.png ├── hero-dark.svg ├── hero-light.svg ├── java │ ├── class-diagrams.puml │ ├── java-mcp-client-architecture.jpg │ ├── java-mcp-server-architecture.jpg │ ├── java-mcp-uml-classdiagram.svg │ └── mcp-stack.svg ├── mcp-inspector.png ├── og-image.png ├── quickstart-approve.png ├── quickstart-developer.png ├── quickstart-filesystem.png ├── quickstart-hammer.png ├── quickstart-menu.png ├── quickstart-screenshot.png ├── quickstart-tools.png ├── visual-indicator-mcp-tools.png └── weather-alerts.png ├── introduction.mdx ├── logo ├── dark.png ├── dark.svg ├── light.png └── light.svg ├── package.json ├── quickstart ├── client.mdx ├── server.mdx └── user.mdx ├── sdk └── java │ ├── mcp-client.mdx │ ├── mcp-overview.mdx │ └── mcp-server.mdx ├── snippets └── snippet-intro.mdx └── tutorials ├── building-a-client-node.mdx └── building-mcp-with-llms.mdx /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/.DS_Store -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | package-lock.json 2 | node_modules -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | *.mdx -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | mcp-coc@anthropic.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to MCP Documentation 2 | 3 | Thank you for your interest in contributing to the Model Context Protocol (MCP) documentation! This guide will help you get started with contributing. 4 | 5 | ## Getting Started 6 | 7 | 1. Install the required tools: 8 | - Node.js 9 | - Git 10 | - [Mintlify CLI](https://www.npmjs.com/package/mintlify): `npm i -g mintlify` 11 | 2. Fork and clone the repository 12 | 3. Create a new branch for your changes 13 | 4. Run `mintlify dev` to preview changes locally 14 | 15 | ## Documentation Guidelines 16 | 17 | - Keep content clear, concise, and technically accurate 18 | - Follow the existing file structure and naming conventions 19 | - Include code examples where appropriate 20 | - Use proper MDX formatting and components 21 | - Test all links and code samples 22 | 23 | ## Content Types 24 | 25 | You can contribute to: 26 | 27 | - Conceptual guides 28 | - API reference documentation 29 | - Tutorials and quickstarts 30 | - Best practices and examples 31 | - Troubleshooting guides 32 | 33 | ## Pull Request Process 34 | 35 | 1. Ensure your changes follow our documentation guidelines 36 | 2. Update the relevant table of contents if needed 37 | 3. Test your changes locally using `mintlify dev` 38 | 4. Submit a pull request with a clear description of your changes 39 | 5. Wait for review and address any feedback 40 | 41 | ## Need Help? 42 | 43 | - Check existing documentation at [modelcontextprotocol.io](https://modelcontextprotocol.io) 44 | - [Open an issue](https://github.com/modelcontextprotocol/docs/issues) for bugs or concerns 45 | - Join our [community discussions](https://github.com/modelcontextprotocol/docs/discussions) 46 | 47 | ## Code of Conduct 48 | 49 | Please note that this project follows our [Code of Conduct](CODE_OF_CONDUCT.md). By participating, you agree to uphold these guidelines. 50 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MCP协议中文网 2 | 3 | [模型上下文协议(MCP协议)](https://modelcontextprotocol.io)的官方文档。 4 | 5 | 有关详细的贡献指南、开发设置和故障排除,请参阅我们的[贡献指南](CONTRIBUTING.md)。 6 | 7 | ### 发布更改 8 | 9 | 推送到默认分支的更改将自动部署到生产环境。 10 | 11 | ### 关于我 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /clients.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "示例客户端" 3 | description: "支持 MCP 集成的应用程序列表" 4 | --- 5 | 6 | 本页面概述了支持模型上下文协议(MCP协议)的应用程序。每个客户端可能支持不同的 MCP 功能,从而实现与 MCP 服务器的不同集成级别。 7 | 8 | ## 功能支持矩阵 9 | 10 | | 客户端 | [资源] | [提示] | [工具] | [采样] | 根节点 | 备注 | 11 | |---------------------------------------------|-------------|-----------|---------|------------|--------|-----------------------------------------------------------------------------| 12 | | [Claude 桌面应用][Claude] | ✅ | ✅ | ✅ | ❌ | ❌ | 支持所有 MCP 功能 | 13 | | [5ire][5ire] | ❌ | ❌ | ✅ | ❌ | ❌ | 支持工具。 | 14 | | [BeeAI 框架][BeeAI Framework] | ❌ | ❌ | ✅ | ❌ | ❌ | 支持代理工作流中的工具。 | 15 | | [Cline][Cline] | ✅ | ❌ | ✅ | ❌ | ❌ | 支持工具和资源。 | 16 | | [Continue][Continue] | ✅ | ✅ | ✅ | ❌ | ❌ | 支持所有 MCP 功能 | 17 | | [Cursor][Cursor] | ❌ | ❌ | ✅ | ❌ | ❌ | 支持工具。 | 18 | | [Emacs Mcp][Mcp.el] | ❌ | ❌ | ✅ | ❌ | ❌ | 在 Emacs 中支持工具。 | 19 | | [Firebase Genkit][Genkit] | ⚠️ | ✅ | ✅ | ❌ | ❌ | 通过工具支持资源列表和查找。 | 20 | | [GenAIScript][GenAIScript] | ❌ | ❌ | ✅ | ❌ | ❌ | 支持工具。 | 21 | | [Goose][Goose] | ❌ | ❌ | ✅ | ❌ | ❌ | 支持工具。 | 22 | | [LibreChat][LibreChat] | ❌ | ❌ | ✅ | ❌ | ❌ | 支持代理的工具 | 23 | | [mcp-agent][mcp-agent] | ❌ | ❌ | ✅ | ⚠️ | ❌ | 支持工具、服务器连接管理和代理工作流。 | 24 | | [oterm][oterm] | ❌ | ❌ | ✅ | ❌ | ❌ | 支持工具。 | 25 | | [Roo Code][Roo Code] | ✅ | ❌ | ✅ | ❌ | ❌ | 支持工具和资源。 | 26 | | [Sourcegraph Cody][Cody] | ✅ | ❌ | ❌ | ❌ | ❌ | 通过 OpenCTX 支持资源 | 27 | | [Superinterface][Superinterface] | ❌ | ❌ | ✅ | ❌ | ❌ | 支持工具 | 28 | | [TheiaAI/TheiaIDE][TheiaAI/TheiaIDE] | ❌ | ❌ | ✅ | ❌ | ❌ | 在 Theia AI 和 AI 驱动的 Theia IDE 中支持代理的工具 | 29 | | [Windsurf Editor][Windsurf] | ❌ | ❌ | ✅ | ❌ | ❌ | 支持 AI Flow 的协作开发工具。 | 30 | | [Zed][Zed] | ❌ | ✅ | ❌ | ❌ | ❌ | 提示以斜杠命令形式出现 | 31 | | [SpinAI][SpinAI] | ❌ | ❌ | ✅ | ❌ | ❌ | 支持 TypeScript AI 代理的工具 | 32 | | [OpenSumi][OpenSumi] | ❌ | ❌ | ✅ | ❌ | ❌ | 在 OpenSumi 中支持工具 | 33 | | [Daydreams Agents][Daydreams] | ✅ | ✅ | ✅ | ❌ | ❌ | 支持将服务器集成到 Daydreams 代理中 | 34 | 35 | [Claude]: https://claude.ai/download 36 | [Cursor]: https://cursor.com 37 | [Zed]: https://zed.dev 38 | [Cody]: https://sourcegraph.com/cody 39 | [Genkit]: https://github.com/firebase/genkit 40 | [Continue]: https://github.com/continuedev/continue 41 | [GenAIScript]: https://microsoft.github.io/genaiscript/reference/scripts/mcp-tools/ 42 | [Cline]: https://github.com/cline/cline 43 | [LibreChat]: https://github.com/danny-avila/LibreChat 44 | [TheiaAI/TheiaIDE]: https://eclipsesource.com/blogs/2024/12/19/theia-ide-and-theia-ai-support-mcp/ 45 | [Superinterface]: https://superinterface.ai 46 | [5ire]: https://github.com/nanbingxyz/5ire 47 | [BeeAI Framework]: https://i-am-bee.github.io/beeai-framework 48 | [mcp-agent]: https://github.com/lastmile-ai/mcp-agent 49 | [Mcp.el]: https://github.com/lizqwerscott/mcp.el 50 | [Roo Code]: https://roocode.com 51 | [Goose]: https://block.github.io/goose/docs/goose-architecture/#interoperability-with-extensions 52 | [Windsurf]: https://codeium.com/windsurf 53 | [Daydreams]: https://github.com/daydreamsai/daydreams 54 | [SpinAI]: https://spinai.dev 55 | [oterm]: https://github.com/ggozad/oterm 56 | [OpenSumi]: https://github.com/opensumi/core 57 | 58 | [资源]: /docs/concepts/resources 59 | [提示]: /docs/concepts/prompts 60 | [工具]: /docs/concepts/tools 61 | [采样]: /docs/concepts/sampling 62 | 63 | ## 客户端详情 64 | 65 | ### Claude 桌面应用 66 | Claude 桌面应用程序全面支持 MCP,能够与本地工具和数据源深度集成。 67 | 68 | **主要功能:** 69 | - 完全支持资源,允许附加本地文件和数据 70 | - 支持提示模板 71 | - 工具集成,用于执行命令和脚本 72 | - 本地服务器连接,增强隐私和安全性 73 | 74 | > ⓘ 注意:Claude.ai 网页应用目前不支持 MCP。MCP 功能仅在桌面应用中可用。 75 | 76 | ### 5ire 77 | [5ire](https://github.com/nanbingxyz/5ire) 是一个开源的跨平台桌面 AI 助手,支持通过 MCP 服务器使用工具。 78 | 79 | **主要功能:** 80 | - 内置 MCP 服务器可以快速启用和禁用。 81 | - 用户可以通过修改配置文件添加更多服务器。 82 | - 开源且用户友好,适合初学者。 83 | - 未来将持续改进对 MCP 的支持。 84 | 85 | ### BeeAI 框架 86 | [BeeAI 框架](https://i-am-bee.github.io/beeai-framework) 是一个开源框架,用于构建、部署和服务强大的代理工作流。该框架包括 **MCP 工具**,这是一个原生功能,简化了将 MCP 服务器集成到代理工作流中的过程。 87 | 88 | **主要功能:** 89 | - 无缝将 MCP 工具集成到代理工作流中。 90 | - 快速从连接的 MCP 客户端实例化框架原生工具。 91 | - 计划未来支持代理 MCP 功能。 92 | 93 | **了解更多:** 94 | - [在代理工作流中使用 MCP 工具的示例](https://i-am-bee.github.io/beeai-framework/#/typescript/tools?id=using-the-mcptool-class) 95 | 96 | ### Cline 97 | [Cline](https://github.com/cline/cline) 是 VS Code 中的自主编码代理,可以编辑文件、运行命令、使用浏览器等——每一步都需要您的许可。 98 | 99 | **主要功能:** 100 | - 通过自然语言创建和添加工具(例如“添加一个可以搜索网络的工具”) 101 | - 通过 `~/Documents/Cline/MCP` 目录与他人分享 Cline 创建的自定义 MCP 服务器 102 | - 显示配置的 MCP 服务器及其工具、资源和任何错误日志 103 | 104 | ### Continue 105 | [Continue](https://github.com/continuedev/continue) 是一个开源的 AI 代码助手,内置对所有 MCP 功能的支持。 106 | 107 | **主要功能** 108 | - 输入 "@" 提及 MCP 资源 109 | - 提示模板以斜杠命令形式出现 110 | - 在聊天中直接使用内置和 MCP 工具 111 | - 支持 VS Code 和 JetBrains IDE,兼容任何 LLM 112 | 113 | ### Cursor 114 | [Cursor](https://docs.cursor.com/advanced/model-context-protocol) 是一个 AI 代码编辑器。 115 | 116 | **主要功能:** 117 | - 在 Cursor Composer 中支持 MCP 工具 118 | - 支持 STDIO 和 SSE 119 | 120 | ### Emacs Mcp 121 | [Emacs Mcp](https://github.com/lizqwerscott/mcp.el) 是一个 Emacs 客户端,旨在与 MCP 服务器接口,实现无缝连接和交互。它为 AI 插件(如 [gptel](https://github.com/karthink/gptel) 和 [llm](https://github.com/ahyatt/llm))提供 MCP 工具调用支持,遵循 Emacs 的标准工具调用格式。这种集成增强了 Emacs 生态系统中 AI 工具的功能。 122 | 123 | **主要功能:** 124 | - 为 Emacs 提供 MCP 工具支持。 125 | 126 | ### Firebase Genkit 127 | [Genkit](https://github.com/firebase/genkit) 是 Firebase 的 SDK,用于构建和集成 GenAI 功能到应用程序中。[genkitx-mcp](https://github.com/firebase/genkit/tree/main/js/plugins/mcp) 插件支持将 MCP 服务器作为客户端使用,或从 Genkit 工具和提示创建 MCP 服务器。 128 | 129 | **主要功能:** 130 | - 客户端支持工具和提示(部分支持资源) 131 | - 在 Genkit 的 Dev UI 游乐场中支持丰富的发现功能 132 | - 与 Genkit 现有工具和提示的无缝互操作性 133 | - 兼容来自顶级提供商的多种 GenAI 模型 134 | 135 | ### GenAIScript 136 | 使用 [GenAIScript](https://microsoft.github.io/genaiscript/)(JavaScript)以编程方式组装 LLM 的提示。在 JavaScript 中编排 LLM、工具和数据。 137 | 138 | **主要功能:** 139 | - 用于处理提示的 JavaScript 工具箱 140 | - 抽象化使其易于使用且高效 141 | - 与 Visual Studio Code 无缝集成 142 | 143 | ### Goose 144 | [Goose](https://github.com/block/goose) 是一个开源 AI 代理,通过自动化编码任务来增强您的软件开发。 145 | 146 | **主要功能:** 147 | - 通过工具向 Goose 暴露 MCP 功能。 148 | - 可以通过 [扩展目录](https://block.github.io/goose/v1/extensions/)、CLI 或 UI 直接安装 MCP。 149 | - Goose 允许您通过 [构建自己的 MCP 服务器](https://block.github.io/goose/docs/tutorials/custom-extensions) 扩展其功能。 150 | - 包括用于开发、网页抓取、自动化、内存以及与 JetBrains 和 Google Drive 集成的内置工具。 151 | 152 | ### LibreChat 153 | [LibreChat](https://github.com/danny-avila/LibreChat) 是一个开源、可定制的 AI 聊天 UI,支持多个 AI 提供商,现在包括 MCP 集成。 154 | 155 | **主要功能:** 156 | - 通过 MCP 服务器扩展当前工具生态系统,包括 [代码解释器](https://www.librechat.ai/docs/features/code_interpreter) 和图像生成工具 157 | - 将工具添加到可定制的 [代理](https://www.librechat.ai/docs/features/agents) 中,使用来自顶级提供商的多种 LLM 158 | - 开源且可自托管,支持安全的多用户功能 159 | - 未来路线图包括扩展 MCP 功能支持 160 | 161 | ### mcp-agent 162 | [mcp-agent] 是一个简单、可组合的框架,用于使用模型上下文协议(MCP协议)构建代理。 163 | 164 | **主要功能:** 165 | - 自动管理 MCP 服务器的连接。 166 | - 向 LLM 暴露来自多个服务器的工具。 167 | - 实现 [构建有效代理](https://www.anthropic.com/research/building-effective-agents) 中定义的每种模式。 168 | - 支持工作流暂停/恢复信号,例如等待人类反馈。 169 | 170 | ### oterm 171 | [oterm] 是 Ollama 的终端客户端,允许用户创建聊天/代理。 172 | 173 | **主要功能:** 174 | - 支持与 Ollama 连接的多个完全可定制的聊天会话,并配备工具。 175 | - 支持 MCP 工具。 176 | 177 | ### Roo Code 178 | [Roo Code](https://roocode.com) 通过 MCP 提供 AI 编码辅助。 179 | 180 | **主要功能:** 181 | - 支持 MCP 工具和资源 182 | - 与开发工作流集成 183 | - 可扩展的 AI 功能 184 | 185 | ### Sourcegraph Cody 186 | [Cody](https://openctx.org/docs/providers/modelcontextprotocol) 是 Sourcegraph 的 AI 编码助手,通过 OpenCTX 实现 MCP。 187 | 188 | **主要功能:** 189 | - 支持 MCP 资源 190 | - 与 Sourcegraph 的代码智能集成 191 | - 使用 OpenCTX 作为抽象层 192 | - 计划未来支持更多 MCP 功能 193 | 194 | ### SpinAI 195 | [SpinAI](https://spinai.dev) 是一个开源的 TypeScript 框架,用于构建可观察的 AI 代理。该框架提供原生 MCP 兼容性,允许代理无缝集成 MCP 服务器和工具。 196 | 197 | **主要功能:** 198 | - 内置 MCP 兼容性,支持 AI 代理 199 | - 开源 TypeScript 框架 200 | - 可观察的代理架构 201 | - 原生支持 MCP 工具集成 202 | 203 | ### Superinterface 204 | [Superinterface](https://superinterface.ai) 是 AI 基础设施和开发者平台,用于构建支持 MCP、交互组件、客户端函数调用等的应用内 AI 助手。 205 | 206 | **主要功能:** 207 | - 在通过 React 组件或脚本标签嵌入的助手中使用 MCP 服务器的工具 208 | - 支持 SSE 传输 209 | - 使用来自任何 AI 提供商的任何 AI 模型(OpenAI、Anthropic、Ollama 等) 210 | 211 | ### TheiaAI/TheiaIDE 212 | [Theia AI](https://eclipsesource.com/blogs/2024/10/07/introducing-theia-ai/) 是一个用于构建 AI 增强工具和 IDE 的框架。[AI 驱动的 Theia IDE](https://eclipsesource.com/blogs/2024/10/08/introducting-ai-theia-ide/) 是一个基于 Theia AI 构建的开放且灵活的开发环境。 213 | 214 | **主要功能:** 215 | - **工具集成**:Theia AI 使 AI 代理(包括 Theia IDE 中的代理)能够利用 MCP 服务器进行无缝工具交互。 216 | - **可定制的提示**:Theia IDE 允许用户定义和调整提示,动态集成 MCP 服务器以实现定制工作流。 217 | - **自定义代理**:Theia IDE 支持创建利用 MCP 功能的自定义代理,使用户能够动态设计专用工作流。 218 | 219 | Theia AI 和 Theia IDE 的 MCP 集成为用户提供了灵活性,使其成为探索和适应 MCP 的强大平台。 220 | 221 | **了解更多:** 222 | - [Theia IDE 和 Theia AI MCP 公告](https://eclipsesource.com/blogs/2024/12/19/theia-ide-and-theia-ai-support-mcp/) 223 | - [下载 AI 驱动的 Theia IDE](https://theia-ide.org/) 224 | 225 | ### Windsurf Editor 226 | [Windsurf Editor](https://codeium.com/windsurf) 是一个代理 IDE,将 AI 辅助与开发者工作流相结合。它采用创新的 AI Flow 系统,支持协作和独立的 AI 交互,同时保持开发者控制。 227 | 228 | **主要功能:** 229 | - 革命性的 AI Flow 范式,支持人机协作 230 | - 智能代码生成和理解 231 | - 丰富的开发工具,支持多模型 232 | 233 | ### Zed 234 | [Zed](https://zed.dev/docs/assistant/model-context-protocol) 是一个高性能代码编辑器,内置 MCP 支持,专注于提示模板和工具集成。 235 | 236 | **主要功能:** 237 | - 提示模板以斜杠命令形式出现在编辑器中 238 | - 工具集成,增强编码工作流 239 | - 与编辑器功能和工作区上下文的紧密集成 240 | - 不支持 MCP 资源 241 | 242 | ### OpenSumi 243 | [OpenSumi](https://github.com/opensumi/core) 是一个帮助您快速构建 AI 原生 IDE 产品的框架。 244 | 245 | **主要功能:** 246 | - 在 OpenSumi 中支持 MCP 工具 247 | - 支持内置 IDE MCP 服务器和自定义 MCP 服务器 248 | 249 | ### Daydreams 250 | [Daydreams](https://github.com/daydreamsai/daydreams) 是一个生成代理框架,用于在链上执行任何操作。 251 | 252 | **主要功能:** 253 | - 支持在配置中使用 MCP 服务器 254 | - 暴露 MCP 客户端 255 | 256 | ## 为您的应用程序添加 MCP 支持 257 | 258 | 如果您已为您的应用程序添加了 MCP 支持,我们鼓励您提交拉取请求将其添加到此列表中。MCP 集成可以为您的用户提供强大的上下文 AI 功能,并使您的应用程序成为不断增长的 MCP 生态系统的一部分。 259 | 260 | 添加 MCP 支持的好处: 261 | - 允许用户自带上下文和工具 262 | - 加入不断增长的互操作 AI 应用程序生态系统 263 | - 为用户提供灵活的集成选项 264 | - 支持本地优先的 AI 工作流 265 | 266 | 要开始在您的应用程序中实现 MCP,请查看我们的 [Python](https://github.com/modelcontextprotocol/python-sdk) 或 [TypeScript SDK 文档](https://github.com/modelcontextprotocol/typescript-sdk) 267 | 268 | ## 更新和更正 269 | 270 | 此列表由社区维护。如果您发现任何不准确之处或希望更新有关 MCP 支持的信息,请提交拉取请求或[在我们的文档仓库中提出问题](https://github.com/modelcontextprotocol/docs/issues)。 -------------------------------------------------------------------------------- /development/contributing.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: 贡献 3 | description: 如何参与 Model Context Protocol 的开发 4 | --- 5 | 6 | 我们欢迎社区的贡献!请查看我们的[贡献指南](https://github.com/modelcontextprotocol/.github/blob/main/CONTRIBUTING.md)了解如何提交更改的详细信息。 7 | 8 | 所有贡献者必须遵守我们的[行为准则](https://github.com/modelcontextprotocol/.github/blob/main/CODE_OF_CONDUCT.md)。 9 | 10 | 如有问题和讨论,请使用[GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions)。 -------------------------------------------------------------------------------- /development/roadmap.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: 路线图 3 | description: 我们的 Model Context Protocol 发展计划(2025 年上半年) 4 | --- 5 | 6 | Model Context Protocol 正在快速发展。本页概述了我们对 **2025 年上半年** 关键优先事项和未来方向的当前思考,尽管随着项目的发展,这些内容可能会发生重大变化。 7 | 8 | 此处提出的想法并非承诺——我们可能会以不同于描述的方式解决这些挑战,或者某些挑战可能根本不会实现。这也不是一份**详尽**的清单;我们可能会纳入未在此提及的工作。 9 | 10 | 我们鼓励社区参与!每个部分都链接到相关讨论,您可以在其中了解更多信息并贡献您的想法。 11 | 12 | ## 远程 MCP 支持 13 | 14 | 我们的首要任务是改善[远程 MCP 连接](https://github.com/modelcontextprotocol/specification/discussions/112),允许客户端通过互联网安全地连接到 MCP 服务器。关键举措包括: 15 | 16 | - [**认证与授权**](https://github.com/modelcontextprotocol/specification/discussions/64):添加标准化的认证能力,特别是专注于 OAuth 2.0 支持。 17 | 18 | - [**服务发现**](https://github.com/modelcontextprotocol/specification/discussions/69):定义客户端如何发现并连接到远程 MCP 服务器。 19 | 20 | - [**无状态操作**](https://github.com/modelcontextprotocol/specification/discussions/102):思考 MCP 是否也可以涵盖无服务器环境,在这些环境中需要主要是无状态的。 21 | 22 | ## 参考实现 23 | 24 | 为了帮助开发者使用 MCP 进行构建,我们希望提供以下文档: 25 | 26 | - **客户端示例**:全面的参考客户端实现,展示所有协议功能。 27 | - **协议起草**:简化的新协议功能提议和纳入流程。 28 | 29 | ## 分发与发现 30 | 31 | 展望未来,我们正在探索如何使 MCP 服务器更易于访问。我们可能会研究的一些领域包括: 32 | 33 | - **包管理**:MCP 服务器的标准化打包格式。 34 | - **安装工具**:简化 MCP 客户端之间的服务器安装。 35 | - **沙盒化**:通过服务器隔离提高安全性。 36 | - **服务器注册表**:用于发现可用 MCP 服务器的公共目录。 37 | 38 | ## 代理支持 39 | 40 | 我们正在扩展 MCP 的[复杂代理工作流](https://github.com/modelcontextprotocol/specification/discussions/111)能力,特别关注: 41 | 42 | - [**分层代理系统**](https://github.com/modelcontextprotocol/specification/discussions/94):通过命名空间和拓扑感知改进对代理树的支持。 43 | 44 | - [**交互式工作流**](https://github.com/modelcontextprotocol/specification/issues/97):更好地处理跨代理层次结构的用户权限和信息请求,以及将输出发送给用户而非模型的方式。 45 | 46 | - [**流式结果**](https://github.com/modelcontextprotocol/specification/issues/117):从长时间运行的代理操作中获取实时更新。 47 | 48 | ## 更广泛的生态系统 49 | 50 | 我们还致力于: 51 | 52 | - **社区主导的标准开发**:培育一个协作生态系统,让所有 AI 提供商通过平等参与和共享治理来帮助塑造 MCP 作为开放标准,确保其满足多样化 AI 应用和用例的需求。 53 | - [**多模态支持**](https://github.com/modelcontextprotocol/specification/discussions/88):超越文本,支持音频、视频和其他格式。 54 | - [**标准化**]:考虑通过标准化机构进行标准化。 55 | 56 | ## 参与进来 57 | 58 | 我们欢迎社区参与塑造 MCP 的未来。访问我们的 [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions) 加入对话并贡献您的想法。 -------------------------------------------------------------------------------- /development/updates.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "最新动态" 3 | description: 'MCP 的最新更新和改进' 4 | --- 5 | 6 | 7 | - 我们很高兴地宣布,由 VMware Tanzu 的 Spring AI 团队开发的 Java SDK 现已成为 MCP 的官方 [Java SDK](https://github.com/modelcontextprotocol/java-sdk)。 8 | 这是我们不断增长的支持语言列表中的一员,与现有的 Kotlin SDK 并列。Spring AI 团队将作为 Model Context Protocol 组织的一部分维护该 SDK。我们非常欢迎他们加入 MCP 社区! 9 | 10 | 11 | 12 | - MCP Python SDK 的 [1.2.1](https://github.com/modelcontextprotocol/python-sdk/releases/tag/v1.2.1) 版本已发布,带来了重要的稳定性改进和错误修复。 13 | 14 | 15 | 16 | - 在 [TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) 中简化了类似 Express 的 API。 17 | - 在 [clients 页面](/clients) 中添加了 8 个新客户端。 18 | 19 | 20 | 21 | - 在 [Python SDK](https://github.com/modelcontextprotocol/python-sdk) 中引入了 FastMCP API。 22 | - 在 [servers 仓库](https://github.com/modelcontextprotocol/servers) 中提供了 Docker 化的 MCP 服务器。 23 | 24 | 25 | 26 | - Jetbrains 发布了 MCP 的 Kotlin SDK! 27 | - 有关 MCP Kotlin 服务器的示例,请查看 [此仓库](https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples/kotlin-mcp-server)。 28 | -------------------------------------------------------------------------------- /docs.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://mintlify.com/docs.json", 3 | "theme": "linden", 4 | "name": "MCP,MCP协议,MCP 中文网,MCP协议中文网,模型上下文协议(MCP协议),模型上下文协议(MCP协议)中文网", 5 | "colors": { 6 | "primary": "#09090b", 7 | "light": "#FAFAFA", 8 | "dark": "#09090b" 9 | }, 10 | "integrations": { 11 | "ga4": { 12 | "measurementId": "G-0D3FGBKS4M" 13 | }, 14 | "gtm": { 15 | "tagId": "GTM-NRHWLWVK" 16 | } 17 | }, 18 | "favicon": "/favicon.svg", 19 | "navigation": { 20 | "languages": [ 21 | { 22 | "language": "zh", 23 | "default": true, 24 | "tabs": [ 25 | { 26 | "tab": "文档", 27 | "groups": [ 28 | { 29 | "group": "开始", 30 | "pages": [ 31 | "introduction", 32 | { 33 | "group": "快速入门", 34 | "pages": [ 35 | "quickstart/server", 36 | "quickstart/client", 37 | "quickstart/user" 38 | ] 39 | }, 40 | "examples", 41 | "clients" 42 | ] 43 | }, 44 | { 45 | "group": "教程", 46 | "pages": [ 47 | "tutorials/building-mcp-with-llms", 48 | "docs/tools/debugging", 49 | "docs/tools/inspector" 50 | ] 51 | }, 52 | { 53 | "group": "概念", 54 | "pages": [ 55 | "docs/concepts/architecture", 56 | "docs/concepts/resources", 57 | "docs/concepts/prompts", 58 | "docs/concepts/tools", 59 | "docs/concepts/sampling", 60 | "docs/concepts/roots", 61 | "docs/concepts/transports" 62 | ] 63 | }, 64 | { 65 | "group": "开发", 66 | "pages": [ 67 | "development/updates", 68 | "development/roadmap", 69 | "development/contributing" 70 | ] 71 | } 72 | ] 73 | }, 74 | { 75 | "tab": "SDKs", 76 | "icon": "book-open", 77 | "groups": [ 78 | { 79 | "group": "Java", 80 | "pages": [ 81 | "sdk/java/mcp-overview", 82 | "sdk/java/mcp-client", 83 | "sdk/java/mcp-server" 84 | ] 85 | } 86 | ] 87 | }, 88 | { 89 | "tab": "关于我", 90 | "icon": "mail", 91 | "pages": [ 92 | "ext/me" 93 | ] 94 | }, 95 | { 96 | "tab": "扩展", 97 | "icon": "book-open", 98 | "pages": [ 99 | "ext/article" 100 | ] 101 | } 102 | ] 103 | } 104 | ], 105 | "global": { 106 | "anchors": [ 107 | { 108 | "anchor": "Python SDK(官方)", 109 | "href": "https://github.com/modelcontextprotocol/python-sdk", 110 | "icon": "python" 111 | }, 112 | { 113 | "anchor": "TypeScript SDK(官方)", 114 | "href": "https://github.com/modelcontextprotocol/typescript-sdk", 115 | "icon": "square-js" 116 | }, 117 | { 118 | "anchor": "Java SDK(官方)", 119 | "href": "https://github.com/modelcontextprotocol/java-sdk", 120 | "icon": "java" 121 | }, 122 | { 123 | "anchor": "Kotlin SDK(官方)", 124 | "href": "https://github.com/modelcontextprotocol/kotlin-sdk", 125 | "icon": "square-k" 126 | }, 127 | { 128 | "anchor": "Golang SDK(社区)", 129 | "href": "https://github.com/mark3labs/mcp-go", 130 | "icon": "golang" 131 | }, 132 | { 133 | "anchor": "Golang SDK(社区)", 134 | "href": "https://github.com/metoro-io/mcp-golang", 135 | "icon": "golang" 136 | }, 137 | { 138 | "anchor": "规范", 139 | "href": "https://spec.modelcontextprotocol.io", 140 | "icon": "book" 141 | } 142 | ] 143 | } 144 | }, 145 | "logo": { 146 | "light": "/logo/light.svg", 147 | "dark": "/logo/dark.svg" 148 | }, 149 | "navbar": { 150 | "links": [], 151 | "primary": { 152 | "type": "button", 153 | "label": "GitHub", 154 | "href": "https://github.com/ccb1900/modelcontextprotocol-docs" 155 | } 156 | }, 157 | "seo": { 158 | "metatags": { 159 | "google-adsense-account": "ca-pub-1817374283725610", 160 | "og:image": "https://raw.githubusercontent.com/modelcontextprotocol/docs/2eb6171ddbfeefde349dc3b8d5e2b87414c26250/images/og-image.png" 161 | }, 162 | "indexing": "navigable" 163 | }, 164 | "footer": { 165 | "socials": { 166 | "github": "https://github.com/ccb1900/modelcontextprotocol-docs" 167 | } 168 | }, 169 | "redirects": [ 170 | { 171 | "source": "/tutorials/building-a-client", 172 | "destination": "/quickstart/client" 173 | }, 174 | { 175 | "source": "/quickstart", 176 | "destination": "/quickstart/server" 177 | } 178 | ] 179 | } -------------------------------------------------------------------------------- /docs/concepts/architecture.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "核心架构" 3 | description: "了解 MCP 如何连接客户端、服务器和 LLM" 4 | --- 5 | 6 | Model Context Protocol (MCP) 基于一个灵活、可扩展的架构,使 LLM 应用程序与集成之间的通信无缝衔接。本文档涵盖了核心架构组件和概念。 7 | 8 | ## 概述 9 | 10 | MCP 遵循客户端-服务器架构,其中: 11 | 12 | - **主机**是发起连接的 LLM 应用程序(如 Claude Desktop 或 IDE)。 13 | - **客户端**在主机应用程序内部与服务器保持 1:1 的连接。 14 | - **服务器**为客户端提供上下文、工具和提示。 15 | 16 | ```mermaid 17 | flowchart LR 18 | subgraph "主机" 19 | client1[MCP 客户端] 20 | client2[MCP 客户端] 21 | end 22 | subgraph "服务器进程" 23 | server1[MCP 服务器] 24 | end 25 | subgraph "服务器进程" 26 | server2[MCP 服务器] 27 | end 28 | 29 | client1 <-->|传输层| server1 30 | client2 <-->|传输层| server2 31 | ``` 32 | 33 | ## 核心组件 34 | 35 | ### 协议层 36 | 37 | 协议层处理消息帧、请求/响应链接以及高级通信模式。 38 | 39 | 40 | 41 | ```typescript 42 | class Protocol { 43 | // 处理传入请求 44 | setRequestHandler(schema: T, handler: (request: T, extra: RequestHandlerExtra) => Promise): void 45 | 46 | // 处理传入通知 47 | setNotificationHandler(schema: T, handler: (notification: T) => Promise): void 48 | 49 | // 发送请求并等待响应 50 | request(request: Request, schema: T, options?: RequestOptions): Promise 51 | 52 | // 发送单向通知 53 | notification(notification: Notification): Promise 54 | } 55 | ``` 56 | 57 | 58 | ```python 59 | class Session(BaseSession[RequestT, NotificationT, ResultT]): 60 | async def send_request( 61 | self, 62 | request: RequestT, 63 | result_type: type[Result] 64 | ) -> Result: 65 | """ 66 | 发送请求并等待响应。如果响应包含错误,则引发 McpError。 67 | """ 68 | # 请求处理实现 69 | 70 | async def send_notification( 71 | self, 72 | notification: NotificationT 73 | ) -> None: 74 | """发送不需要响应的单向通知。""" 75 | # 通知处理实现 76 | 77 | async def _received_request( 78 | self, 79 | responder: RequestResponder[ReceiveRequestT, ResultT] 80 | ) -> None: 81 | """处理来自另一端的传入请求。""" 82 | # 请求处理实现 83 | 84 | async def _received_notification( 85 | self, 86 | notification: ReceiveNotificationT 87 | ) -> None: 88 | """处理来自另一端的传入通知。""" 89 | # 通知处理实现 90 | ``` 91 | 92 | 93 | 94 | 关键类包括: 95 | 96 | * `Protocol` 97 | * `Client` 98 | * `Server` 99 | 100 | ### 传输层 101 | 102 | 传输层处理客户端和服务器之间的实际通信。MCP 支持多种传输机制: 103 | 104 | 1. **标准输入输出传输** 105 | - 使用标准输入/输出进行通信。 106 | - 适用于本地进程。 107 | 108 | 2. **HTTP 与 SSE 传输** 109 | - 使用服务器发送事件 (SSE) 进行服务器到客户端的消息传递。 110 | - 使用 HTTP POST 进行客户端到服务器的消息传递。 111 | 112 | 所有传输都使用 [JSON-RPC](https://www.jsonrpc.org/) 2.0 来交换消息。有关 Model Context Protocol 消息格式的详细信息,请参阅[规范](https://spec.modelcontextprotocol.io)。 113 | 114 | ### 消息类型 115 | 116 | MCP 有以下主要消息类型: 117 | 118 | 1. **请求**期望从另一端获得响应: 119 | ```typescript 120 | interface Request { 121 | method: string; 122 | params?: { ... }; 123 | } 124 | ``` 125 | 126 | 2. **结果**是请求的成功响应: 127 | ```typescript 128 | interface Result { 129 | [key: string]: unknown; 130 | } 131 | ``` 132 | 133 | 3. **错误**表示请求失败: 134 | ```typescript 135 | interface Error { 136 | code: number; 137 | message: string; 138 | data?: unknown; 139 | } 140 | ``` 141 | 142 | 4. **通知**是不期望响应的单向消息: 143 | ```typescript 144 | interface Notification { 145 | method: string; 146 | params?: { ... }; 147 | } 148 | ``` 149 | 150 | ## 连接生命周期 151 | 152 | ### 1. 初始化 153 | 154 | ```mermaid 155 | sequenceDiagram 156 | participant Client 157 | participant Server 158 | 159 | Client->>Server: 初始化请求 160 | Server->>Client: 初始化响应 161 | Client->>Server: 初始化通知 162 | 163 | Note over Client,Server: 连接准备就绪 164 | ``` 165 | 166 | 1. 客户端发送 `initialize` 请求,包含协议版本和能力。 167 | 2. 服务器响应其协议版本和能力。 168 | 3. 客户端发送 `initialized` 通知作为确认。 169 | 4. 正常消息交换开始。 170 | 171 | ### 2. 消息交换 172 | 173 | 初始化后,支持以下模式: 174 | 175 | - **请求-响应**:客户端或服务器发送请求,另一端响应。 176 | - **通知**:任一方发送单向消息。 177 | 178 | ### 3. 终止 179 | 180 | 任一方可以终止连接: 181 | - 通过 `close()` 进行干净关闭。 182 | - 传输断开。 183 | - 错误情况。 184 | 185 | ## 错误处理 186 | 187 | MCP 定义了以下标准错误代码: 188 | 189 | ```typescript 190 | enum ErrorCode { 191 | // 标准 JSON-RPC 错误代码 192 | ParseError = -32700, 193 | InvalidRequest = -32600, 194 | MethodNotFound = -32601, 195 | InvalidParams = -32602, 196 | InternalError = -32603 197 | } 198 | ``` 199 | 200 | SDK 和应用程序可以在 -32000 以上定义自己的错误代码。 201 | 202 | 错误通过以下方式传播: 203 | - 对请求的错误响应。 204 | - 传输上的错误事件。 205 | - 协议级别的错误处理程序。 206 | 207 | ## 实现示例 208 | 209 | 以下是一个实现 MCP 服务器的基本示例: 210 | 211 | 212 | 213 | ```typescript 214 | import { Server } from "@modelcontextprotocol/sdk/server/index.js"; 215 | import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; 216 | 217 | const server = new Server({ 218 | name: "example-server", 219 | version: "1.0.0" 220 | }, { 221 | capabilities: { 222 | resources: {} 223 | } 224 | }); 225 | 226 | // 处理请求 227 | server.setRequestHandler(ListResourcesRequestSchema, async () => { 228 | return { 229 | resources: [ 230 | { 231 | uri: "example://resource", 232 | name: "Example Resource" 233 | } 234 | ] 235 | }; 236 | }); 237 | 238 | // 连接传输 239 | const transport = new StdioServerTransport(); 240 | await server.connect(transport); 241 | ``` 242 | 243 | 244 | ```python 245 | import asyncio 246 | import mcp.types as types 247 | from mcp.server import Server 248 | from mcp.server.stdio import stdio_server 249 | 250 | app = Server("example-server") 251 | 252 | @app.list_resources() 253 | async def list_resources() -> list[types.Resource]: 254 | return [ 255 | types.Resource( 256 | uri="example://resource", 257 | name="Example Resource" 258 | ) 259 | ] 260 | 261 | async def main(): 262 | async with stdio_server() as streams: 263 | await app.run( 264 | streams[0], 265 | streams[1], 266 | app.create_initialization_options() 267 | ) 268 | 269 | if __name__ == "__main__": 270 | asyncio.run(main) 271 | ``` 272 | 273 | 274 | 275 | ## 最佳实践 276 | 277 | ### 传输选择 278 | 279 | 1. **本地通信** 280 | - 对本地进程使用标准输入输出传输。 281 | - 对同一台机器上的通信高效。 282 | - 简单的进程管理。 283 | 284 | 2. **远程通信** 285 | - 对需要 HTTP 兼容性的场景使用 SSE。 286 | - 考虑包括认证和授权的安全影响。 287 | 288 | ### 消息处理 289 | 290 | 1. **请求处理** 291 | - 彻底验证输入。 292 | - 使用类型安全的模式。 293 | - 优雅地处理错误。 294 | - 实现超时。 295 | 296 | 2. **进度报告** 297 | - 对长时间操作使用进度令牌。 298 | - 增量报告进度。 299 | - 在已知时包括总进度。 300 | 301 | 3. **错误管理** 302 | - 使用适当的错误代码。 303 | - 包括有用的错误消息。 304 | - 在错误时清理资源。 305 | 306 | ## 安全考虑 307 | 308 | 1. **传输安全** 309 | - 对远程连接使用 TLS。 310 | - 验证连接来源。 311 | - 在需要时实现认证。 312 | 313 | 2. **消息验证** 314 | - 验证所有传入消息。 315 | - 清理输入。 316 | - 检查消息大小限制。 317 | - 验证 JSON-RPC 格式。 318 | 319 | 3. **资源保护** 320 | - 实现访问控制。 321 | - 验证资源路径。 322 | - 监控资源使用。 323 | - 限速请求。 324 | 325 | 4. **错误处理** 326 | - 不要泄露敏感信息。 327 | - 记录与安全相关的错误。 328 | - 实现适当的清理。 329 | - 处理 DoS 场景。 330 | 331 | ## 调试和监控 332 | 333 | 1. **日志记录** 334 | - 记录协议事件。 335 | - 跟踪消息流。 336 | - 监控性能。 337 | - 记录错误。 338 | 339 | 2. **诊断** 340 | - 实现健康检查。 341 | - 监控连接状态。 342 | - 跟踪资源使用。 343 | - 分析性能。 344 | 345 | 3. **测试** 346 | - 测试不同的传输。 347 | - 验证错误处理。 348 | - 检查边缘情况。 349 | - 对服务器进行负载测试。 -------------------------------------------------------------------------------- /docs/concepts/prompts.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "提示" 3 | description: "创建可重用的提示模板和工作流" 4 | --- 5 | 6 | 提示使服务器能够定义可重用的提示模板和工作流,客户端可以轻松地将其展示给用户和 LLM。它们提供了一种强大的方式来标准化和共享常见的 LLM 交互。 7 | 8 | 9 | 提示设计为**用户控制**,这意味着它们从服务器暴露给客户端,目的是让用户能够明确选择使用它们。 10 | 11 | 12 | ## 概述 13 | 14 | MCP 中的提示是预定义的模板,可以: 15 | - 接受动态参数 16 | - 包含来自资源的上下文 17 | - 链式多个交互 18 | - 引导特定的工作流 19 | - 作为 UI 元素(如斜杠命令)展示 20 | 21 | ## 提示结构 22 | 23 | 每个提示的定义包括: 24 | 25 | ```typescript 26 | { 27 | name: string; // 提示的唯一标识符 28 | description?: string; // 人类可读的描述 29 | arguments?: [ // 可选的参数列表 30 | { 31 | name: string; // 参数标识符 32 | description?: string; // 参数描述 33 | required?: boolean; // 参数是否为必填 34 | } 35 | ] 36 | } 37 | ``` 38 | 39 | ## 发现提示 40 | 41 | 客户端可以通过 `prompts/list` 端点发现可用的提示: 42 | 43 | ```typescript 44 | // 请求 45 | { 46 | method: "prompts/list" 47 | } 48 | 49 | // 响应 50 | { 51 | prompts: [ 52 | { 53 | name: "analyze-code", 54 | description: "分析代码以寻找改进空间", 55 | arguments: [ 56 | { 57 | name: "language", 58 | description: "编程语言", 59 | required: true 60 | } 61 | ] 62 | } 63 | ] 64 | } 65 | ``` 66 | 67 | ## 使用提示 68 | 69 | 要使用提示,客户端发出 `prompts/get` 请求: 70 | 71 | ```typescript 72 | // 请求 73 | { 74 | method: "prompts/get", 75 | params: { 76 | name: "analyze-code", 77 | arguments: { 78 | language: "python" 79 | } 80 | } 81 | } 82 | 83 | // 响应 84 | { 85 | description: "分析 Python 代码以寻找改进空间", 86 | messages: [ 87 | { 88 | role: "user", 89 | content: { 90 | type: "text", 91 | text: "请分析以下 Python 代码以寻找改进空间:\n\n```python\ndef calculate_sum(numbers):\n total = 0\n for num in numbers:\n total = total + num\n return total\n\nresult = calculate_sum([1, 2, 3, 4, 5])\nprint(result)\n```" 92 | } 93 | } 94 | ] 95 | } 96 | ``` 97 | 98 | ## 动态提示 99 | 100 | 提示可以是动态的,并包括: 101 | 102 | ### 嵌入资源上下文 103 | 104 | ```json 105 | { 106 | "name": "analyze-project", 107 | "description": "分析项目日志和代码", 108 | "arguments": [ 109 | { 110 | "name": "timeframe", 111 | "description": "分析日志的时间段", 112 | "required": true 113 | }, 114 | { 115 | "name": "fileUri", 116 | "description": "要审查的代码文件的 URI", 117 | "required": true 118 | } 119 | ] 120 | } 121 | ``` 122 | 123 | 在处理 `prompts/get` 请求时: 124 | 125 | ```json 126 | { 127 | "messages": [ 128 | { 129 | "role": "user", 130 | "content": { 131 | "type": "text", 132 | "text": "分析这些系统日志和代码文件以寻找任何问题:" 133 | } 134 | }, 135 | { 136 | "role": "user", 137 | "content": { 138 | "type": "resource", 139 | "resource": { 140 | "uri": "logs://recent?timeframe=1h", 141 | "text": "[2024-03-14 15:32:11] ERROR: Connection timeout in network.py:127\n[2024-03-14 15:32:15] WARN: Retrying connection (attempt 2/3)\n[2024-03-14 15:32:20] ERROR: Max retries exceeded", 142 | "mimeType": "text/plain" 143 | } 144 | } 145 | }, 146 | { 147 | "role": "user", 148 | "content": { 149 | "type": "resource", 150 | "resource": { 151 | "uri": "file:///path/to/code.py", 152 | "text": "def connect_to_service(timeout=30):\n retries = 3\n for attempt in range(retries):\n try:\n return establish_connection(timeout)\n except TimeoutError:\n if attempt == retries - 1:\n raise\n time.sleep(5)\n\ndef establish_connection(timeout):\n # Connection implementation\n pass", 153 | "mimeType": "text/x-python" 154 | } 155 | } 156 | } 157 | ] 158 | } 159 | ``` 160 | 161 | ### 多步工作流 162 | 163 | ```typescript 164 | const debugWorkflow = { 165 | name: "debug-error", 166 | async getMessages(error: string) { 167 | return [ 168 | { 169 | role: "user", 170 | content: { 171 | type: "text", 172 | text: `我看到的错误是:${error}` 173 | } 174 | }, 175 | { 176 | role: "assistant", 177 | content: { 178 | type: "text", 179 | text: "我会帮助分析这个错误。你到目前为止尝试了什么?" 180 | } 181 | }, 182 | { 183 | role: "user", 184 | content: { 185 | type: "text", 186 | text: "我尝试重启了服务,但错误仍然存在。" 187 | } 188 | } 189 | ]; 190 | } 191 | }; 192 | ``` 193 | 194 | ## 示例实现 195 | 196 | 以下是在 MCP 服务器中实现提示的完整示例: 197 | 198 | 199 | 200 | ```typescript 201 | import { Server } from "@modelcontextprotocol/sdk/server"; 202 | import { 203 | ListPromptsRequestSchema, 204 | GetPromptRequestSchema 205 | } from "@modelcontextprotocol/sdk/types"; 206 | 207 | const PROMPTS = { 208 | "git-commit": { 209 | name: "git-commit", 210 | description: "生成 Git 提交消息", 211 | arguments: [ 212 | { 213 | name: "changes", 214 | description: "Git diff 或变更描述", 215 | required: true 216 | } 217 | ] 218 | }, 219 | "explain-code": { 220 | name: "explain-code", 221 | description: "解释代码的工作原理", 222 | arguments: [ 223 | { 224 | name: "code", 225 | description: "要解释的代码", 226 | required: true 227 | }, 228 | { 229 | name: "language", 230 | description: "编程语言", 231 | required: false 232 | } 233 | ] 234 | } 235 | }; 236 | 237 | const server = new Server({ 238 | name: "example-prompts-server", 239 | version: "1.0.0" 240 | }, { 241 | capabilities: { 242 | prompts: {} 243 | } 244 | }); 245 | 246 | // 列出可用提示 247 | server.setRequestHandler(ListPromptsRequestSchema, async () => { 248 | return { 249 | prompts: Object.values(PROMPTS) 250 | }; 251 | }); 252 | 253 | // 获取特定提示 254 | server.setRequestHandler(GetPromptRequestSchema, async (request) => { 255 | const prompt = PROMPTS[request.params.name]; 256 | if (!prompt) { 257 | throw new Error(`提示未找到:${request.params.name}`); 258 | } 259 | 260 | if (request.params.name === "git-commit") { 261 | return { 262 | messages: [ 263 | { 264 | role: "user", 265 | content: { 266 | type: "text", 267 | text: `为这些变更生成简洁但描述性的提交消息:\n\n${request.params.arguments?.changes}` 268 | } 269 | } 270 | ] 271 | }; 272 | } 273 | 274 | if (request.params.name === "explain-code") { 275 | const language = request.params.arguments?.language || "Unknown"; 276 | return { 277 | messages: [ 278 | { 279 | role: "user", 280 | content: { 281 | type: "text", 282 | text: `解释这段 ${language} 代码的工作原理:\n\n${request.params.arguments?.code}` 283 | } 284 | } 285 | ] 286 | }; 287 | } 288 | 289 | throw new Error("提示实现未找到"); 290 | }); 291 | ``` 292 | 293 | 294 | ```python 295 | from mcp.server import Server 296 | import mcp.types as types 297 | 298 | # 定义可用提示 299 | PROMPTS = { 300 | "git-commit": types.Prompt( 301 | name="git-commit", 302 | description="生成 Git 提交消息", 303 | arguments=[ 304 | types.PromptArgument( 305 | name="changes", 306 | description="Git diff 或变更描述", 307 | required=True 308 | ) 309 | ], 310 | ), 311 | "explain-code": types.Prompt( 312 | name="explain-code", 313 | description="解释代码的工作原理", 314 | arguments=[ 315 | types.PromptArgument( 316 | name="code", 317 | description="要解释的代码", 318 | required=True 319 | ), 320 | types.PromptArgument( 321 | name="language", 322 | description="编程语言", 323 | required=False 324 | ) 325 | ], 326 | ) 327 | } 328 | 329 | # 初始化服务器 330 | app = Server("example-prompts-server") 331 | 332 | @app.list_prompts() 333 | async def list_prompts() -> list[types.Prompt]: 334 | return list(PROMPTS.values()) 335 | 336 | @app.get_prompt() 337 | async def get_prompt( 338 | name: str, arguments: dict[str, str] | None = None 339 | ) -> types.GetPromptResult: 340 | if name not in PROMPTS: 341 | raise ValueError(f"提示未找到:{name}") 342 | 343 | if name == "git-commit": 344 | changes = arguments.get("changes") if arguments else "" 345 | return types.GetPromptResult( 346 | messages=[ 347 | types.PromptMessage( 348 | role="user", 349 | content=types.TextContent( 350 | type="text", 351 | text=f"为这些变更生成简洁但描述性的提交消息:\n\n{changes}" 352 | ) 353 | ) 354 | ] 355 | ) 356 | 357 | if name == "explain-code": 358 | code = arguments.get("code") if arguments else "" 359 | language = arguments.get("language", "Unknown") if arguments else "Unknown" 360 | return types.GetPromptResult( 361 | messages=[ 362 | types.PromptMessage( 363 | role="user", 364 | content=types.TextContent( 365 | type="text", 366 | text=f"解释这段 {language} 代码的工作原理:\n\n{code}" 367 | ) 368 | ) 369 | ] 370 | ) 371 | 372 | raise ValueError("提示实现未找到") 373 | ``` 374 | 375 | 376 | 377 | ## 最佳实践 378 | 379 | 在实现提示时: 380 | 381 | 1. 使用清晰、描述性的提示名称 382 | 2. 提供提示和参数的详细描述 383 | 3. 验证所有必需的参数 384 | 4. 优雅地处理缺失的参数 385 | 5. 考虑对提示模板进行版本控制 386 | 6. 在适当的情况下缓存动态内容 387 | 7. 实现错误处理 388 | 8. 记录预期的参数格式 389 | 9. 考虑提示的可组合性 390 | 10. 使用各种输入测试提示 391 | 392 | ## UI 集成 393 | 394 | 提示可以作为以下 UI 元素展示: 395 | - 斜杠命令 396 | - 快速操作 397 | - 上下文菜单项 398 | - 命令面板条目 399 | - 引导式工作流 400 | - 交互式表单 401 | 402 | ## 更新和变更 403 | 404 | 服务器可以通知客户端有关提示的变更: 405 | 406 | 1. 服务器能力:`prompts.listChanged` 407 | 2. 通知:`notifications/prompts/list_changed` 408 | 3. 客户端重新获取提示列表 409 | 410 | ## 安全考虑 411 | 412 | 在实现提示时: 413 | - 验证所有参数 414 | - 清理用户输入 415 | - 考虑限速 416 | - 实现访问控制 417 | - 审计提示使用情况 418 | - 适当处理敏感数据 419 | - 验证生成的内容 420 | - 实现超时 421 | - 考虑提示注入风险 422 | - 记录安全要求 -------------------------------------------------------------------------------- /docs/concepts/resources.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "资源" 3 | description: "将服务器上的数据和内容暴露给LLM使用" 4 | --- 5 | 6 | 资源是模型上下文协议(MCP协议)中的核心原语,允许服务器暴露数据和内容,客户端可以读取这些资源并将其用作LLM交互的上下文。 7 | 8 | 9 | 资源设计为**应用程序控制**,意味着客户端应用程序可以决定如何以及何时使用它们。 10 | 不同的MCP客户端可能会以不同的方式处理资源。例如: 11 | - Claude Desktop目前要求用户在使用资源之前明确选择资源 12 | - 其他客户端可能会基于启发式自动选择资源 13 | - 某些实现甚至可能允许AI模型本身决定使用哪些资源 14 | 15 | 服务器作者在实现资源支持时应准备好处理这些交互模式。为了自动向模型暴露数据,服务器作者应使用**模型控制**的原语,例如[工具](./tools)。 16 | 17 | 18 | ## 概述 19 | 20 | 资源代表MCP服务器希望向客户端提供的任何类型的数据。这可以包括: 21 | 22 | - 文件内容 23 | - 数据库记录 24 | - API响应 25 | - 实时系统数据 26 | - 截图和图像 27 | - 日志文件 28 | - 以及其他 29 | 30 | 每个资源由唯一的URI标识,可以包含文本或二进制数据。 31 | 32 | ## 资源URI 33 | 34 | 资源使用以下格式的URI进行标识: 35 | 36 | ``` 37 | [协议]://[主机]/[路径] 38 | ``` 39 | 40 | 例如: 41 | - `file:///home/user/documents/report.pdf` 42 | - `postgres://database/customers/schema` 43 | - `screen://localhost/display1` 44 | 45 | 协议和路径结构由MCP服务器实现定义。服务器可以定义自己的自定义URI方案。 46 | 47 | ## 资源类型 48 | 49 | 资源可以包含两种类型的内容: 50 | 51 | ### 文本资源 52 | 53 | 文本资源包含UTF-8编码的文本数据。这些适用于: 54 | - 源代码 55 | - 配置文件 56 | - 日志文件 57 | - JSON/XML数据 58 | - 纯文本 59 | 60 | ### 二进制资源 61 | 62 | 二进制资源包含base64编码的原始二进制数据。这些适用于: 63 | - 图像 64 | - PDF文件 65 | - 音频文件 66 | - 视频文件 67 | - 其他非文本格式 68 | 69 | ## 资源发现 70 | 71 | 客户端可以通过两种主要方法发现可用资源: 72 | 73 | ### 直接资源 74 | 75 | 服务器通过`resources/list`端点暴露具体资源列表。每个资源包括: 76 | 77 | ```typescript 78 | { 79 | uri: string; // 资源的唯一标识符 80 | name: string; // 人类可读的名称 81 | description?: string; // 可选描述 82 | mimeType?: string; // 可选的MIME类型 83 | } 84 | ``` 85 | 86 | ### 资源模板 87 | 88 | 对于动态资源,服务器可以暴露[URI模板](https://datatracker.ietf.org/doc/html/rfc6570),客户端可以使用这些模板构建有效的资源URI: 89 | 90 | ```typescript 91 | { 92 | uriTemplate: string; // 遵循RFC 6570的URI模板 93 | name: string; // 该类型的人类可读名称 94 | description?: string; // 可选描述 95 | mimeType?: string; // 所有匹配资源的可选MIME类型 96 | } 97 | ``` 98 | 99 | ## 读取资源 100 | 101 | 要读取资源,客户端使用资源URI发出`resources/read`请求。 102 | 103 | 服务器响应包含资源内容列表: 104 | 105 | ```typescript 106 | { 107 | contents: [ 108 | { 109 | uri: string; // 资源的URI 110 | mimeType?: string; // 可选的MIME类型 111 | 112 | // 以下之一: 113 | text?: string; // 对于文本资源 114 | blob?: string; // 对于二进制资源(base64编码) 115 | } 116 | ] 117 | } 118 | ``` 119 | 120 | 121 | 服务器可能会响应一个`resources/read`请求返回多个资源。例如,当读取目录时,可以返回目录中的文件列表。 122 | 123 | 124 | ## 资源更新 125 | 126 | MCP通过两种机制支持资源的实时更新: 127 | 128 | ### 列表更改 129 | 130 | 服务器可以通过`notifications/resources/list_changed`通知客户端可用资源列表的更改。 131 | 132 | ### 内容更改 133 | 134 | 客户端可以订阅特定资源的更新: 135 | 136 | 1. 客户端发送`resources/subscribe`并附带资源URI 137 | 2. 当资源更改时,服务器发送`notifications/resources/updated` 138 | 3. 客户端可以使用`resources/read`获取最新内容 139 | 4. 客户端可以使用`resources/unsubscribe`取消订阅 140 | 141 | ## 示例实现 142 | 143 | 以下是一个在MCP服务器中实现资源支持的简单示例: 144 | 145 | 146 | 147 | ```typescript 148 | const server = new Server({ 149 | name: "example-server", 150 | version: "1.0.0" 151 | }, { 152 | capabilities: { 153 | resources: {} 154 | } 155 | }); 156 | 157 | // 列出可用资源 158 | server.setRequestHandler(ListResourcesRequestSchema, async () => { 159 | return { 160 | resources: [ 161 | { 162 | uri: "file:///logs/app.log", 163 | name: "Application Logs", 164 | mimeType: "text/plain" 165 | } 166 | ] 167 | }; 168 | }); 169 | 170 | // 读取资源内容 171 | server.setRequestHandler(ReadResourceRequestSchema, async (request) => { 172 | const uri = request.params.uri; 173 | 174 | if (uri === "file:///logs/app.log") { 175 | const logContents = await readLogFile(); 176 | return { 177 | contents: [ 178 | { 179 | uri, 180 | mimeType: "text/plain", 181 | text: logContents 182 | } 183 | ] 184 | }; 185 | } 186 | 187 | throw new Error("Resource not found"); 188 | }); 189 | ``` 190 | 191 | 192 | ```python 193 | app = Server("example-server") 194 | 195 | @app.list_resources() 196 | async def list_resources() -> list[types.Resource]: 197 | return [ 198 | types.Resource( 199 | uri="file:///logs/app.log", 200 | name="Application Logs", 201 | mimeType="text/plain" 202 | ) 203 | ] 204 | 205 | @app.read_resource() 206 | async def read_resource(uri: AnyUrl) -> str: 207 | if str(uri) == "file:///logs/app.log": 208 | log_contents = await read_log_file() 209 | return log_contents 210 | 211 | raise ValueError("Resource not found") 212 | 213 | # 启动服务器 214 | async with stdio_server() as streams: 215 | await app.run( 216 | streams[0], 217 | streams[1], 218 | app.create_initialization_options() 219 | ) 220 | ``` 221 | 222 | 223 | 224 | ## 最佳实践 225 | 226 | 在实现资源支持时: 227 | 228 | 1. 使用清晰、描述性的资源名称和URI 229 | 2. 包含有用的描述以指导LLM理解 230 | 3. 在已知时设置适当的MIME类型 231 | 4. 为动态内容实现资源模板 232 | 5. 对频繁更改的资源使用订阅 233 | 6. 使用清晰的错误消息优雅地处理错误 234 | 7. 对于大型资源列表考虑分页 235 | 8. 在适当时缓存资源内容 236 | 9. 在处理之前验证URI 237 | 10. 记录您的自定义URI方案 238 | 239 | ## 安全考虑 240 | 241 | 在暴露资源时: 242 | 243 | - 验证所有资源URI 244 | - 实施适当的访问控制 245 | - 清理文件路径以防止目录遍历 246 | - 谨慎处理二进制数据 247 | - 考虑对资源读取进行速率限制 248 | - 审计资源访问 249 | - 加密传输中的敏感数据 250 | - 验证MIME类型 251 | - 对长时间运行的读取实施超时 252 | - 适当处理资源清理 -------------------------------------------------------------------------------- /docs/concepts/roots.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "根目录" 3 | description: "理解MCP中的根目录" 4 | --- 5 | 6 | 根目录是MCP中的一个概念,用于定义服务器可以操作的边界。它们提供了一种方式,让客户端能够告知服务器相关资源及其位置。 7 | 8 | ## 什么是根目录? 9 | 10 | 根目录是客户端建议服务器应关注的URI。当客户端连接到服务器时,它会声明服务器应处理哪些根目录。虽然主要用于文件系统路径,但根目录可以是任何有效的URI,包括HTTP URL。 11 | 12 | 例如,根目录可以是: 13 | 14 | ``` 15 | file:///home/user/projects/myapp 16 | https://api.example.com/v1 17 | ``` 18 | 19 | ## 为什么使用根目录? 20 | 21 | 根目录有以下几个重要用途: 22 | 23 | 1. **引导**:它们告知服务器相关资源及其位置 24 | 2. **清晰性**:根目录明确了哪些资源属于你的工作空间 25 | 3. **组织性**:多个根目录允许你同时处理不同的资源 26 | 27 | ## 根目录的工作原理 28 | 29 | 当客户端支持根目录时,它会: 30 | 31 | 1. 在连接期间声明`roots`能力 32 | 2. 向服务器提供建议的根目录列表 33 | 3. 在根目录发生变化时通知服务器(如果支持) 34 | 35 | 虽然根目录是信息性的,并不强制执行,但服务器应: 36 | 37 | 1. 尊重提供的根目录 38 | 2. 使用根目录URI来定位和访问资源 39 | 3. 优先在根目录边界内进行操作 40 | 41 | ## 常见用例 42 | 43 | 根目录通常用于定义: 44 | 45 | - 项目目录 46 | - 仓库位置 47 | - API端点 48 | - 配置位置 49 | - 资源边界 50 | 51 | ## 最佳实践 52 | 53 | 在处理根目录时: 54 | 55 | 1. 仅建议必要的资源 56 | 2. 使用清晰、描述性的名称来命名根目录 57 | 3. 监控根目录的可访问性 58 | 4. 优雅地处理根目录的变化 59 | 60 | ## 示例 61 | 62 | 以下是一个典型的MCP客户端如何暴露根目录的示例: 63 | 64 | ```json 65 | { 66 | "roots": [ 67 | { 68 | "uri": "file:///home/user/projects/frontend", 69 | "name": "前端仓库" 70 | }, 71 | { 72 | "uri": "https://api.example.com/v1", 73 | "name": "API端点" 74 | } 75 | ] 76 | } 77 | ``` 78 | 79 | 此配置建议服务器同时关注本地仓库和API端点,并在逻辑上保持它们的分离。 -------------------------------------------------------------------------------- /docs/concepts/sampling.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "采样" 3 | description: "让你的服务器通过客户端请求LLM的补全" 4 | --- 5 | 6 | 采样是MCP的一项强大功能,允许服务器通过客户端请求LLM补全,从而实现复杂的代理行为,同时保持安全性和隐私性。 7 | 8 | 9 | MCP的这一功能目前尚未在Claude Desktop客户端中支持。 10 | 11 | 12 | ## 采样的工作原理 13 | 14 | 采样的流程遵循以下步骤: 15 | 16 | 1. 服务器向客户端发送`sampling/createMessage`请求 17 | 2. 客户端审查请求并可以对其进行修改 18 | 3. 客户端从LLM中进行采样 19 | 4. 客户端审查补全结果 20 | 5. 客户端将结果返回给服务器 21 | 22 | 这种“人在回路”的设计确保用户能够控制LLM看到和生成的内容。 23 | 24 | ## 消息格式 25 | 26 | 采样请求使用标准化的消息格式: 27 | 28 | ```typescript 29 | { 30 | messages: [ 31 | { 32 | role: "user" | "assistant", 33 | content: { 34 | type: "text" | "image", 35 | 36 | // 对于文本: 37 | text?: string, 38 | 39 | // 对于图像: 40 | data?: string, // base64编码 41 | mimeType?: string 42 | } 43 | } 44 | ], 45 | modelPreferences?: { 46 | hints?: [{ 47 | name?: string // 建议的模型名称/系列 48 | }], 49 | costPriority?: number, // 0-1,最小化成本的重要性 50 | speedPriority?: number, // 0-1,低延迟的重要性 51 | intelligencePriority?: number // 0-1,模型能力的重要性 52 | }, 53 | systemPrompt?: string, 54 | includeContext?: "none" | "thisServer" | "allServers", 55 | temperature?: number, 56 | maxTokens: number, 57 | stopSequences?: string[], 58 | metadata?: Record 59 | } 60 | ``` 61 | 62 | ## 请求参数 63 | 64 | ### 消息 65 | 66 | `messages`数组包含要发送给LLM的对话历史。每条消息包含: 67 | 68 | - `role`:可以是"user"或"assistant" 69 | - `content`:消息内容,可以是: 70 | - 文本内容,带有`text`字段 71 | - 图像内容,带有`data`(base64编码)和`mimeType`字段 72 | 73 | ### 模型偏好 74 | 75 | `modelPreferences`对象允许服务器指定其模型选择的偏好: 76 | 77 | - `hints`:模型名称建议的数组,客户端可以使用这些建议来选择适当的模型: 78 | - `name`:字符串,可以匹配完整或部分模型名称(例如"claude-3","sonnet") 79 | - 客户端可以将提示映射到不同提供商的等效模型 80 | - 多个提示按优先顺序进行评估 81 | 82 | - 优先级值(0-1标准化): 83 | - `costPriority`:最小化成本的重要性 84 | - `speedPriority`:低延迟响应的重要性 85 | - `intelligencePriority`:高级模型能力的重要性 86 | 87 | 客户端根据这些偏好和其可用模型进行最终的模型选择。 88 | 89 | ### 系统提示 90 | 91 | 可选的`systemPrompt`字段允许服务器请求特定的系统提示。客户端可以修改或忽略此提示。 92 | 93 | ### 上下文包含 94 | 95 | `includeContext`参数指定要包含的MCP上下文: 96 | 97 | - `"none"`:不包含额外上下文 98 | - `"thisServer"`:包含请求服务器的上下文 99 | - `"allServers"`:包含所有连接的MCP服务器的上下文 100 | 101 | 客户端控制实际包含的上下文。 102 | 103 | ### 采样参数 104 | 105 | 通过以下参数微调LLM采样: 106 | 107 | - `temperature`:控制随机性(0.0到1.0) 108 | - `maxTokens`:生成的最大token数 109 | - `stopSequences`:停止生成的序列数组 110 | - `metadata`:额外的提供商特定参数 111 | 112 | ## 响应格式 113 | 114 | 客户端返回补全结果: 115 | 116 | ```typescript 117 | { 118 | model: string, // 使用的模型名称 119 | stopReason?: "endTurn" | "stopSequence" | "maxTokens" | string, 120 | role: "user" | "assistant", 121 | content: { 122 | type: "text" | "image", 123 | text?: string, 124 | data?: string, 125 | mimeType?: string 126 | } 127 | } 128 | ``` 129 | 130 | ## 示例请求 131 | 132 | 以下是一个向客户端请求采样的示例: 133 | ```json 134 | { 135 | "method": "sampling/createMessage", 136 | "params": { 137 | "messages": [ 138 | { 139 | "role": "user", 140 | "content": { 141 | "type": "text", 142 | "text": "当前目录中有哪些文件?" 143 | } 144 | } 145 | ], 146 | "systemPrompt": "你是一个有用的文件系统助手。", 147 | "includeContext": "thisServer", 148 | "maxTokens": 100 149 | } 150 | } 151 | ``` 152 | 153 | ## 最佳实践 154 | 155 | 在实现采样时: 156 | 157 | 1. 始终提供清晰、结构化的提示 158 | 2. 正确处理文本和图像内容 159 | 3. 设置合理的token限制 160 | 4. 通过`includeContext`包含相关上下文 161 | 5. 在使用之前验证响应 162 | 6. 优雅地处理错误 163 | 7. 考虑对采样请求进行速率限制 164 | 8. 记录预期的采样行为 165 | 9. 使用各种模型参数进行测试 166 | 10. 监控采样成本 167 | 168 | ## 人在回路控制 169 | 170 | 采样设计时考虑了人工监督: 171 | 172 | ### 对于提示 173 | 174 | - 客户端应向用户显示提议的提示 175 | - 用户应能够修改或拒绝提示 176 | - 系统提示可以被过滤或修改 177 | - 上下文包含由客户端控制 178 | 179 | ### 对于补全 180 | 181 | - 客户端应向用户显示补全结果 182 | - 用户应能够修改或拒绝补全 183 | - 客户端可以过滤或修改补全 184 | - 用户控制使用的模型 185 | 186 | ## 安全考虑 187 | 188 | 在实现采样时: 189 | 190 | - 验证所有消息内容 191 | - 清理敏感信息 192 | - 实施适当的速率限制 193 | - 监控采样使用情况 194 | - 加密传输中的数据 195 | - 处理用户数据隐私 196 | - 审计采样请求 197 | - 控制成本暴露 198 | - 实现超时机制 199 | - 优雅地处理模型错误 200 | 201 | ## 常见模式 202 | 203 | ### 代理工作流 204 | 205 | 采样支持以下代理模式: 206 | 207 | - 读取和分析资源 208 | - 基于上下文做出决策 209 | - 生成结构化数据 210 | - 处理多步骤任务 211 | - 提供交互式帮助 212 | 213 | ### 上下文管理 214 | 215 | 上下文的最佳实践: 216 | 217 | - 请求最小必要的上下文 218 | - 清晰地结构化上下文 219 | - 处理上下文大小限制 220 | - 根据需要更新上下文 221 | - 清理过时的上下文 222 | 223 | ### 错误处理 224 | 225 | 稳健的错误处理应: 226 | 227 | - 捕获采样失败 228 | - 处理超时错误 229 | - 管理速率限制 230 | - 验证响应 231 | - 提供备用行为 232 | - 适当记录错误 233 | 234 | ## 限制 235 | 236 | 请注意以下限制: 237 | 238 | - 采样依赖于客户端的能力 239 | - 用户控制采样行为 240 | - 上下文大小有限制 241 | - 可能适用速率限制 242 | - 应考虑成本 243 | - 模型可用性各不相同 244 | - 响应时间不同 245 | - 并非所有内容类型都受支持 -------------------------------------------------------------------------------- /docs/concepts/tools.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "工具" 3 | description: "通过你的服务器让LLM执行操作" 4 | --- 5 | 6 | 工具是模型上下文协议(MCP协议)中的一项强大原语,允许服务器向客户端暴露可执行的功能。通过工具,LLM可以与外部系统交互、执行计算并在现实世界中采取行动。 7 | 8 | 9 | 工具设计为**模型控制**,意味着服务器向客户端暴露工具的目的是让AI模型能够自动调用它们(在人工监督下授予批准)。 10 | 11 | 12 | ## 概述 13 | 14 | MCP中的工具允许服务器暴露可执行函数,客户端可以调用这些函数,LLM可以使用它们来执行操作。工具的关键方面包括: 15 | 16 | - **发现**:客户端可以通过`tools/list`端点列出可用工具 17 | - **调用**:使用`tools/call`端点调用工具,服务器执行请求的操作并返回结果 18 | - **灵活性**:工具可以从简单的计算到复杂的API交互 19 | 20 | 与[资源](/docs/concepts/resources)类似,工具由唯一的名称标识,并且可以包含描述以指导其使用。然而,与资源不同,工具代表可以修改状态或与外部系统交互的动态操作。 21 | 22 | ## 工具定义结构 23 | 24 | 每个工具的定义结构如下: 25 | 26 | ```typescript 27 | { 28 | name: string; // 工具的唯一标识符 29 | description?: string; // 人类可读的描述 30 | inputSchema: { // 工具参数的JSON Schema 31 | type: "object", 32 | properties: { ... } // 工具特定参数 33 | } 34 | } 35 | ``` 36 | 37 | ## 实现工具 38 | 39 | 以下是在MCP服务器中实现基本工具的示例: 40 | 41 | 42 | 43 | ```typescript 44 | const server = new Server({ 45 | name: "example-server", 46 | version: "1.0.0" 47 | }, { 48 | capabilities: { 49 | tools: {} 50 | } 51 | }); 52 | 53 | // 定义可用工具 54 | server.setRequestHandler(ListToolsRequestSchema, async () => { 55 | return { 56 | tools: [{ 57 | name: "calculate_sum", 58 | description: "将两个数字相加", 59 | inputSchema: { 60 | type: "object", 61 | properties: { 62 | a: { type: "number" }, 63 | b: { type: "number" } 64 | }, 65 | required: ["a", "b"] 66 | } 67 | }] 68 | }; 69 | }); 70 | 71 | // 处理工具执行 72 | server.setRequestHandler(CallToolRequestSchema, async (request) => { 73 | if (request.params.name === "calculate_sum") { 74 | const { a, b } = request.params.arguments; 75 | return { 76 | content: [ 77 | { 78 | type: "text", 79 | text: String(a + b) 80 | } 81 | ] 82 | }; 83 | } 84 | throw new Error("未找到工具"); 85 | }); 86 | ``` 87 | 88 | 89 | ```python 90 | app = Server("example-server") 91 | 92 | @app.list_tools() 93 | async def list_tools() -> list[types.Tool]: 94 | return [ 95 | types.Tool( 96 | name="calculate_sum", 97 | description="将两个数字相加", 98 | inputSchema={ 99 | "type": "object", 100 | "properties": { 101 | "a": {"type": "number"}, 102 | "b": {"type": "number"} 103 | }, 104 | "required": ["a", "b"] 105 | } 106 | ) 107 | ] 108 | 109 | @app.call_tool() 110 | async def call_tool( 111 | name: str, 112 | arguments: dict 113 | ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]: 114 | if name == "calculate_sum": 115 | a = arguments["a"] 116 | b = arguments["b"] 117 | result = a + b 118 | return [types.TextContent(type="text", text=str(result))] 119 | raise ValueError(f"未找到工具: {name}") 120 | ``` 121 | 122 | 123 | 124 | ## 工具模式示例 125 | 126 | 以下是一些服务器可以提供的工具类型示例: 127 | 128 | ### 系统操作 129 | 130 | 与本地系统交互的工具: 131 | 132 | ```typescript 133 | { 134 | name: "execute_command", 135 | description: "运行shell命令", 136 | inputSchema: { 137 | type: "object", 138 | properties: { 139 | command: { type: "string" }, 140 | args: { type: "array", items: { type: "string" } } 141 | } 142 | } 143 | } 144 | ``` 145 | 146 | ### API集成 147 | 148 | 封装外部API的工具: 149 | 150 | ```typescript 151 | { 152 | name: "github_create_issue", 153 | description: "创建GitHub issue", 154 | inputSchema: { 155 | type: "object", 156 | properties: { 157 | title: { type: "string" }, 158 | body: { type: "string" }, 159 | labels: { type: "array", items: { type: "string" } } 160 | } 161 | } 162 | } 163 | ``` 164 | 165 | ### 数据处理 166 | 167 | 转换或分析数据的工具: 168 | 169 | ```typescript 170 | { 171 | name: "analyze_csv", 172 | description: "分析CSV文件", 173 | inputSchema: { 174 | type: "object", 175 | properties: { 176 | filepath: { type: "string" }, 177 | operations: { 178 | type: "array", 179 | items: { 180 | enum: ["sum", "average", "count"] 181 | } 182 | } 183 | } 184 | } 185 | } 186 | ``` 187 | 188 | ## 最佳实践 189 | 190 | 在实现工具时: 191 | 192 | 1. 提供清晰、描述性的名称和描述 193 | 2. 使用详细的JSON Schema定义参数 194 | 3. 在工具描述中包含示例,以演示模型应如何使用它们 195 | 4. 实现适当的错误处理和验证 196 | 5. 对长时间操作使用进度报告 197 | 6. 保持工具操作专注和原子化 198 | 7. 记录预期的返回值结构 199 | 8. 实现适当的超时机制 200 | 9. 对资源密集型操作考虑速率限制 201 | 10. 记录工具使用情况以便调试和监控 202 | 203 | ## 安全考虑 204 | 205 | 在暴露工具时: 206 | 207 | ### 输入验证 208 | 209 | - 根据模式验证所有参数 210 | - 清理文件路径和系统命令 211 | - 验证URL和外部标识符 212 | - 检查参数大小和范围 213 | - 防止命令注入 214 | 215 | ### 访问控制 216 | 217 | - 在需要时实施身份验证 218 | - 使用适当的授权检查 219 | - 审计工具使用情况 220 | - 对请求进行速率限制 221 | - 监控滥用行为 222 | 223 | ### 错误处理 224 | 225 | - 不要向客户端暴露内部错误 226 | - 记录与安全相关的错误 227 | - 适当处理超时 228 | - 在错误后清理资源 229 | - 验证返回值 230 | 231 | ## 工具发现和更新 232 | 233 | MCP支持动态工具发现: 234 | 235 | 1. 客户端可以随时列出可用工具 236 | 2. 服务器可以使用`notifications/tools/list_changed`通知客户端工具更改 237 | 3. 可以在运行时添加或删除工具 238 | 4. 工具定义可以更新(尽管应谨慎进行) 239 | 240 | ## 错误处理 241 | 242 | 工具错误应在结果对象中报告,而不是作为MCP协议级别的错误。这使得LLM能够看到并可能处理错误。当工具遇到错误时: 243 | 244 | 1. 在结果中将`isError`设置为`true` 245 | 2. 在`content`数组中包含错误详细信息 246 | 247 | 以下是工具的正确错误处理示例: 248 | 249 | 250 | 251 | ```typescript 252 | try { 253 | // 工具操作 254 | const result = performOperation(); 255 | return { 256 | content: [ 257 | { 258 | type: "text", 259 | text: `操作成功: ${result}` 260 | } 261 | ] 262 | }; 263 | } catch (error) { 264 | return { 265 | isError: true, 266 | content: [ 267 | { 268 | type: "text", 269 | text: `错误: ${error.message}` 270 | } 271 | ] 272 | }; 273 | } 274 | ``` 275 | 276 | 277 | ```python 278 | try: 279 | # 工具操作 280 | result = perform_operation() 281 | return types.CallToolResult( 282 | content=[ 283 | types.TextContent( 284 | type="text", 285 | text=f"操作成功: {result}" 286 | ) 287 | ] 288 | ) 289 | except Exception as error: 290 | return types.CallToolResult( 291 | isError=True, 292 | content=[ 293 | types.TextContent( 294 | type="text", 295 | text=f"错误: {str(error)}" 296 | ) 297 | ] 298 | ) 299 | ``` 300 | 301 | 302 | 303 | 这种方法允许LLM看到发生了错误,并可能采取纠正措施或请求人工干预。 304 | 305 | ## 测试工具 306 | 307 | MCP工具的全面测试策略应涵盖: 308 | 309 | - **功能测试**:验证工具在有效输入下正确执行,并正确处理无效输入 310 | - **集成测试**:使用真实和模拟的依赖项测试工具与外部系统的交互 311 | - **安全测试**:验证身份验证、授权、输入清理和速率限制 312 | - **性能测试**:检查负载下的行为、超时处理和资源清理 313 | - **错误处理**:确保工具通过MCP协议正确报告错误并清理资源 -------------------------------------------------------------------------------- /docs/concepts/transports.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "传输" 3 | description: "了解 MCP 的通信机制" 4 | --- 5 | 6 | 模型上下文协议(MCP协议)中的传输为客户端和服务器之间的通信提供了基础。传输负责处理消息发送和接收的底层机制。 7 | 8 | ## 消息格式 9 | 10 | MCP 使用 [JSON-RPC](https://www.jsonrpc.org/) 2.0 作为其传输格式。传输层负责将 MCP 协议消息转换为 JSON-RPC 格式进行传输,并将接收到的 JSON-RPC 消息转换回 MCP 协议消息。 11 | 12 | 使用了三种类型的 JSON-RPC 消息: 13 | 14 | ### 请求 15 | ```typescript 16 | { 17 | jsonrpc: "2.0", 18 | id: number | string, 19 | method: string, 20 | params?: object 21 | } 22 | ``` 23 | 24 | ### 响应 25 | ```typescript 26 | { 27 | jsonrpc: "2.0", 28 | id: number | string, 29 | result?: object, 30 | error?: { 31 | code: number, 32 | message: string, 33 | data?: unknown 34 | } 35 | } 36 | ``` 37 | 38 | ### 通知 39 | ```typescript 40 | { 41 | jsonrpc: "2.0", 42 | method: string, 43 | params?: object 44 | } 45 | ``` 46 | 47 | ## 内置传输类型 48 | 49 | MCP 包含两种标准传输实现: 50 | 51 | ### 标准输入/输出(stdio) 52 | 53 | stdio 传输通过标准输入和输出流实现通信。这对于本地集成和命令行工具特别有用。 54 | 55 | 使用 stdio 的场景: 56 | - 构建命令行工具 57 | - 实现本地集成 58 | - 需要简单的进程通信 59 | - 使用 shell 脚本 60 | 61 | 62 | 63 | ```typescript 64 | const server = new Server({ 65 | name: "example-server", 66 | version: "1.0.0" 67 | }, { 68 | capabilities: {} 69 | }); 70 | 71 | const transport = new StdioServerTransport(); 72 | await server.connect(transport); 73 | ``` 74 | 75 | 76 | ```typescript 77 | const client = new Client({ 78 | name: "example-client", 79 | version: "1.0.0" 80 | }, { 81 | capabilities: {} 82 | }); 83 | 84 | const transport = new StdioClientTransport({ 85 | command: "./server", 86 | args: ["--option", "value"] 87 | }); 88 | await client.connect(transport); 89 | ``` 90 | 91 | 92 | ```python 93 | app = Server("example-server") 94 | 95 | async with stdio_server() as streams: 96 | await app.run( 97 | streams[0], 98 | streams[1], 99 | app.create_initialization_options() 100 | ) 101 | ``` 102 | 103 | 104 | ```python 105 | params = StdioServerParameters( 106 | command="./server", 107 | args=["--option", "value"] 108 | ) 109 | 110 | async with stdio_client(params) as streams: 111 | async with ClientSession(streams[0], streams[1]) as session: 112 | await session.initialize() 113 | ``` 114 | 115 | 116 | 117 | ### 服务器发送事件(SSE) 118 | 119 | SSE 传输通过 HTTP POST 请求实现服务器到客户端的流式通信。 120 | 121 | 使用 SSE 的场景: 122 | - 仅需要服务器到客户端的流式通信 123 | - 在受限网络中工作 124 | - 实现简单的更新 125 | 126 | 127 | 128 | ```typescript 129 | import express from "express"; 130 | 131 | const app = express(); 132 | 133 | const server = new Server({ 134 | name: "example-server", 135 | version: "1.0.0" 136 | }, { 137 | capabilities: {} 138 | }); 139 | 140 | let transport: SSEServerTransport | null = null; 141 | 142 | app.get("/sse", (req, res) => { 143 | transport = new SSEServerTransport("/messages", res); 144 | server.connect(transport); 145 | }); 146 | 147 | app.post("/messages", (req, res) => { 148 | if (transport) { 149 | transport.handlePostMessage(req, res); 150 | } 151 | }); 152 | 153 | app.listen(3000); 154 | ``` 155 | 156 | 157 | ```typescript 158 | const client = new Client({ 159 | name: "example-client", 160 | version: "1.0.0" 161 | }, { 162 | capabilities: {} 163 | }); 164 | 165 | const transport = new SSEClientTransport( 166 | new URL("http://localhost:3000/sse") 167 | ); 168 | await client.connect(transport); 169 | ``` 170 | 171 | 172 | ```python 173 | from mcp.server.sse import SseServerTransport 174 | from starlette.applications import Starlette 175 | from starlette.routing import Route 176 | 177 | app = Server("example-server") 178 | sse = SseServerTransport("/messages") 179 | 180 | async def handle_sse(scope, receive, send): 181 | async with sse.connect_sse(scope, receive, send) as streams: 182 | await app.run(streams[0], streams[1], app.create_initialization_options()) 183 | 184 | async def handle_messages(scope, receive, send): 185 | await sse.handle_post_message(scope, receive, send) 186 | 187 | starlette_app = Starlette( 188 | routes=[ 189 | Route("/sse", endpoint=handle_sse), 190 | Route("/messages", endpoint=handle_messages, methods=["POST"]), 191 | ] 192 | ) 193 | ``` 194 | 195 | 196 | ```python 197 | async with sse_client("http://localhost:8000/sse") as streams: 198 | async with ClientSession(streams[0], streams[1]) as session: 199 | await session.initialize() 200 | ``` 201 | 202 | 203 | 204 | ## 自定义传输 205 | 206 | MCP 使得为特定需求实现自定义传输变得容易。任何传输实现只需符合传输接口即可: 207 | 208 | 您可以实现自定义传输的场景: 209 | - 自定义网络协议 210 | - 专用通信通道 211 | - 与现有系统集成 212 | - 性能优化 213 | 214 | 215 | 216 | ```typescript 217 | interface Transport { 218 | // 开始处理消息 219 | start(): Promise; 220 | 221 | // 发送 JSON-RPC 消息 222 | send(message: JSONRPCMessage): Promise; 223 | 224 | // 关闭连接 225 | close(): Promise; 226 | 227 | // 回调 228 | onclose?: () => void; 229 | onerror?: (error: Error) => void; 230 | onmessage?: (message: JSONRPCMessage) => void; 231 | } 232 | ``` 233 | 234 | 235 | 请注意,虽然 MCP 服务器通常使用 asyncio 实现,但我们建议使用 `anyio` 实现低级接口(如传输)以获得更广泛的兼容性。 236 | ```python 237 | @contextmanager 238 | async def create_transport( 239 | read_stream: MemoryObjectReceiveStream[JSONRPCMessage | Exception], 240 | write_stream: MemoryObjectSendStream[JSONRPCMessage] 241 | ): 242 | """ 243 | MCP 的传输接口。 244 | 245 | 参数: 246 | read_stream: 用于读取传入消息的流 247 | write_stream: 用于写入传出消息的流 248 | """ 249 | async with anyio.create_task_group() as tg: 250 | try: 251 | # 开始处理消息 252 | tg.start_soon(lambda: process_messages(read_stream)) 253 | 254 | # 发送消息 255 | async with write_stream: 256 | yield write_stream 257 | 258 | except Exception as exc: 259 | # 处理错误 260 | raise exc 261 | finally: 262 | # 清理 263 | tg.cancel_scope.cancel() 264 | await write_stream.aclose() 265 | await read_stream.aclose() 266 | ``` 267 | 268 | 269 | 270 | ## 错误处理 271 | 272 | 传输实现应处理各种错误场景: 273 | 274 | 1. 连接错误 275 | 2. 消息解析错误 276 | 3. 协议错误 277 | 4. 网络超时 278 | 5. 资源清理 279 | 280 | 错误处理示例: 281 | 282 | 283 | 284 | ```typescript 285 | class ExampleTransport implements Transport { 286 | async start() { 287 | try { 288 | // 连接逻辑 289 | } catch (error) { 290 | this.onerror?.(new Error(`连接失败: ${error}`)); 291 | throw error; 292 | } 293 | } 294 | 295 | async send(message: JSONRPCMessage) { 296 | try { 297 | // 发送逻辑 298 | } catch (error) { 299 | this.onerror?.(new Error(`发送消息失败: ${error}`)); 300 | throw error; 301 | } 302 | } 303 | } 304 | ``` 305 | 306 | 307 | 请注意,虽然 MCP 服务器通常使用 asyncio 实现,但我们建议使用 `anyio` 实现低级接口(如传输)以获得更广泛的兼容性。 308 | ```python 309 | @contextmanager 310 | async def example_transport(scope: Scope, receive: Receive, send: Send): 311 | try: 312 | # 创建用于双向通信的流 313 | read_stream_writer, read_stream = anyio.create_memory_object_stream(0) 314 | write_stream, write_stream_reader = anyio.create_memory_object_stream(0) 315 | 316 | async def message_handler(): 317 | try: 318 | async with read_stream_writer: 319 | # 消息处理逻辑 320 | pass 321 | except Exception as exc: 322 | logger.error(f"处理消息失败: {exc}") 323 | raise exc 324 | 325 | async with anyio.create_task_group() as tg: 326 | tg.start_soon(message_handler) 327 | try: 328 | # 生成用于通信的流 329 | yield read_stream, write_stream 330 | except Exception as exc: 331 | logger.error(f"传输错误: {exc}") 332 | raise exc 333 | finally: 334 | tg.cancel_scope.cancel() 335 | await write_stream.aclose() 336 | await read_stream.aclose() 337 | except Exception as exc: 338 | logger.error(f"初始化传输失败: {exc}") 339 | raise exc 340 | ``` 341 | 342 | 343 | 344 | ## 最佳实践 345 | 346 | 在实现或使用 MCP 传输时: 347 | 348 | 1. 正确处理连接生命周期 349 | 2. 实现适当的错误处理 350 | 3. 在连接关闭时清理资源 351 | 4. 使用适当的超时 352 | 5. 在发送前验证消息 353 | 6. 记录传输事件以便调试 354 | 7. 在适当的情况下实现重连逻辑 355 | 8. 处理消息队列中的背压 356 | 9. 监控连接健康状态 357 | 10. 实施适当的安全措施 358 | 359 | ## 安全注意事项 360 | 361 | 在实现传输时: 362 | 363 | ### 认证与授权 364 | - 实施适当的认证机制 365 | - 验证客户端凭据 366 | - 使用安全的令牌处理 367 | - 实施授权检查 368 | 369 | ### 数据安全 370 | - 使用 TLS 进行网络传输 371 | - 加密敏感数据 372 | - 验证消息完整性 373 | - 实施消息大小限制 374 | - 清理输入数据 375 | 376 | ### 网络安全 377 | - 实施速率限制 378 | - 使用适当的超时 379 | - 处理拒绝服务场景 380 | - 监控异常模式 381 | - 实施适当的防火墙规则 382 | 383 | ## 调试传输 384 | 385 | 调试传输问题的技巧: 386 | 387 | 1. 启用调试日志 388 | 2. 监控消息流 389 | 3. 检查连接状态 390 | 4. 验证消息格式 391 | 5. 测试错误场景 392 | 6. 使用网络分析工具 393 | 7. 实施健康检查 394 | 8. 监控资源使用情况 395 | 9. 测试边缘情况 396 | 10. 使用适当的错误跟踪 -------------------------------------------------------------------------------- /docs/tools/debugging.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: 调试 3 | description: 调试模型上下文协议(MCP协议)集成的全面指南 4 | --- 5 | 6 | 有效的调试在开发 MCP 服务器或将其与应用程序集成时至关重要。本指南涵盖了 MCP 生态系统中可用的调试工具和方法。 7 | 8 | 9 | 本指南适用于 macOS。其他平台的指南即将推出。 10 | 11 | 12 | ## 调试工具概述 13 | 14 | MCP 提供了多种工具,用于在不同层次进行调试: 15 | 16 | 1. **MCP 检查器** 17 | - 交互式调试界面 18 | - 直接测试服务器 19 | - 详情请参阅[检查器指南](/docs/tools/inspector) 20 | 21 | 2. **Claude 桌面开发者工具** 22 | - 集成测试 23 | - 日志收集 24 | - Chrome DevTools 集成 25 | 26 | 3. **服务器日志** 27 | - 自定义日志实现 28 | - 错误跟踪 29 | - 性能监控 30 | 31 | ## 在 Claude 桌面中调试 32 | 33 | ### 检查服务器状态 34 | 35 | Claude.app 界面提供了基本的服务器状态信息: 36 | 37 | 1. 点击 图标查看: 38 | - 已连接的服务器 39 | - 可用的提示和资源 40 | 41 | 2. 点击 图标查看: 42 | - 提供给模型的工具 43 | 44 | ### 查看日志 45 | 46 | 从 Claude 桌面查看详细的 MCP 日志: 47 | 48 | ```bash 49 | # 实时跟踪日志 50 | tail -n 20 -F ~/Library/Logs/Claude/mcp*.log 51 | ``` 52 | 53 | 日志记录的内容包括: 54 | - 服务器连接事件 55 | - 配置问题 56 | - 运行时错误 57 | - 消息交换 58 | 59 | ### 使用 Chrome DevTools 60 | 61 | 在 Claude 桌面中访问 Chrome 的开发者工具,以调查客户端错误: 62 | 63 | 1. 创建一个 `developer_settings.json` 文件,并将 `allowDevTools` 设置为 true: 64 | 65 | ```bash 66 | echo '{"allowDevTools": true}' > ~/Library/Application\ Support/Claude/developer_settings.json 67 | ``` 68 | 69 | 2. 打开 DevTools:`Command-Option-Shift-i` 70 | 71 | 注意:您会看到两个 DevTools 窗口: 72 | - 主内容窗口 73 | - 应用标题栏窗口 74 | 75 | 使用 Console 面板检查客户端错误。 76 | 77 | 使用 Network 面板检查: 78 | - 消息负载 79 | - 连接时间 80 | 81 | ## 常见问题 82 | 83 | ### 工作目录 84 | 85 | 当在 Claude 桌面中使用 MCP 服务器时: 86 | 87 | - 通过 `claude_desktop_config.json` 启动的服务器的当前工作目录可能未定义(例如 macOS 上的 `/`),因为 Claude 桌面可能从任何位置启动 88 | - 始终在配置和 `.env` 文件中使用绝对路径以确保可靠运行 89 | - 通过命令行直接测试服务器时,当前工作目录将是您运行命令的位置 90 | 91 | 例如,在 `claude_desktop_config.json` 中,使用: 92 | ```json 93 | { 94 | "command": "npx", 95 | "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/username/data"] 96 | } 97 | ``` 98 | 而不是相对路径,如 `./data` 99 | 100 | ### 环境变量 101 | 102 | MCP 服务器自动继承的环境变量只有一部分,例如 `USER`、`HOME` 和 `PATH`。 103 | 104 | 要覆盖默认变量或提供自己的变量,可以在 `claude_desktop_config.json` 中指定 `env` 键: 105 | 106 | ```json 107 | { 108 | "myserver": { 109 | "command": "mcp-server-myapp", 110 | "env": { 111 | "MYAPP_API_KEY": "some_key", 112 | } 113 | } 114 | } 115 | ``` 116 | 117 | ### 服务器初始化 118 | 119 | 常见的初始化问题: 120 | 121 | 1. **路径问题** 122 | - 服务器可执行文件路径错误 123 | - 缺少必需文件 124 | - 权限问题 125 | - 尝试为 `command` 使用绝对路径 126 | 127 | 2. **配置错误** 128 | - 无效的 JSON 语法 129 | - 缺少必填字段 130 | - 类型不匹配 131 | 132 | 3. **环境问题** 133 | - 缺少环境变量 134 | - 变量值错误 135 | - 权限限制 136 | 137 | ### 连接问题 138 | 139 | 当服务器连接失败时: 140 | 141 | 1. 检查 Claude 桌面日志 142 | 2. 验证服务器进程是否正在运行 143 | 3. 使用[检查器](/docs/tools/inspector)进行独立测试 144 | 4. 验证协议兼容性 145 | 146 | ## 实现日志记录 147 | 148 | ### 服务器端日志记录 149 | 150 | 当构建使用本地 stdio [传输](/docs/concepts/transports)的服务器时,所有记录到 stderr(标准错误)的消息将自动被主机应用程序(例如 Claude 桌面)捕获。 151 | 152 | 153 | 本地 MCP 服务器不应将消息记录到 stdout(标准输出),因为这会影响协议操作。 154 | 155 | 156 | 对于所有[传输](/docs/concepts/transports),您还可以通过发送日志消息通知向客户端提供日志记录: 157 | 158 | 159 | 160 | ```python 161 | server.request_context.session.send_log_message( 162 | level="info", 163 | data="Server started successfully", 164 | ) 165 | ``` 166 | 167 | 168 | ```typescript 169 | server.sendLoggingMessage({ 170 | level: "info", 171 | data: "Server started successfully", 172 | }); 173 | ``` 174 | 175 | 176 | 177 | 需要记录的重要事件: 178 | - 初始化步骤 179 | - 资源访问 180 | - 工具执行 181 | - 错误情况 182 | - 性能指标 183 | 184 | ### 客户端日志记录 185 | 186 | 在客户端应用程序中: 187 | 188 | 1. 启用调试日志 189 | 2. 监控网络流量 190 | 3. 跟踪消息交换 191 | 4. 记录错误状态 192 | 193 | ## 调试工作流 194 | 195 | ### 开发周期 196 | 197 | 1. 初始开发 198 | - 使用[检查器](/docs/tools/inspector)进行基本测试 199 | - 实现核心功能 200 | - 添加日志记录点 201 | 202 | 2. 集成测试 203 | - 在 Claude 桌面中测试 204 | - 监控日志 205 | - 检查错误处理 206 | 207 | ### 测试更改 208 | 209 | 为了高效测试更改: 210 | 211 | - **配置更改**:重启 Claude 桌面 212 | - **服务器代码更改**:使用 Command-R 重新加载 213 | - **快速迭代**:在开发过程中使用[检查器](/docs/tools/inspector) 214 | 215 | ## 最佳实践 216 | 217 | ### 日志记录策略 218 | 219 | 1. **结构化日志记录** 220 | - 使用一致的格式 221 | - 包含上下文 222 | - 添加时间戳 223 | - 跟踪请求 ID 224 | 225 | 2. **错误处理** 226 | - 记录堆栈跟踪 227 | - 包含错误上下文 228 | - 跟踪错误模式 229 | - 监控恢复情况 230 | 231 | 3. **性能跟踪** 232 | - 记录操作时间 233 | - 监控资源使用情况 234 | - 跟踪消息大小 235 | - 测量延迟 236 | 237 | ### 安全注意事项 238 | 239 | 在调试时: 240 | 241 | 1. **敏感数据** 242 | - 清理日志 243 | - 保护凭据 244 | - 屏蔽个人信息 245 | 246 | 2. **访问控制** 247 | - 验证权限 248 | - 检查身份验证 249 | - 监控访问模式 250 | 251 | ## 获取帮助 252 | 253 | 遇到问题时: 254 | 255 | 1. **第一步** 256 | - 检查服务器日志 257 | - 使用[检查器](/docs/tools/inspector)测试 258 | - 检查配置 259 | - 验证环境 260 | 261 | 2. **支持渠道** 262 | - GitHub 问题 263 | - GitHub 讨论 264 | 265 | 3. **提供信息** 266 | - 日志摘录 267 | - 配置文件 268 | - 重现步骤 269 | - 环境详情 270 | 271 | ## 下一步 272 | 273 | 274 | 279 | 学习使用 MCP 检查器 280 | 281 | -------------------------------------------------------------------------------- /docs/tools/inspector.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: 检查器 3 | description: 使用 MCP 检查器测试和调试模型上下文协议(MCP协议)服务器的深入指南 4 | --- 5 | 6 | [MCP 检查器](https://github.com/modelcontextprotocol/inspector) 是一个用于测试和调试 MCP 服务器的交互式开发者工具。虽然[调试指南](/docs/tools/debugging) 将检查器作为整体调试工具包的一部分进行了介绍,但本文档详细探讨了检查器的功能和能力。 7 | 8 | ## 开始使用 9 | 10 | ### 安装和基本用法 11 | 12 | 检查器可以直接通过 `npx` 运行,无需安装: 13 | 14 | ```bash 15 | npx @modelcontextprotocol/inspector 16 | ``` 17 | 18 | ```bash 19 | npx @modelcontextprotocol/inspector 20 | ``` 21 | 22 | #### 检查来自 NPM 或 PyPi 的服务器 23 | 24 | 从 [NPM](https://npmjs.com) 或 [PyPi](https://pypi.com) 启动服务器包的常见方式。 25 | 26 | 27 | 28 | 29 | ```bash 30 | npx -y @modelcontextprotocol/inspector npx 31 | # 例如 32 | npx -y @modelcontextprotocol/inspector npx server-postgres postgres://127.0.0.1/testdb 33 | ``` 34 | 35 | 36 | 37 | ```bash 38 | npx @modelcontextprotocol/inspector uvx 39 | # 例如 40 | npx @modelcontextprotocol/inspector uvx mcp-server-git --repository ~/code/mcp/servers.git 41 | ``` 42 | 43 | 44 | 45 | #### 检查本地开发的服务器 46 | 47 | 要检查本地开发或下载为仓库的服务器,最常见的方式是: 48 | 49 | 50 | 51 | ```bash 52 | npx @modelcontextprotocol/inspector node path/to/server/index.js args... 53 | ``` 54 | 55 | 56 | ```bash 57 | npx @modelcontextprotocol/inspector \ 58 | uv \ 59 | --directory path/to/server \ 60 | run \ 61 | package-name \ 62 | args... 63 | ``` 64 | 65 | 66 | 67 | 请仔细阅读附带的 README 以获取最准确的说明。 68 | 69 | ## 功能概述 70 | 71 | 72 | 73 | 74 | 75 | 检查器提供了多种功能,用于与您的 MCP 服务器进行交互: 76 | 77 | ### 服务器连接面板 78 | - 允许选择用于连接服务器的[传输](/docs/concepts/transports) 79 | - 对于本地服务器,支持自定义命令行参数和环境 80 | 81 | ### 资源选项卡 82 | - 列出所有可用资源 83 | - 显示资源元数据(MIME 类型、描述) 84 | - 允许检查资源内容 85 | - 支持订阅测试 86 | 87 | ### 提示选项卡 88 | - 显示可用的提示模板 89 | - 显示提示参数和描述 90 | - 支持使用自定义参数测试提示 91 | - 预览生成的消息 92 | 93 | ### 工具选项卡 94 | - 列出可用工具 95 | - 显示工具模式和描述 96 | - 支持使用自定义输入测试工具 97 | - 显示工具执行结果 98 | 99 | ### 通知面板 100 | - 显示从服务器记录的所有日志 101 | - 显示从服务器接收的通知 102 | 103 | ## 最佳实践 104 | 105 | ### 开发工作流 106 | 107 | 1. 开始开发 108 | - 使用检查器启动您的服务器 109 | - 验证基本连接性 110 | - 检查能力协商 111 | 112 | 2. 迭代测试 113 | - 进行服务器更改 114 | - 重新构建服务器 115 | - 重新连接检查器 116 | - 测试受影响的功能 117 | - 监控消息 118 | 119 | 3. 测试边缘情况 120 | - 无效输入 121 | - 缺少提示参数 122 | - 并发操作 123 | - 验证错误处理和错误响应 124 | 125 | ## 下一步 126 | 127 | 128 | 133 | 查看 MCP 检查器源代码 134 | 135 | 136 | 141 | 学习更广泛的调试策略 142 | 143 | 144 | ``` -------------------------------------------------------------------------------- /examples.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: 示例服务器 3 | description: '示例服务器和实现的列表' 4 | --- 5 | 6 | 本页面展示了各种模型上下文协议(MCP协议)服务器,这些服务器展示了协议的功能和多样性。这些服务器使大型语言模型(LLMs)能够安全地访问工具和数据源。 7 | 8 | ## 参考实现 9 | 10 | 这些官方参考服务器展示了 MCP 的核心功能和 SDK 的用法: 11 | 12 | ### 数据和文件系统 13 | - **[文件系统](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem)** - 具有可配置访问控制的安全文件操作 14 | - **[PostgreSQL](https://github.com/modelcontextprotocol/servers/tree/main/src/postgres)** - 具有模式检查功能的只读数据库访问 15 | - **[SQLite](https://github.com/modelcontextprotocol/servers/tree/main/src/sqlite)** - 数据库交互和商业智能功能 16 | - **[Google Drive](https://github.com/modelcontextprotocol/servers/tree/main/src/gdrive)** - Google Drive 的文件访问和搜索功能 17 | 18 | ### 开发工具 19 | - **[Git](https://github.com/modelcontextprotocol/servers/tree/main/src/git)** - 读取、搜索和操作 Git 仓库的工具 20 | - **[GitHub](https://github.com/modelcontextprotocol/servers/tree/main/src/github)** - 仓库管理、文件操作和 GitHub API 集成 21 | - **[GitLab](https://github.com/modelcontextprotocol/servers/tree/main/src/gitlab)** - GitLab API 集成,支持项目管理 22 | - **[Sentry](https://github.com/modelcontextprotocol/servers/tree/main/src/sentry)** - 从 Sentry.io 检索和分析问题 23 | 24 | ### 网络和浏览器自动化 25 | - **[Brave 搜索](https://github.com/modelcontextprotocol/servers/tree/main/src/brave-search)** - 使用 Brave 的搜索 API 进行网络和本地搜索 26 | - **[Fetch](https://github.com/modelcontextprotocol/servers/tree/main/src/fetch)** - 为 LLM 使用优化的网页内容抓取和转换 27 | - **[Puppeteer](https://github.com/modelcontextprotocol/servers/tree/main/src/puppeteer)** - 浏览器自动化和网页抓取功能 28 | 29 | ### 生产力和通信 30 | - **[Slack](https://github.com/modelcontextprotocol/servers/tree/main/src/slack)** - 频道管理和消息功能 31 | - **[Google 地图](https://github.com/modelcontextprotocol/servers/tree/main/src/google-maps)** - 位置服务、路线和地点详情 32 | - **[Memory](https://github.com/modelcontextprotocol/servers/tree/main/src/memory)** - 基于知识图谱的持久记忆系统 33 | 34 | ### AI 和专用工具 35 | - **[EverArt](https://github.com/modelcontextprotocol/servers/tree/main/src/everart)** - 使用各种模型生成 AI 图像 36 | - **[Sequential Thinking](https://github.com/modelcontextprotocol/servers/tree/main/src/sequentialthinking)** - 通过思维序列进行动态问题解决 37 | - **[AWS KB 检索](https://github.com/modelcontextprotocol/servers/tree/main/src/aws-kb-retrieval-server)** - 使用 Bedrock Agent Runtime 从 AWS 知识库中检索 38 | 39 | ## 官方集成 40 | 41 | 这些 MCP 服务器由公司为其平台维护: 42 | 43 | - **[Axiom](https://github.com/axiomhq/mcp-server-axiom)** - 使用自然语言查询和分析日志、跟踪和事件数据 44 | - **[Browserbase](https://github.com/browserbase/mcp-server-browserbase)** - 在云端自动化浏览器交互 45 | - **[Cloudflare](https://github.com/cloudflare/mcp-server-cloudflare)** - 在 Cloudflare 开发者平台上部署和管理资源 46 | - **[E2B](https://github.com/e2b-dev/mcp-server)** - 在安全的云沙箱中执行代码 47 | - **[Neon](https://github.com/neondatabase/mcp-server-neon)** - 与 Neon 无服务器 Postgres 平台交互 48 | - **[Obsidian Markdown 笔记](https://github.com/calclavia/mcp-obsidian)** - 读取和搜索 Obsidian 仓库中的 Markdown 笔记 49 | - **[Qdrant](https://github.com/qdrant/mcp-server-qdrant/)** - 使用 Qdrant 向量搜索引擎实现语义记忆 50 | - **[Raygun](https://github.com/MindscapeHQ/mcp-server-raygun)** - 访问崩溃报告和监控数据 51 | - **[Search1API](https://github.com/fatwang2/search1api-mcp)** - 用于搜索、爬取和站点地图的统一 API 52 | - **[Stripe](https://github.com/stripe/agent-toolkit)** - 与 Stripe API 交互 53 | - **[Tinybird](https://github.com/tinybirdco/mcp-tinybird)** - 与 Tinybird 无服务器 ClickHouse 平台交互 54 | - **[Weaviate](https://github.com/weaviate/mcp-server-weaviate)** - 通过您的 Weaviate 集合启用 Agentic RAG 55 | 56 | ## 社区亮点 57 | 58 | 不断增长的社区开发服务器生态系统扩展了 MCP 的功能: 59 | 60 | - **[Docker](https://github.com/ckreiling/mcp-server-docker)** - 管理容器、镜像、卷和网络 61 | - **[Kubernetes](https://github.com/Flux159/mcp-server-kubernetes)** - 管理 Pod、部署和服务 62 | - **[Linear](https://github.com/jerhadf/linear-mcp-server)** - 项目管理和问题跟踪 63 | - **[Snowflake](https://github.com/datawiz168/mcp-snowflake-service)** - 与 Snowflake 数据库交互 64 | - **[Spotify](https://github.com/varunneal/spotify-mcp)** - 控制 Spotify 播放和管理播放列表 65 | - **[Todoist](https://github.com/abhiz123/todoist-mcp-server)** - 任务管理集成 66 | 67 | > **注意:** 社区服务器未经测试,使用风险自负。它们与 Anthropic 无关,也未获得其认可。 68 | 69 | 有关社区服务器的完整列表,请访问 [MCP 服务器仓库](https://github.com/modelcontextprotocol/servers)。 70 | 71 | ## 开始使用 72 | 73 | ### 使用参考服务器 74 | 75 | 基于 TypeScript 的服务器可以直接使用 `npx` 运行: 76 | 77 | ```bash 78 | npx -y @modelcontextprotocol/server-memory 79 | ``` 80 | 81 | 基于 Python 的服务器可以使用 `uvx`(推荐)或 `pip` 运行: 82 | 83 | ```bash 84 | # 使用 uvx 85 | uvx mcp-server-git 86 | 87 | # 使用 pip 88 | pip install mcp-server-git 89 | python -m mcp_server_git 90 | ``` 91 | 92 | ### 与 Claude 配置 93 | 94 | 要将 MCP 服务器与 Claude 一起使用,请将其添加到您的配置中: 95 | 96 | ```json 97 | { 98 | "mcpServers": { 99 | "memory": { 100 | "command": "npx", 101 | "args": ["-y", "@modelcontextprotocol/server-memory"] 102 | }, 103 | "filesystem": { 104 | "command": "npx", 105 | "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"] 106 | }, 107 | "github": { 108 | "command": "npx", 109 | "args": ["-y", "@modelcontextprotocol/server-github"], 110 | "env": { 111 | "GITHUB_PERSONAL_ACCESS_TOKEN": "" 112 | } 113 | } 114 | } 115 | } 116 | ``` 117 | 118 | ## 其他资源 119 | 120 | - [MCP 服务器仓库](https://github.com/modelcontextprotocol/servers) - 参考实现和社区服务器的完整集合 121 | - [Awesome MCP 服务器](https://github.com/punkpeye/awesome-mcp-servers) - 精选的 MCP 服务器列表 122 | - [MCP CLI](https://github.com/wong2/mcp-cli) - 用于测试 MCP 服务器的命令行检查器 123 | - [MCP Get](https://mcp-get.com) - 安装和管理 MCP 服务器的工具 124 | - [Supergateway](https://github.com/supercorp-ai/supergateway) - 通过 SSE 运行 MCP stdio 服务器 125 | 126 | 访问我们的 [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions) 与 MCP 社区互动。 -------------------------------------------------------------------------------- /ext/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/ext/.DS_Store -------------------------------------------------------------------------------- /ext/ad/myact.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/ext/ad/myact.jpg -------------------------------------------------------------------------------- /ext/ad/灯塔红白间.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/ext/ad/灯塔红白间.jpg -------------------------------------------------------------------------------- /ext/article.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: 文章 3 | description: 社区中一些介绍MCP协议的中文资源 4 | --- 5 | 6 | - [一文看懂:MCP(大模型上下文)](https://zhuanlan.zhihu.com/p/27327515233) 7 | - [MCP协议上篇 - 一文了解MCP是什么](https://zhuanlan.zhihu.com/p/10122577918) 8 | - [MCP协议](https://www.cnblogs.com/ghj1976/p/18572770/mcp-xie-yi) -------------------------------------------------------------------------------- /ext/me.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: 联系我 3 | description: 一起讨论MCP协议、大模型或者交个朋友 4 | --- 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /favicon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /images/available-mcp-tools.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/images/available-mcp-tools.png -------------------------------------------------------------------------------- /images/claude-desktop-mcp-hammer-icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /images/claude-desktop-mcp-plug-icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /images/client-claude-cli-python.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/images/client-claude-cli-python.png -------------------------------------------------------------------------------- /images/current-weather.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/images/current-weather.png -------------------------------------------------------------------------------- /images/hero-dark.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | -------------------------------------------------------------------------------- /images/hero-light.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | -------------------------------------------------------------------------------- /images/java/class-diagrams.puml: -------------------------------------------------------------------------------- 1 | @startuml Core Components 2 | 3 | ' Core Interfaces 4 | interface McpTransport { 5 | +Mono connect(Function, Mono> handler) 6 | +Mono sendMessage(JSONRPCMessage message) 7 | +void close() 8 | +Mono closeGracefully() 9 | + T unmarshalFrom(Object data, TypeReference typeRef) 10 | } 11 | 12 | interface McpSession { 13 | + Mono sendRequest(String method, Object requestParams, TypeReference typeRef) 14 | +Mono sendNotification(String method, Map params) 15 | +Mono closeGracefully() 16 | +void close() 17 | } 18 | 19 | ' Core Implementation Classes 20 | class DefaultMcpSession { 21 | +interface RequestHandler 22 | +interface NotificationHandler 23 | } 24 | 25 | ' Client Classes 26 | class McpClient { 27 | +{static} Builder using(ClientMcpTransport transport) 28 | } 29 | 30 | class McpAsyncClient { 31 | +Mono initialize() 32 | +ServerCapabilities getServerCapabilities() 33 | +Implementation getServerInfo() 34 | +ClientCapabilities getClientCapabilities() 35 | +Implementation getClientInfo() 36 | +void close() 37 | +Mono closeGracefully() 38 | +Mono ping() 39 | +Mono addRoot(Root root) 40 | +Mono removeRoot(String rootUri) 41 | +Mono rootsListChangedNotification() 42 | +Mono callTool(CallToolRequest request) 43 | +Mono listTools() 44 | +Mono listResources() 45 | +Mono readResource(ReadResourceRequest request) 46 | +Mono listResourceTemplates() 47 | +Mono subscribeResource(SubscribeRequest request) 48 | +Mono unsubscribeResource(UnsubscribeRequest request) 49 | +Mono listPrompts() 50 | +Mono getPrompt(GetPromptRequest request) 51 | +Mono setLoggingLevel(LoggingLevel level) 52 | } 53 | 54 | class McpSyncClient { 55 | +InitializeResult initialize() 56 | +ServerCapabilities getServerCapabilities() 57 | +Implementation getServerInfo() 58 | +ClientCapabilities getClientCapabilities() 59 | +Implementation getClientInfo() 60 | +void close() 61 | +boolean closeGracefully() 62 | +Object ping() 63 | +void addRoot(Root root) 64 | +void removeRoot(String rootUri) 65 | +void rootsListChangedNotification() 66 | +CallToolResult callTool(CallToolRequest request) 67 | +ListToolsResult listTools() 68 | +ListResourcesResult listResources() 69 | +ReadResourceResult readResource(ReadResourceRequest request) 70 | +ListResourceTemplatesResult listResourceTemplates() 71 | +void subscribeResource(SubscribeRequest request) 72 | +void unsubscribeResource(UnsubscribeRequest request) 73 | +ListPromptsResult listPrompts() 74 | +GetPromptResult getPrompt(GetPromptRequest request) 75 | +void setLoggingLevel(LoggingLevel level) 76 | } 77 | 78 | ' Server Classes 79 | class McpServer { 80 | +{static} Builder using(ServerMcpTransport transport) 81 | } 82 | 83 | class McpAsyncServer { 84 | 85 | +ServerCapabilities getServerCapabilities() 86 | +Implementation getServerInfo() 87 | +ClientCapabilities getClientCapabilities() 88 | +Implementation getClientInfo() 89 | +void close() 90 | +Mono closeGracefully() 91 | 92 | ' Tool Management 93 | +Mono addTool(ToolRegistration toolRegistration) 94 | +Mono removeTool(String toolName) 95 | +Mono notifyToolsListChanged() 96 | 97 | ' Resource Management 98 | +Mono addResource(ResourceRegistration resourceHandler) 99 | +Mono removeResource(String resourceUri) 100 | +Mono notifyResourcesListChanged() 101 | 102 | ' Prompt Management 103 | +Mono addPrompt(PromptRegistration promptRegistration) 104 | +Mono removePrompt(String promptName) 105 | +Mono notifyPromptsListChanged() 106 | 107 | ' Logging 108 | +Mono loggingNotification(LoggingMessageNotification notification) 109 | 110 | ' Sampling 111 | +Mono createMessage(CreateMessageRequest request) 112 | } 113 | 114 | class McpSyncServer { 115 | +McpAsyncServer getAsyncServer() 116 | 117 | +ServerCapabilities getServerCapabilities() 118 | +Implementation getServerInfo() 119 | +ClientCapabilities getClientCapabilities() 120 | +Implementation getClientInfo() 121 | +void close() 122 | +void closeGracefully() 123 | 124 | ' Tool Management 125 | +void addTool(ToolRegistration toolHandler) 126 | +void removeTool(String toolName) 127 | +void notifyToolsListChanged() 128 | 129 | ' Resource Management 130 | +void addResource(ResourceRegistration resourceHandler) 131 | +void removeResource(String resourceUri) 132 | +void notifyResourcesListChanged() 133 | 134 | ' Prompt Management 135 | +void addPrompt(PromptRegistration promptRegistration) 136 | +void removePrompt(String promptName) 137 | +void notifyPromptsListChanged() 138 | 139 | ' Logging 140 | +void loggingNotification(LoggingMessageNotification notification) 141 | 142 | ' Sampling 143 | +CreateMessageResult createMessage(CreateMessageRequest request) 144 | } 145 | 146 | ' Transport Implementations 147 | class StdioClientTransport implements ClientMcpTransport { 148 | +void setErrorHandler(Consumer errorHandler) 149 | +Sinks.Many getErrorSink() 150 | } 151 | 152 | class StdioServerTransport implements ServerMcpTransport { 153 | } 154 | 155 | 156 | class HttpServletSseServerTransport implements ServerMcpTransport { 157 | } 158 | 159 | 160 | class HttpClientSseClientTransport implements ClientMcpTransport { 161 | } 162 | 163 | 164 | class WebFluxSseClientTransport implements ClientMcpTransport { 165 | } 166 | 167 | 168 | class WebFluxSseServerTransport implements ServerMcpTransport { 169 | +RouterFunction getRouterFunction() 170 | } 171 | 172 | class WebMvcSseServerTransport implements ServerMcpTransport { 173 | +RouterFunction getRouterFunction() 174 | } 175 | 176 | 177 | ' Schema and Error Classes 178 | class McpSchema { 179 | +class ErrorCodes 180 | +interface Request 181 | +interface JSONRPCMessage 182 | +interface ResourceContents 183 | +interface Content 184 | +interface ServerCapabilities 185 | +{static} JSONRPCMessage deserializeJsonRpcMessage() 186 | } 187 | 188 | class McpError { 189 | } 190 | 191 | ' Relationships 192 | McpTransport <|.. ClientMcpTransport 193 | McpTransport <|.. ServerMcpTransport 194 | 195 | McpSession <|.. DefaultMcpSession 196 | DefaultMcpSession --o McpAsyncClient 197 | DefaultMcpSession --o McpAsyncServer 198 | 199 | McpClient ..> McpAsyncClient : creates 200 | McpClient ..> McpSyncClient : creates 201 | McpSyncClient --> McpAsyncClient : delegates to 202 | 203 | McpServer ..> McpAsyncServer : creates 204 | McpServer ..> McpSyncServer : creates 205 | McpSyncServer o-- McpAsyncServer 206 | 207 | DefaultMcpSession o-- McpTransport 208 | McpSchema <.. McpSession : uses 209 | McpError ..> McpSession : throws 210 | 211 | @enduml 212 | 213 | @startuml Message Flow 214 | 215 | package "MCP Schema" { 216 | interface JSONRPCMessage { 217 | +String jsonrpc() 218 | } 219 | 220 | interface Request { 221 | } 222 | 223 | class InitializeRequest 224 | class CallToolRequest 225 | class ListToolsRequest 226 | class ListResourcesRequest 227 | class ReadResourceRequest 228 | class ListResourceTemplatesRequest 229 | class ListPromptsRequest 230 | class GetPromptRequest 231 | } 232 | 233 | package "Resource Types" { 234 | interface ResourceContents { 235 | +String uri() 236 | +String mimeType() 237 | } 238 | 239 | class TextResourceContents 240 | class BlobResourceContents 241 | 242 | interface Content { 243 | +String type() 244 | } 245 | 246 | class TextContent 247 | class ImageContent 248 | class EmbeddedResource 249 | 250 | interface Annotated { 251 | +Annotations annotations() 252 | } 253 | 254 | interface PromptOrResourceReference { 255 | +String type() 256 | } 257 | 258 | class PromptReference 259 | class ResourceReference 260 | } 261 | 262 | JSONRPCMessage <|.. Request 263 | Request <|.. InitializeRequest 264 | Request <|.. CallToolRequest 265 | Request <|.. ListToolsRequest 266 | Request <|.. ListResourcesRequest 267 | Request <|.. ReadResourceRequest 268 | Request <|.. ListResourceTemplatesRequest 269 | Request <|.. ListPromptsRequest 270 | Request <|.. GetPromptRequest 271 | 272 | ResourceContents <|.. TextResourceContents 273 | ResourceContents <|.. BlobResourceContents 274 | 275 | Content <|.. TextContent 276 | Content <|.. ImageContent 277 | Content <|.. EmbeddedResource 278 | 279 | PromptOrResourceReference <|.. PromptReference 280 | PromptOrResourceReference <|.. ResourceReference 281 | 282 | @enduml 283 | -------------------------------------------------------------------------------- /images/java/java-mcp-client-architecture.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/images/java/java-mcp-client-architecture.jpg -------------------------------------------------------------------------------- /images/java/java-mcp-server-architecture.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/images/java/java-mcp-server-architecture.jpg -------------------------------------------------------------------------------- /images/mcp-inspector.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/images/mcp-inspector.png -------------------------------------------------------------------------------- /images/og-image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/images/og-image.png -------------------------------------------------------------------------------- /images/quickstart-approve.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/images/quickstart-approve.png -------------------------------------------------------------------------------- /images/quickstart-developer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/images/quickstart-developer.png -------------------------------------------------------------------------------- /images/quickstart-filesystem.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/images/quickstart-filesystem.png -------------------------------------------------------------------------------- /images/quickstart-hammer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/images/quickstart-hammer.png -------------------------------------------------------------------------------- /images/quickstart-menu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/images/quickstart-menu.png -------------------------------------------------------------------------------- /images/quickstart-screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/images/quickstart-screenshot.png -------------------------------------------------------------------------------- /images/quickstart-tools.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/images/quickstart-tools.png -------------------------------------------------------------------------------- /images/visual-indicator-mcp-tools.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/images/visual-indicator-mcp-tools.png -------------------------------------------------------------------------------- /images/weather-alerts.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/images/weather-alerts.png -------------------------------------------------------------------------------- /introduction.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: 简介 3 | description: '开始使用模型上下文协议(MCP协议) (MCP)' 4 | --- 5 | 6 | 7 | 8 | 9 | 10 | 11 | Java SDK 已发布!查看[最新动态](/development/updates)。 12 | 13 | MCP 是一个开放协议,用于标准化应用程序如何为大型语言模型(LLMs)提供上下文。可以将 MCP 视为 AI 应用程序的 USB-C 接口。正如 USB-C 提供了一种标准化的方式来连接设备与各种外设和配件,MCP 提供了一种标准化的方式,将 AI 模型连接到不同的数据源和工具。 14 | 15 | ## 为什么选择 MCP? 16 | 17 | MCP 帮助您在 LLMs 之上构建代理和复杂的工作流。LLMs 经常需要与数据和工具集成,而 MCP 提供了: 18 | - 不断增长的预构建集成列表,您的 LLM 可以直接接入 19 | - 在 LLM 提供商和供应商之间切换的灵活性 20 | - 在基础设施内保护数据的最佳实践 21 | 22 | ### 总体架构 23 | 24 | MCP 的核心遵循客户端-服务器架构,其中主机应用程序可以连接到多个服务器: 25 | 26 | ```mermaid 27 | flowchart LR 28 | subgraph "您的计算机" 29 | Host["带有 MCP 客户端的主机\n(Claude, IDEs, 工具)"] 30 | S1["MCP 服务器 A"] 31 | S2["MCP 服务器 B"] 32 | S3["MCP 服务器 C"] 33 | Host <-->|"MCP 协议"| S1 34 | Host <-->|"MCP 协议"| S2 35 | Host <-->|"MCP 协议"| S3 36 | S1 <--> D1[("本地\n数据源 A")] 37 | S2 <--> D2[("本地\n数据源 B")] 38 | end 39 | subgraph "互联网" 40 | S3 <-->|"Web APIs"| D3[("远程\n服务 C")] 41 | end 42 | ``` 43 | 44 | - **MCP 主机**:如 Claude Desktop、IDE 或 AI 工具等程序,希望通过 MCP 访问数据 45 | - **MCP 客户端**:协议客户端,与服务器保持 1:1 连接 46 | - **MCP 服务器**:轻量级程序,每个服务器通过标准化的模型上下文协议(MCP协议)暴露特定功能 47 | - **本地数据源**:您的计算机上的文件、数据库和服务,MCP 服务器可以安全访问 48 | - **远程服务**:通过互联网(例如通过 API)访问的外部系统,MCP 服务器可以连接 49 | 50 | ## 开始使用 51 | 52 | 选择最适合您需求的路径: 53 | 54 | #### 快速入门 55 | 56 | 61 | 开始构建您自己的服务器,用于 Claude Desktop 和其他客户端 62 | 63 | 68 | 开始构建您自己的客户端,可以与所有 MCP 服务器集成 69 | 70 | 75 | 开始在 Claude Desktop 中使用预构建的服务器 76 | 77 | 78 | 79 | #### 示例 80 | 81 | 86 | 查看我们的官方 MCP 服务器和实现示例库 87 | 88 | 93 | 查看支持 MCP 集成的客户端列表 94 | 95 | 96 | 97 | ## 教程 98 | 99 | 100 | 105 | 学习如何使用 Claude 等 LLMs 加速您的 MCP 开发 106 | 107 | 111 | 学习如何有效调试 MCP 服务器和集成 112 | 113 | 118 | 使用我们的交互式调试工具测试和检查您的 MCP 服务器 119 | 120 | 121 | 126 | 127 | 128 | 129 | 130 | ## 探索 MCP 131 | 132 | 深入了解 MCP 的核心概念和功能: 133 | 134 | 135 | 140 | 了解 MCP 如何连接客户端、服务器和 LLMs 141 | 142 | 147 | 将服务器中的数据与内容暴露给 LLMs 148 | 149 | 154 | 创建可重用的提示模板和工作流 155 | 156 | 161 | 使 LLMs 能够通过您的服务器执行操作 162 | 163 | 168 | 让您的服务器从 LLMs 请求补全 169 | 170 | 175 | 了解 MCP 的通信机制 176 | 177 | 178 | 179 | ## 贡献 180 | 181 | 想要贡献?查看我们的[贡献指南](/development/contributing),了解如何帮助改进 MCP。 182 | 183 | ## 支持与反馈 184 | 185 | 以下是获取帮助或提供反馈的方式: 186 | 187 | - 对于与 MCP 规范、SDK 或文档(开源)相关的错误报告和功能请求,请[创建 GitHub 问题](https://github.com/modelcontextprotocol) 188 | - 对于 MCP 规范的讨论或问答,请使用[规范讨论](https://github.com/modelcontextprotocol/specification/discussions) 189 | - 对于其他 MCP 开源组件的讨论或问答,请使用[组织讨论](https://github.com/orgs/modelcontextprotocol/discussions) 190 | - 对于与 Claude.app 和 claude.ai 的 MCP 集成相关的错误报告、功能请求和问题,请发送邮件至 mcp-support@anthropic.com -------------------------------------------------------------------------------- /logo/dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/logo/dark.png -------------------------------------------------------------------------------- /logo/dark.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /logo/light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccb1900/modelcontextprotocol-docs/399d1d694bb6eba3237955262312f3e8e27dc0ee/logo/light.png -------------------------------------------------------------------------------- /logo/light.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "scripts": { 3 | "dev": "mintlify dev --port 4444" 4 | }, 5 | "dependencies": { 6 | "mintlify": "^4.0.433", 7 | "sharp": "^0.33.5" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /quickstart/user.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "面向 Claude Desktop 用户" 3 | description: "开始在 Claude for Desktop 中使用预构建的服务器。" 4 | --- 5 | 6 | 在本教程中,您将扩展 [Claude for Desktop](https://claude.ai/download) 的功能,使其能够读取计算机的文件系统、写入新文件、移动文件,甚至搜索文件。 7 | 8 | 9 | 10 | 11 | 12 | 不用担心 —— 在执行这些操作之前,它会征求您的许可! 13 | 14 | ## 1. 下载 Claude for Desktop 15 | 16 | 首先下载 [Claude for Desktop](https://claude.ai/download),选择 macOS 或 Windows。(Linux 目前不支持 Claude for Desktop。) 17 | 18 | 按照安装说明进行操作。 19 | 20 | 如果您已经安装了 Claude for Desktop,请确保它是最新版本,方法是点击计算机上的 Claude 菜单并选择“检查更新...”。 21 | 22 | 23 | 由于服务器是本地运行的,MCP 目前仅支持桌面主机。远程主机正在积极开发中。 24 | 25 | 26 | ## 2. 添加文件系统 MCP 服务器 27 | 28 | 为了添加此文件系统功能,我们将安装一个预构建的 [文件系统 MCP 服务器](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem) 到 Claude for Desktop。这是 Anthropic 和社区创建的众多[服务器](https://github.com/modelcontextprotocol/servers/tree/main)之一。 29 | 30 | 首先,打开计算机上的 Claude 菜单并选择“设置...”。请注意,这些不是应用程序窗口中的 Claude 账户设置。 31 | 32 | 在 Mac 上应该是这样的: 33 | 34 | 35 | 36 | 37 | 点击设置窗格左侧栏中的“开发者”,然后点击“编辑配置”: 38 | 39 | 40 | 41 | 42 | 这将在以下位置创建一个配置文件: 43 | - macOS:`~/Library/Application Support/Claude/claude_desktop_config.json` 44 | - Windows:`%APPDATA%\Claude\claude_desktop_config.json` 45 | 46 | 如果文件不存在,它将创建该文件并在文件系统中显示它。 47 | 48 | 在任何文本编辑器中打开配置文件。将文件内容替换为以下内容: 49 | 50 | 51 | ```json 52 | { 53 | "mcpServers": { 54 | "filesystem": { 55 | "command": "npx", 56 | "args": [ 57 | "-y", 58 | "@modelcontextprotocol/server-filesystem", 59 | "/Users/username/Desktop", 60 | "/Users/username/Downloads" 61 | ] 62 | } 63 | } 64 | } 65 | ``` 66 | 67 | 68 | ```json 69 | { 70 | "mcpServers": { 71 | "filesystem": { 72 | "command": "npx", 73 | "args": [ 74 | "-y", 75 | "@modelcontextprotocol/server-filesystem", 76 | "C:\\Users\\username\\Desktop", 77 | "C:\\Users\\username\\Downloads" 78 | ] 79 | } 80 | } 81 | } 82 | ``` 83 | 84 | 85 | 86 | 确保将 `username` 替换为您的计算机用户名。路径应指向您希望 Claude 能够访问和修改的有效目录。它设置为适用于桌面和下载文件夹,但您也可以添加更多路径。 87 | 88 | 您还需要在计算机上安装 [Node.js](https://nodejs.org) 才能正常运行。要验证您是否安装了 Node,请在计算机上打开命令行。 89 | - 在 macOS 上,从应用程序文件夹中打开终端 90 | - 在 Windows 上,按 Windows + R,输入“cmd”,然后按 Enter 91 | 92 | 进入命令行后,通过输入以下命令验证您是否安装了 Node: 93 | ```bash 94 | node --version 95 | ``` 96 | 如果出现“command not found”或“node is not recognized”错误,请从 [nodejs.org](https://nodejs.org/) 下载 Node。 97 | 98 | 99 | **配置文件如何工作?** 100 | 101 | 此配置文件告诉 Claude for Desktop 每次启动应用程序时要启动哪些 MCP 服务器。在本例中,我们添加了一个名为“filesystem”的服务器,它将使用 Node 的 `npx` 命令安装并运行 `@modelcontextprotocol/server-filesystem`。此服务器在[此处](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem)描述,它将允许您在 Claude for Desktop 中访问您的文件系统。 102 | 103 | 104 | 105 | **命令权限** 106 | 107 | Claude for Desktop 将以您用户账户的权限运行配置文件中的命令,并访问您的本地文件。仅在您理解并信任来源的情况下添加命令。 108 | 109 | 110 | ## 3. 重新启动 Claude 111 | 112 | 更新配置文件后,您需要重新启动 Claude for Desktop。 113 | 114 | 重新启动后,您应该会在输入框的右下角看到一个锤子 图标: 115 | 116 | 117 | 118 | 119 | 120 | 点击锤子图标后,您应该会看到文件系统 MCP 服务器附带的工具: 121 | 122 | 123 | 124 | 125 | 126 | 如果您的服务器未被 Claude for Desktop 识别,请继续阅读[故障排除](#troubleshooting)部分以获取调试提示。 127 | 128 | ## 4. 试试看! 129 | 130 | 您现在可以与 Claude 对话并询问它有关文件系统的问题。它应该知道何时调用相关工具。 131 | 132 | 您可以尝试询问 Claude 的一些问题: 133 | - 你能写一首诗并保存到我的桌面吗? 134 | - 我的下载文件夹中有哪些与工作相关的文件? 135 | - 你能将桌面上的所有图片移动到一个名为“Images”的新文件夹中吗? 136 | 137 | 根据需要,Claude 将调用相关工具并在执行操作之前征求您的许可: 138 | 139 | 140 | 141 | 142 | ## 故障排除 143 | 144 | 145 | 146 | 1. 完全重新启动 Claude for Desktop 147 | 2. 检查您的 `claude_desktop_config.json` 文件语法 148 | 3. 确保 `claude_desktop_config.json` 中包含的文件路径有效,并且它们是绝对路径而不是相对路径 149 | 4. 查看[日志](#getting-logs-from-claude-for-desktop)以了解服务器未连接的原因 150 | 5. 在命令行中,尝试手动运行服务器(替换 `username` 为 `claude_desktop_config.json` 中的内容),查看是否出现错误: 151 | 152 | 153 | ```bash 154 | npx -y @modelcontextprotocol/server-filesystem /Users/username/Desktop /Users/username/Downloads 155 | ``` 156 | 157 | 158 | ```bash 159 | npx -y @modelcontextprotocol/server-filesystem C:\Users\username\Desktop C:\Users\username\Downloads 160 | ``` 161 | 162 | 163 | 164 | 165 | Claude.app 与 MCP 相关的日志写入以下位置的日志文件: 166 | - macOS:`~/Library/Logs/Claude` 167 | - Windows:`%APPDATA%\Claude\logs` 168 | 169 | - `mcp.log` 将包含有关 MCP 连接和连接失败的一般日志。 170 | - 名为 `mcp-server-SERVERNAME.log` 的文件将包含来自指定服务器的错误(stderr)日志。 171 | 172 | 您可以运行以下命令以列出最近的日志并跟踪任何新日志(在 Windows 上,它只会显示最近的日志): 173 | 174 | 175 | ```bash 176 | # 检查 Claude 的日志以查找错误 177 | tail -n 20 -f ~/Library/Logs/Claude/mcp*.log 178 | ``` 179 | 180 | 181 | ```bash 182 | type "%APPDATA%\Claude\logs\mcp*.log" 183 | ``` 184 | 185 | 186 | 187 | 188 | 如果 Claude 尝试使用工具但失败: 189 | 190 | 1. 检查 Claude 的日志以查找错误 191 | 2. 验证您的服务器是否构建并运行无误 192 | 3. 尝试重新启动 Claude for Desktop 193 | 194 | 195 | 请参阅我们的[调试指南](/docs/tools/debugging)以获取更好的调试工具和更详细的指导。 196 | 197 | 198 | 如果配置的服务器无法加载,并且您在其日志中看到路径中引用了 `${APPDATA}` 的错误,您可能需要在 `claude_desktop_config.json` 中的 `env` 键中添加 `%APPDATA%` 的扩展值: 199 | 200 | ```json 201 | { 202 | "brave-search": { 203 | "command": "npx", 204 | "args": ["-y", "@modelcontextprotocol/server-brave-search"], 205 | "env": { 206 | "APPDATA": "C:\\Users\\user\\AppData\\Roaming\\", 207 | "BRAVE_API_KEY": "..." 208 | } 209 | } 210 | } 211 | ``` 212 | 213 | 进行此更改后,再次启动 Claude Desktop。 214 | 215 | 216 | **NPM 应全局安装** 217 | 218 | 如果 NPM 未全局安装,`npx` 命令可能会继续失败。如果 NPM 已全局安装,您将在系统上找到 `%APPDATA%\npm`。如果没有,您可以通过运行以下命令全局安装 NPM: 219 | 220 | ```bash 221 | npm install -g npm 222 | ``` 223 | 224 | 225 | 226 | 227 | 228 | ## 后续步骤 229 | 230 | 235 | 查看我们的官方 MCP 服务器和实现库 236 | 237 | 242 | 现在构建您自己的自定义服务器以在 Claude for Desktop 和其他客户端中使用 243 | 244 | -------------------------------------------------------------------------------- /sdk/java/mcp-client.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: MCP客户端 3 | description: 学习如何使用模型上下文协议(MCP协议)客户端与MCP服务器进行交互 4 | --- 5 | 6 | # 模型上下文协议(MCP协议)客户端 7 | 8 | MCP客户端是模型上下文协议(MCP协议)架构中的关键组件,负责建立和管理与MCP服务器的连接。它实现了协议的客户端部分,处理以下任务: 9 | 10 | - 协议版本协商以确保与服务器的兼容性 11 | - 能力协商以确定可用功能 12 | - 消息传输和JSON-RPC通信 13 | - 工具发现与执行 14 | - 资源访问与管理 15 | - 提示系统交互 16 | - 可选功能,如根目录管理和采样支持 17 | 18 | 客户端提供了同步和异步API,以适应不同的应用场景。 19 | 20 | 21 | 22 | ```java 23 | // 使用自定义配置创建同步客户端 24 | McpSyncClient client = McpClient.sync(transport) 25 | .requestTimeout(Duration.ofSeconds(10)) 26 | .capabilities(ClientCapabilities.builder() 27 | .roots(true) // 启用根目录支持 28 | .sampling() // 启用采样支持 29 | .build()) 30 | .sampling(request -> new CreateMessageResult(response)) 31 | .build(); 32 | 33 | // 初始化连接 34 | client.initialize(); 35 | 36 | // 列出可用工具 37 | ListToolsResult tools = client.listTools(); 38 | 39 | // 调用工具 40 | CallToolResult result = client.callTool( 41 | new CallToolRequest("calculator", 42 | Map.of("operation", "add", "a", 2, "b", 3)) 43 | ); 44 | 45 | // 列出并读取资源 46 | ListResourcesResult resources = client.listResources(); 47 | ReadResourceResult resource = client.readResource( 48 | new ReadResourceRequest("resource://uri") 49 | ); 50 | 51 | // 列出并使用提示 52 | ListPromptsResult prompts = client.listPrompts(); 53 | GetPromptResult prompt = client.getPrompt( 54 | new GetPromptRequest("greeting", Map.of("name", "Spring")) 55 | ); 56 | 57 | // 添加/移除根目录 58 | client.addRoot(new Root("file:///path", "description")); 59 | client.removeRoot("file:///path"); 60 | 61 | // 关闭客户端 62 | client.closeGracefully(); 63 | ``` 64 | 65 | 66 | 67 | ```java 68 | // 使用自定义配置创建异步客户端 69 | McpAsyncClient client = McpClient.async(transport) 70 | .requestTimeout(Duration.ofSeconds(10)) 71 | .capabilities(ClientCapabilities.builder() 72 | .roots(true) // 启用根目录支持 73 | .sampling() // 启用采样支持 74 | .build()) 75 | .sampling(request -> Mono.just(new CreateMessageResult(response))) 76 | .toolsChangeConsumer(tools -> Mono.fromRunnable(() -> { 77 | logger.info("工具已更新: {}", tools); 78 | })) 79 | .resourcesChangeConsumer(resources -> Mono.fromRunnable(() -> { 80 | logger.info("资源已更新: {}", resources); 81 | })) 82 | .promptsChangeConsumer(prompts -> Mono.fromRunnable(() -> { 83 | logger.info("提示已更新: {}", prompts); 84 | })) 85 | .build(); 86 | 87 | // 初始化连接并使用功能 88 | client.initialize() 89 | .flatMap(initResult -> client.listTools()) 90 | .flatMap(tools -> { 91 | return client.callTool(new CallToolRequest( 92 | "calculator", 93 | Map.of("operation", "add", "a", 2, "b", 3) 94 | )); 95 | }) 96 | .flatMap(result -> { 97 | return client.listResources() 98 | .flatMap(resources -> 99 | client.readResource(new ReadResourceRequest("resource://uri")) 100 | ); 101 | }) 102 | .flatMap(resource -> { 103 | return client.listPrompts() 104 | .flatMap(prompts -> 105 | client.getPrompt(new GetPromptRequest( 106 | "greeting", 107 | Map.of("name", "Spring") 108 | )) 109 | ); 110 | }) 111 | .flatMap(prompt -> { 112 | return client.addRoot(new Root("file:///path", "description")) 113 | .then(client.removeRoot("file:///path")); 114 | }) 115 | .doFinally(signalType -> { 116 | client.closeGracefully().subscribe(); 117 | }) 118 | .subscribe(); 119 | ``` 120 | 121 | 122 | 123 | ## 客户端传输 124 | 125 | 传输层负责MCP客户端与服务器之间的通信,为不同的用例提供了多种实现。客户端传输管理消息序列化、连接建立和协议特定的通信模式。 126 | 127 | 128 | 129 | 创建用于进程内通信的传输 130 | ```java 131 | ServerParameters params = ServerParameters.builder("npx") 132 | .args("-y", "@modelcontextprotocol/server-everything", "dir") 133 | .build(); 134 | McpTransport transport = new StdioClientTransport(params); 135 | ``` 136 | 137 | 138 | 创建一个框架无关的(纯Java API)SSE客户端传输。包含在核心mcp模块中。 139 | ```java 140 | McpTransport transport = new HttpClientSseClientTransport("http://your-mcp-server"); 141 | ``` 142 | 143 | 144 | 创建基于WebFlux的SSE客户端传输。需要mcp-webflux-sse-transport依赖。 145 | ```java 146 | WebClient.Builder webClientBuilder = WebClient.builder() 147 | .baseUrl("http://your-mcp-server"); 148 | McpTransport transport = new WebFluxSseClientTransport(webClientBuilder); 149 | ``` 150 | 151 | 152 | 153 | ## 客户端能力 154 | 155 | 客户端可以配置多种能力: 156 | 157 | ```java 158 | var capabilities = ClientCapabilities.builder() 159 | .roots(true) // 启用文件系统根目录支持及变更通知 160 | .sampling() // 启用LLM采样支持 161 | .build(); 162 | ``` 163 | 164 | ### 根目录支持 165 | 166 | 根目录定义了服务器可以在文件系统中操作的边界: 167 | 168 | ```java 169 | // 动态添加根目录 170 | client.addRoot(new Root("file:///path", "description")); 171 | 172 | // 移除根目录 173 | client.removeRoot("file:///path"); 174 | 175 | // 通知服务器根目录变更 176 | client.rootsListChangedNotification(); 177 | ``` 178 | 179 | 根目录能力允许服务器: 180 | 181 | - 请求可访问的文件系统根目录列表 182 | - 接收根目录列表变更的通知 183 | - 了解哪些目录和文件是可访问的 184 | 185 | 186 | ### 采样支持 187 | 188 | 采样使服务器能够通过客户端请求LLM交互(“补全”或“生成”): 189 | 190 | ```java 191 | // 配置采样处理器 192 | Function samplingHandler = request -> { 193 | // 与LLM交互的采样实现 194 | return new CreateMessageResult(response); 195 | }; 196 | 197 | // 创建支持采样的客户端 198 | var client = McpClient.sync(transport) 199 | .capabilities(ClientCapabilities.builder() 200 | .sampling() 201 | .build()) 202 | .sampling(samplingHandler) 203 | .build(); 204 | ``` 205 | 206 | 此能力允许: 207 | - 服务器无需API密钥即可利用AI能力 208 | - 客户端保持对模型访问和权限的控制 209 | - 支持文本和图像交互 210 | - 可选地在提示中包含MCP服务器上下文 211 | 212 | 213 | ## 使用MCP客户端 214 | 215 | ### 工具执行 216 | 217 | 工具是服务器端的功能,客户端可以发现并执行它们。MCP客户端提供了列出可用工具并使用特定参数执行它们的方法。每个工具都有唯一的名称并接受参数映射。 218 | 219 | 220 | 221 | ```java 222 | // 列出可用工具及其名称 223 | var tools = client.listTools(); 224 | tools.forEach(tool -> System.out.println(tool.getName())); 225 | 226 | // 使用参数执行工具 227 | var result = client.callTool("calculator", Map.of( 228 | "operation", "add", 229 | "a", 1, 230 | "b", 2 231 | )); 232 | ``` 233 | 234 | 235 | 236 | ```java 237 | // 异步列出可用工具 238 | client.listTools() 239 | .doOnNext(tools -> tools.forEach(tool -> 240 | System.out.println(tool.getName()))) 241 | .subscribe(); 242 | 243 | // 异步执行工具 244 | client.callTool("calculator", Map.of( 245 | "operation", "add", 246 | "a", 1, 247 | "b", 2 248 | )) 249 | .subscribe(); 250 | ``` 251 | 252 | 253 | 254 | ### 资源访问 255 | 256 | 资源代表服务器端的数据源,客户端可以使用URI模板访问它们。MCP客户端提供了发现可用资源并通过标准化接口检索其内容的方法。 257 | 258 | 259 | 260 | ```java 261 | // 列出可用资源及其名称 262 | var resources = client.listResources(); 263 | resources.forEach(resource -> System.out.println(resource.getName())); 264 | 265 | // 使用URI模板检索资源内容 266 | var content = client.getResource("file", Map.of( 267 | "path", "/path/to/file.txt" 268 | )); 269 | ``` 270 | 271 | 272 | 273 | ```java 274 | // 异步列出可用资源 275 | client.listResources() 276 | .doOnNext(resources -> resources.forEach(resource -> 277 | System.out.println(resource.getName()))) 278 | .subscribe(); 279 | 280 | // 异步检索资源内容 281 | client.getResource("file", Map.of( 282 | "path", "/path/to/file.txt 283 | )) 284 | .subscribe(); 285 | ``` 286 | 287 | 288 | 289 | ### 提示系统 290 | 291 | 提示系统支持与服务器端提示模板的交互。这些模板可以被发现并使用自定义参数执行,从而基于预定义的模式生成动态文本。 292 | 293 | 294 | 295 | ```java 296 | // 列出可用提示模板 297 | var prompts = client.listPrompts(); 298 | prompts.forEach(prompt -> System.out.println(prompt.getName())); 299 | 300 | // 使用参数执行提示模板 301 | var response = client.executePrompt("echo", Map.of( 302 | "text", "Hello, World!" 303 | )); 304 | ``` 305 | 306 | 307 | 308 | ```java 309 | // 异步列出可用提示模板 310 | client.listPrompts() 311 | .doOnNext(prompts -> prompts.forEach(prompt -> 312 | System.out.println(prompt.getName()))) 313 | .subscribe(); 314 | 315 | // 异步执行提示模板 316 | client.executePrompt("echo", Map.of( 317 | "text", "Hello, World!" 318 | )) 319 | .subscribe(); 320 | ``` 321 | 322 | -------------------------------------------------------------------------------- /sdk/java/mcp-overview.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: 概述 3 | description: 模型上下文协议(MCP协议)Java SDK 简介 4 | --- 5 | 6 | [模型上下文协议(MCP协议)](https://modelcontextprotocol.org/docs/concepts/architecture)的Java SDK,支持AI模型与工具之间的标准化集成。 7 | 8 | ## 特性 9 | 10 | - MCP客户端和MCP服务器实现,支持: 11 | - 协议[版本兼容性协商](https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization) 12 | - [工具](https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/)发现、执行和列表变更通知 13 | - 使用URI模板的[资源](https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/)管理 14 | - [根目录](https://spec.modelcontextprotocol.io/specification/2024-11-05/client/roots/)列表管理及通知 15 | - [提示](https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/)处理与管理 16 | - 支持AI模型交互的[采样](https://spec.modelcontextprotocol.io/specification/2024-11-05/client/sampling/)功能 17 | - 多种传输实现: 18 | - 默认传输: 19 | - 基于Stdio的传输,用于进程间通信 20 | - 基于Java HttpClient的SSE客户端传输,用于HTTP SSE客户端流 21 | - 基于Servlet的SSE服务器传输,用于HTTP SSE服务器流 22 | - 基于Spring的传输: 23 | - WebFlux SSE客户端和服务器传输,用于响应式HTTP流 24 | - WebMVC SSE传输,用于基于Servlet的HTTP流 25 | - 支持同步和异步编程范式 26 | 27 | ## 架构 28 | 29 | SDK采用分层架构,职责清晰: 30 | 31 | ![MCP堆栈架构](/images/java/mcp-stack.svg) 32 | 33 | - **客户端/服务器层(McpClient/McpServer)**:均使用McpSession进行同步/异步操作,McpClient处理客户端协议操作,McpServer管理服务器端协议操作。 34 | - **会话层(McpSession)**:使用DefaultMcpSession实现管理通信模式和状态。 35 | - **传输层(McpTransport)**:通过以下方式处理JSON-RPC消息的序列化/反序列化: 36 | - 核心模块中的StdioTransport(stdin/stdout) 37 | - 专用传输模块中的HTTP SSE传输(Java HttpClient、Spring WebFlux、Spring WebMVC) 38 | 39 | MCP客户端是模型上下文协议(MCP协议)架构中的关键组件,负责建立和管理与MCP服务器的连接。它实现了协议的客户端部分。 40 | 41 | ![Java MCP客户端架构](/images/java/java-mcp-client-architecture.jpg) 42 | 43 | MCP服务器是模型上下文协议(MCP协议)架构中的基础组件,为客户端提供工具、资源和能力。它实现了协议的服务器端部分。 44 | 45 | ![Java MCP服务器架构](/images/java/java-mcp-server-architecture.jpg) 46 | 47 | 关键交互: 48 | 49 | - **客户端/服务器初始化**:传输设置、协议兼容性检查、能力协商和实现细节交换。 50 | - **消息流**:JSON-RPC消息处理,包括验证、类型安全响应处理和错误处理。 51 | - **资源管理**:资源发现、基于URI模板的访问、订阅系统和内容检索。 52 | 53 | ## 依赖 54 | 55 | 将以下Maven依赖项添加到您的项目中: 56 | 57 | 58 | 59 | 核心MCP功能: 60 | 61 | ```xml 62 | 63 | io.modelcontextprotocol.sdk 64 | mcp 65 | 66 | ``` 67 | 68 | 对于HTTP SSE传输实现,请添加以下依赖项之一: 69 | 70 | ```xml 71 | 72 | 73 | io.modelcontextprotocol.sdk 74 | mcp-spring-webflux 75 | 76 | 77 | 78 | 79 | io.modelcontextprotocol.sdk 80 | mcp-spring-webmvc 81 | 82 | ``` 83 | 84 | 85 | 核心MCP功能: 86 | 87 | ```groovy 88 | dependencies { 89 | implementation platform("io.modelcontextprotocol.sdk:mcp") 90 | //... 91 | } 92 | ``` 93 | 94 | 对于HTTP SSE传输实现,请添加以下依赖项之一: 95 | 96 | ```groovy 97 | // 基于Spring WebFlux的SSE客户端和服务器传输 98 | dependencies { 99 | implementation platform("io.modelcontextprotocol.sdk:mcp-spring-webflux") 100 | } 101 | 102 | // 基于Spring WebMVC的SSE服务器传输 103 | dependencies { 104 | implementation platform("io.modelcontextprotocol.sdk:mcp-spring-webmvc") 105 | } 106 | ``` 107 | 108 | 109 | 110 | ### 物料清单(BOM) 111 | 112 | 物料清单(BOM)声明了给定版本中所有依赖项的推荐版本。在应用程序的构建脚本中使用BOM,可以避免您自己指定和维护依赖项版本。相反,您使用的BOM版本决定了所使用的依赖项版本。它还确保默认情况下您使用的是受支持和测试的依赖项版本,除非您选择覆盖它们。 113 | 114 | 将BOM添加到您的项目中: 115 | 116 | 117 | 118 | ```xml 119 | 120 | 121 | 122 | io.modelcontextprotocol.sdk 123 | mcp-bom 124 | 0.7.0 125 | pom 126 | import 127 | 128 | 129 | 130 | ``` 131 | 132 | 133 | 134 | ```groovy 135 | dependencies { 136 | implementation platform("io.modelcontextprotocol.sdk:mcp-bom:0.7.0") 137 | //... 138 | } 139 | ``` 140 | 141 | Gradle用户还可以通过使用Gradle(5.0+)原生支持声明依赖约束的Maven BOM来利用Spring AI MCP BOM。通过在Gradle构建脚本的依赖项部分添加'platform'依赖处理程序方法来实现。如上所示,随后可以声明您希望使用的一个或多个spring-ai模块的无版本Starter依赖项,例如spring-ai-openai。 142 | 143 | 144 | 145 | 将版本号替换为您要使用的BOM版本。 146 | 147 | ### 可用依赖项 148 | 149 | 以下依赖项由BOM管理: 150 | 151 | - 核心依赖项 152 | - `io.modelcontextprotocol.sdk:mcp` - 核心MCP库,提供模型上下文协议(MCP协议)实现的基本功能和API。 153 | - 传输依赖项 154 | - `io.modelcontextprotocol.sdk:mcp-spring-webflux` - 基于WebFlux的服务器发送事件(SSE)传输实现,用于响应式应用程序。 155 | - `io.modelcontextprotocol.sdk:mcp-spring-webmvc` - 基于WebMVC的服务器发送事件(SSE)传输实现,用于基于Servlet的应用程序。 156 | - 测试依赖项 157 | - `io.modelcontextprotocol.sdk:mcp-test` - 用于MCP应用程序的测试工具和支持。 -------------------------------------------------------------------------------- /sdk/java/mcp-server.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: MCP服务器 3 | description: 学习如何实现和配置模型上下文协议(MCP协议)服务器 4 | --- 5 | 6 | ## 概述 7 | 8 | MCP服务器是模型上下文协议(MCP协议)架构中的基础组件,为客户端提供工具、资源和能力。它实现了协议的服务器端部分,负责: 9 | 10 | - 暴露客户端可以发现和执行的工具 11 | - 使用基于URI的访问模式管理资源 12 | - 提供提示模板并处理提示请求 13 | - 支持与客户端的能力协商 14 | - 实现服务器端协议操作 15 | - 管理并发客户端连接 16 | - 提供结构化日志和通知 17 | 18 | 服务器支持同步和异步API,允许在不同的应用场景中灵活集成。 19 | 20 | 21 | 22 | ```java 23 | // 使用自定义配置创建服务器 24 | McpSyncServer syncServer = McpServer.sync(transport) 25 | .serverInfo("my-server", "1.0.0") 26 | .capabilities(ServerCapabilities.builder() 27 | .resources(true) // 启用资源支持 28 | .tools(true) // 启用工具支持 29 | .prompts(true) // 启用提示支持 30 | .logging() // 启用日志支持 31 | .build()) 32 | .build(); 33 | 34 | // 注册工具、资源和提示 35 | syncServer.addTool(syncToolRegistration); 36 | syncServer.addResource(syncResourceRegistration); 37 | syncServer.addPrompt(syncPromptRegistration); 38 | 39 | // 发送日志通知 40 | syncServer.loggingNotification(LoggingMessageNotification.builder() 41 | .level(LoggingLevel.INFO) 42 | .logger("custom-logger") 43 | .data("服务器已初始化") 44 | .build()); 45 | 46 | // 完成后关闭服务器 47 | syncServer.close(); 48 | ``` 49 | 50 | 51 | 52 | ```java 53 | // 使用自定义配置创建异步服务器 54 | McpAsyncServer asyncServer = McpServer.async(transport) 55 | .serverInfo("my-server", "1.0.0") 56 | .capabilities(ServerCapabilities.builder() 57 | .resources(true) // 启用资源支持 58 | .tools(true) // 启用工具支持 59 | .prompts(true) // 启用提示支持 60 | .logging() // 启用日志支持 61 | .build()) 62 | .build(); 63 | 64 | // 注册工具、资源和提示 65 | asyncServer.addTool(asyncToolRegistration) 66 | .doOnSuccess(v -> logger.info("工具已注册")) 67 | .subscribe(); 68 | 69 | asyncServer.addResource(asyncResourceRegistration) 70 | .doOnSuccess(v -> logger.info("资源已注册")) 71 | .subscribe(); 72 | 73 | asyncServer.addPrompt(asyncPromptRegistration) 74 | .doOnSuccess(v -> logger.info("提示已注册")) 75 | .subscribe(); 76 | 77 | // 发送日志通知 78 | asyncServer.loggingNotification(LoggingMessageNotification.builder() 79 | .level(LoggingLevel.INFO) 80 | .logger("custom-logger") 81 | .data("服务器已初始化") 82 | .build()); 83 | 84 | // 完成后关闭服务器 85 | asyncServer.close() 86 | .doOnSuccess(v -> logger.info("服务器已关闭")) 87 | .subscribe(); 88 | ``` 89 | 90 | 91 | 92 | 93 | ## 服务器传输 94 | 95 | MCP SDK中的传输层负责处理客户端与服务器之间的通信。它提供了不同的实现以支持各种通信协议和模式。SDK包括多种内置的传输实现: 96 | 97 | 98 | 99 | 100 | <> 101 | 创建基于进程的传输: 102 | 103 | ```java 104 | StdioServerTransport transport = new StdioServerTransport(new ObjectMapper()); 105 | ``` 106 | 107 | 通过标准输入/输出流提供双向JSON-RPC消息处理,支持非阻塞消息处理、序列化/反序列化和优雅关闭。 108 | 109 | 关键特性: 110 |
    111 |
  • 通过stdin/stdout进行双向通信
  • 112 |
  • 支持基于进程的集成
  • 113 |
  • 简单的设置和配置
  • 114 |
  • 轻量级实现
  • 115 |
116 | 117 |
118 | 119 | 120 | <> 121 |

创建基于WebFlux的SSE服务器传输。
需要mcp-spring-webflux依赖。

122 | 123 | ```java 124 | @Configuration 125 | class McpConfig { 126 | @Bean 127 | WebFluxSseServerTransport webFluxSseServerTransport(ObjectMapper mapper) { 128 | return new WebFluxSseServerTransport(mapper, "/mcp/message"); 129 | } 130 | 131 | @Bean 132 | RouterFunction mcpRouterFunction(WebFluxSseServerTransport transport) { 133 | return transport.getRouterFunction(); 134 | } 135 | } 136 | ``` 137 | 138 |

实现MCP HTTP与SSE传输规范,提供:

139 |
    140 |
  • 使用WebFlux的响应式HTTP流
  • 141 |
  • 通过SSE端点支持并发客户端连接
  • 142 |
  • 消息路由和会话管理
  • 143 |
  • 优雅关闭能力
  • 144 |
145 | 146 |
147 | 148 | 149 | 150 | <> 151 |

创建基于WebMvc的SSE服务器传输。
需要mcp-spring-webmvc依赖。

152 | 153 | ```java 154 | @Configuration 155 | @EnableWebMvc 156 | class McpConfig { 157 | @Bean 158 | WebMvcSseServerTransport webMvcSseServerTransport(ObjectMapper mapper) { 159 | return new WebMvcSseServerTransport(mapper, "/mcp/message"); 160 | } 161 | 162 | @Bean 163 | RouterFunction mcpRouterFunction(WebMvcSseServerTransport transport) { 164 | return transport.getRouterFunction(); 165 | } 166 | } 167 | ``` 168 | 169 |

实现MCP HTTP与SSE传输规范,提供:

170 |
    171 |
  • 服务器端事件流
  • 172 |
  • 与Spring WebMVC集成
  • 173 |
  • 支持传统Web应用程序
  • 174 |
  • 同步操作处理
  • 175 |
176 | 177 |
178 | 179 | 180 | 181 | <> 182 |

183 | 创建一个基于Servlet的SSE服务器传输。它包含在核心mcp模块中。
184 | HttpServletSseServerTransport可以与任何Servlet容器一起使用。
185 | 要在Spring Web应用程序中使用它,可以将其注册为Servlet bean: 186 |

187 | 188 | ```java 189 | @Configuration 190 | @EnableWebMvc 191 | public class McpServerConfig implements WebMvcConfigurer { 192 | 193 | @Bean 194 | public HttpServletSseServerTransport servletSseServerTransport() { 195 | return new HttpServletSseServerTransport(new ObjectMapper(), "/mcp/message"); 196 | } 197 | 198 | @Bean 199 | public ServletRegistrationBean customServletBean(HttpServletSseServerTransport servlet) { 200 | return new ServletRegistrationBean(servlet); 201 | } 202 | } 203 | ``` 204 | 205 |

206 | 使用传统的Servlet API实现MCP HTTP与SSE传输规范,提供: 207 |

208 |
    209 |
  • 使用Servlet 6.0异步支持进行异步消息处理
  • 210 |
  • 管理多个客户端连接的会话
  • 211 |
  • 212 | 两种类型的端点: 213 |
      214 |
    • SSE端点(/sse)用于服务器到客户端的事件
    • 215 |
    • 消息端点(可配置)用于客户端到服务器的请求
    • 216 |
    217 |
  • 218 |
  • 错误处理和响应格式化
  • 219 |
  • 优雅关闭支持
  • 220 |
221 | 222 |
223 | 224 |
225 | 226 | 227 | ## 服务器能力 228 | 229 | 服务器可以配置多种能力: 230 | 231 | ```java 232 | var capabilities = ServerCapabilities.builder() 233 | .resources(false, true) // 资源支持及列表变更通知 234 | .tools(true) // 工具支持及列表变更通知 235 | .prompts(true) // 提示支持及列表变更通知 236 | .logging() // 启用日志支持(默认启用,日志级别为INFO) 237 | .build(); 238 | ``` 239 | 240 | ### 日志支持 241 | 242 | 服务器提供结构化日志功能,允许向客户端发送不同严重级别的日志消息: 243 | 244 | ```java 245 | // 向客户端发送日志消息 246 | server.loggingNotification(LoggingMessageNotification.builder() 247 | .level(LoggingLevel.INFO) 248 | .logger("custom-logger") 249 | .data("自定义日志消息") 250 | .build()); 251 | ``` 252 | 253 | 客户端可以通过`mcpClient.setLoggingLevel(level)`请求控制接收的最低日志级别。低于设置级别的消息将被过滤掉。 254 | 支持的日志级别(按严重程度递增):DEBUG (0), INFO (1), NOTICE (2), WARNING (3), ERROR (4), CRITICAL (5), ALERT (6), EMERGENCY (7) 255 | 256 | ### 工具注册 257 | 258 | 259 | 260 | ```java 261 | // 同步工具注册 262 | var schema = """ 263 | { 264 | "type" : "object", 265 | "id" : "urn:jsonschema:Operation", 266 | "properties" : { 267 | "operation" : { 268 | "type" : "string" 269 | }, 270 | "a" : { 271 | "type" : "number" 272 | }, 273 | "b" : { 274 | "type" : "number" 275 | } 276 | } 277 | } 278 | """; 279 | var syncToolRegistration = new McpServerFeatures.SyncToolRegistration( 280 | new Tool("calculator", "基本计算器", schema), 281 | arguments -> { 282 | // 工具实现 283 | return new CallToolResult(result, false); 284 | } 285 | ); 286 | ``` 287 | 288 | 289 | 290 | ```java 291 | // 异步工具注册 292 | var schema = """ 293 | { 294 | "type" : "object", 295 | "id" : "urn:jsonschema:Operation", 296 | "properties" : { 297 | "operation" : { 298 | "type" : "string" 299 | }, 300 | "a" : { 301 | "type" : "number" 302 | }, 303 | "b" : { 304 | "type" : "number" 305 | } 306 | } 307 | } 308 | """; 309 | var asyncToolRegistration = new McpServerFeatures.AsyncToolRegistration( 310 | new Tool("calculator", "基本计算器", schema), 311 | arguments -> { 312 | // 工具实现 313 | return Mono.just(new CallToolResult(result, false)); 314 | } 315 | ); 316 | ``` 317 | 318 | 319 | 320 | ### 资源注册 321 | 322 | 323 | 324 | ```java 325 | // 同步资源注册 326 | var syncResourceRegistration = new McpServerFeatures.SyncResourceRegistration( 327 | new Resource("custom://resource", "name", "description", "mime-type", null), 328 | request -> { 329 | // 资源读取实现 330 | return new ReadResourceResult(contents); 331 | } 332 | ); 333 | ``` 334 | 335 | 336 | 337 | ```java 338 | // 异步资源注册 339 | var asyncResourceRegistration = new McpServerFeatures.AsyncResourceRegistration( 340 | new Resource("custom://resource", "name", "description", "mime-type", null), 341 | request -> { 342 | // 资源读取实现 343 | return Mono.just(new ReadResourceResult(contents)); 344 | } 345 | ); 346 | ``` 347 | 348 | 349 | 350 | ### 提示注册 351 | 352 | 353 | 354 | ```java 355 | // 同步提示注册 356 | var syncPromptRegistration = new McpServerFeatures.SyncPromptRegistration( 357 | new Prompt("greeting", "description", List.of( 358 | new PromptArgument("name", "description", true) 359 | )), 360 | request -> { 361 | // 提示实现 362 | return new GetPromptResult(description, messages); 363 | } 364 | ); 365 | ``` 366 | 367 | 368 | 369 | ```java 370 | // 异步提示注册 371 | var asyncPromptRegistration = new McpServerFeatures.AsyncPromptRegistration( 372 | new Prompt("greeting", "description", List.of( 373 | new PromptArgument("name", "description", true) 374 | )), 375 | request -> { 376 | // 提示实现 377 | return Mono.just(new GetPromptResult(description, messages)); 378 | } 379 | ); 380 | ``` 381 | 382 | 383 | 384 | ## 错误处理 385 | 386 | SDK通过McpError类提供全面的错误处理,涵盖协议兼容性、传输通信、JSON-RPC消息、工具执行、资源管理、提示处理、超时和连接问题。这种统一的错误处理方法确保在同步和异步操作中一致且可靠的错误管理。 -------------------------------------------------------------------------------- /snippets/snippet-intro.mdx: -------------------------------------------------------------------------------- 1 | 软件开发的核心原则之一是 DRY(Don't Repeat Yourself,不要重复自己)。这一原则同样适用于文档编写。如果你发现自己在多个地方重复相同的内容,应该考虑创建一个自定义片段,以保持内容同步。 -------------------------------------------------------------------------------- /tutorials/building-a-client-node.mdx: -------------------------------------------------------------------------------- 1 | 2 | ## 系统要求 3 | 4 | 在开始之前,请确保您的系统满足以下要求: 5 | - Mac 或 Windows 电脑 6 | - 已安装 Node.js 16 或更高版本 7 | - npm(随 Node.js 一起安装) 8 | 9 | ## 设置您的环境 10 | 11 | 首先,创建一个新的 Node.js 项目: 12 | 13 | ```bash 14 | # 创建项目目录 15 | mkdir mcp-client 16 | cd mcp-client 17 | 18 | # 初始化 npm 项目 19 | npm init -y 20 | 21 | # 安装依赖项 22 | npm install @modelcontextprotocol/sdk @anthropic-ai/sdk dotenv 23 | npm install -D typescript @types/node 24 | 25 | # 创建 TypeScript 配置文件 26 | npx tsc --init 27 | 28 | # 创建必要的文件 29 | mkdir src 30 | touch src/client.ts 31 | touch .env 32 | ``` 33 | 34 | 更新 `package.json` 以添加必要的配置: 35 | 36 | ```json 37 | { 38 | "type": "module", 39 | "scripts": { 40 | "build": "tsc", 41 | "start": "node build/client.js" 42 | } 43 | } 44 | ``` 45 | 46 | 更新 `tsconfig.json` 以设置适当的配置: 47 | 48 | ```json 49 | { 50 | "compilerOptions": { 51 | "target": "ES2022", 52 | "module": "Node16", 53 | "moduleResolution": "Node16", 54 | "outDir": "./build", 55 | "rootDir": "./src", 56 | "strict": true, 57 | "esModuleInterop": true, 58 | "skipLibCheck": true, 59 | "forceConsistentCasingInFileNames": true 60 | }, 61 | "include": ["src/**/*"] 62 | } 63 | ``` 64 | 65 | ## 设置您的 API 密钥 66 | 67 | 您需要从 [Anthropic 控制台](https://console.anthropic.com/settings/keys) 获取一个 Anthropic API 密钥。 68 | 69 | 创建 `.env` 文件: 70 | ```bash 71 | ANTHROPIC_API_KEY=your_key_here 72 | ``` 73 | 74 | 将 `.env` 添加到 `.gitignore` 文件中: 75 | ```bash 76 | echo ".env" >> .gitignore 77 | ``` 78 | 79 | ## 创建客户端 80 | 81 | 首先,在 `src/client.ts` 中设置导入并创建基本的客户端类: 82 | 83 | ```typescript 84 | import { Client } from "@modelcontextprotocol/sdk/client/index.js"; 85 | import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; 86 | import Anthropic from "@anthropic-ai/sdk"; 87 | import dotenv from "dotenv"; 88 | import { 89 | CallToolResultSchema, 90 | ListToolsResultSchema, 91 | } from "@modelcontextprotocol/sdk/types.js"; 92 | import * as readline from "node:readline"; 93 | 94 | dotenv.config(); 95 | 96 | interface MCPClientConfig { 97 | name?: string; 98 | version?: string; 99 | } 100 | 101 | class MCPClient { 102 | private client: Client | null = null; 103 | private anthropic: Anthropic; 104 | private transport: StdioClientTransport | null = null; 105 | 106 | constructor(config: MCPClientConfig = {}) { 107 | this.anthropic = new Anthropic(); 108 | } 109 | 110 | // 方法将在此处添加 111 | } 112 | ``` 113 | 114 | ## 服务器连接管理 115 | 116 | 接下来,实现连接到 MCP 服务器的方法: 117 | 118 | ```typescript 119 | async connectToServer(serverScriptPath: string): Promise { 120 | const isPython = serverScriptPath.endsWith(".py"); 121 | const isJs = serverScriptPath.endsWith(".js"); 122 | 123 | if (!isPython && !isJs) { 124 | throw new Error("服务器脚本必须是 .py 或 .js 文件"); 125 | } 126 | 127 | const command = isPython ? "python" : "node"; 128 | 129 | this.transport = new StdioClientTransport({ 130 | command, 131 | args: [serverScriptPath], 132 | }); 133 | 134 | this.client = new Client( 135 | { 136 | name: "mcp-client", 137 | version: "1.0.0", 138 | }, 139 | { 140 | capabilities: {}, 141 | } 142 | ); 143 | 144 | await this.client.connect(this.transport); 145 | 146 | // 列出可用工具 147 | const response = await this.client.request( 148 | { method: "tools/list" }, 149 | ListToolsResultSchema 150 | ); 151 | 152 | console.log( 153 | "\n连接到服务器,可用工具:", 154 | response.tools.map((tool: any) => tool.name) 155 | ); 156 | } 157 | ``` 158 | 159 | ## 查询处理逻辑 160 | 161 | 现在添加处理查询和处理工具调用的核心功能: 162 | 163 | ```typescript 164 | async processQuery(query: string): Promise { 165 | if (!this.client) { 166 | throw new Error("客户端未连接"); 167 | } 168 | 169 | // 初始化消息数组,包含用户查询 170 | let messages: Anthropic.MessageParam[] = [ 171 | { 172 | role: "user", 173 | content: query, 174 | }, 175 | ]; 176 | 177 | // 获取可用工具 178 | const toolsResponse = await this.client.request( 179 | { method: "tools/list" }, 180 | ListToolsResultSchema 181 | ); 182 | 183 | const availableTools = toolsResponse.tools.map((tool: any) => ({ 184 | name: tool.name, 185 | description: tool.description, 186 | input_schema: tool.inputSchema, 187 | })); 188 | 189 | const finalText: string[] = []; 190 | let currentResponse = await this.anthropic.messages.create({ 191 | model: "claude-3-5-sonnet-20241022", 192 | max_tokens: 1000, 193 | messages, 194 | tools: availableTools, 195 | }); 196 | 197 | // 处理响应和任何工具调用 198 | while (true) { 199 | // 将 Claude 的响应添加到最终文本和消息中 200 | for (const content of currentResponse.content) { 201 | if (content.type === "text") { 202 | finalText.push(content.text); 203 | } else if (content.type === "tool_use") { 204 | const toolName = content.name; 205 | const toolArgs = content.input; 206 | 207 | // 执行工具调用 208 | const result = await this.client.request( 209 | { 210 | method: "tools/call", 211 | params: { 212 | name: toolName, 213 | arguments: toolArgs, 214 | }, 215 | }, 216 | CallToolResultSchema 217 | ); 218 | 219 | finalText.push( 220 | `[调用工具 ${toolName},参数为 ${JSON.stringify(toolArgs)}]` 221 | ); 222 | 223 | // 将 Claude 的响应(包括工具使用)添加到消息中 224 | messages.push({ 225 | role: "assistant", 226 | content: currentResponse.content, 227 | }); 228 | 229 | // 将工具结果添加到消息中 230 | messages.push({ 231 | role: "user", 232 | content: [ 233 | { 234 | type: "tool_result", 235 | tool_use_id: content.id, 236 | content: [ 237 | { type: "text", text: JSON.stringify(result.content) }, 238 | ], 239 | }, 240 | ], 241 | }); 242 | 243 | // 获取 Claude 的下一轮响应,包含工具结果 244 | currentResponse = await this.anthropic.messages.create({ 245 | model: "claude-3-5-sonnet-20241022", 246 | max_tokens: 1000, 247 | messages, 248 | tools: availableTools, 249 | }); 250 | 251 | // 将 Claude 对工具结果的解释添加到最终文本中 252 | if (currentResponse.content[0]?.type === "text") { 253 | finalText.push(currentResponse.content[0].text); 254 | } 255 | 256 | // 继续循环以处理任何额外的工具调用 257 | continue; 258 | } 259 | } 260 | 261 | // 如果到达此处,响应中没有工具调用 262 | break; 263 | } 264 | 265 | return finalText.join("\n"); 266 | } 267 | 268 | ``` 269 | 270 | ## 交互式聊天界面 271 | 272 | 添加聊天循环和清理功能: 273 | 274 | ```typescript 275 | async chatLoop(): Promise { 276 | console.log("\nMCP 客户端已启动!"); 277 | console.log("输入您的查询或输入 'quit' 退出。"); 278 | 279 | // 使用 Node 的 readline 进行控制台输入 280 | const rl = readline.createInterface({ 281 | input: process.stdin, 282 | output: process.stdout, 283 | }); 284 | 285 | const askQuestion = () => { 286 | rl.question("\n查询:", async (query: string) => { 287 | try { 288 | if (query.toLowerCase() === "quit") { 289 | await this.cleanup(); 290 | rl.close(); 291 | return; 292 | } 293 | 294 | const response = await this.processQuery(query); 295 | console.log("\n" + response); 296 | askQuestion(); 297 | } catch (error) { 298 | console.error("\n错误:", error); 299 | askQuestion(); 300 | } 301 | }); 302 | }; 303 | 304 | askQuestion(); 305 | } 306 | 307 | async cleanup(): Promise { 308 | if (this.transport) { 309 | await this.transport.close(); 310 | } 311 | } 312 | ``` 313 | 314 | ## 主入口点 315 | 316 | 最后,在类外部添加主执行逻辑: 317 | 318 | ```typescript 319 | // 主执行逻辑 320 | async function main() { 321 | if (process.argv.length < 3) { 322 | console.log("用法:ts-node client.ts "); 323 | process.exit(1); 324 | } 325 | 326 | const client = new MCPClient(); 327 | try { 328 | await client.connectToServer(process.argv[2]); 329 | await client.chatLoop(); 330 | } catch (error) { 331 | console.error("错误:", error); 332 | await client.cleanup(); 333 | process.exit(1); 334 | } 335 | } 336 | 337 | // 如果这是主模块,则运行 main 338 | if (import.meta.url === new URL(process.argv[1], "file:").href) { 339 | main(); 340 | } 341 | 342 | export default MCPClient; 343 | ``` 344 | 345 | ## 运行客户端 346 | 347 | 要使用任何 MCP 服务器运行您的客户端: 348 | 349 | ```bash 350 | # 构建 TypeScript 代码。确保每次更新 `client.ts` 后重新运行此命令! 351 | npm run build 352 | 353 | # 运行客户端 354 | node build/client.js path/to/server.py # 用于 Python 服务器 355 | node build/client.js path/to/server.js # 用于 Node.js 服务器 356 | ``` 357 | 358 | 客户端将: 359 | 1. 连接到指定的服务器 360 | 2. 列出可用工具 361 | 3. 启动交互式聊天会话,您可以: 362 | - 输入查询 363 | - 查看工具执行 364 | - 获取 Claude 的响应 365 | 366 | ## 关键组件解释 367 | 368 | #### 1. 客户端初始化 369 | - `MCPClient` 类初始化时会话管理和 API 客户端 370 | - 使用基本功能设置 MCP 客户端 371 | - 配置 Anthropic 客户端以进行 Claude 交互 372 | 373 | #### 2. 服务器连接 374 | - 支持 Python 和 Node.js 服务器 375 | - 验证服务器脚本类型 376 | - 设置适当的通信通道 377 | - 连接时列出可用工具 378 | 379 | #### 3. 查询处理 380 | - 维护对话上下文 381 | - 处理 Claude 的响应和工具调用 382 | - 管理 Claude 和工具之间的消息流 383 | - 将结果组合成连贯的响应 384 | 385 | #### 4. 交互式界面 386 | - 提供简单的命令行界面 387 | - 处理用户输入并显示响应 388 | - 包括基本错误处理 389 | - 允许优雅退出 390 | 391 | #### 5. 资源管理 392 | - 正确清理资源 393 | - 处理连接问题 394 | - 优雅的关闭程序 395 | 396 | ### 常见自定义点 397 | 398 | 1. **工具处理** 399 | - 修改 `processQuery()` 以处理特定工具类型 400 | - 添加工具调用的自定义错误处理 401 | - 实现工具特定的响应格式化 402 | 403 | 2. **响应处理** 404 | - 自定义工具结果的格式化 405 | - 添加响应过滤或转换 406 | - 实现自定义日志记录 407 | 408 | 3. **用户界面** 409 | - 添加 GUI 或 Web 界面 410 | - 实现丰富的控制台输出 411 | - 添加命令历史记录或自动补全 412 | 413 | ### 最佳实践 414 | 415 | 1. **错误处理** 416 | - 始终将工具调用包装在 try-catch 块中 417 | - 提供有意义的错误消息 418 | - 优雅地处理连接问题 419 | 420 | 2. **资源管理** 421 | - 使用适当的清理方法 422 | - 完成后关闭连接 423 | - 处理服务器断开连接 424 | 425 | 3. **安全性** 426 | - 将 API 密钥安全地存储在 `.env` 中 427 | - 验证服务器响应 428 | - 谨慎处理工具权限 429 | 430 | ### 故障排除 431 | 432 | #### 服务器路径问题 433 | - 仔细检查服务器脚本的路径 434 | - 如果相对路径不起作用,请使用绝对路径 435 | - 对于 Windows 用户,使用正斜杠 (/) 或转义反斜杠 (\\) 436 | - 验证服务器文件是否具有正确的扩展名(.py 或 .js) 437 | 438 | 正确路径用法的示例: 439 | ```bash 440 | # 相对路径 441 | node build/client.js ./server/weather.js 442 | 443 | # 绝对路径 444 | node build/client.js /Users/username/projects/mcp-server/weather.js 445 | 446 | # Windows 路径(两种格式均可) 447 | node build/client.js C:/projects/mcp-server/weather.js 448 | node build/client.js C:\\projects\\mcp-server\\weather.js 449 | ``` 450 | 451 | #### 连接问题 452 | - 验证服务器脚本是否存在并具有正确的权限 453 | - 检查服务器脚本是否可执行 454 | - 确保服务器脚本的依赖项已安装 455 | - 尝试直接运行服务器脚本以检查错误 456 | 457 | #### 工具执行问题 458 | - 检查服务器日志以获取错误消息 459 | - 验证工具输入参数是否与模式匹配 460 | - 确保工具依赖项可用 461 | - 添加调试日志以跟踪执行流程 462 | -------------------------------------------------------------------------------- /tutorials/building-mcp-with-llms.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | title: "使用 LLM 构建 MCP" 3 | description: "使用 Claude 等 LLM 加速您的 MCP 开发!" 4 | --- 5 | 6 | 本指南将帮助您使用 LLM 来构建自定义的 Model Context Protocol (MCP) 服务器和客户端。本教程将重点介绍 Claude,但您可以使用任何前沿的 LLM 来完成此操作。 7 | 8 | ## 准备文档 9 | 10 | 在开始之前,收集必要的文档以帮助 Claude 理解 MCP: 11 | 12 | 1. 访问 https://modelcontextprotocol.io/llms-full.txt 并复制完整的文档文本 13 | 2. 导航到 [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) 或 [Python SDK 仓库](https://github.com/modelcontextprotocol/python-sdk) 14 | 3. 复制 README 文件和其他相关文档 15 | 4. 将这些文档粘贴到您与 Claude 的对话中 16 | 17 | ## 描述您的服务器 18 | 19 | 在提供文档后,请清晰地描述您要构建的服务器类型。具体说明: 20 | 21 | - 您的服务器将暴露哪些资源 22 | - 它将提供哪些工具 23 | - 它应该提供哪些提示 24 | - 它需要与哪些外部系统交互 25 | 26 | 例如: 27 | ``` 28 | 构建一个 MCP 服务器,该服务器: 29 | - 连接到公司 PostgreSQL 数据库 30 | - 将表模式暴露为资源 31 | - 提供运行只读 SQL 查询的工具 32 | - 包括常见数据分析任务的提示 33 | ``` 34 | 35 | ## 与 Claude 合作 36 | 37 | 在与 Claude 合作开发 MCP 服务器时: 38 | 39 | 1. 首先从核心功能开始,然后逐步添加更多功能 40 | 2. 请 Claude 解释您不理解的任何代码部分 41 | 3. 根据需要请求修改或改进 42 | 4. 让 Claude 帮助您测试服务器并处理边缘情况 43 | 44 | Claude 可以帮助实现所有关键的 MCP 功能: 45 | 46 | - 资源管理和暴露 47 | - 工具定义和实现 48 | - 提示模板和处理程序 49 | - 错误处理和日志记录 50 | - 连接和传输设置 51 | 52 | ## 最佳实践 53 | 54 | 在使用 Claude 构建 MCP 服务器时: 55 | 56 | - 将复杂的服务器分解为较小的部分 57 | - 在继续之前彻底测试每个组件 58 | - 牢记安全性 - 验证输入并适当限制访问 59 | - 为将来的维护记录好代码 60 | - 仔细遵循 MCP 协议规范 61 | 62 | ## 后续步骤 63 | 64 | 在 Claude 帮助您构建服务器后: 65 | 66 | 1. 仔细审查生成的代码 67 | 2. 使用 MCP Inspector 工具测试服务器 68 | 3. 将其连接到 Claude.app 或其他 MCP 客户端 69 | 4. 根据实际使用和反馈进行迭代 70 | 71 | 请记住,Claude 可以帮助您根据需求的变化修改和改进您的服务器。 72 | 73 | 需要更多指导?只需向 Claude 提出有关实现 MCP 功能或解决出现的问题的具体问题。 --------------------------------------------------------------------------------