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.
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
uvpackage manager (recommended) orpip
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:
-
Install MCP Inspector:
npm install -g @modelcontextprotocol/inspector -
Run the inspector:
mcp-inspector uv run mcp_server.py -
Test the tools in the web interface:
- Open the URL provided by the inspector (usually
http://localhost:5173) - You'll see the available tools:
addandsubtract - Click on a tool to test it with sample inputs
- View the responses in real-time
- Open the URL provided by the inspector (usually
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:
-
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
- Windows:
-
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
- Windows: Use double backslashes
command: The executable to run (uv,python, etc.)args: Arguments passed to the commandenv: Optional environment variables (empty object{}for none)
-
Verify the configuration:
- The
cwdpath must exist and containmcp_server.py - Ensure
uvis 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
- The
-
Restart Claude Desktop completely:
- Close Claude Desktop entirely (check system tray/menu bar)
- Reopen Claude Desktop
- The math operations tools should now appear
-
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 addb(number, required): Second number to add
Returns:
result: The sum of a and boperation: "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 fromb(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:
- Navigate to
http://localhost:8000/docs - Click on an endpoint to expand it
- Click "Try it out"
- Enter test values
- 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:
-
Check server status:
- Open Claude Desktop settings
- Look for MCP Servers section
- Verify "math-operations" shows as "Connected" (green indicator)
-
Test the tools:
- Start a new conversation in Claude Desktop
- Ask: "Can you add 15 and 25 for me?"
- Claude should use the
addtool from your MCP server - Check the response includes tool usage indicator
-
View logs:
- Windows:
%APPDATA%\Claude\logs\mcp-*.log - macOS:
~/Library/Logs/Claude/mcp-*.log - Linux:
~/.config/Claude/logs/mcp-*.log
- Windows:
Development
Adding New Operations
To add new math operations (e.g., multiply, divide):
- 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}
)
- Add router to main.py:
from api.multiply import router as multiply_router
app.include_router(multiply_router, prefix="/api", tags=["Math Operations"])
- 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
-
Verify configuration path:
# Windows type "%APPDATA%\Claude\claude_desktop_config.json" # macOS/Linux cat ~/Library/Application\ Support/Claude/claude_desktop_config.json -
Check the cwd path exists:
# Windows dir "d:\Projects\MCP\mcp_server.py" # macOS/Linux ls -la /path/to/MCP/mcp_server.py -
Verify uv is installed:
uv --version -
Test server manually:
cd d:\Projects\MCP uv run mcp_server.py -
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
- Completely quit Claude Desktop (check system tray)
- Verify JSON syntax in config file (use JSONLint.com)
- Ensure no trailing commas in JSON
- Restart Claude Desktop
- 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 ofprint()for debugging
Resources
- Model Context Protocol Documentation
- FastAPI Documentation
- MCP Python SDK
- Claude Desktop MCP Configuration Guide
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!
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.