Skip to content

moonlight-lupin/agent-skills / plugins/dev-pipeline/skills/review-lessons

review-lessons

Verified

Library of lessons from past build-review loops — not a stage. Use when a review or fix round hits a specific case: a reviewer BLOCKING that contradicts the brief, a test that passes but checks nothing, a feature dead in production, SQLite/WAL migrations, MCP tool surfaces, REST API authz, app ↔ external-source sync, Android/APK verification, fill-template extraction, CLI/git mechanics, reviewer outages. Load the one file the case needs; never load the whole library.

FileKindSize
SKILL.mdexecutableskill md5.5 KB
references/architecture-refactor-test-updates.mdexecutablescript2.9 KB
references/beta-gate-release-hardening.mdexecutablescript3.3 KB
references/ci-and-repo-hygiene.mdexecutablescript3.7 KB
references/confirm-loop-lessons.mdexecutablescript24.2 KB
references/cross-model-parallel-review.mdexecutablescript4.8 KB
references/data-integrity-principles.mdexecutablescript7.3 KB
references/delegate-skills-adaptation.mdexecutablescript2.1 KB
references/evidence-pairs.mdexecutablescript2.5 KB
references/extraction-from-filled-docs.mdexecutablescript6.1 KB
references/field-briefing-integration.mdexecutablescript5.2 KB
references/full-module-replacement-scoping.mdexecutablescript6.3 KB
references/generated-frontmatter-and-reviewer-outages.mdexecutablescript3.0 KB
references/loop-pitfalls.mdexecutablescript27.9 KB
references/mcp-category-tool-implementation.mdexecutablescript5.3 KB
references/mcp-design-review-patterns.mdexecutablescript5.7 KB
references/minified-bundle-selector-research.mdexecutablescript4.4 KB
references/mobile-app-verification.mdexecutablescript4.8 KB
references/multi-batch-sequencing.mdexecutablescript5.7 KB
references/parallel-dual-review.mdexecutablescript10.8 KB
references/pitfalls-dispatch-semantics.mdexecutablescript6.3 KB
references/pitfalls-fix-round-verification.mdexecutablescript6.6 KB
references/planning-with-files-adaptation.mdexecutablescript2.6 KB
references/plugin-gates-and-fix-rounds.mdexecutablescript8.2 KB
references/production-reachability-review.mdexecutablescript5.0 KB
references/reconciliation-review-findings.mdexecutablescript3.1 KB
references/rest-api-review-checklist.mdexecutablescript13.0 KB
references/review-findings-adjudication.mdexecutablescript34.4 KB
references/scope-test-in-process-execution.mdexecutablescript4.2 KB
references/security-property-tests.mdexecutablescript14.2 KB
references/sqlite-migration-pitfalls.mdexecutablescript4.1 KB
references/sqlite-wal-review-findings.mdexecutablescript5.0 KB
references/sync-pipeline-review-patterns.mdexecutablescript13.2 KB
references/tool-mechanics-pitfalls.mdexecutablescript44.1 KB
references/upgrade-path-test-pattern.mdexecutablescript3.0 KB

references/mcp-category-tool-implementation.md

View on GitHub
# MCP Category-Based Tool Implementation — Phase 5.14

Reference implementation for a 12-domain MCP tool surface with JIT discovery,
built on top of an existing CLI with 212 `cmd_*` handlers.

## Contents

- Architecture
- Key Design Decisions
- Test Coverage
- Pitfalls Encountered

## Architecture

```
CLI (212 cmd_* handlers)
  → _output/_error return (data, exit_code) tuples  [T2 refactor]
  → _run() wrapper in main() prints + exits for CLI

CommandRegistry (command_registry.py)
  → CommandMeta(name, domain, scope, description, handler)
  → Explicit scope per command (read/write/admin), default-deny
  → 12 domains: gl, ar_ap, company, crm, inventory, payroll,
    reports, recon_fx, budget, consolidation, documents, admin

MCP Server (mcp_server.py)
  → 12 @mcp.tool() functions (ledger_gl, ledger_ar_ap, ...)
  → _dispatch_domain() shared helper
  → Dynamic scope check inside execute (not just decorator)
  → Old 22 tools remain as backward-compat aliases
```

## Key Design Decisions

### 1. Return tuples instead of sys.exit (T2)

Handlers return `(data, exit_code)`. A thin `_run()` wrapper in `main()` prints
and exits for CLI. The registry's `execute()` method returns only `data`.

```python
def _output(data, exit_code=0):
    return (_serialize(data), exit_code)

def _error(msg: str):
    return ({"error": msg}, 1)

def _run(handler, args):
    result = handler(args)
    if isinstance(result, int):
        sys.exit(result)      # cmd_onboard returns int
    if isinstance(result, tuple):
        _print_and_exit(result)
    sys.exit(0)
```

### 2. Default-deny scope classification (T3)

Every `cmd_*` gets an EXPLICIT scope. Two allowlists (READ_COMMANDS,
ADMIN_COMMANDS), everything else defaults to `write`.

```python
READ_COMMANDS = frozenset({
    "cmd_entity_list", "cmd_user_list", "cmd_company_list", ...
})
ADMIN_COMMANDS = frozenset({
    "cmd_backup", "cmd_restore", "cmd_vacuum", "cmd_l10n_install", ...
})

def _scope_for(name: str) -> str:
    if name in ADMIN_COMMANDS:
        return "admin"
    if name in READ_COMMANDS:
        return "read"
    return "write"  # default-deny
```

### 3. Domain mapping with exact overrides (T3)

Some commands need exact-name overrides (checked before prefix matching):

```python
_DOMAIN_EXACT = {
    "cmd_report_ageing": "ar_ap",   # ageing report, not reports
    "cmd_init": "company",
    "cmd_backup": "admin",
    "cmd_export_trial_balance": "reports",
}
```

### 4. Dynamic scope check inside _dispatch_domain (T4)

The `@_require_scope("ledger:read")` decorator is the MINIMUM. The actual
write/admin check happens inside `_dispatch_domain` based on the command's
scope:

```python
def _dispatch_domain(domain, entity, action, args=None):
    _check_entity_access(entity, _get_principal())

    if action == "list":
        return [{"name": c.name, "scope": c.scope, ...}
                for c in COMMAND_REGISTRY.list_commands(domain)]

    if action == "execute":
        cmd_name = args.get("command")
        meta = COMMAND_REGISTRY.get(cmd_name)
        if meta.domain != domain:
            raise ValueError("wrong domain")
        # Dynamic scope check
        principal = _get_principal()
        if meta.scope == "write":
            _require_write_scope(principal)
        elif meta.scope == "admin":
            _require_admin_scope(principal)
        return COMMAND_REGISTRY.execute(cmd_name, call_args)
```

This lets a viewer call `ledger_admin(entity, action="list")` to SEE admin
commands (read scope is enough for discovery), but blocks execution of
admin-scoped commands (requires `ledger:admin`).

### 5. Three OAuth scopes (T1+T6)

```python
SCOPE_READ = "ledger:read"
SCOPE_WRITE = "ledger:write"
SCOPE_ADMIN = "ledger:admin"

def scopes_for_role(role):
    if role == "admin":
        return {SCOPE_READ, SCOPE_WRITE, SCOPE_ADMIN}
    if role == "accountant":
        return {SCOPE_READ, SCOPE_WRITE}
    return {SCOPE_READ}  # viewer
```

### 6. Nil principal = local stdio (no auth)

All scope helpers check `if principal is None: return` — local stdio MCP
(used by Claude Desktop) has no OAuth principal, so all operations are allowed.
The scope checks only fire when an HTTP transport provides a Bearer token.

## Test Coverage

| Test file | Tests | What it covers |
|---|---|---|
| test_command_registry.py | 13 | All 212 commands classified, scope/domain correctness |
| test_mcp_category_tools.py | 27 | list/execute dispatch, scope enforcement, entity isolation, all 12 domains |
| test_mcp_security.py | 40 (existing) | Old 22 tools backward compat — must pass unchanged |

## Pitfalls Encountered

1. **`cmd_onboard` returns `int`, not a tuple** — the `_run()` wrapper handles
   this with `isinstance(result, int)` check. Do not refactor `cmd_onboard`
   to return tuples; it's documented as "Never calls sys.exit" and returns
   0/1/2.

2. **`cmd_report_ageing` domain** — it's an ageing report but belongs to
   `ar_ap`, not `reports`. The `_DOMAIN_EXACT` dict handles this.

3. **213 dispatch sites, not 212** — there are 212 `cmd_*` handlers but 213
   `sys.exit(cmd_X(args))` calls in `main()` (one command has a subcommand
   alias). The regex replacement handles both.

4. **`_print_and_exit` sends errors to stderr** — the brief said stdout, but
   Cursor correctly sent errors to stderr as compact JSON so CLI output stays
   clean for piped consumers. This was a Cursor improvement over the brief.
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 322kUpdated Claude CodeCodexVerifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 322kUpdated Claude CodeCodexVerifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 322kUpdated Claude CodeCodexVerifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 198kUpdated Claude CodeCodexVerifiedInstall