MCP Python SDK

活跃
GitHub Python MIT

简介

MCP Python SDK 是官方 Python 实现,用于构建 MCP server 与 Agent 端集成,适合在 Python Agent 项目中快速接入标准化工具协议。

核心特性

  • FastMCP 高级接口 — 用装饰器快速定义 MCP Server 的工具、资源和提示词
  • 多传输协议支持 — 支持 stdio、SSE 和 Streamable HTTP 三种标准传输方式
  • 结构化输出 — 工具返回值自动序列化为结构化 JSON 响应
  • 资源与提示词系统 — 通过 Resources 暴露数据、通过 Prompts 定义交互模板
  • OAuth 认证支持 — 客户端内置 OAuth 认证流程支持
  • ASGI 挂载 — 可挂载到现有 FastAPI/Starlette 应用作为子应用运行

适用场景

💡 为 LLM 应用快速构建暴露数据库查询能力的 MCP Server
💡 将现有 Python API 包装为 MCP 兼容的工具服务供 Agent 调用
💡 构建连接 Claude Desktop 的本地 MCP Server 实现工具扩展
💡 在 FastAPI 应用中挂载 MCP Server 提供标准化的 LLM 上下文接口
💡 构建 MCP 客户端连接和调用任何标准 MCP Server

快速开始

uv init mcp-server-demo
cd mcp-server-demo
uv add "mcp[cli]"

# server.py
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Demo", json_response=True)

@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two numbers"""
    return a + b

@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
    return f"Hello, {name}!"

if __name__ == "__main__":
    mcp.run(transport="streamable-http")

相关项目

相关文章