Skip to main content
Glama
README.md
# invariants-mcp

A small read-only [MCP](https://modelcontextprotocol.io) server that tells a coding agent which
domain invariants govern a file before it changes that file.

I built it for my own monorepo (an Expo / React Native + Supabase app). There, about 1,100
binding domain rules ("invariants") live as one Markdown file each. A generated table maps file
paths and code keywords to those rules.

## The setup it plugs into

Each invariant is a file at `.ai/domain/<domain>/inv/<ID>.md`, with front matter like this:

```yaml
---
id: INV-ORDER-3
domain: order
status: binding
consumers: ["packages/api/src/order.ts", "apps/web/src/checkout/**"]
content: ["rpc_place_order"]
tests: ["packages/api/test/order_total.test.ts"]
related: ["INV-ORDER-1"]
---
- **INV-ORDER-3 — An order total is computed once, on the server.** …
```

A generator compiles all front matter into one tab-separated table,
`.ai/rule/gate/invariants.tsv`. Each row is `id · file · path_re · content_re`, where `-` means
"any".

An editor hook (a Claude Code `PreToolUse` hook) reads that table. On the first edit of a matching
file, it pushes the matching invariants into the agent's context.

This server reads the **same table**. It keeps no copy of the rules, so there is still one source
of truth.

## Why a server next to the hook

The hook **pushes**:

- It fires only on an edit.
- It sends each invariant once per session.
- The agent can't ask it anything.

The server lets the agent **pull**:

- before planning a change, so the rules shape the plan and not only the edit;
- for a file it is only reading;
- again later in the session;
- from any MCP client, not only the one with the hook.

| | Hook | Server |
|-|-|-|
| Trigger | automatic, on an edit | the agent asks |
| Guaranteed to be seen | yes | only if called |
| Keyword rows match | the text of the edit | the whole file (broader) |
| Works for reads and planning | no | yes |
| Structured result (`has_test`, `matched_by`) | no | yes |

Neither one checks the code against the rules. Both only deliver them.

## Tools

- **`get_invariants_for_file(path)`** returns every invariant that applies to a file. Each one
  has `id`, `domain`, `status`, `text`, `has_test` / `tests` (the tests listed in its front
  matter), `related`, `source` and `matched_by`.
  - `matched_by` is `path` when a `consumers` glob matched.
  - It is `keyword: <regex>` when a `content` regex occurs in the file.
  - Like the hook, keyword rows are skipped under `.ai/`, `.claude/`, `tools/` and `docs/`.
- **`get_invariant(id)`** returns one invariant by its id.

Both tools are annotated read-only. The server reads files under the repository root and nothing
else: no writes, no network calls, no subprocesses. It talks over stdio.

### Errors

Errors come back as MCP tool results with `is_error: true`:

| Case | Message |
|-|-|
| The file doesn't exist | `file not found: …` |
| Nothing matches | `no invariants apply to …` |
| A `..` path, an absolute path elsewhere, or a symlink that leaves the repo | `path is outside the repository: …` |
| A broken table line | `malformed mapping entry at .ai/rule/gate/invariants.tsv:<line>: <reason>` |

A broken table line has the wrong column count, a bad id or file path, or a regex that doesn't
compile. The server fails closed on it. A partial table could wrongly report a file as
ungoverned, so the server gives no answer at all.

### Path check

The path check runs in two steps:

1. **Lexical.** The path is normalised and must lie under the root. This catches `../x` and
   `/etc/passwd`, even when the target doesn't exist.
2. **Resolved.** Symlinks are followed and the result must still lie under the root. This catches
   a link inside the repo that points outside it.

Ids and the invariant file paths in the table are checked against strict patterns too. So a
tampered table can't point the server at other files.

## Run

You need Python 3.10 or newer.

```bash
python3 -m venv .venv
.venv/bin/pip install -e '.[test]'
.venv/bin/python -m pytest -q
.venv/bin/invariants-mcp --repo-root /path/to/your/repo   # stdio; normally started by the client
```

Instead of `--repo-root` you can set `INVARIANTS_REPO_ROOT`.

## Register in Claude Code

```bash
claude mcp add --scope local invariants -- /abs/path/invariants-mcp/.venv/bin/invariants-mcp --repo-root /abs/path/to/repo
```

`--scope local` keeps it private to you in that project. `--scope project` writes a shared
`.mcp.json` instead. Check it with `claude mcp list`. The tools appear as
`mcp__invariants__get_invariants_for_file` and `mcp__invariants__get_invariant`.

## Example

```json
{"name": "get_invariants_for_file", "arguments": {"path": "src/governed.ts"}}
```

```json
{
  "path": "src/governed.ts",
  "count": 1,
  "invariants": [
    {
      "id": "INV-DEMO-1",
      "domain": "demo",
      "status": "binding",
      "has_test": true,
      "tests": ["src/__tests__/governed.test.ts"],
      "related": [],
      "source": ".ai/domain/demo/inv/INV-DEMO-1.md",
      "matched_by": ["path"],
      "text": "- **INV-DEMO-1 — Demo rule.** Volume is weight times reps."
    }
  ]
}
```

```json
{"name": "get_invariants_for_file", "arguments": {"path": "../secrets.txt"}}
```

```text
is_error: true
Error executing tool get_invariants_for_file: path is outside the repository: ../secrets.txt
```

## Limits

- An invariant with no `consumers` and no `content` can't be found by file, by the hook or by
  this server.
- `status` is passed through, not filtered.
- `has_test` means a test is listed. It does not mean the test exists or passes.
- The patterns are written as POSIX ERE for bash `=~`, and the server evaluates them with Python
  `re`. The generated path patterns mean the same in both. Hand-written keyword regexes could
  differ in rare cases.

Built on the official MCP Python SDK (`mcp` 2.x, `MCPServer`).