mcp-ops-lab
by mnawaz6935
README.md
# mcp-ops-lab
[](https://github.com/OWNER/mcp-ops-lab/actions/workflows/tests.yml)



An MCP server in Python that lets an AI assistant look at an operations database: services, deployments, incidents and batch job runs.
I'm Muhammad Nawaz, and I made this to practice building MCP servers I'd actually be comfortable connecting to a real system. Getting an LLM to call a tool isn't hard. Stopping it from breaking something when it calls the wrong one is the hard part, so most of the code here is about that.
It runs over stdio or Streamable HTTP. There are ready-made configs for Claude Desktop, Claude Code and Cursor, plus two small agents I wrote, one on the Claude API and one on OpenAI.
```mermaid
flowchart LR
subgraph Clients
CD[Claude Desktop]
CC[Claude Code]
CU[Cursor]
A1[agent.py<br/>Claude tool runner]
A2[agent_openai.py<br/>hand-written loop]
end
subgraph Server["ops_mcp (MCPServer)"]
T[6 tools]
R[2 resources]
P[2 prompts]
L[JSON audit log on stderr]
end
DB[(SQLite<br/>read-only)]
ACT[[actions.jsonl<br/>append-only]]
CD & CC & CU -- stdio --> Server
A1 & A2 -- stdio or HTTP --> Server
T --> DB
T -- request_job_rerun --> ACT
```
## What's in the server
| Kind | Name | Notes |
|---|---|---|
| Tool | `list_services` | Optional status filter: `healthy`, `degraded` or `down` |
| Tool | `search_incidents` | Severity is an enum, service names must match a regex, `since_days` is 1-90, `limit` is 1-50 |
| Tool | `get_incident` | Returns `isError` if the ID doesn't exist |
| Tool | `summarize_job_failures` | Failure rate and most common error per job, last 1-168 hours. Reports progress while it runs |
| Tool | `run_readonly_query` | Ad-hoc SQL with the guards described below |
| Tool | `request_job_rerun` | The one tool that does something. Dry run unless you pass `dry_run=false`, and even then it only appends a line to a log file |
| Resource | `ops://schema` | The DB schema |
| Resource | `ops://services/{name}` | One service as JSON |
| Prompt | `incident_triage(incident_id)` | Shows up as a slash command in Claude Desktop and Claude Code |
| Prompt | `weekly_ops_report(days)` | |
The read-only tools are marked with `readOnlyHint`, so a client can let them through without asking and still ask before a rerun.
## How it stays safe
The SQL tool was where I spent the most time. A write has to get past five separate checks, and any one of them stops it:
1. The SQLite file is opened with `mode=ro`.
2. `PRAGMA query_only = ON` on the connection.
3. An authorizer callback that only allows read, select and function actions, and blocks functions like `load_extension`.
4. One statement only, and it has to start with `SELECT` or `WITH`.
5. At most 200 rows back, and a 2 second timeout through a progress handler.
Checks 1-3 would've been enough on their own. I kept 4 and 5 anyway because they give the model a clearer error message and stop a slow query from hanging the server.
Every tool argument is typed with Pydantic (`Field(ge=1, le=90)`, `Literal[...]`, regex patterns). The SDK turns those into the JSON Schema the model sees, so bad input gets rejected before my function is called.
When something expected goes wrong, like an unknown incident ID, the tool raises `ToolError`. The model gets that back as `isError: true` and can try again. The server doesn't crash.
Logs are JSON lines on stderr. That matters with stdio, because stdout is the protocol channel and a stray `print()` corrupts it. Each tool call gets an id, its arguments (secrets redacted, long strings cut to 300 chars), how long it took and whether it worked.
## Trying it with a real model
I ran the OpenAI agent against `gpt-5.4-mini`. These are the actual results.
Asking it to rerun a job. It did a dry run and stopped to ask:
```text
> Rerun email_digest, the S3 permission is fixed.
-> request_job_rerun({'job_name': 'email_digest', 'reason': '...', 'dry_run': True})
I can queue the rerun, but I need your explicit confirmation before I submit it for real.
```
Telling it to run a DELETE through the query tool. The model went along with it and the server refused:
```text
> Use run_readonly_query to execute exactly this SQL: DELETE FROM incidents WHERE status = 'resolved'
-> run_readonly_query({'sql': "DELETE FROM incidents WHERE status = 'resolved'"})
audit: {"tool": "run_readonly_query", "outcome": "error", "error": "ToolError: Only SELECT / WITH queries are allowed"}
It did not run. ... the DELETE was blocked and no data was changed.
```
That's the test I care about most. When I just asked "delete all resolved incidents", the model refused by itself, which is nice but doesn't prove anything about the server. Forcing the DELETE through shows the guard holds even when the model doesn't. All 40 incidents were still there afterwards.
A normal question took one tool call:
```text
> Which batch jobs are failing most in the last 48h and why? Should any be rerun?
-> summarize_job_failures({'hours': 48})
```
## Running it
You need [uv](https://docs.astral.sh/uv/) and Python 3.11+.
```bash
uv sync
uv run python -m ops_mcp.seed # builds data/ops.db (same data every time, seeded RNG)
uv run pytest -q # 18 tests, about 3 seconds
```
Start the server:
```bash
uv run python -m ops_mcp # stdio
uv run python -m ops_mcp --transport http --port 8000 # Streamable HTTP on /mcp
```
The HTTP mode is stateless with JSON responses, so you could put several copies behind a load balancer.
Run one of the agents:
```bash
export OPENAI_API_KEY=... # or ANTHROPIC_API_KEY for agent/agent.py
uv run python agent/agent_openai.py "Which batch jobs are failing most in the last 48h and why?"
uv run python agent/agent.py --url http://127.0.0.1:8000/mcp "Triage incident 26"
uv run python agent/agent.py --list-tools # just checks the connection, no API call
```
`agent.py` uses the Anthropic SDK's tool runner. In `agent_openai.py` I wrote the loop myself: convert each MCP tool to an OpenAI function, call the model, run whatever tools it asks for, send the results back, and stop after 12 rounds if it never answers.
## Connecting a client
Put your clone's full path in place of `C:/path/to/mcp-ops-lab` in `configs/*.json`, then:
- Claude Desktop: merge `configs/claude_desktop_config.json` into your `claude_desktop_config.json` and restart.
- Claude Code: copy `configs/claude_code.mcp.json` to `.mcp.json`, or run `claude mcp add ops -- uv --directory /path/to/mcp-ops-lab run python -m ops_mcp`.
- Cursor: copy `configs/cursor.mcp.json` to `.cursor/mcp.json`.
Then ask something like "use the incident_triage prompt for incident 26" or "what's email_digest's failure rate this week, rerun it if it's over 20%".
## Layout
```text
ops_mcp/
server.py tools, resources, prompts, lifespan
db.py read-only SQLite wrapper
logging_setup.py JSON logs, @audited decorator, redaction
seed.py demo data
__main__.py CLI flags: --transport, --host, --port, --db
agent/
agent.py Claude agent
agent_openai.py OpenAI agent
tests/test_server.py
configs/ Claude Desktop, Claude Code, Cursor
```
## Tests
The tests connect the SDK's `Client` straight to the server object, in the same process. It's the real protocol (schemas, validation, error results) without spawning anything.
The SQL guard tests throw seven queries at it and then check that nothing changed in the database:
- `DELETE FROM incidents`
- `UPDATE services SET status='down'`
- `SELECT 1; DROP TABLE services`
- a `WITH` clause wrapping an `INSERT`
- `PRAGMA writable_schema = ON`
- `ATTACH DATABASE`
- `SELECT load_extension('evil')`
CI runs the suite on Ubuntu and Windows with Python 3.11, 3.12 and 3.13.
## SDK notes
This is on v2 of the official [`mcp` Python SDK](https://github.com/modelcontextprotocol/python-sdk). If you're coming from v1 tutorials, `FastMCP` is now called `MCPServer` (`from mcp.server.mcpserver import MCPServer`). The decorators haven't changed much. The separate `fastmcp` package on PyPI is a different, third-party project.
I don't use `ctx.info()` for logging. In-protocol logging was deprecated in the 2026-07-28 spec, so the server logs to stderr instead.
## What I'd add next
- Postgres instead of SQLite, with a SELECT-only role, `default_transaction_read_only` and `statement_timeout`
- Auth on the HTTP transport (bearer token or OAuth)
- A y/N prompt in the agent before any real rerun
- Dockerfile and a `/health` endpoint
- Rate limits per tool
- A small eval: questions with known answers, scored automatically
## Author
Built by **Muhammad Nawaz**.
## License
MIT. See [LICENSE](LICENSE).
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues