MCP Python SDK部署指南:从开发到生产的完整部署流程

MCP Python SDK部署指南:从开发到生产的完整部署流程

【免费下载链接】python-sdk The official Python SDK for Model Context Protocol servers and clients 【免费下载链接】python-sdk 项目地址: https://gitcode.com/gh_mirrors/pythonsd/python-sdk

1. 引言

MCP(Model Context Protocol)Python SDK是用于构建和部署MCP服务器与客户端的官方工具包。本指南将详细介绍从环境准备到生产部署的完整流程,帮助开发者快速上手并构建稳定可靠的MCP服务。

2. 环境准备

2.1 系统要求

部署MCP Python SDK需要满足以下系统要求:

  • Python 3.8+
  • 操作系统:Linux/macOS/Windows
  • 网络环境:可访问互联网(用于安装依赖)

2.2 安装依赖管理工具

MCP项目推荐使用uv作为依赖管理工具,它比传统的pip更快且更可靠:

# 安装uv
curl -LsSf https://astral.sh/uv/install.sh | sh

2.3 获取项目代码

通过以下命令克隆项目仓库:

git clone https://gitcode.com/gh_mirrors/pythonsd/python-sdk.git
cd python-sdk

3. 开发环境部署

3.1 项目结构概览

MCP Python SDK的项目结构如下:

python-sdk/
├── docs/           # 文档
├── examples/       # 示例代码
│   ├── clients/    # 客户端示例
│   ├── servers/    # 服务器示例
│   └── snippets/   # 代码片段
├── src/            # 源代码
└── tests/          # 测试代码

3.2 安装项目依赖

在项目根目录执行以下命令安装依赖:

uv install

3.3 运行示例服务器

MCP提供了多种服务器示例,以simple-auth服务器为例:

# 进入simple-auth服务器目录
cd examples/servers/simple-auth

# 安装示例依赖
uv install

# 启动授权服务器
uv run mcp-simple-auth-as --port=9000

在另一个终端窗口启动资源服务器:

# 进入simple-auth服务器目录
cd examples/servers/simple-auth

# 启动资源服务器
uv run mcp-simple-auth-rs --port=8001 --auth-server=http://localhost:9000 --transport=streamable-http

4. 服务器开发

4.1 创建简单资源服务器

以下是一个简单的资源服务器实现,它提供静态文本资源:

# 代码来源: examples/servers/simple-resource/mcp_simple_resource/server.py
import anyio
import click
import mcp.types as types
from mcp.server.lowlevel import Server
from mcp.server.lowlevel.helper_types import ReadResourceContents
from pydantic import AnyUrl, FileUrl
from starlette.requests import Request

SAMPLE_RESOURCES = {
    "greeting": {
        "content": "Hello! This is a sample text resource.",
        "title": "Welcome Message",
    },
    "help": {
        "content": "This server provides a few sample text resources for testing.",
        "title": "Help Documentation",
    },
    "about": {
        "content": "This is the simple-resource MCP server implementation.",
        "title": "About This Server",
    },
}

@click.command()
@click.option("--port", default=8000, help="Port to listen on for SSE")
@click.option(
    "--transport",
    type=click.Choice(["stdio", "sse"]),
    default="stdio",
    help="Transport type",
)
def main(port: int, transport: str) -> int:
    app = Server("mcp-simple-resource")

    @app.list_resources()
    async def list_resources() -> list[types.Resource]:
        return [
            types.Resource(
                uri=FileUrl(f"file:///{name}.txt"),
                name=name,
                title=SAMPLE_RESOURCES[name]["title"],
                description=f"A sample text resource named {name}",
                mimeType="text/plain",
            )
            for name in SAMPLE_RESOURCES.keys()
        ]

    @app.read_resource()
    async def read_resource(uri: AnyUrl):
        if uri.path is None:
            raise ValueError(f"Invalid resource path: {uri}")
        name = uri.path.replace(".txt", "").lstrip("/")

        if name not in SAMPLE_RESOURCES:
            raise ValueError(f"Unknown resource: {uri}")

        return [ReadResourceContents(content=SAMPLE_RESOURCES[name]["content"], mime_type="text/plain")]

    # 启动服务器代码省略...

if __name__ == "__main__":
    main()

4.2 创建工具服务器

以下是一个简单的工具服务器实现,它提供网页抓取功能:

# 代码来源: examples/servers/simple-tool/mcp_simple_tool/server.py
from typing import Any

import anyio
import click
import mcp.types as types
from mcp.server.lowlevel import Server
from mcp.shared._httpx_utils import create_mcp_http_client
from starlette.requests import Request


async def fetch_website(
    url: str,
) -> list[types.ContentBlock]:
    headers = {"User-Agent": "MCP Test Server (github.com/modelcontextprotocol/python-sdk)"}
    async with create_mcp_http_client(headers=headers) as client:
        response = await client.get(url)
        response.raise_for_status()
        return [types.TextContent(type="text", text=response.text)]


@click.command()
@click.option("--port", default=8000, help="Port to listen on for SSE")
@click.option(
    "--transport",
    type=click.Choice(["stdio", "sse"]),
    default="stdio",
    help="Transport type",
)
def main(port: int, transport: str) -> int:
    app = Server("mcp-website-fetcher")

    @app.call_tool()
    async def fetch_tool(name: str, arguments: dict[str, Any]) -> list[types.ContentBlock]:
        if name != "fetch":
            raise ValueError(f"Unknown tool: {name}")
        if "url" not in arguments:
            raise ValueError("Missing required argument 'url'")
        return await fetch_website(arguments["url"])

    @app.list_tools()
    async def list_tools() -> list[types.Tool]:
        return [
            types.Tool(
                name="fetch",
                title="Website Fetcher",
                description="Fetches a website and returns its content",
                inputSchema={
                    "type": "object",
                    "required": ["url"],
                    "properties": {
                        "url": {
                            "type": "string",
                            "description": "URL to fetch",
                        }
                    },
                },
            )
        ]

    # 启动服务器代码省略...

if __name__ == "__main__":
    main()

5. 客户端开发

5.1 简单认证客户端

MCP提供了simple-auth-client示例,演示如何与认证服务器交互:

# 进入simple-auth-client目录
cd examples/clients/simple-auth-client

# 安装依赖
uv install

# 运行客户端
MCP_SERVER_PORT=8001 MCP_TRANSPORT_TYPE=streamable-http uv run mcp-simple-auth-client

5.2 客户端API使用

以下是使用MCP客户端API的基本示例:

# 代码来源: examples/snippets/clients/completion_client.py
from mcp.client import MCPClient

async def main():
    # 创建客户端
    client = MCPClient("http://localhost:8001", transport_type="streamable-http")
    
    # 调用工具
    result = await client.call_tool("fetch", {"url": "https://example.com"})
    print(result)
    
    # 获取资源
    resource = await client.read_resource("resource://greeting")
    print(resource)

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

6. 测试与调试

6.1 运行测试

MCP项目提供了完整的测试套件,运行以下命令执行测试:

# 在项目根目录执行
uv test

6.2 调试服务器

使用以下命令启动带调试功能的服务器:

uv run --debug mcp-simple-auth-as --port=9000

7. 生产环境部署

7.1 配置生产环境

生产环境需要修改以下配置:

  1. 禁用调试模式
  2. 配置日志级别
  3. 设置适当的超时时间
  4. 配置HTTPS

7.2 使用Gunicorn作为WSGI服务器

在生产环境中,推荐使用Gunicorn作为WSGI服务器:

# 安装Gunicorn
uv add gunicorn

# 启动服务器
gunicorn --workers 4 --bind 0.0.0.0:8000 "src.mcp.server.fastmcp.server:create_app()"

7.3 使用Nginx作为反向代理

配置Nginx作为反向代理,提供负载均衡和SSL终止:

server {
    listen 443 ssl;
    server_name mcp.example.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    location / {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

7.4 部署架构

生产环境推荐的部署架构如下:

mermaid

7.5 安全最佳实践

生产环境部署需遵循以下安全最佳实践:

  1. 使用HTTPS加密传输
  2. 实施适当的认证和授权机制
  3. 定期更新依赖包
  4. 限制服务器暴露的端口和服务
  5. 配置适当的防火墙规则

8. 监控与维护

8.1 日志配置

MCP使用Python标准日志模块,可在生产环境中配置如下:

# 代码来源: src/mcp/server/fastmcp/utilities/logging.py
import logging
from logging.config import dictConfig

def configure_logging(log_level: str = "INFO"):
    dictConfig({
        "version": 1,
        "formatters": {
            "default": {
                "format": "%(asctime)s %(levelname)s %(name)s: %(message)s",
            }
        },
        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "formatter": "default",
            },
            "file": {
                "class": "logging.handlers.RotatingFileHandler",
                "formatter": "default",
                "filename": "mcp.log",
                "maxBytes": 1024 * 1024 * 10,  # 10MB
                "backupCount": 5,
            }
        },
        "root": {
            "level": log_level,
            "handlers": ["console", "file"],
        },
    })

8.2 性能监控

使用Prometheus和Grafana监控MCP服务性能:

  1. 安装Prometheus客户端:
uv add prometheus-client
  1. 添加监控代码:
from prometheus_client import Counter, start_http_server

# 定义指标
REQUEST_COUNT = Counter('mcp_requests_total', 'Total MCP requests')

# 在请求处理函数中增加计数
@server.tool()
async def my_tool(param: str) -> str:
    REQUEST_COUNT.inc()
    # 工具实现...

# 启动监控服务器
start_http_server(8000)

9. 常见问题解决

9.1 连接问题

如果客户端无法连接服务器,请检查:

  1. 服务器是否正常运行
  2. 防火墙是否允许端口访问
  3. 服务器地址和端口是否正确

9.2 认证失败

认证失败可能的原因:

  1. 令牌过期 - 需要重新获取令牌
  2. 权限不足 - 检查客户端权限配置
  3. 服务器配置错误 - 检查认证服务器配置

9.3 性能问题

解决性能问题的方法:

  1. 增加服务器资源
  2. 优化数据库查询
  3. 启用缓存
  4. 水平扩展服务

10. 结论

本指南详细介绍了MCP Python SDK的部署流程,从开发环境搭建到生产环境部署。通过遵循这些步骤,开发者可以快速构建和部署可靠的MCP服务。更多高级功能和最佳实践,请参考官方文档和示例代码。

官方文档:docs/index.md API参考:src/mcp/server/fastmcp/server.py 示例代码:examples/

【免费下载链接】python-sdk The official Python SDK for Model Context Protocol servers and clients 【免费下载链接】python-sdk 项目地址: https://gitcode.com/gh_mirrors/pythonsd/python-sdk

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值