Python MCP服务器模板

一个用于构建Python MCP服务器的生产就绪的启动模板,旨在成为干净、可维护和可扩展代码库的典范。

  • by unrealandychan
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 unrealandychan/mcp-server-template-python

使用说明


Python MCP服务器模板

A. 生产就绪 建筑起始模板 模型上下文协议(MCP) Python服务器,旨在成为 榜样 用于干净、可维护和可扩展的代码库。


目录


特性

  • ✅ src 布局 –使用Hatchling构建后端进行适当的Python打包
  • ✅ FastMCP –具有完整类型支持的现代MCP服务器框架
  • ✅ Pydantic v2配置 –强类型、环境驱动的配置
  • ✅ 结构化日志记录 –旋转文件+控制台日志记录,通过env进行级别控制
  • ✅ 类型CLI – mcp-server start / mcp-server version 在丰富的帮助下
  • ✅ 内置工具库 –实用程序、数学、文本和日期时间工具模块
  • ✅ 完整的测试套件 –pytest具有覆盖率,可用于CI
  • ✅ GitHub操作CI –皮棉→ test → 建立在每一次推/公关之上
  • ✅ GitHub操作发布 –自动化TestPyPI→ PyPI上的版本标签推送
  • ✅ scripts/publish.sh –local一个命令发布助手

项目结构

mcp-server-template-python/
├── src/
│   └── mcp_server/
│       ├── __init__.py            # Package version & public API
│       ├── main.py                # Server entry point & tool registration
│       ├── cli.py                 # Typer CLI (start / version)
│       ├── config/
│       │   ├── __init__.py
│       │   └── config.py          # Pydantic config models + load_config()
│       ├── tools/
│       │   ├── __init__.py
│       │   ├── utility.py         # Echo, Ping, Server Info
│       │   ├── math_tools.py      # Add, Subtract, Multiply, Divide, Power, √, !
│       │   ├── text_tools.py      # Upper/Lower, Reverse, Word Count, Emails …
│       │   └── datetime_tools.py  # UTC time, timezone, date arithmetic …
│       └── utils/
│           ├── __init__.py
│           └── logging.py         # Rotating-file + console logging setup
├── tests/
│   ├── __init__.py
│   ├── test_config.py
│   ├── test_logging.py
│   ├── test_main.py
│   ├── test_tools_utility.py
│   ├── test_tools_math.py
│   ├── test_tools_text.py
│   └── test_tools_datetime.py
├── examples/
│   └── basic_usage.py             # Minimal runnable example
├── docs/
│   └── README.md                  # Extended documentation
├── scripts/
│   └── publish.sh                 # Local PyPI publish helper
├── .github/
│   └── workflows/
│       ├── ci.yml                 # Lint → Test → Build
│       └── publish.yml            # Publish to TestPyPI → PyPI on tag
├── .env.example                   # Environment variable reference
├── pyproject.toml                 # PEP 621 metadata + Hatchling build
├── CHANGELOG.md
├── CONTRIBUTING.md
└── LICENSE

快速开始

1–安装

# Clone
git clone https://github.com/your-username/mcp-server-template-python.git
cd mcp-server-template-python

# Create & activate a virtual environment
python -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate

# Install in editable mode (dev extras include pytest, ruff, mypy, black…)
pip install -e ".[dev]"

# Copy and configure env
cp .env.example .env

2–跑步

# HTTP transport (default)
mcp-server start

# stdio transport (for Claude Desktop / Cursor integration)
mcp-server start --transport stdio

# Custom host / port
mcp-server start --host 127.0.0.1 --port 9000

3–验证

# Check version
mcp-server version

# Run as a Python module
python -m mcp_server.main

配置

所有设置均从环境变量中读取(.env 自动加载)。

变量 默认值 描述
APP_NAME mcp_server 服务器名称
HOST 0.0.0.0 绑定主机
PORT 8000 绑定端口
DEBUG false 启用调试模式
TRANSPORT streamable-http 运输(stdio, streamable-http, sse)
LOG_LEVEL INFO 日志级别
LOG_FORMAT %(asctime)s - %(name)s - %(levelname)s - %(message)s 日志格式
LOG_FILE_ENABLED true 将日志写入文件
LOG_FILE_DIR logs 日志文件目录
API_KEY_ENABLED false 启用API密钥身份验证
API_KEY (未设置) API关键值
CORS_ORIGINS * 逗号分隔的允许来源

可用工具

效用

工具名称 描述
hello-world 返回给定名字的问候语
Echo Message 返回消息不变
Get Server Info 返回服务器名称、版本、描述
Ping 健康检查-退货 "pong"

数学

工具名称 描述
Add Numbers a ____ b
Subtract Numbers a−b
Multiply Numbersa ____ b
Divide Numbers a÷b(零除数上调)
Power 基数指数
Square Root √值
Factorial n

文本

工具名称 描述
Uppercase Text 转换为大写
Lowercase Text 转换为小写
Reverse Text 反转字符串
Count Words 统计文本中的单词
Count Characters 计算字符数(可选择排除空格)
Title Case 转换为标题案例
Split Text 按分隔符拆分
Replace Text 替换所有事件
Trim Text 去掉前导/尾随空格
Extract Emails 在文本中查找所有电子邮件地址

日期时间

工具名称 描述
Current UTC Time ISO 8601中的当前UTC日期时间
Current Date ISO 8601中的今天日期(UTC)
Time In Timezone 给定IANA时区的当前时间
Add Days To Date 从日期中添加/减去天数
Days Between Dates 计算两个日期之间的天数
Format Datetime 使用strftime重新格式化ISO日期时间

CLI 参考

mcp-server --help

Commands:
  start    Start the MCP server
  version  Display the current version

mcp-server start --help

Options:
  -h, --host        Host to bind the server to  [default: 0.0.0.0]
  -p, --port        Port to bind the server to  [default: 8000]
  -t, --transport   Transport protocol           [default: streamable-http]
  -d, --debug       Enable debug mode
  -l, --log-level   Log level                   [default: INFO]

运行测试

# All tests
pytest

# With coverage
pytest --cov=src/mcp_server --cov-report=term-missing

# Single module
pytest tests/test_tools_math.py -v

添加新工具

  1. 创建 src/mcp_server/tools/<category>_tools.py.
  2. 实施 register_<category>_tools(mcp_instance: FastMCP) -> None.
  3. 添加注册呼叫 src/mcp_server/main.py.
  4. 出口自 src/mcp_server/tools/__init__.py.
  5. 在中编写测试 tests/test_tools_<category>.py.

看 贡献.md 获取完整的框架和指导方针。


发布到PyPI

自动(推荐)

推送版本标签以触发GitHub Actions发布工作流:

# Bump version in pyproject.toml and src/mcp_server/__init__.py first, then:
git commit -am "chore: release v0.2.0"
git tag v0.2.0
git push origin main --tags

工作流发布到 TestPyPI 首先,然后推广到 PyPI.
您必须配置 可信发布 (OIDC)-不需要API令牌。

看 PyPI可信发布文档 用于设置。

手册

# Build only (no upload)
./scripts/publish.sh --build-only

# Upload to TestPyPI
./scripts/publish.sh --test

# Upload to PyPI
./scripts/publish.sh

贡献

欢迎投稿!请阅读 贡献.md 在打开PR之前。


许可证

麻省理工学院 ©你的名字