modelcontextprotocol/python-sdk

The official Python SDK for Model Context Protocol servers and clients

What it is

MCP Python SDK – 一个实现了 Model Context Protocol (MCP) 的 Python 库。MCP 是一种标准化的方式,让大型语言模型 (LLM) 应用通过类似 Web API 的协议来与外部服务(工具、资源、提示词)进行通信。

What you can do with it

  • Write MCP servers:只需几行 Python 代码即可编写 MCP 服务器。通过对类型注解的函数进行装饰,您可以将其暴露为 LLM 可以调用的 tools(可调用动作)或 resources(模板化 URL)
  • Write MCP clients:编写能够通过任何支持的传输方式(stdio, Streamable HTTP, Server-Sent Events)调用这些工具/resources 的 MCP 客户端。客户端会处理架构生成、请求/响应编码,并返回结构化结果。
  • Use the bundled CLI (mcp dev, mcp run, mcp install):使用内置的 CLI 进行快速开发、本地测试和 MCP 包的安装。

How it works (high-level)

  1. Server side – 您会创建一个 MCPServer 实例,并通过 @mcp.tool()@mcp.resource() 装饰函数。SDK 会提取 Python 类型提示和 docstrings,自动构建 JSON-Schema 描述,然后通过所选的传输方式提供服务。
  2. Transport layer – MCP 支持三种标准传输方式:
    • stdio – 适用于将服务器嵌入到子进程中。
    • Streamable HTTP – 一个轻量级的 HTTP 端点,用于流式传输消息。
    • SSE – Server-Sent Events,用于推送式通信。
  3. Client sideClient 对象连接到服务器 URL(或 stdio 子进程)并提供 call_tool(name, args) 等方法,返回一个带有 structured_content 的响应对象。

Who might use it

  • LLM application developers:需要一个干净、有类型的接口来向 LLM 暴露自定义工具(例如:计算器、数据库查询)的开发者。
  • Platform builders:正在创建可复用的 LLM 兼容性服务市场的人员。
  • Researchers:正在正在进行 LLM 与外部代码之间新交互模式的原型设计研究人员。

Getting started (quick example)

# server.py
from mcp.server import MCPServer

mcp = MCPServer("Demo")

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

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

本地运行:

uv run mcp dev server.py   # starts a dev server (streamable-http by default)

客户端端:

import asyncio
from mcp import Client

async def main():
    async with Client("http://localhost:8000/mcp") as client:
        res = await client.call_tool("add", {"a": 1, "b": 2})
        print(res.structured_content)  # → {'result': 3}

asyncio.run(main())

Documentation & resources

License

MIT – 免费使用、修改和分发。


All details are taken directly from the repository's README.

相关

  • 项目
  • 项目
  • 项目
  • 项目
  • 项目