agentleFS
CaseyRoCaseyRo/mcp-stolperfalle/CLAUDE.md

mcp-stolperfalle

CLAUDE.md1 starsChanged 5 months agoMITView on GitHub

mcp-stolperfalle — a FastMCP server that captures and recalls experiential knowledge ("Knowledge Units" / KUs) for AI coding agents. Internal model is a superset of Mozilla AI's upstream cq schema; strict-mode serializer (to_cq_json_strict()) emits upstream-valid payloads, to_cq_json_rich() emits the full internal shape with Stolperfalle extensions. Upstream discussion of the extensions we propose: mozilla-ai/cq#286. Registry of extensions: docs/cq-extensions.md. Stolperfalle is an independent open-source project that Casey builds and maintains. Its longer aim is a machine-readable org layer: agents across teams and…

  • Reads credentials

The file

We split this CLAUDE.md into the rules it gives an agent

4 rules. About 0 are common, 1 is distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Add the method to KnowledgeStore (async, returns a dict via .model_dump(mode="json")).

    line 58
  2. Very specific:

    Add a test in tests/ using the store fixture (temp DB + NoOp embeddings + zero-signing-key).

    line 61
  3. Distinctive:

    Never edit existing columns in place.

    line 65
  4. Very specific:

    If you add a field that would ship on the wire, decide between strict upstream and Stolperfalle extension: extensions go in models.py AND …

    line 79

≈ “Common” is an estimate: at least 1 in 5 of the 29,248 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Project

mcp-stolperfalle — a FastMCP server that captures and recalls experiential knowledge ("Knowledge Units" / KUs) for AI coding agents. Internal model is a superset of Mozilla AI's upstream cq schema; strict-mode serializer (to_cq_json_strict()) emits upstream-valid payloads, to_cq_json_rich() emits the full internal shape with Stolperfalle extensions. Upstream discussion of the extensions we propose: mozilla-ai/cq#286. Registry of extensions: docs/cq-extensions.md.

Stolperfalle is an independent open-source project that Casey builds and maintains. Its longer aim is a machine-readable org layer: agents across teams and organisations sharing what they learn. Multi-tenant primitives (owner_org, TRUSTED_ORGS visibility) and emergent-signal detection are foundations, not the whole product.

Commands

Dependency + env management is uv.

uv sync                              # install deps (incl. dev group)
uv run mcp-stolperfalle              # run the server (stdio or HTTP per TRANSPORT env)
uv run mcp-stolperfalle migrate      # apply pending DB migrations + exit
uv run mcp-stolperfalle prune-backups [--confirm]   # clean .bak-pre-v<N> files
uv run mcp-stolperfalle detect-emergent             # run emergent-signal aggregation
uv run pytest                        # full test suite
uv run pytest tests/test_store.py::test_name        # single test
uv run ruff check src tests plugin   # lint
uv run mypy src                      # type-check
docker compose up --build            # HTTP mode on :8716 with persistent volumes

Tests force TRANSPORT=stdio, inject a deterministic zero-signing-key via MCP_STOLPERFALLE_SIGNING_KEY, and use NoOpEmbeddings. Do not rely on sentence-transformers being loaded in unit tests.

Architecture

Six MCP tools: query, propose, confirm, flag, reflect, status (see server.py). A thin tool layer over KnowledgeStore in store.py.

Schema evolution goes through migrations/. store._init_baseline() creates the v0-shape tables on a fresh install; then migrations.run() applies the ordered mNNNN_*.py modules to bring the DB to current (currently schema_version 6). Every migration declares version: int, breaking: bool, slug: str, and up(conn). Before any breaking=True migration, the runner copies the DB to <db>.bak-pre-v<N> and refuses to overwrite an existing backup.

KU model (models.py). Nested Pydantic: Context, Evidence, Provenance. On the wire:

  • to_cq_json_strict() — upstream-valid, extensions stripped, created_by from proposer_did, flag reasons mapped (dangerous → incorrect + local marker).
  • to_cq_json_rich() — full internal superset.

Stolperfalle extensions (all local-only, all documented in docs/cq-extensions.md): evidence.severity, evidence.contributing_orgs, context.environment, top-level kind/status/staleness_policy/related[]/owner_org, provenance.graduation_history/emergent.

Store layer (store.py). knowledge_units carries flat columns (one per scalar, JSON for arrays). FTS5 (ku_fts) + vec0 (ku_embeddings) virtual tables for hybrid search. query() applies the TRUSTED_ORGS visibility filter BEFORE confidence/severity ranking; zero-result queries record a row in query_misses for emergent detection. Every Nth miss triggers emergent.detect_emergent as a fire-and-forget background task.

Provenance (provenance.py). One Ed25519 keypair per install, identifier is did:key:z6Mk.... The private key lives OUTSIDE the DB — either /data/stolperstein.key (mode 0o600, on-disk filename intentionally unchanged by the product rename — see provenance.py) or MCP_STOLPERFALLE_SIGNING_KEY env var (base64). DB stores only the public key and DID string. This is security-critical (see security-review H1) — a DB leak must not compromise signing capability.

Emergent signals (emergent.py). Simple clustering: cosine ≥0.8 on miss embeddings, ≥5 misses across ≥2 distinct hour-buckets → emits a new tool-gap-signal KU with provenance.emergent=true. 7-day dedupe against recent emergent KUs. Runtime-disableable via STOLPERFALLE_EMERGENT_DISABLED or EMERGENT_DETECT_EVERY_N=0.

Reflect (reflect.py). LLM-driven extraction (Claude via the anthropic SDK, structured outputs, low effort) with a heuristic NLP fallback when CQ_LLM_API_KEY is unset or the call fails transiently (timeout, 5xx, refusal, bad output). Provider 400/401/403/404 is a config error and raises (LLMConfigError → ToolError / HTTP 502) instead of falling back; fallbacks are counted per reason in status.reflect_fallbacks. Candidates return flat context_* + severity so callers pass straight to propose().

Auth (auth.py). FastMCP's MultiAuth: Cloudflare Access OIDC for browser OAuth clients + static bearer tokens for Claude Code / n8n. Only engages when TRANSPORT=http. hmac.compare_digest for token comparison. Source of truth for deployment config is compose.yaml + .env.example.

Sync. There is no sync module: the SiYuan and cq team sync described in the early openspec changes was removed as dead code. compose.yaml passes no CQ_TEAM_* / CQ_SIYUAN_* variables.

Hook handlers (plugin/stolperfalle/hooks/handlers/). on_prompt.py, on_bash.py, on_stop.py + shared helpers (_client.py, _rate_limit.py, _inject.py, _signals.py, _debug.py). Require the server reachable over HTTP — hooks use MCP_STOLPERFALLE_PUBLIC_URL + MCP_STOLPERFALLE_API_KEY. Handlers are fully stdlib (no fastmcp import — Claude Code runs them with whatever python3 is on $PATH); _client.py POSTs to the /hook/* REST endpoints (1.5s query budget, bearer-token sanitization in error surfaces). All decisions are traceable via STOLPERFALLE_HOOKS_DEBUG=1 → $TMPDIR/stolperfalle-hooks-debug.jsonl; user-facing Stop-hook output must go through the JSON systemMessage field (stderr is invisible on exit 0). on_bash.py is registered for BOTH PostToolUse and PostToolUseFailure — PostToolUse never fires on nonzero exits (claude-code#6371), so without the failure registration the hook misses exactly the events it exists for. For a local-path marketplace install, hooks execute from THIS repo (CLAUDE_PLUGIN_ROOT = the repo's plugin dir), not the ~/.claude/plugins/cache copy — handler edits are live for the next hook firing, but hooks.json registration changes need a Claude Code restart.

Adding a new MCP tool

  1. Add the method to KnowledgeStore (async, returns a dict via .model_dump(mode="json")).
  2. Register in server.py with @mcp.tool(annotations=ToolAnnotations(...)). Be honest about idempotent_hint — confirm and flag are explicitly False because they mutate counters / state.
  3. Raise fastmcp.exceptions.ToolError with an actionable recovery hint on validation failure (never bare ValueError — LLM clients see it as an opaque internal error).
  4. Add a test in tests/ using the store fixture (temp DB + NoOp embeddings + zero-signing-key).

Schema changes

Never edit existing columns in place. Add a new migration module:

# src/stolperfalle/migrations/m000N_your_slug.py
version = N
breaking = True   # or False if purely additive
slug = "your_slug"

def up(conn: sqlite3.Connection) -> None:
    ...  # DDL + backfill
  • Tag renames, drops, retypes as breaking=True so the runner takes a snapshot.
  • Migrations run inside a single transaction each — raises roll back automatically.
  • If you add a field that would ship on the wire, decide between strict upstream and Stolperfalle extension: extensions go in models.py AND get a row in docs/cq-extensions.md.

Plugin

plugin/stolperfalle/ is a Claude Code plugin (registered via .claude-plugin/marketplace.json) that wraps these tools with SKILL.md (usage guidance + what's strict-CQ vs extension) and a real hooks.json manifest firing the three Python handlers above. See plugin/stolperfalle/SKILL.md for the STOLPERFALLE_HOOKS_DISABLED escape hatch and per-project overrides.

Deployment

Production builds from source on each merge to main (build: ., no registry) and sits behind a tunnel and an MCP portal. The container persists SQLite to the stolperstein-data volume (on-disk volume name intentionally unchanged by the product rename — see openspec/changes/archive/2026-07-11-rename-product-name/design.md) and FastMCP's OAuth client cache to fastmcp-data (FASTMCP_HOME=/data/fastmcp). The compose project name is pinned to the pre-rename value so those volumes are reused, not recreated. Deployment host details are kept out of this public repo.

The private signing key (/data/stolperstein.key) is sensitive. Filename intentionally unchanged by the rename. Exclude from volume backups and docker cp. Deploy-time checklist + rollback procedure in README.md.

Phase 1 vs Phase 2. owner_org + TRUSTED_ORGS land as foundation only — read-filter visibility, default-trust-all. Enforceable write-side org permissions, per-org UI, selective graduation are Phase 2 scope in a follow-up change. Don't attempt them here.

fastmcp 4 idioms

  • fastmcp>=4.0.10,<5.0.0; streamable-http with stateless_http=True passed to run()/http_app(), never the constructor (v4 rejects it).
  • Annotations are snake_case (read_only_hint, destructive_hint, ...). CI runs with FASTMCP_MCP_CAMELCASE_COMPAT=false, so camelCase access fails the build.
  • Failures raise ToolError. A returned error payload is logged by usage telemetry as outcome: ok.
  • src/stolperfalle/usage.py is vendored verbatim from the fleet's shared usage middleware; re-copy it, never edit it here.
  • Releases are tag-only by convention (no version-bump commits); this repo has no release workflow or tags yet. A merge to main redeploys (rebuild from source). Required checks: test and security.
  • Testing: the mcp-testing skill. Release/deploy: the cdit-release-pipeline skill.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.