Skip to main content
Glama
guarded-config-mcp

guarded-config-mcp

README.md
# guarded-config-mcp

**An MCP server that lets an AI agent change live SaaS configuration, but only what a human has approved, only once, and never over someone else's edit.**

[![tests](https://github.com/harshithaneelam/guarded-config-mcp/actions/workflows/tests.yml/badge.svg)](https://github.com/harshithaneelam/guarded-config-mcp/actions/workflows/tests.yml)
![python](https://img.shields.io/badge/python-3.12%20%7C%203.13-blue)
![mcp](https://img.shields.io/badge/MCP%20Python%20SDK-2.3.0-informational)
![api](https://img.shields.io/badge/SaaS%20API-MOCK-lightgrey)
[![license](https://img.shields.io/badge/license-MIT-green)](LICENSE)

> **The configuration API in this repo is a mock** (`src/guarded_config/mock_api/`): a small FastAPI app with
> HR/payroll-style settings for two tenants, held in memory. It is not a real product.

| | |
|---|---|
| **What** | 9 MCP tools: reads, dry-run proposals, approved applies, rollback, audit history, per-call cost |
| **Guards** | fixed tenant · capability manifest · dry run · out-of-band human approval · apply-once claim · stale-version check · append-only audit · fail-fast startup |
| **Evidence** | 158 tests on Windows + Linux · **26 guards broken on purpose** and shown to fail · real-agent runs recorded |
| **Built with** | Python, FastAPI, httpx, SQLite, MCP Python SDK v2, pytest |

---

## Why

When an agent changes live configuration for a customer, one wrong call is enough to cause damage: the wrong
tenant, a value that fails halfway through an onboarding, the same change applied twice, or someone's edit from a
minute ago quietly overwritten. And "the agent says it worked" isn't proof. I wanted to work out what a server has
to guarantee before I'd let an agent make writes at all.

## How it works

```mermaid
sequenceDiagram
    autonumber
    actor Human
    participant Agent as Agent (MCP client)
    participant Server as Guarded MCP server
    participant Store as SQLite (proposals, audit, costs)
    participant API as MOCK config API

    Agent->>Server: propose_change(leave.annual_days, 30)
    Server->>API: GET current value + version
    Server->>Store: proposal = pending (base_version 1)
    Server-->>Agent: change_id (nothing changed yet)
    Agent->>Server: apply_change(change_id)
    Server-->>Agent: refused: not approved
    Human->>Store: approver CLI approves change_id (as a named person)
    Agent->>Server: apply_change(change_id)
    Server->>Store: claim: approved → applying (one conditional UPDATE)
    Server->>API: PUT value, expected_version = base_version
    API-->>Server: 200 (or 409 if someone changed it since)
    Server->>Store: applied / failed + audit event, same transaction
    Server-->>Agent: applied once, version 2
```

Approval lives only in the approver CLI. No MCP tool, argument or code path can approve or reject.

### Guarantees

| Guarantee | How | Decision |
|---|---|---|
| Fixed tenant | Set at startup from `GUARDED_TENANT_ID`; no tool takes a tenant argument; the mock also rejects a mismatched tenant header | [0001](docs/decisions/0001-mock-domain-and-tenancy.md) |
| Only covered settings | `capabilities` is the manifest; any other key is refused **before** an HTTP call is made | [guard checks](docs/guard-checks.md) |
| Dry run first | `propose_change` validates and records a pending proposal; it never sends a write | [0006](docs/decisions/0006-dry-run-validation-source.md) |
| Human approval, out of band | Only the approver CLI can move a proposal to approved | [0002](docs/decisions/0002-where-approval-happens.md) · [0007](docs/decisions/0007-agent-with-a-shell-and-the-approver.md) |
| Apply once | One conditional UPDATE claims the proposal; a second apply finds nothing to claim | [0003](docs/decisions/0003-concurrency-and-staleness.md) |
| Never over a newer edit | The write carries the proposal's `base_version`; the mock's compare-and-set answers 409 if the setting moved | [0003](docs/decisions/0003-concurrency-and-staleness.md) |
| No blind retries | Lost connection or unexpected status → stays `applying` for a human to check | [0003](docs/decisions/0003-concurrency-and-staleness.md) |
| Trustworthy audit | Append-only (triggers refuse UPDATE/DELETE); each event commits in the same transaction as its state change | [guard checks](docs/guard-checks.md) |
| Safe rollback | A rollback is just another proposal, based on the version the change produced, so it needs approval and fails as stale if the setting moved | [guard checks](docs/guard-checks.md) |
| Fail fast | No tenant → exit 2; a database with a different layout version → refused at startup (server and CLI) | [guard checks](docs/guard-checks.md) |
| Cost per call | SDK middleware records time, bytes, mock HTTP calls and **estimated** tokens for every call; telemetry fails open, audit fails closed | [0004](docs/decisions/0004-cost-tracking.md) |
| Known build | `server_info` reports the git commit and whether the tree was dirty, captured at startup | — |

### Tools

| Tool | Does |
|---|---|
| `capabilities` | What's covered, what's out of scope, and that the API is a mock |
| `list_settings` / `get_setting` | Read covered settings |
| `propose_change` | Dry run: validate and record a pending proposal |
| `get_proposal` | A proposal and its audit history (this tenant only) |
| `apply_change` | Apply a human-approved proposal, once |
| `propose_rollback` | Propose undoing an applied change (needs approval too) |
| `cost_report` | Per-tool calls, errors, time, mock HTTP calls, estimated tokens |
| `server_info` | Version, git commit, dirty flag, MCP SDK version |

## Quickstart

Python 3.12+. Commands below are PowerShell; on macOS/Linux use `.venv/bin/python`.

```powershell
git clone https://github.com/harshithaneelam/guarded-config-mcp.git
cd guarded-config-mcp
py -3.13 -m venv .venv                      # or: python3 -m venv .venv
.venv\Scripts\python.exe -m pip install -r requirements-lock.txt -e ".[dev]"
.venv\Scripts\python.exe -m pytest           # 158 passed
```

**Run it with a real agent**

1. Start the mock API and leave it running:
   ```powershell
   .venv\Scripts\python.exe -m uvicorn guarded_config.mock_api.app:create_app --factory --port 8765
   ```
2. Copy `.mcp.json.example` to `.mcp.json` (git-ignored), fill in the absolute paths, and open a new Claude Code
   session in the repo folder. Any MCP client that speaks stdio works.
3. Talk to the agent in plain English, and approve as the human:
   ```powershell
   .venv\Scripts\python.exe -m guarded_config.approver --db guarded.db --tenant acme list
   .venv\Scripts\python.exe -m guarded_config.approver --db guarded.db --tenant acme approve CHANGE_ID --as "Your Name"
   .venv\Scripts\python.exe -m guarded_config.approver --db guarded.db --tenant acme audit
   .venv\Scripts\python.exe -m guarded_config.approver --db guarded.db --tenant acme costs
   ```
   Replace `CHANGE_ID` with the id the agent gives you (`list` shows them too).

## What it looks like

From a recorded run with Claude Code as the client. The agent's replies are shortened; the full run is in
[docs/manual-checks.md](docs/manual-checks.md).

```text
You:    Set annual leave to 30 days.
Agent:  Annual leave isn't changed yet. I've only proposed the change; it's waiting for your approval.
        Change: 24 (version 1) → 30 · Change ID: 6d71a202…
You:    Apply it.
Agent:  I can't apply it yet because the change hasn't been approved.
        [human runs: approver approve 6d71a202… --as "Harshitha Neelam"]
You:    Apply it.
Agent:  Annual leave is now 30 days. I didn't rely on the apply tool's reply; reading it back from the
        mock API gives value 30, version 2, and the audit trail records four events in order.
You:    Undo that change.
Agent:  I've only proposed the undo, and like any change it needs your approval.
        [human approves the rollback]
Agent:  Back to 24 days, at version 3. The version went up rather than back to 1.
```

```text
$ approver ... costs
tool             calls  errors   avg_ms  est_output_tokens  mock_http_calls
get_setting          3       0    14.41                 54                3
propose_change       1       0    13.68                 72                1
apply_change         2       0    35.69                102                2
...
token_note: estimated as response bytes / 4; this server cannot see the model's real token usage
```

My 60-second demo script is in [docs/demo.md](docs/demo.md).

## Evidence

**I made every guard fail on purpose before I trusted it.** For each of the 26 breaks in
[docs/guard-checks.md](docs/guard-checks.md), the guard was switched off with a throwaway edit, its test was shown
failing for the right reason, and the code was restored. The ones that taught me the most:

| Guard switched off | What happened |
|---|---|
| A hidden write inside the dry run | The tool still replied **"Nothing was changed"** while the mock held the new value. Only reading the mock's own state caught it. |
| The mock's compare-and-set lock | **16 of 16** concurrent writes succeeded, and the version still looked right (every writer computed 1 + 1). Fifteen lost writes only showed up when I counted the 200 responses. |
| Write with a freshly read version instead of `base_version` | A stale change **overwrote someone else's edit**. A rollback built from a fresh read did the same. |
| Audit event outside the state change's transaction | An approval committed **with no audit record**. |

- **Tests:** 158 (89 functions, some parametrised). I ran them on Windows and Linux; CI runs them on both for
  Python 3.12 and 3.13 on every push (badge above).
- **Races:** claims, approve-vs-reject decisions and the mock's compare-and-set each run 20 rounds × 16 threads
  released together, with exactly one winner every round. Read-sleep-write versions lost 16 of 16.
- **Real agent:** out-of-scope reads never reached the mock; an unapproved apply was refused; an approved change
  applied exactly once; a stale apply was refused and the other person's edit survived; rollback, audit and cost
  report all matched the session ([docs/manual-checks.md](docs/manual-checks.md)).

## Limits

- **The API is a mock**, in memory, fresh each run. No real product, OAuth/OIDC, browser automation, Kubernetes or
  multi-process deployment.
- **Approval is out of band only from the MCP side** ([0007](docs/decisions/0007-agent-with-a-shell-and-the-approver.md)).
  An agent running as the same OS user with a shell could run the approver CLI. In my last run Claude Code, in Auto
  permission mode, started the mock API on its own and ran the CLI's read-only commands, but chose not to approve. That
  was the model's choice, not something the system enforces. In production, approvals belong in a separate service
  with authenticated approvers; `--as` isn't authenticated here.
- **Token counts are estimates** (response bytes / 4); the server can't see the model's real usage, and every
  `cost_report` result says so.
- **Validation rules exist twice** (server and mock). A drift test compares them on a table of sample values; values
  outside it aren't compared. The mock still validates on write.
- **Races were tested with threads in one process**, not separate processes.
- **The SDK's middleware API is marked provisional** in mcp 2.3.0; the lock file pins it and the cost tests would catch
  a change.
- **No migrations:** a database with an older layout is refused at startup; delete it and start again.
- **Small things:** approver names aren't trimmed inside a list (`" hr "` ≠ `"hr"`); a body that isn't valid JSON gets a
  422 before the mock's tenant check; stdio is the only transport.

## How I built it

Claude Code wrote the code, one small step at a time (M0–M8 in [PLAN.md](PLAN.md)), from prompts I wrote. Every prompt
said what to build, what not to touch, which tests to write first, and to report the diff and test output. I planned
each step and reviewed every report and diff with Claude in a separate chat before committing. Each design choice is a
short record in [docs/decisions/](docs/decisions/). The confident mistakes the agents made, and how they were caught, are
in [AGENT_LOG.md](AGENT_LOG.md). [CLAUDE.md](CLAUDE.md) holds the rules the coding agent worked under.

## Project layout

```
src/guarded_config/
  mock_api/        MOCK configuration API (FastAPI)
  mcp_server/      guarded MCP server (server.py), store (store.py), stdio entrypoint
  approver/        human-only approver CLI
tests/             158 tests
docs/
  decisions/       decision records 0001–0007
  guard-checks.md  every guard break with its failing output
  manual-checks.md runs with a real MCP client
  demo.md          60-second demo script
AGENT_LOG.md       confident agent mistakes, how they were caught, the fix
```

## License

[MIT](LICENSE) © 2026 Harshitha Neelam