MCP Server Demo
一个基于 Python 的 Model Context Protocol (MCP) 服务器示例项目,展示了 MCP 的核心功能。
📖 项目简介
本项目是一个功能完整的 MCP 服务器实现,演示了如何使用 MCP 框架构建智能化工具服务。它提供了以下核心功能:
- 工具(Tools): 提供可执行的函数工具
- 资源(Resources): 动态资源生成和管理
- 提示词(Prompts): 预定义的提示词模板
✨ 功能特性
1. 加法工具 (add)
提供两个整数相加的功能。
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b使用示例:
- 输入:
add(1, 2) - 输出:
3
2. 问候资源 (greeting)
动态生成个性化问候语的资源。
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
"""Get a personalized greeting"""
return f"Hello, {name}!"使用示例:
- 访问资源:
greeting://Alice - 输出:
Hello, Alice!
3. 问候提示词 (greet_user)
生成不同风格的问候提示词。
@mcp.prompt()
def greet_user(name: str, style: str = "friendly") -> str:
"""Generate a greeting prompt"""支持的问候风格:
friendly: 温暖友好的问候formal: 正式专业的问候casual: 轻松随意的问候
🚀 快速开始
环境要求
- Python >= 3.13
- uv 包管理器(推荐)或 pip
安装步骤
- 克隆项目
git clone https://github.com/chengmuxuan-cmyk/mcp_server_dome.git
cd mcp_server_dome- 安装依赖
使用 uv(推荐):
uv sync或使用 pip:
pip install -e .运行服务器
python main.py服务器将启动在 http://127.0.0.1:8000,使用 streamable-http 传输方式。
端点说明:
- MCP 服务端点:
http://127.0.0.1:8000/mcp - ⚠️ 注意:客户端必须连接
/mcp端点,而非根路径
🔧 配置说明
客户端连接配置
如果您使用 MCP 客户端连接此服务器,请确保配置正确:
{
"mcpServers": {
"mcp_server_dome": {
"url": "http://127.0.0.1:8000/mcp"
}
}
}常见问题
1. 端口被占用错误
错误信息:
ERROR: [Errno 10048] error while attempting to bind on address ('127.0.0.1', 8000)解决方案:
# Windows - 查找占用端口的进程
netstat -ano | findstr :8000
# 终止占用进程(替换
为实际进程 ID)
taskkill /F /PID
2. 404 错误
错误信息:
failed to create MCP client: unexpected status code: 404原因: 客户端访问了错误的端点路径
解决方案: 确保客户端连接到 http://127.0.0.1:8000/mcp 而不是 http://127.0.0.1:8000
📦 项目结构
mcp_server_dome/
├── main.py # 主程序入口
├── pyproject.toml # 项目配置和依赖管理
├── README.md # 项目文档
├── .gitignore # Git 忽略文件配置
└── uv.lock # 依赖锁定文件🛠️ 技术栈
- Python: 主要开发语言
- MCP SDK: Model Context Protocol 框架
- FastMCP: MCP 提供的快速开发接口
- uv: 现代化的 Python 包管理器
📝 API 参考
工具(Tools)
| 名称 | 参数 | 返回值 | 描述 |
|---|---|---|---|
add | a: int, b: int | int | 计算两个整数的和 |
资源(Resources)
| URI 模板 | 参数 | 描述 |
|---|---|---|
greeting://{name} | name: str | 获取个性化问候语 |
提示词(Prompts)
| 名称 | 参数 | 默认值 | 描述 |
|---|---|---|---|
greet_user | name: str, style: str | "friendly" | 生成问候提示词 |
🔍 调试技巧
测试服务器是否正常启动
# 启动服务器
python main.py
# 在另一个终端测试端点(需要设置正确的 Accept 头)
curl -H "Accept: text/event-stream" http://127.0.0.1:8000/mcp查看服务器日志
服务器启动后会输出详细日志:
INFO: Started server process [XXXX]
INFO: Waiting for application startup.
INFO: StreamableHTTP session manager started
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000🤝 贡献指南
欢迎提交 Issue 和 Pull Request!
- Fork 本项目
- 创建特性分支 (
git checkout -b feature/AmazingFeature) - 提交更改 (
git commit -m 'Add some AmazingFeature') - 推送到分支 (
git push origin feature/AmazingFeature) - 开启 Pull Request
📄 许可证
本项目采用 MIT 许可证 - 查看 LICENSE 文件了解详情。
🔗 相关链接
📮 联系方式
- 作者: chengmuxuan-cmyk
- 项目地址: https://github.com/chengmuxuan-cmyk/mcp_server_dome
Enjoy coding with MCP! 🎉
