MCP 课程文档
MCP SDK
加入 Hugging Face 社区
并获得增强的文档体验
开始使用
MCP SDK
模型上下文协议为 JavaScript、Python 和其他语言提供了官方 SDK。这使得在您的应用程序中实现 MCP 客户端和服务器变得容易。这些 SDK 处理底层协议细节,让您可以专注于构建应用程序的功能。
SDK 概述
两个 SDK 都提供类似的核心功能,遵循我们之前讨论的 MCP 协议规范。它们处理:
- 协议级通信
- 功能注册和发现
- 消息序列化/反序列化
- 连接管理
- 错误处理
核心原语实现
让我们探讨如何使用这两个 SDK 实现每个核心原语(工具、资源和提示)。
python
javascript
from mcp.server.fastmcp import FastMCP
# Create an MCP server
mcp = FastMCP("Weather Service")
# Tool implementation
@mcp.tool()
def get_weather(location: str) -> str:
"""Get the current weather for a specified location."""
return f"Weather in {location}: Sunny, 72°F"
# Resource implementation
@mcp.resource("weather://{location}")
def weather_resource(location: str) -> str:
"""Provide weather data as a resource."""
return f"Weather data for {location}: Sunny, 72°F"
# Prompt implementation
@mcp.prompt()
def weather_report(location: str) -> str:
"""Create a weather report prompt."""
return f"""You are a weather reporter. Weather report for {location}?"""
# Run the server
if __name__ == "__main__":
mcp.run()
实现服务器后,可以通过运行服务器脚本来启动它。
mcp dev server.py
这将初始化一个开发服务器,运行文件 `server.py`。并记录以下输出:
Starting MCP inspector... ⚙️ Proxy server listening on port 6277 Spawned stdio transport Connected MCP client to backing server transport Created web app transport Set up MCP proxy 🔍 MCP Inspector is up and running at http://127.0.0.1:6274 🚀
然后您可以打开 MCP Inspector(地址:http://127.0.0.1:6274)以查看服务器的功能并与之交互。
您将看到服务器的功能以及通过 UI 调用它们的能力。
MCP SDK
MCP 旨在与语言无关,并为几种流行的编程语言提供官方 SDK
语言 | 代码库 | 维护者 | 状态 |
---|---|---|---|
TypeScript | github.com/modelcontextprotocol/typescript-sdk | Anthropic | 活跃 |
Python | github.com/modelcontextprotocol/python-sdk | Anthropic | 活跃 |
Java | github.com/modelcontextprotocol/java-sdk | Spring AI (VMware) | 活跃 |
Kotlin | github.com/modelcontextprotocol/kotlin-sdk | JetBrains | 活跃 |
C# | github.com/modelcontextprotocol/csharp-sdk | 微软 | 活跃(预览) |
Swift | github.com/modelcontextprotocol/swift-sdk | loopwork-ai | 活跃 |
Rust | github.com/modelcontextprotocol/rust-sdk | Anthropic/社区 | 活跃 |
Dart | https://github.com/leehack/mcp_dart | Flutter 社区 | 活跃 |
这些 SDK 提供了特定于语言的抽象,简化了 MCP 协议的使用,让您可以专注于实现服务器或客户端的核心逻辑,而不是处理底层协议细节。
后续步骤
我们只触及了 MCP 功能的皮毛,但您已经运行了一个基本服务器。事实上,您还使用浏览器中的 MCP 客户端连接到了它。
在下一节中,我们将探讨如何从 LLM 连接到您的服务器。
< > 在 GitHub 上更新