Math Operations MCP Server

Math Operations MCP Server

Enables AI applications to perform basic mathematical operations like addition and subtraction through MCP tools. Also provides REST API endpoints for the same operations.

Category
访问服务器

README

Math Operations API & MCP Server

A FastAPI application with MCP (Model Context Protocol) server integration for performing basic math operations. This project exposes addition and subtraction operations both as REST APIs and as MCP tools for AI applications.

Project Structure

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

Features

  • FastAPI REST API: Traditional REST endpoints for math operations
  • MCP Server: Expose operations as tools for AI applications (Claude Desktop, etc.)
  • Router-based Architecture: Clean, scalable code organization
  • Type Safety: Pydantic models for request/response validation

Installation

Prerequisites

  • Python 3.10 or higher
  • uv package manager (recommended) or pip

Install Dependencies

Using uv:

uv pip install -r requirements.txt

Using pip:

pip install -r requirements.txt

Usage

1. Running the FastAPI Server

Start the REST API server:

python main.py

The server will be available at:

  • API Base: http://localhost:8000
  • Interactive Docs: http://localhost:8000/docs
  • Add endpoint: POST http://localhost:8000/api/add
  • Subtract endpoint: POST http://localhost:8000/api/subtract

Example API Requests

Add two numbers:

curl -X POST "http://localhost:8000/api/add" \
  -H "Content-Type: application/json" \
  -d '{"a": 10.5, "b": 5.5}'

Subtract two numbers:

curl -X POST "http://localhost:8000/api/subtract" \
  -H "Content-Type: application/json" \
  -d '{"a": 20.0, "b": 5.5}'

2. Running the MCP Server

The MCP server allows AI applications to use the math operations as tools.

Testing MCP Server Locally

You can test the MCP server using the MCP Inspector tool:

  1. Install MCP Inspector:

    npm install -g @modelcontextprotocol/inspector
    
  2. Run the inspector:

    mcp-inspector uv run mcp_server.py
    
  3. Test the tools in the web interface:

    • Open the URL provided by the inspector (usually http://localhost:5173)
    • You'll see the available tools: add and subtract
    • Click on a tool to test it with sample inputs
    • View the responses in real-time

Alternative Testing with stdio

You can also test the MCP server directly via stdio:

uv run mcp_server.py

Then send JSON-RPC requests manually. Example:

{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}
{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "add", "arguments": {"a": 10, "b": 5}}}

Integration with AI Applications

For Claude Desktop:
  1. Locate your Claude Desktop configuration file:

    • Windows: %APPDATA%\Claude\claude_desktop_config.json
    • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
    • Linux: ~/.config/Claude/claude_desktop_config.json
  2. Add the MCP server configuration:

{
  "mcpServers": {
    "math-operations": {
      "command": "uv",
      "args": [
        "run",
        "mcp_server.py"
      ],
      "cwd": "d:\\Projects\\MCP",
      "env": {}
    }
  }
}

Important Configuration Notes:

  • cwd (Current Working Directory): MUST be the absolute path to your project directory
    • Windows: Use double backslashes \\ or forward slashes /
    • macOS/Linux: Use absolute path like /home/user/projects/MCP
  • command: The executable to run (uv, python, etc.)
  • args: Arguments passed to the command
  • env: Optional environment variables (empty object {} for none)
  1. Verify the configuration:

    • The cwd path must exist and contain mcp_server.py
    • Ensure uv is installed and accessible from your PATH
    • On Windows, you can verify the path by running: dir "d:\Projects\MCP\mcp_server.py"
    • On macOS/Linux, verify with: ls -la /path/to/MCP/mcp_server.py
  2. Restart Claude Desktop completely:

    • Close Claude Desktop entirely (check system tray/menu bar)
    • Reopen Claude Desktop
    • The math operations tools should now appear
  3. Verify the connection:

    • In Claude Desktop, check the settings or tools panel
    • Look for "math-operations" server status (should show as connected)
    • If there's an error, check the logs (see Troubleshooting section)
For Other AI Applications:

Most MCP-compatible AI applications use similar configuration. Copy from mcp.json and adapt:

For Cline/VSCode: Add to your VSCode settings or Cline configuration:

{
  "cline.mcpServers": {
    "math-operations": {
      "command": "uv",
      "args": ["run", "mcp_server.py"],
      "cwd": "/absolute/path/to/MCP"
    }
  }
}

For Continue.dev: Add to ~/.continue/config.json:

{
  "mcpServers": [
    {
      "name": "math-operations",
      "command": "uv",
      "args": ["run", "mcp_server.py"],
      "cwd": "/absolute/path/to/MCP"
    }
  ]
}

MCP Tools Documentation

Tool: add

Adds two numbers together.

Parameters:

  • a (number, required): First number to add
  • b (number, required): Second number to add

Returns:

  • result: The sum of a and b
  • operation: "addition"
  • inputs: The input values

Example:

{
  "a": 10.5,
  "b": 5.5
}

Response:

Result: 16.0
Operation: addition
Inputs: a=10.5, b=5.5

Tool: subtract

Subtracts b from a.

Parameters:

  • a (number, required): Number to subtract from
  • b (number, required): Number to subtract

Returns:

  • result: The difference (a - b)
  • operation: "subtraction"
  • inputs: The input values

Example:

{
  "a": 20.0,
  "b": 5.5
}

Response:

Result: 14.5
Operation: subtraction
Inputs: a=20.0, b=5.5

Testing & Validation

1. Testing FastAPI Endpoints

Using 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())

Using the interactive docs:

  1. Navigate to http://localhost:8000/docs
  2. Click on an endpoint to expand it
  3. Click "Try it out"
  4. Enter test values
  5. Click "Execute"

2. Testing MCP Server

Method 1: Using MCP Inspector (Recommended)

# 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

Method 2: Manual stdio Testing

# 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

Method 3: Using Python MCP Client

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. Validating Claude Desktop Integration

After configuring Claude Desktop:

  1. Check server status:

    • Open Claude Desktop settings
    • Look for MCP Servers section
    • Verify "math-operations" shows as "Connected" (green indicator)
  2. Test the tools:

    • Start a new conversation in Claude Desktop
    • Ask: "Can you add 15 and 25 for me?"
    • Claude should use the add tool from your MCP server
    • Check the response includes tool usage indicator
  3. View logs:

    • Windows: %APPDATA%\Claude\logs\mcp-*.log
    • macOS: ~/Library/Logs/Claude/mcp-*.log
    • Linux: ~/.config/Claude/logs/mcp-*.log

Development

Adding New Operations

To add new math operations (e.g., multiply, divide):

  1. Create API endpoint in 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}
    )
  1. Add router to main.py:
from api.multiply import router as multiply_router
app.include_router(multiply_router, prefix="/api", tags=["Math Operations"])
  1. Add MCP tool in mcp_server.py:

Update 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"]
    }
)

Update call_tool():

elif name == "multiply":
    result = a * b
    operation = "multiplication"
    logger.info(f"Executing multiply: {a} * {b} = {result}")

Project Dependencies

  • fastapi: Modern web framework for building APIs
  • uvicorn: ASGI server for running FastAPI
  • pydantic: Data validation using Python type annotations
  • mcp: Model Context Protocol SDK for AI integrations

Troubleshooting

MCP Server Issues

Problem: Server not connecting in Claude Desktop

  1. Verify configuration path:

    # Windows
    type "%APPDATA%\Claude\claude_desktop_config.json"
    
    # macOS/Linux
    cat ~/Library/Application\ Support/Claude/claude_desktop_config.json
    
  2. Check the cwd path exists:

    # Windows
    dir "d:\Projects\MCP\mcp_server.py"
    
    # macOS/Linux
    ls -la /path/to/MCP/mcp_server.py
    
  3. Verify uv is installed:

    uv --version
    
  4. Test server manually:

    cd d:\Projects\MCP
    uv run mcp_server.py
    
  5. Check Claude Desktop logs:

    • Look for error messages in MCP log files
    • Common issues: wrong path, missing dependencies, permission errors

Problem: Tools not appearing in Claude Desktop

  1. Completely quit Claude Desktop (check system tray)
  2. Verify JSON syntax in config file (use JSONLint.com)
  3. Ensure no trailing commas in JSON
  4. Restart Claude Desktop
  5. Wait 10-30 seconds for server initialization

Problem: "Module not found" errors

# Reinstall dependencies
cd d:\Projects\MCP
uv pip install -r requirements.txt

# Or using pip
pip install -r requirements.txt

FastAPI Server Issues

Problem: Port 8000 already in use

# Windows - Find and kill process
netstat -ano | findstr :8000
taskkill /PID <PID> /F

# macOS/Linux
lsof -ti:8000 | xargs kill -9

Problem: Import errors

Ensure you're running from the correct directory:

cd d:\Projects\MCP
python main.py

Testing Issues

Problem: MCP Inspector won't start

# Update npm and reinstall inspector
npm install -g npm@latest
npm install -g @modelcontextprotocol/inspector --force

Problem: stdio communication hangs

  • Check for print statements or logging that might interfere with stdio
  • Ensure JSON-RPC messages are properly formatted
  • Use logger.info() instead of print() for debugging

Resources

License

This project is provided as-is for educational and development purposes.

Contributing

Feel free to extend this project with additional math operations or features!

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选