内容
# MCP Simple Server
一个最小的、参考 Model Context Protocol 服务器实现,带有可流式传输的 HTTP 传输。使用 FastMCP 构建,遵循官方 Anthropic MCP 规范 2025-06-18。是构建远程 MCP 服务器的完美起点。
## 🎯 Purpose
该项目为希望以下目的的开发者提供了一个简单、文档完善的参考:
- 构建他们的第一个 MCP 服务器
- 将 MCP 服务器部署到云平台 (Railway, Heroku, Render)
- 了解 MCP 协议的实现
- 为更复杂的 MCP 解决方案创建基础
## Features
- ✅ **Two Math Tools**: `add` 和 `multiply` 函数
- ✅ **Streamable HTTP Transport**: 现代 MCP 协议,支持 SSE
- ✅ **Session Management**: 正确的 MCP 初始化流程
- ✅ **Remote Deployment**: Railway, Heroku, Render 部署配置
- ✅ **Automated Testing**: 完整的协议验证和调试工具
- ✅ **Claude Desktop Integration**: 准备好进行 AI 助手集成
- ✅ **Reference Implementation**: 用于学习的文档完善的代码
## Quick Start
### Local Development
```bash
git clone https://github.com/oleksandrsirenko/mcp-simple-server.git
cd mcp-simple-server
uv sync
source .venv/bin/activate
python main.py
```
服务器启动于:`http://localhost:8000/mcp/`
### Test the Server
```bash
python test_server.py
```
预期输出:
```
🧪 Starting MCP Server Tests
✅ Initialize successful - Server: Simple Server
✅ Initialized notification sent
✅ Found 2 tools: add, multiply
✅ Add tool returned correct result
✅ Multiply tool returned correct result
🎉 All tests passed!
```
## Available Tools
### `add(a, b)`
将两个数字相加。
**Example:**
```json
{"name": "add", "arguments": {"a": 25, "b": 17}}
→ Returns: 42
```
### `multiply(a, b)`
将两个数字相乘。
**Example:**
```json
{"name": "multiply", "arguments": {"a": 8, "b": 6}}
→ Returns: 48
```
## Manual Testing with curl
### Local Testing (Development)
用于测试在 `localhost:8000` 上运行的本地开发服务器:
#### 1. Initialize Session
```bash
curl -X POST http://localhost:8000/mcp/ \
-H "Content-Type: application/json" \
-H "MCP-Protocol-Version: 2025-06-18" \
-H "Accept: application/json, text/event-stream" \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{"tools":{}},"clientInfo":{"name":"test-client","version":"1.0.0"}}}'
```
#### 2. Send Initialized Notification
```bash
curl -X POST http://localhost:8000/mcp/ \
-H "Content-Type: application/json" \
-H "MCP-Protocol-Version: 2025-06-18" \
-H "Accept: application/json, text/event-stream" \
-H "Mcp-Session-Id: YOUR_SESSION_ID" \
-d '{"jsonrpc":"2.0","method":"notifications/initialized"}'
```
#### 3. List Tools
```bash
curl -X POST http://localhost:8000/mcp/ \
-H "Content-Type: application/json" \
-H "MCP-Protocol-Version: 2025-06-18" \
-H "Accept: application/json, text/event-stream" \
-H "Mcp-Session-Id: YOUR_SESSION_ID" \
-d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}'
```
#### 4. Call Add Tool
```bash
curl -X POST http://localhost:8000/mcp/ \
-H "Content-Type: application/json" \
-H "MCP-Protocol-Version: 2025-06-18" \
-H "Accept: application/json, text/event-stream" \
-H "Mcp-Session-Id: YOUR_SESSION_ID" \
-d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"add","arguments":{"a":25,"b":17}}}'
```
### Remote Testing (Production)
用于测试已部署的服务器,请将 `localhost:8000` 替换为您的部署 URL:
```bash
# Example with Railway deployment
curl -X POST https://your-app.railway.app/mcp/ \
-H "Content-Type: application/json" \
-H "MCP-Protocol-Version: 2025-06-18" \
-H "Accept: application/json, text/event-stream" \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{"tools":{}},"clientInfo":{"name":"test-client","version":"1.0.0"}}}'
```
**Note**: 对于全面的远程测试,请使用自动化测试脚本:
```bash
python test_deployment.py your-app.railway.app
```
## Deployment
### Railway (Recommended)
1. **Push to GitHub**:
```bash
git add .
git commit -m "ready for deployment"
git push origin main
```
2. **Deploy to Railway**:
- 前往 [railway.app](https://railway.app)
- 点击 "Deploy from GitHub repo"
- 选择您的仓库
- Railway 自动检测 Dockerfile 并进行部署
3. **Test your deployment**:
```bash
python test_deployment.py your-app-name.up.railway.app
```
4. **Your MCP URL**: `https://your-app.railway.app/mcp/`
### Heroku
```bash
heroku create your-mcp-server
git push heroku main
```
**Your MCP URL**: `https://your-mcp-server.herokuapp.com/mcp/`
### Render
1. 将 GitHub 仓库连接到 Render
2. Render 自动检测 `render.yaml` 和 Dockerfile
3. 自动部署
**Your MCP URL**: `https://your-service.onrender.com/mcp/`
### Docker
```bash
docker build -t mcp-simple-server .
docker run -p 8000:8000 mcp-simple-server
```
## Claude Desktop Integration
### Local Server Configuration
```json
{
"mcpServers": {
"simple-server": {
"command": "python",
"args": ["main.py"],
"cwd": "/path/to/mcp-simple-server"
}
}
}
```
### Remote Server Configuration (Recommended)
对于部署到 Railway、Heroku 或 Render 的远程服务器,请使用 `mcp-remote` 包:
```json
{
"mcpServers": {
"simple-server-remote": {
"command": "npx",
"args": [
"-y",
"mcp-remote",
"https://your-app.railway.app/mcp/",
"--allow-http",
"--header",
"Accept: application/json, text/event-stream"
]
}
}
}
```
**Key Configuration Notes:**
- 使用带有 `-y` 标志的 `npx` 自动安装 `mcp-remote`
- 在 URL 中包含尾部斜杠:`/mcp/`
- 添加 `--allow-http` 标志以进行 HTTP 连接
- 包含 Accept 标头以获得正确的 SSE 支持
### Alternative: Direct Python Proxy (Advanced)
对于高级用户或调试目的,您可以创建一个自定义 Python 代理:
```json
{
"mcpServers": {
"simple-server-proxy": {
"command": "python",
"args": ["claude_mcp_proxy.py"],
"cwd": "/path/to/mcp-simple-server"
}
}
}
```
**Note**: 这需要仓库中的 `claude_mcp_proxy.py` 脚本,主要用于调试目的。对于生产环境,请使用 `mcp-remote`。
**Configuration File Locations:**
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
## Test with Claude
集成后,询问 Claude:
- "Can you add 42 and 18 for me?"
- "What's 7 times 9?"
- "What tools do you have available?"
Claude 将使用您的 MCP 服务器来执行计算! 🎉
## Development
### Adding New Tools
```python
@mcp.tool()
def subtract(a: float, b: float) -> float:
"""Subtract two numbers"""
return a - b
@mcp.tool()
def divide(a: float, b: float) -> float:
"""Divide two numbers"""
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
```
### Environment Variables
- `HOST`: 服务器主机(默认值:127.0.0.1,部署时使用 0.0.0.0)
- `PORT`: 服务器端口(默认值:8000,Railway 会自动设置)
```bash
HOST=0.0.0.0 PORT=3000 python main.py
```
注意:对于 Railway 部署,FastMCP 将自动绑定到 `0.0.0.0:$PORT`。
## Project Structure
```
mcp-simple-server/
├── main.py # MCP server (~25 lines)
├── test_server.py # Local server tests (~300 lines)
├── test_deployment.py # Remote deployment tests
├── test_host_binding.py # Host binding tests
├── test_proxy_script.py # Proxy testing script
├── test_streamable_app.py # Streamable HTTP tests
├── test_tool_verification.py # Tool verification tests
├── debug_railway_server.py # Railway debugging utilities
├── debug_fastmcp.py # FastMCP debugging utilities
├── claude_mcp_proxy.py # Claude Desktop proxy (optional)
├── start.sh # Shell startup script
├── pyproject.toml # Project configuration
├── README.md # This documentation
├── uv.lock # Dependency lock file
├── .gitignore # Git ignore patterns
├── .python-version # Python version specification
├── Dockerfile # Docker deployment
├── railway.toml # Railway configuration
├── Procfile # Heroku configuration
└── render.yaml # Render configuration
```
## Architecture
- **FastMCP**: 来自 Anthropic 的高级 MCP 实现
- **Streamable HTTP**: 具有 SSE 流支持的现代传输
- **Session Management**: 具有会话 ID 的有状态连接
- **JSON-RPC 2.0**: 用于消息交换的标准协议
- **Protocol 2025-06-18**: 最新 MCP 规范
- **Port 8000**: 默认 FastMCP 服务器端口(可通过 PORT 环境变量配置)
## Technical Details
### Server Implementation
- **Framework**: FastMCP (官方 Anthropic 库)
- **Transport**: 具有 Server-Sent Events 的可流式 HTTP
- **Protocol**: MCP 2025-06-18 规范
- **Dependencies**: `httpx>=0.28.1`, `mcp>=1.9.4`
### MCP Protocol Flow
1. 客户端发送 `initialize` 请求
2. 服务器响应功能和会话 ID
3. 客户端发送 `initialized` 通知
4. 正常操作开始(tools/list, tools/call 等)
### Tool Response Format
工具返回简单的 Python 值(float、int、str),FastMCP 会自动将其包装在正确的 MCP 响应格式中。
## Troubleshooting
### Server Won't Start
```bash
# Check if port is in use
lsof -i :8000
# Try different port
PORT=3000 python main.py
```
### MCP Protocol Errors
```bash
# Run automated test
python test_server.py
# Check server logs for detailed errors
```
### Claude Desktop Not Connecting
1. **Verify JSON configuration syntax** - 使用 JSON 验证器
2. **Check server URL accessibility** - 使用 `curl` 或浏览器进行测试
3. **Restart Claude Desktop** 在配置更改后
4. **Ensure proper MCP endpoint path** - 使用 `/mcp/` 并带有尾部斜杠
5. **Use `mcp-remote` for remote servers** - 不要使用 `curl` 进行远程连接
### Test Remote Deployment
使用提供的脚本测试已部署的服务器:
```bash
# Test your deployed server (replace with your URL)
python test_deployment.py your-app.railway.app
# Or with full URL
python test_deployment.py https://your-app.railway.app
```
这将针对您的远程服务器运行完整的 MCP 协议测试套件。
### Common Issues
- **Wrong endpoint**: 使用 `/mcp/`(带有尾部斜杠)
- **Missing headers**: 包含所有必需的 MCP 标头
- **Session management**: 必须在 `initialize` 之后发送 `initialized` 通知
- **Remote connections**: 使用 `mcp-remote`,而不是 `curl` 用于 Claude Desktop
- **Port binding**: 使用 `0.0.0.0:$PORT` 进行部署,而不是 `127.0.0.1`
## Dependencies
```toml
dependencies = [
"httpx>=0.28.1", # HTTP client for testing
"mcp>=1.9.4", # Official Anthropic MCP library
]
```
该项目使用:
- **mcp**: 官方 Anthropic MCP Python SDK
- **httpx**: 用于自动化测试的现代 HTTP 客户端
- **Python**: 需要 Python >=3.10
## Contributing
1. Fork the repository
2. Make your changes
3. Run tests: `python test_server.py`
4. Test deployment: `python test_deployment.py your-test-url`
5. Ensure all tests pass
6. Submit a pull request
## License
MIT License
## Resources
- [MCP Specification 2025-06-18](https://modelcontextprotocol.io/specification/2025-06-18/)
- [FastMCP Documentation](https://mcp.so/docs)
- [Claude Desktop](https://claude.ai/download)
- [Railway Deployment](https://railway.app)
- [Render Deployment](https://render.com)
- [mcp-remote Package](https://www.npmjs.com/package/mcp-remote)
连接信息
猜你喜欢
X视频文案提取
X / Twitter 视频文案提取 MCP Server — 专注解析 X 平台公开视频链接(x.com / twitter.com status...
cc-switch
跨平台的Claude Code、Codex和Gemini CLI一体化助手。
awesome-mcp-servers
一组 MCP 服务器。
Git
一个用于Git自动化和交互的模型上下文协议服务器。
oh-my-opencode
背景代理 · 精心挑选的代理,如 oracle、librarians、frontend engineer · 预构建工具,如 LSP/AST ·...
TrendRadar
TrendRadar:30秒内为您提供真实新闻的热点助手。