Exposes math operations as REST API endpoints for addition and subtraction with request/response validation
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Math Operations MCP Serveradd 15 and 27"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
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 endpointFeatures
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.txtUsing pip:
pip install -r requirements.txtUsage
1. Running the FastAPI Server
Start the REST API server:
python main.pyThe server will be available at:
API Base:
http://localhost:8000Interactive Docs:
http://localhost:8000/docsAdd endpoint:
POST http://localhost:8000/api/addSubtract 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/inspectorRun the inspector:
mcp-inspector uv run mcp_server.pyTest the tools in the web interface:
Open the URL provided by the inspector (usually
http://localhost:5173)You'll see the available tools:
addandsubtractClick 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.pyThen 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.jsonmacOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonLinux:
~/.config/Claude/claude_desktop_config.json
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 directoryWindows: 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 commandenv: Optional environment variables (empty object{}for none)
Verify the configuration:
The
cwdpath must exist and containmcp_server.pyEnsure
uvis installed and accessible from your PATHOn 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
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.5Tool: 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.5Testing & 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/docsClick 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 interactivelyMethod 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.pyMethod 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 serverCheck the response includes tool usage indicator
View logs:
Windows:
%APPDATA%\Claude\logs\mcp-*.logmacOS:
~/Library/Logs/Claude/mcp-*.logLinux:
~/.config/Claude/logs/mcp-*.log
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.jsonCheck the cwd path exists:
# Windows dir "d:\Projects\MCP\mcp_server.py" # macOS/Linux ls -la /path/to/MCP/mcp_server.pyVerify uv is installed:
uv --versionTest server manually:
cd d:\Projects\MCP uv run mcp_server.pyCheck 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.txtFastAPI 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 -9Problem: Import errors
Ensure you're running from the correct directory:
cd d:\Projects\MCP
python main.pyTesting Issues
Problem: MCP Inspector won't start
# Update npm and reinstall inspector
npm install -g npm@latest
npm install -g @modelcontextprotocol/inspector --forceProblem: 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
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!
This server cannot be installed
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.