数学计算服务器

一个基于Go的MCP服务器,提供13种数学工具,包括基础运算、高级函数、统计分析和金融计算等功能,适用于科学计算和金融建模。

  • by avisangle
  • Go
  • 本地部署
  • 7 星标
  • 更新于
在 GitHub 查看 avisangle/calculator-server

使用说明

计算器服务器-Go MCP服务器

全面 基于Go的MCP(模型上下文协议)服务器 用于数学计算,实现 13数学工具 具有先进的功能和高精度的计算。

所有者和维护者: 阿维纳什·桑格尔(avinash.sangle123@gmail.com)

🧮 特性

核心数学工具(13个工具)

基础数学工具(6个工具)

  1. 基础数学运算 -具有可配置小数位数的精确算术

    • 加法、减法、乘法、除法
    • 多操作数支持
    • 小数精度控制(0-15位)
  2. 高级数学函数 -科学计算

    • 三角函数: sin, cos, tan, asin, acos, atan
    • 对数: log, log10, ln
    • 其他: sqrt, abs, factorial, exp, pow
    • 单位支持:三角函数的度数/弧度
    • 具有基数和指数参数的幂函数
  3. 表达式求值 -复杂的数学表达式

    • 变量替换支持
    • 数学常数(π, e)
    • 带括号的嵌套表达式
    • 表达式中的函数调用
  4. 统计分析 -综合数据分析

    • 描述性统计:平均值、中位数、众数
    • 变异性:标准差、方差
    • 百分位数计算
    • 数据验证和错误处理
  5. 单位转换 -多类别单位转换

    • 长度:mm、cm、m、km、in、ft、yd、mi、mil、μm、nm
    • 重量:mg、g、kg、t、oz、lb、st(石)、ton(美吨)
    • 温度:°C、°F、K、R(朗肯)
    • 体积:ml、cl、dl、l、kl、fl_oz、杯、pt、qt、gal、tsp、tbsp、bbl
    • 区域:mm²、cm²、m²、km²、in²、ft²、yd²、mi²、英亩、公顷
  6. 财务计算 -综合财务建模

    • 利息计算:简单和复合
    • 贷款支付计算
    • 投资回报率(ROI)
    • 当前/未来价值计算
    • 净现值(NPV)和内部收益率(IRR)

高级专用工具(7种工具)

  1. 统计摘要 -数据集综合统计汇总

    • 完整的统计概述,包括所有指标
    • 带有第一个/最后一个元素的数据预览
    • 常见百分位数(第25、50、75位)
  2. 百分位数计算 -计算特定百分位数(0-100)

    • 0到100之间的任何百分位值
    • 数据计数和预览信息
    • 使用经验方法进行精确的百分位数计算
  3. 批量单位转换 -一次在单位之间转换多个值

    • 批量转换操作
    • 与单次转换相同的单位类别
    • 高效的批处理
  4. 净现值(NPV) -使用现金流进行高级净现值计算

    • 多个现金流期
    • 贴现率计算
    • 投资决策支持
  5. 内部收益率(IRR) -投资分析的内部收益率计算

    • 现金流量分析
    • 精确计算IRR的Newton-Raphson方法
    • 投资业绩评价
  6. 贷款比较 -比较多种贷款方案

    • 多种贷款选择分析
    • 每种情况的付款计算
    • 比较指标和建议
  7. 投资方案 -比较多种投资方案

    • 多种投资选择分析
    • 每种情景的未来价值计算
    • 投资比较和建议

技术特性

  • 高精度:用途 shopspring/decimal 用于财务计算
  • 科学计算:技术支持 gonum.org/v1/gonum
  • 表达式引擎:高级解析 govaluate
  • 综合测试:>95%的测试覆盖率
  • 错误处理:详细的错误消息和验证
  • MCP协议:完全符合MCP规范
  • 构建自动化:完整的Makefile,支持CI/CD
  • 可流式HTTP传输:支持SSE的MCP兼容HTTP传输

🚀 快速开始

先决条件

  • 转到1.21+ (必填)
  • Git (用于版本控制)

安装

# Clone the repository
git clone <repository-url>
cd calculator-server

# Install dependencies
make deps

# Build the server
make build

# Run the server
make run

替代设置

# Initialize Go module
go mod init calculator-server
go mod tidy

# Build and run
go build -o calculator-server ./cmd/server
./calculator-server -transport=stdio

📊 使用示例

基础数学

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "basic_math",
    "arguments": {
      "operation": "add",
      "operands": [15.5, 20.3, 10.2],
      "precision": 2
    }
  }
}

答复:

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "content": [
      {
        "type": "text", 
        "text": "{\"result\": 46.0}"
      }
    ]
  }
}

高级数学函数

{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "advanced_math",
    "arguments": {
      "function": "pow",
      "value": 2,
      "exponent": 8
    }
  }
}

统计摘要

{
  "jsonrpc": "2.0",
  "id": 3,
  "method": "tools/call",
  "params": {
    "name": "stats_summary",
    "arguments": {
      "data": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    }
  }
}

百分位数计算

{
  "jsonrpc": "2.0",
  "id": 4,
  "method": "tools/call",
  "params": {
    "name": "percentile",
    "arguments": {
      "data": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
      "percentile": 90
    }
  }
}

净现值

{
  "jsonrpc": "2.0",
  "id": 5,
  "method": "tools/call",
  "params": {
    "name": "npv",
    "arguments": {
      "cashFlows": [-50000, 15000, 20000, 25000, 30000],
      "discountRate": 8
    }
  }
}

批量单位转换

{
  "jsonrpc": "2.0",
  "id": 6,
  "method": "tools/call",
  "params": {
    "name": "batch_conversion",
    "arguments": {
      "values": [100, 200, 300],
      "fromUnit": "cm",
      "toUnit": "m",
      "category": "length"
    }
  }
}

🌐 MCP流式HTTP传输

服务器实现 符合MCP标准的流式HTTP传输 根据官方MCP规范,提供与服务器发送事件(SSE)流媒体支持的实时通信。

MCP协议合规性

✅ 单端点: /mcp 仅限(根据MCP规范)
✅ 所需标题: MCP-Protocol-Version, Accept
✅ 会话管理:加密安全会话ID
✅ SSE流媒体:服务器发送实时响应事件
✅ CORS支持:源验证和安全标头

HTTP端点

单MCP端点(符合规范)

  • POST/mcp -MCP JSON-RPC,可选SSE流
  • GET/mcp -SSE流建立
  • 选项/mcp -CORS飞行前处理

示例用法

# Start MCP-compliant HTTP server
./calculator-server -transport=http -port=8080

# Basic JSON-RPC request
curl -X POST http://localhost:8080/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -H "MCP-Protocol-Version: 2024-11-05" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "basic_math",
      "arguments": {
        "operation": "add",
        "operands": [15, 25],
        "precision": 2
      }
    }
  }'

# SSE streaming request (for real-time responses)
curl -X POST http://localhost:8080/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -H "MCP-Protocol-Version: 2024-11-05" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "stats_summary",
      "arguments": {"data": [1,2,3,4,5]}
    }
  }'

🏗️ 项目结构

calculator-server/
├── cmd/
│   └── server/
│       └── main.go              # Main server entry point
├── internal/
│   ├── calculator/
│   │   ├── basic.go            # Basic math operations
│   │   ├── advanced.go         # Advanced mathematical functions
│   │   ├── expression.go       # Expression evaluation
│   │   ├── statistics.go       # Statistical analysis
│   │   ├── units.go           # Unit conversion
│   │   └── financial.go       # Financial calculations
│   ├── handlers/
│   │   ├── math_handler.go    # Math operation handlers
│   │   ├── stats_handler.go   # Statistics & specialized handlers
│   │   └── finance_handler.go # Financial handlers
│   ├── config/
│   │   ├── config.go          # Configuration structures
│   │   ├── loader.go          # Configuration loader
│   │   └── errors.go          # Configuration errors
│   └── types/
│       └── requests.go        # Request/response types
├── pkg/
│   └── mcp/
│       ├── protocol.go        # MCP protocol handling
│       └── streamable_http_transport.go # HTTP transport
├── tests/
│   ├── basic_test.go         # Basic math tests
│   ├── advanced_test.go      # Advanced math tests
│   ├── expression_test.go    # Expression evaluation tests
│   ├── integration_test.go   # Integration tests
│   ├── config_test.go        # Configuration tests
│   └── streamable_http_transport_test.go # HTTP transport tests
├── config.sample.yaml        # Sample YAML configuration
├── config.sample.json        # Sample JSON configuration
├── go.mod                    # Go module definition
├── go.sum                    # Go module checksums
├── Makefile                  # Build automation
└── README.md                 # Project documentation

🛠️ 发展

建筑

# Build for current platform
make build

# Build for all platforms
make build-all

# Install to $GOPATH/bin
make install

测试

# Run all tests
make test

# Run tests with coverage
make coverage

# Run tests with race detection
make test-race

# Run benchmarks
make benchmark

质量保证

# Format code
make fmt

# Run linter
make lint

# Run vet
make vet

# Run all quality checks
make quality

# Pre-commit checks
make pre-commit

# CI pipeline
make ci

发展模式

# Run without building (development)
make run-dev

# Run with rebuild
make run

📋 可用工具

核心工具(6)

1. basic_math

目的: 具有精度控制的基本算术运算

参数:

  • operation (字符串):“加”、“减”、“乘”、“除”
  • operands (数字数组):要操作的数字(至少2个)
  • precision (整数,可选):小数位(0-15,默认值:2)

2. advanced_math

目的: 高级数学函数

参数:

  • function (string):函数名(sin、cos、tan、asin、acos、atan、log、log10、ln、sqrt、abs、阶乘、pow、exp)
  • value (数字):输入值(pow函数的基础)
  • exponent (数字,可选):pow函数的指数(pow需要)
  • unit (字符串,可选):trig函数的“弧度”或“度”

3. expression_eval

目的: 计算带有变量的数学表达式

参数:

  • expression (string):要计算的数学表达式
  • variables (对象,可选):变量名-值对

4. statistics

目的: 数据集的统计分析

参数:

  • data (数字数组):要分析的数据集
  • operation (字符串):统计运算(平均值、中位数、众数、标准偏差、方差、百分位数)

5. unit_conversion

目的: 在测量单位之间转换

参数:

  • value (number):要转换的值
  • fromUnit (string):源单位
  • toUnit (string):目标单位
  • category (字符串):单位类别(长度、重量、温度、体积、面积)

6. financial

目的: 财务计算和建模

参数:

  • operation (string):财务操作类型(复合利息、简单利息、贷款支付、投资回报率、当前值、未来值)
  • principal (数字):本金金额
  • rate (数字):利率(百分比)
  • time (数字):时间段(年)
  • periods (整数,可选):每年的复合期
  • futureValue (数字,可选):某些计算的未来值

专用工具(7)

7. stats_summary

目的: 数据集综合统计汇总

参数:

  • data (数字数组):用于汇总统计的数据集

8. percentile

目的: 计算特定百分位数

参数:

  • data (数字数组):要分析的数据集
  • percentile (数字):要计算的百分位数(0-100)

9. batch_conversion

目的: 在单位之间转换多个值

参数:

  • values (数字数组):要转换的值
  • fromUnit (string):源单位
  • toUnit (string):目标单位
  • category (string):单位类别

10. npv

目的: 计算净现值

参数:

  • cashFlows (一系列数字):现金流(流出为负,流入为正)
  • discountRate (数字):贴现率百分比

11. irr

目的: 计算内部收益率

参数:

  • cashFlows (数字数组):现金流(至少2个值)

12. loan_comparison

目的: 比较多种贷款方案

参数:

  • loans (对象数组):包含本金、利率和时间的贷款场景

13. investment_scenarios

目的: 比较多种投资方案

参数:

  • scenarios (对象数组):包含本金、利率和时间的投资场景

🔧 配置

命令行选项

./calculator-server [OPTIONS]

Options:
  -transport string
        Transport method (stdio, http) (default "stdio")
  -port int
        Port for HTTP transport (default 8080)
  -host string
        Host for HTTP transport (default "127.0.0.1")
  -config string
        Path to configuration file (YAML or JSON)

Examples:
  ./calculator-server                           # Run with stdio transport (default)
  ./calculator-server -transport=http          # Run with HTTP transport on port 8080
  ./calculator-server -transport=http -port=9000 -host=localhost  # Custom host/port
  ./calculator-server -config=config.yaml     # Load configuration from file

配置文件

服务器支持YAML和JSON格式的配置文件。在以下位置搜索配置文件:

  1. 当前目录(./config.yaml, ./config.json)
  2. ./config/ 目录
  3. /etc/calculator-server/
  4. $HOME/.calculator-server/

YAML配置示例

server:
  transport: "http"
  http:
    host: "127.0.0.1"  # Localhost for security
    port: 8080
    session_timeout: "5m"
    max_connections: 100
    cors:
      enabled: true
      origins: ["http://localhost:3000", "http://127.0.0.1:3000"]  # Never use "*" in production

logging:
  level: "info"
  format: "json"
  output: "stdout"

tools:
  precision:
    max_decimal_places: 15
    default_decimal_places: 2
  expression_eval:
    timeout: "10s"
    max_variables: 100
  statistics:
    max_data_points: 10000
  financial:
    currency_default: "USD"

security:
  rate_limiting:
    enabled: true
    requests_per_minute: 100
  request_size_limit: "1MB"

环境变量

环境变量覆盖配置文件设置:

  • CALCULATOR_TRANSPORT:传输方法(stdio、http)
  • CALCULATOR_HTTP_HOST:HTTP服务器主机
  • CALCULATOR_HTTP_PORT:HTTP服务器端口
  • CALCULATOR_LOG_LEVEL:设置日志记录级别(调试、信息、警告、错误)
  • CALCULATOR_LOG_FORMAT:日志格式(json、文本)
  • CALCULATOR_LOG_OUTPUT:日志输出(stdout、stderr)

📈 演出

基准测试

  • 基本操作:每次操作约1-5μs
  • 高级功能:每次操作约10-50μs
  • 表达式求值:每次表达约100-500μs
  • 统计操作:每个数据集约10-100μs(取决于大小)
  • 单位转换:每次转换约1-10μs
  • 财务计算:每次计算约50-200μs

内存使用

  • 基本内存:约10-20mb
  • 每操作:约1-10KB额外
  • 大型数据集:随数据大小线性缩放

🧪 测试

该项目包括覆盖率>95%的综合测试:

  • 单元测试:测试单个计算器和功能
  • 集成测试:测试MCP协议集成
  • 错误处理测试:验证错误条件
  • 性能测试:基准关键业务
# Run specific test suites
go test ./tests/basic_test.go -v
go test ./tests/advanced_test.go -v
go test ./tests/integration_test.go -v

# Generate coverage report
make coverage

🚢 部署

Docker部署

# Build Docker image
make docker-build

# Run in Docker
make docker-run

# Push to registry
make docker-push

二进制发布

# Create release build
make release

# Binaries will be in ./dist/release/
ls -la ./dist/release/

📝 api参考

MCP协议支持

服务器实现了完整的MCP(模型上下文协议)规范:

  • 初始化:服务器初始化和能力协商
  • 工具列表:动态工具发现
  • 工具调用:工具执行与参数验证
  • 错误处理:全面的错误响应

工具架构

所有工具都包括用于参数验证和文档的全面JSON模式定义。模式是自动生成的,包括:

  • 参数类型和验证规则
  • 必需参数与可选参数
  • 默认值和约束
  • 文档字符串

📏 单位转换参考

长度单位

单位 缩写 换算为米
毫米 mm 0.001
厘米 cm 0.01
仪表 m 1.0
公里 km 1000.0
英寸 in 0.0254
脚 ft 0.3048
庭院 yd 0.9144
英里 mi 1609.344
米尔 mil 0.0000254
千分尺 μm 0.000001
纳米级 nm 0.000000001

重量/质量单位

单位 缩写 转换为克
毫克 mg 0.001
克 g 1.0
千克 kg 1000.0
公吨 t 1000000.0
盎司 oz 28.3495
英镑 lb 453.592
石头 st 6350.29
美国吨 ton 907185

温度单位

单位 缩写 描述
摄氏度 C 摄氏度
华氏温度 F 华氏度
开尔文 K 开尔文(绝对)
兰金 R 兰金学位

体积单位

单位 缩写 转换为升
毫升 ml 0.001
Centiliter cl 0.01
分升 dl 0.1
升 l 1.0
千升 kl 1000.0
美国流体盎司 fl_oz 0.0295735
美国杯 cup 0.236588
美国Pint pt 0.473176
美国四分之一。 qt 0.946353
美国加仑 gal 3.78541
茶匙 tsp 0.00492892
汤匙 tbsp 0.0147868
桶 bbl 158.987

面积单位

单位 缩写 换算为m²
平方毫米 mm2 0.000001
平方厘米 cm2 0.0001
平方米 m2 1.0
平方公里 km2 1000000.0
平方英寸 in2 0.00064516
平方英尺 ft2 0.092903
广场庭院 yd2 0.836127
平方英里 mi2 2589988.11
英亩 acre 4046.86
赫克托 ha 10000.0

🔢 数学函数参考

三角函数

函数 语法 描述 示例
Sine sin(x) x正弦(弧度) sin(pi/2) → 1.0
Cosine cos(x) x的余弦(弧度) cos(0) → 1.0
切线 tan(x) x切线(弧度) tan(pi/4) → 1.0
Arcsine asin(x) 反正弦 asin(1) → 1.5708
反正弦 acos(x) 反余弦 acos(1) → 0.0
反正切 atan(x) 反切线 atan(1) → 0.7854

对数函数

函数 语法 描述 示例
通用日志 log(x) 以10为底的对数 log(100) → 2.0
天然原木 ln(x) 自然对数(以e为底) ln(e) → 1.0

电源和根功能

函数 语法 描述 示例
平方根 sqrt(x) x的平方根 sqrt(16) → 4.0
电源 pow(x, y) x升至y的幂 pow(2, 3) → 8.0
指数型 exp(x) e上升到权力x exp(1) → 2.7183

其他功能

函数 语法 描述 示例
绝对值 abs(x) x的绝对值 abs(-5) → 5.0
保理 factorial(x) x的因式分解 factorial(5) → 120.0

数学常量

常数 值 描述
pi 3.14159… Pi(π)
e 2.71828… 欧拉数

🤝 贡献

  1. 分叉 存储库
  2. 创建 特征分支(git checkout -b feature/amazing-feature)
  3. 提交 变化(git commit -m 'Add amazing feature')
  4. 推 分支机构(git push origin feature/amazing-feature)
  5. 创建 拉取请求

开发指南

  • 遵循Go最佳实践和惯例
  • 保持>95%的测试覆盖率
  • 添加全面的文档
  • 使用有意义的提交消息
  • 跑 make quality 提交前

📄 许可证

此项目根据Apache许可证2.0获得许可-请参阅 许可证 文件以获取详细信息。

🙏 致谢

📞 支持与联系

主要联系人:

项目资源:

  • 问题: GitHub问题
  • 文档:此README和内联代码文档
  • 例子:参见 make example-* 命令

获取帮助:

  1. 查看此README以获取全面的文档
  2. 查看测试文件以获取使用示例
  3. 提交带有详细错误信息的问题
  4. 联系维护人员获得直接支持

内置于❤️ 由Avinash Sangle为IBM MCP Context Forge项目撰写

与作者联系:

有关MCP服务器和Context Forge项目的更多信息,请访问 IBM MCP Context Forge存储库.