calc_mcp
by nocodig
README.md
# calc_mcp
通过 stdio 提供加、减、乘、除四种运算的计算器 MCP 服务。
使用 [官方 MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk/tree/v1.x) 的 FastMCP API,依赖限定在 1.x,避免跨主要版本升级导致接口变化。
## 可用工具
所有工具都接收两个必填数值参数 `a`、`b`,支持整数、小数和负数。
| 工具 | 运算 | 调用参数示例 | 结果 |
| --- | --- | --- | --- |
| `add` | `a + b` | `{"a": 2, "b": 3}` | `5.0` |
| `subtract` | `a - b` | `{"a": 2, "b": 5}` | `-3.0` |
| `multiply` | `a * b` | `{"a": -3, "b": 4}` | `-12.0` |
| `divide` | `a / b` | `{"a": 7, "b": 2}` | `3.5` |
成功调用的 `structuredContent` 为 `{"result": 数值}`,并提供兼容的文本内容。工具不读写文件、不访问网络。
错误以 MCP 工具结果的 `isError: true` 返回,不会中断服务:
- 除数为 `0` 或 `-0.0`:`Cannot divide by zero.`
- 参数为 NaN 或无穷大:`Operands must be finite numbers.`
- 结果溢出为无穷大:`Result exceeds the supported finite number range.`
- 缺少参数或传入无法解析的数值:由 SDK 返回参数校验错误。
运算使用 Python 双精度浮点数,存在通常的浮点舍入误差,例如 `0.1 + 0.2` 可能返回 `0.30000000000000004`。不用于需要十进制精确计算的场景;本版本不支持表达式求值。
## 目录结构
```text
calc_mcp/
├── pyproject.toml # 项目、依赖和命令行入口
├── uv.lock # 依赖版本锁定
├── README.md
├── .gitignore
├── src/calc_mcp/
│ ├── __init__.py
│ ├── __main__.py # python -m calc_mcp 入口
│ ├── server.py # MCP 实例和 stdio 启动
│ └── tools.py # 四则运算、边界检查和工具注册
└── tests/
└── test_server.py # 算术单元测试和 stdio 集成测试
```
## 安装与启动
需要 Python 3.10+ 和 uv。在本项目目录执行:
```sh
uv sync
uv run calc-mcp
```
也可以通过模块入口启动:
```sh
uv run python -m calc_mcp
```
服务通过标准输入/输出与 MCP 客户端通信,不提供网页。直接启动后等待客户端消息属于正常现象。不要向 stdout 打印调试信息;日志应写入 stderr。
## MCP 客户端配置示例
以下适用于使用 `mcpServers` JSON 配置格式的客户端,请根据实际客户端调整:
```json
{
"mcpServers": {
"calc-mcp": {
"command": "uv",
"args": [
"--directory",
"/Users/lifang/product/0826/calc_mcp",
"run",
"calc-mcp"
]
}
}
}
```
如果客户端找不到 `uv`,将 `command` 改为 `uv` 可执行文件的绝对路径。移动项目后需更新目录路径。
## 验证
```sh
uv run python -m unittest discover -s tests -v
```
测试覆盖四则运算、负数、小数、零、非法参数、非有限数和溢出,并启动真实 stdio 子进程,检查 MCP 初始化、工具发现、工具调用以及错误后的正常调用。
## 后续扩展位置
在 `src/calc_mcp/tools.py` 中添加工具定义,并将函数加入 `register_tools()` 的注册列表。`server.py` 的 `create_server()` 会统一注册工具。
TDQS
A4.4/5.0
Scored across 4 tools
Disambiguation5/5
Each tool maps to a single, distinct arithmetic operation: addition, subtraction, multiplication, or division. There is no overlap or ambiguity between tool purposes.
Naming Consistency5/5
All tool names follow the same simple verb-only pattern: add, subtract, multiply, divide. The naming is perfectly consistent and instantly predictable.
Tool Count5/5
Four tools is the ideal size for a basic arithmetic calculator server. Each tool covers a fundamental operation without unnecessary bloat.
Completeness5/5
The tool set fully covers the core arithmetic operations needed for a calculator: addition, subtraction, multiplication, and division, with appropriate edge-case handling for division by zero. It is a complete minimal surface for its stated purpose.
Maintenance
ActivityMaintained
ResponsivenessNo issues