数学运算API与MCP服务器
一个集成了MCP(模型上下文协议)服务器的FastAPI应用程序,用于执行基本的数学运算。该项目同时以REST API和MCP工具的形式提供了加法和减法运算功能,供AI应用使用。
项目结构
MCP/
├── main.py # FastAPI application with routers
├── mcp_server.py # MCP server for AI applications
├── mcp.json # MCP configuration example
├── requirements.txt # Python dependencies
├── README.md # This file
└── api/
├── __init__.py # Python package marker
├── add.py # Addition API endpoint
└── subtract.py # Subtraction API endpoint特点/功能
- FastAPI REST API用于数学运算的传统REST端点
- MCP服务器将操作作为人工智能应用(如Claude Desktop等)的工具进行展示
- 基于路由器的架构整洁、可扩展的代码组织
- 类型安全用于请求/响应验证的 Pydantic 模型
安装
先决条件
- Python 3.10 或更高版本
uv包管理器(推荐)或pip
安装依赖项
使用 uv:
uv pip install -r requirements.txt使用 pip:
pip install -r requirements.txt使用方法
1. 运行FastAPI服务器
启动REST API服务器:
python main.py服务器将在以下地址可用:
- API基础:
http://localhost:8000 - 交互式文档:
http://localhost:8000/docs - 添加端点:
POST http://localhost:8000/api/add - 减法终点:
POST http://localhost:8000/api/subtract
示例API请求
加两个数:
curl -X POST "http://localhost:8000/api/add" \
-H "Content-Type: application/json" \
-d '{"a": 10.5, "b": 5.5}'减去两个数:
curl -X POST "http://localhost:8000/api/subtract" \
-H "Content-Type: application/json" \
-d '{"a": 20.0, "b": 5.5}'2. 运行MCP服务器
MCP服务器允许AI应用程序将数学运算作为工具来使用。
在本地测试MCP服务器
您可以使用MCP Inspector工具测试MCP服务器:
- 安装MCP检查器:
npm install -g @modelcontextprotocol/inspector- 运行检查器:
mcp-inspector uv run mcp_server.py- 在网页界面中测试工具:
- 打开检查器提供的URL(通常 http://localhost:5173) - 你会看到可用的工具: add 并且 subtract - 点击工具以使用示例输入进行测试 - 实时查看回复
使用 stdio 的替代测试
你也可以直接通过标准输入输出(stdio)测试MCP服务器:
uv run mcp_server.py然后手动发送JSON-RPC请求。示例:
{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}
{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "add", "arguments": {"a": 10, "b": 5}}}与人工智能应用的集成
对于Claude Desktop:
- 找到您的Claude桌面配置文件:
- Windows: %APPDATA%\Claude\claude_desktop_config.json - macOS(苹果电脑操作系统): ~/Library/Application Support/Claude/claude_desktop_config.json - Linux(发音近似“林克斯”): ~/.config/Claude/claude_desktop_config.json
- 添加MCP服务器配置:
{
"mcpServers": {
"math-operations": {
"command": "uv",
"args": [
"run",
"mcp_server.py"
],
"cwd": "d:\\Projects\\MCP",
"env": {}
}
}
}重要的配置注意事项:
cwd(当前工作目录)必须是您项目目录的绝对路径
- Windows:使用双反斜杠 \\ 或者正斜杠 / - macOS/Linux:使用类似绝对路径的方式 /home/user/projects/MCP
command要运行的可执行文件(uv,python等args传递给命令的参数env可选的环境变量(空对象{}(对于无者)
- 验证配置:
- 这个(或“它”) cwd 路径必须存在且包含 mcp_server.py - 确保 uv 已安装并且可通过您的 PATH 访问 - 在Windows系统上,您可以通过运行以下命令来验证路径: dir "d:\Projects\MCP\mcp_server.py" - 在 macOS/Linux 上,使用以下命令验证: ls -la /path/to/MCP/mcp_server.py
- 完全重启Claude桌面版:
- 完全关闭Claude桌面程序(检查系统托盘/菜单栏) - 重新打开Claude桌面版 - 数学运算工具现在应该会出现
- 验证连接:
- 在Claude Desktop中,检查设置或工具面板 - 查找“math-operations”服务器状态(应显示为已连接) - 如果出现错误,请检查日志(参见故障排除部分)
对于其他人工智能应用:
大多数兼容MCP的人工智能应用都使用类似的配置。从(某处)复制 mcp.json 翻译为中文是“MCP配置文件(或数据)”。这里,“mcp”可能代表某个特定的名称或缩写,具体含义需根据上下文确定,但“.json”明确表示这是一个JSON格式的文件。因此,整体翻译为“MCP配置文件(或数据)”是合理的 并适应:
对于Cline/VSCode: 在您的VSCode设置或Cline配置中添加:
{
"cline.mcpServers": {
"math-operations": {
"command": "uv",
"args": ["run", "mcp_server.py"],
"cwd": "/absolute/path/to/MCP"
}
}
}对于Continue.dev: 添加到 ~/.continue/config.json:
{
"mcpServers": [
{
"name": "math-operations",
"command": "uv",
"args": ["run", "mcp_server.py"],
"cwd": "/absolute/path/to/MCP"
}
]
}MCP 工具文档
工具: add
将两个数字相加。
参数:
a(数字,必填):要相加的第一个数字b(数字,必填):要相加的第二个数字
返回值:
resulta和b的和operation“addition” 翻译成中文是“增加”或“附加”inputs输入值
示例:
{
"a": 10.5,
"b": 5.5
}回答:
Result: 16.0
Operation: addition
Inputs: a=10.5, b=5.5工具: subtract
从a中减去b。
参数:
a(数字,必填):要从中减去的数字b(数字,必填):要减去的数字
返回值:
result差值(a - b)operation“减法”inputs输入值
示例:
{
"a": 20.0,
"b": 5.5
}回答:
Result: 14.5
Operation: subtraction
Inputs: a=20.0, b=5.5测试与验证
1. 测试 FastAPI 端点
使用Python requests库:
import requests
# Test add endpoint
response = requests.post(
"http://localhost:8000/api/add",
json={"a": 10.5, "b": 5.5}
)
print(response.json())
# Test subtract endpoint
response = requests.post(
"http://localhost:8000/api/subtract",
json={"a": 20.0, "b": 5.5}
)
print(response.json())使用交互式文档:
- 导航至
http://localhost:8000/docs - 点击一个端点以展开它
- 点击“试用一下”
- 输入测试值
- 点击“执行”
2. 测试MCP服务器
方法1:使用MCP Inspector(推荐)
# Install inspector globally
npm install -g @modelcontextprotocol/inspector
# Launch inspector with your MCP server
mcp-inspector uv run mcp_server.py
# Open browser to http://localhost:5173
# Test tools interactively方法2:手动stdio测试
# Run the server
uv run mcp_server.py
# In another terminal, send test requests
echo '{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "test", "version": "1.0"}}}' | uv run mcp_server.py方法3:使用Python MCP客户端
import asyncio
from mcp.client.stdio import stdio_client
async def test_mcp():
async with stdio_client("uv", ["run", "mcp_server.py"]) as (read, write):
# Test listing tools
tools = await read.list_tools()
print("Available tools:", tools)
# Test calling add
result = await read.call_tool("add", {"a": 10, "b": 5})
print("Add result:", result)
asyncio.run(test_mcp())3. 验证Claude桌面集成
配置完Claude Desktop后:
- 检查服务器状态:
- 打开Claude桌面设置 - 查找MCP服务器部分 - 验证“math-operations”显示为“已连接”(绿色指示器)
- 测试工具:
- 在Claude桌面版中开始新对话 - 问:“你能帮我算一下15加25是多少吗?” - 克劳德应该使用 add 来自您MCP服务器的工具 - 检查响应中是否包含工具使用指标
- 查看日志:
- Windows: %APPDATA%\Claude\logs\mcp-*.log - macOS(苹果电脑操作系统): ~/Library/Logs/Claude/mcp-*.log - Linux(发音近似“林克斯”): ~/.config/Claude/logs/mcp-*.log
发展
添加新操作
添加新的数学运算(例如,乘法、除法):
- 创建API端点 在里面
api/multiply.py:
from fastapi import APIRouter
from pydantic import BaseModel
router = APIRouter()
class MultiplyRequest(BaseModel):
a: float
b: float
class MultiplyResponse(BaseModel):
result: float
operation: str
inputs: dict
@router.post("/multiply", response_model=MultiplyResponse)
def multiply_numbers(request: MultiplyRequest):
result = request.a * request.b
return MultiplyResponse(
result=result,
operation="multiplication",
inputs={"a": request.a, "b": request.b}
)- 在main.py中添加路由器:
from api.multiply import router as multiply_router
app.include_router(multiply_router, prefix="/api", tags=["Math Operations"])- 在 mcp_server.py 中添加 MCP 工具:
更新 list_tools():
Tool(
name="multiply",
description="Multiply two numbers together. Returns the product of a and b.",
inputSchema={
"type": "object",
"properties": {
"a": {"type": "number", "description": "First number to multiply"},
"b": {"type": "number", "description": "Second number to multiply"}
},
"required": ["a", "b"]
}
)更新 call_tool():
elif name == "multiply":
result = a * b
operation = "multiplication"
logger.info(f"Executing multiply: {a} * {b} = {result}")项目依赖关系
- FastAPI用于构建API的现代网络框架
- Uvicorn(注:Uvicorn是一个用于运行ASGI应用的ASGI服务器,常用于Python的异步Web框架中,如FastAPI)用于运行 FastAPI 的 ASGI 服务器
- pydantic(注:这是一个Python库的名称,通常不直接翻译,保持原名)使用Python类型注解进行数据验证
- mcp 翻译成中文是“最小化”或“最小化窗口”(在计算机术语中,常用于描述将窗口缩小到任务栏的操作)。不过,具体含义可能根据上下文有所不同用于AI集成的模型上下文协议SDK
故障排除
MCP服务器问题
问题:Claude Desktop 无法连接到服务器
- 验证配置路径:
# Windows
type "%APPDATA%\Claude\claude_desktop_config.json"
# macOS/Linux
cat ~/Library/Application\ Support/Claude/claude_desktop_config.json- 检查当前工作目录(cwd)路径是否存在:
# Windows
dir "d:\Projects\MCP\mcp_server.py"
# macOS/Linux
ls -la /path/to/MCP/mcp_server.py- 验证是否已安装uv:
uv --version- 手动测试服务器:
cd d:\Projects\MCP
uv run mcp_server.py- 检查Claude Desktop日志:
- 在MCP日志文件中查找错误信息 - 常见问题:路径错误、缺少依赖项、权限错误
问题:工具未在Claude桌面显示
- 完全退出 Claude Desktop(检查系统托盘)
- 验证配置文件中的JSON语法(使用JSONLint.com)
- 确保JSON中没有尾随逗号
- 重启Claude桌面版
- 等待10-30秒进行服务器初始化
问题:“模块未找到”错误
# Reinstall dependencies
cd d:\Projects\MCP
uv pip install -r requirements.txt
# Or using pip
pip install -r requirements.txtFastAPI服务器问题
问题:端口8000已被占用
# Windows - Find and kill process
netstat -ano | findstr :8000
taskkill /PID
/F
# macOS/Linux
lsof -ti:8000 | xargs kill -9问题:导入错误
确保你正在从正确的目录运行:
cd d:\Projects\MCP
python main.py测试问题
问题:MCP Inspector 无法启动
# Update npm and reinstall inspector
npm install -g npm@latest
npm install -g @modelcontextprotocol/inspector --force问题:stdio 通信挂起
- 检查是否有打印语句或日志记录可能干扰标准输入输出(stdio)
- 确保JSON-RPC消息格式正确
- 使用
logger.info()而不是print()用于调试
资源
许可证
此项目仅供教育和开发目的使用,提供时不做任何修改。
做出贡献
欢迎随意扩展此项目,添加更多数学运算或功能!
