Skip to main content
Glama

invariants-mcp

A small read-only MCP 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:

---
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.

Related MCP server: repomap

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.

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

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

{"name": "get_invariants_for_file", "arguments": {"path": "src/governed.ts"}}
{
  "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."
    }
  ]
}
{"name": "get_invariants_for_file", "arguments": {"path": "../secrets.txt"}}
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).

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables coding agents to ask where behavior is enforced in a repository, returning source of truth, tests, callers, and line ranges without grepping.
      1
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Provides local-first repository architecture analysis with file-level proof, enabling agents to map codebases, locate implementations, trace call paths, and assess change impact with deterministic evidence.
      6
      15
      MIT
    • F
      license
      Not graded
      quality
      B
      maintenance
      Enables AI coding agents to interrogate a local repository deterministically for symbols, dependencies, call paths, routes, tests, and Git impact, returning verified structured evidence with exact line citations instead of requiring the whole codebase to be read.
      5
      -
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables AI agents to search and trace a unified domain map built from multiple Java repositories and project docs, returning services, classes, methods, routes, and tables with confidence and provenance. It also supports reading immutable evidence by ID, domain mapping, reverse-dependency impact analysis, full-text document search, and symptom-based troubleshooting.
      MIT