Skip to main content
Glama
yuntaozhang999

Calculator MCP Server

README.md
# Calculator MCP Server

A minimal, fully functional Model Context Protocol (MCP) server written in Python using the official `mcp>=2.0` SDK.

This repository serves as a clear reference implementation for understanding:
- How Python type annotations and docstrings generate JSON Schema for AI agents.
- Local IPC pipes (`stdio`) vs. modern cloud transport (`streamable-http`).
- Direct JSON-RPC 2.0 handshake and tool invocation.

---

## Tools Implemented

- `add(a, b)`: Adds two numbers.
- `subtract(a, b)`: Subtracts `b` from `a`.
- `multiply(a, b)`: Multiplies two numbers.
- `divide(a, b)`: Divides `a` by `b` (with divide-by-zero validation).

---

## Quickstart

### 1. Installation

Ensure you have [uv](https://github.com/astral-sh/uv) installed:

```bash
git clone https://github.com/yuntaozhang999/calculator-mcp.git
cd calculator-mcp
uv sync
```

### 2. Local Interactive Inspection (`stdio`)

Run the MCP Inspector to test the tools via a web UI:

```bash
uv run mcp dev server.py
```

### 3. Headless stdio Mode

Run directly in headless mode for AI agents (AGY, Claude Code):

```bash
uv run mcp run server.py
```

---

## Running as a Cloud Service (`streamable-http`)

To run as an HTTP microservice on port 8000:

```python
# In server.py:
if __name__ == "__main__":
    mcp.run(transport="streamable-http", host="127.0.0.1", port=8000)
```

Start the service:
```bash
uv run python server.py
```

### Testing with `curl`

1. **Initialize session and extract the `Mcp-Session-Id` header**:
```bash
curl -i -X POST http://127.0.0.1:8000/mcp \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"curl","version":"1.0"}}}'
```

2. **List available tools**:
```bash
curl -X POST http://127.0.0.1:8000/mcp \
  -H "Content-Type: application/json" \
  -H "Mcp-Session-Id: <YOUR_SESSION_ID>" \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}'
```

3. **Execute tool call**:
```bash
curl -X POST http://127.0.0.1:8000/mcp \
  -H "Content-Type: application/json" \
  -H "Mcp-Session-Id: <YOUR_SESSION_ID>" \
  -d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"add","arguments":{"a":100,"b":250}}}'
```

---

## License

MIT