MCP服务器模板

一个用于构建连接Claude AI与外部API的MCP服务器的Cookiecutter模板,支持多平台兼容、多种认证方式、速率限制和一键部署。

  • by pietroperona
  • Python
  • 本地部署
  • 16 星标
  • 更新于
在 GitHub 查看 pietroperona/mcp-server-template

使用说明



一个实用的Cookiecutter模板,用于构建将Claude AI连接到外部API的MCP服务器。使用FastMCP构建,可用于Render.com部署。

主要特点

  • 多平台兼容性:与Claude Desktop、Claude Web和Claude API一起使用
  • 全面的身份验证支持:API密钥、承载令牌、OAuth2、基本身份验证
  • 速率限制:可配置的请求节流以避免API限制
  • 即用型工具:6个预先构建的通用API工具,适用于任何服务
  • 一键部署:Render.com与预配置设置的集成
  • Docker支持:云部署的容器化(欢迎社区测试)
  • 稳健的错误处理:详细的错误报告和恢复
  • 可测试组件:每个模块都可以独立测试
  • 会话管理:防止“事件循环已关闭”错误

这有什么作用

这个模板生成一个完整的MCP服务器项目,让Claude AI与任何API交互。将其视为Claude和您要使用的外部服务之间的桥梁。

示例场景:

  • 气象服务提供的天气数据
  • 新闻API中的新闻标题
  • 金融数据提供商的股票价格
  • 来自平台API的社交媒体帖子
  • 来自市场API的电子商务数据

技术栈

需求:Python 3.11或更高版本

快速开始

1.生成您的项目

pip install cookiecutter
cookiecutter https://github.com/pietroperona/mcp-server-template

你会被问到几个问题:

project_name: News API Server
project_slug: news-api-server  [auto-generated]
author_name: Your Name
author_email: you@example.com
github_username: yourusername
api_base_url: https://newsapi.org/v2
api_service_type: REST API
auth_type: API Key
include_rate_limiting: yes
include_caching: no
render_deployment: yes
docker_support: yes
license: MIT

2.配置您的API

cd news-api-server
cp .env.example .env

编辑 .env 使用您的API证书:

API_BASE_URL=https://newsapi.org/v2
API_KEY=your_news_api_key

3.安装并运行

pip install -r requirements.txt
python main.py

您的MCP服务器现在正在运行 http://localhost:8000

4.连接到克劳德桌面

将此添加到您的Claude Desktop MCP配置中:

{
  "mcpServers": {
    "news-api": {
      "command": "python",
      "args": ["news-api-server/main.py"],
      "cwd": "news-api-server"
    }
  }
}

现在克劳德可以获取新闻了: “最新的科技头条是什么?”

5.连接到克劳德网络浏览器(Claude.ai)

您的MCP服务器还公开了一个SSE(服务器发送事件)端点,位于 /sse 它可以在浏览器中与Claude Web一起使用:

  1. 将MCP服务器部署到公共URL(请参阅部署部分)
  2. 在Claude Web中,转到设置→ Claude API工具
  3. 添加MCP服务器的公共URL+ /sse 端点:
    https://your-mcp-server.onrender.com/sse
    
  4. Claude Web现在将在“工具”菜单中显示您的工具

备注:The /sse 端点会自动包含在使用此模板生成的所有MCP服务器中。

所得

每个生成的项目包括:

6现成工具

  • get_api_status -检查您的API是否正常工作
  • list_resources -浏览可用数据(文章、用户、产品等)
  • get_resource_by_id -获取特定商品详细信息
  • create_resource -添加新数据
  • update_resource -修改现有数据
  • delete_resource -删除数据

真实示例:新闻API

当你问克劳德 “显示最新的技术新闻”,事情是这样的:

  1. 克劳德打电话来 list_resources(resource_type="articles", category="technology")
  2. 您的MCP服务器点击 https://newsapi.org/v2/everything?q=technology
  3. 克劳德获取新闻数据,并以格式化的文章作为回应

项目结构

news-api-server/
├── core/
│   ├── config.py     # API credentials & settings
│   ├── auth.py       # Handle API authentication  
│   └── client.py     # HTTP client with retries
├── tools/
│   └── example_tools.py  # The 6 MCP tools
├── docs/             # Setup guides & troubleshooting
│   ├── configuration.md  # Detailed configuration options
│   ├── quick-start.md    # Getting started guide
│   ├── README.md         # Overview of documentation
│   └── troubleshooting.md # Common issues & solutions
├── main.py          # FastMCP server
└── .env.example     # Configuration template

注意:当您的服务器运行时,它可能会创建以结尾的目录 _data/ (比如 cache_data/).这些目录通过以下方式自动从git中排除 .gitignore 因为它们包含不应该提交的运行时数据。

身份验证支持

该模板处理不同的身份验证方法:

API密钥 (最常见)

API_KEY=your_key_here
API_KEY_HEADER=X-API-Key

承载令牌

BEARER_TOKEN=your_token_here

OAuth2 (适用于复杂的API)

CLIENT_ID=your_client_id
CLIENT_SECRET=your_client_secret

基本认证

USERNAME=your_username  
PASSWORD=your_password

生产部署

Render.com(推荐)

  1. 将生成的项目推送到GitHub
  2. 连接到Render.com
  3. 设置环境变量
  4. 您的MCP服务器已上线!

模板包括 render.yaml 优化了生产设置。

对Claude Web浏览器很重要: 确保记下已部署服务的公共URL。Claude Web将通过以下方式连接到您的MCP服务器 /sse 端点:

https://your-service-name.onrender.com/sse

码头工人

备注:Docker支持包含在模板中,但尚未经过广泛测试。欢迎社区反馈和贡献。

docker build -t my-mcp-server .
docker run -p 8000:8000 --env-file .env my-mcp-server

对于克劳德·韦伯:访问SSE端点 http://your-docker-host:8000/sse

真实世界的例子

新闻头条服务

# Generate project
cookiecutter https://github.com/pietroperona/mcp-server-template
# Project: News API Server
# API: NewsAPI.org (free tier)
# Result: Claude can fetch latest news by category/keyword

试试看: 新闻API.org -1000个免费请求/天

气象局

# Generate project
cookiecutter https://github.com/pietroperona/mcp-server-template
# Project: Weather API Server
# API: OpenWeatherMap (free)
# Result: Claude can check weather worldwide

试试看: OpenWeatherMap -每天1000次呼叫的免费API

股市数据

# Generate project
cookiecutter https://github.com/pietroperona/mcp-server-template  
# Project: Stock Market Server
# API: Alpha Vantage (free)
# Result: Claude can look up stock prices and market data

试试看: 阿尔法Vantage -免费API密钥,5次调用/分钟

社交媒体整合

# Generate project
cookiecutter https://github.com/pietroperona/mcp-server-template
# Project: Social Media Server
# API: Twitter/X API (paid)
# Result: Claude can post tweets and read social media feeds

详细设置示例

让我们逐步构建一个新闻API服务器:

1.获取新闻API密钥

  • 首选 newsapi.org
  • 注册免费帐户
  • 复制API密钥

2.生成项目

cookiecutter https://github.com/pietroperona/mcp-server-template

project_name: News API Server
project_slug: news-api-server  
author_name: John Smith
api_service_type: REST API
auth_type: API Key
api_base_url: https://newsapi.org/v2
include_rate_limiting: yes
render_deployment: yes

3.配置环境

cd news-api-server
cp .env.example .env

编辑 .env:

API_BASE_URL=https://newsapi.org/v2
API_KEY=your_actual_api_key_here
API_KEY_HEADER=X-API-Key

4.测试您的服务器

python main.py

5.与克劳德一起测试

问克劳德: “最新的技术头条是什么?”

克劳德将使用你的工具:

Tool: list_resources
Parameters: resource_type="articles", category="technology"
Result: Latest tech news articles with titles, descriptions, and URLs

定制

为您的API进行修改

生成的工具是通用的,但易于定制:

# In tools/example_tools.py
async def list_resources_async(resource_type: str = "articles", category: str = "general"):
    # Customize this for your API
    endpoint = f"/everything?category={category}"
    response = await client.get(endpoint)
    return response

添加特定于API的工具

@mcp.tool()
def get_headlines_by_category(category: str, country: str = "us") -> str:
    """Get top headlines by category and country"""
    result = run_async_tool(get_headlines_async, category, country)
    return json.dumps(result, indent=2)

配置速率限制

# In .env
RATE_LIMIT_REQUESTS=60    # 60 requests
RATE_LIMIT_WINDOW=60      # per minute

故障排除

身份验证问题

“身份验证失败”

  • 检查您的API密钥是否正确
  • 验证API_KEY_HEADER名称
  • 首先在浏览器/Postman中测试API密钥

工具连接问题

“工具未出现在Claude中”

  • 重新启动克劳德桌面
  • 检查MCP配置语法
  • 验证服务器启动时没有错误

“Claude Web不显示我的工具”

  • 确保你使用的是正确的 /sse 端点
  • 如果托管在自定义域上,请检查CORS设置
  • 验证您的服务器是否可公开访问

API连接问题

“连接超时”

  • 增加.env中的API_TIMEOUT
  • 检查互联网连接
  • 验证API端点URL

“API版本控制问题”

  • 某些API在URL中不使用版本前缀
  • 集 API_VERSION=none 或者在.env文件中将其留空
  • 此模板自动处理无版本API

技术问题

“事件循环已关闭”错误

  • 在最新模板版本(2025年7月)中已修复此问题
  • 该模板现在为aiohttp使用了更好的会话管理方法
  • 每个请求都会创建一个新的会话,并进行适当的清理
  • 自定义事件循环处理可防止这些错误

发展

运行测试

python core/auth.py      # Test authentication
python core/client.py    # Test API connection  
python main.py          # Start MCP server

调试模式

DEBUG=true python main.py

显示详细的请求/响应日志。

会话管理

此模板使用优化的方法来管理aiohttp会话:

# Create a new session for each request (prevents "Event loop is closed" errors)
async with aiohttp.ClientSession() as session:
    async with session.request(...) as response:
        # Process response

此模式可确保:

  • 每个HTTP请求都会获得一个新的会话
  • 使用后会话已正确关闭
  • 未发生“事件循环已关闭”错误
  • 更好地处理异步事件循环

已知限制

  • Docker支持:虽然包含了Dockerfile和docker compose文件,但docker部署尚未在不同环境中进行广泛测试。我们欢迎社区反馈和测试。
  • OAuth2流:OAuth2实现需要手动令牌交换-基于浏览器的自动流尚未实现。

贡献

  1. 叉起 仓库
  2. 使用不同的API类型测试您的更改
  3. 更新文档
  4. 提交拉取请求

为什么是这个模板?

构建MCP服务器涉及很多样板:

  • 身份验证处理
  • 错误管理
  • 速率限制
  • 配置
  • 部署设置

这个模板可以立即为您提供所有这些,因此您可以专注于连接到特定的API。

基于经过验证的工具构建: FastMCP 对于MCP框架, 模型上下文协议 克劳德整合。

使用:

  • 克劳德桌面(通过本地MCP服务器)
  • 克劳德网络浏览器(通过 /sse 端点)
  • Claude API(通过代理配置)

许可证

MIT许可证-用于任何目的,商业或个人。


最近的更新

  • 2025年7月:通过改进aiohttp会话管理修复了“事件循环已关闭”错误
  • 2025年7月:通过以下方式添加了对Claude Web浏览器的支持 /sse 端点
  • 2025年7月:改进了API版本控制,更好地处理了无版本的API
  • 2025年7月:添加了更好的错误处理和故障排除指南

准备好将Claude连接到您最喜欢的API了吗?

pip install cookiecutter
cookiecutter https://github.com/pietroperona/mcp-server-template