feat(mcp): rule tools with a mandatory preview

Merged
SC
2mo ago
+1649-0

Summary

Closes #3819.

MCP clients can find transactions and edit them one at a time, but they can't see or manage rules. The REST API is read-only for rules. So an assistant that has worked out "every payment named X from this account is a loan repayment" has to walk the user through Settings → Rules instead of making the rule itself.

A rule is also riskier than most writes. It rewrites every matching transaction, and an active rule runs again on every family sync. A small slip, such as greater than 300 instead of equal to 300, keeps rewriting transactions until someone notices. So these tools make a preview part of the flow, and only one tool can activate a rule.

ToolRead/writeWhat it does
get_rulesreadRules with conditions and actions. Account, category, tag and merchant ids come back with their names. Also returns active, effective_date and the latest RuleRun. Paginated (50 per page, like get_categories), with a search that matches the rule name, condition and action values, and the names of categories it sets. With rule_id, it also returns the current match count.
get_rule_optionsreadThe condition types (with operators), action types and value formats. Fixed lists (transaction type, activity labels) are inlined. Id-valued fields point at get_accounts / get_categories / get_tags / get_merchants.
preview_rulereadFor a saved rule_id or an unsaved definition: match_count and a sample of the most recent matches, with their current category and merchant. Changes nothing.
create_rulewriteSaves a definition validated against the registry. Always saved inactive. Returns the same preview.
update_rulewriteRename, replace conditions/actions/effective_date, or active: false. Changing what an active rule matches or does deactivates it. It can't activate a rule.
apply_rulewriteActivates the rule and applies it in the background (Rule#apply_later), like the confirmation page's Apply. Requires the preview_token returned by preview_rule, create_rule or update_rule (never get_rules). The signed token is bound to the user, the rule's definition and its match count, and expires after 30 minutes. A preview with sample_size: 0 issues none. apply_rule refuses (preview_stale, with a fresh preview and token) if the rule or its matches changed since.

Behavior

  • Only apply_rule activates. create_rule ignores active. update_rule rejects active: true, and deactivates the rule when its conditions, actions or effective date change. So every version of a rule that runs has been previewed, with matching transactions shown, by whoever applies it.
  • Hand-set values are kept by default. apply_rule respects attribute locks unless override_locked: true is passed. The web Apply button always overrides them (ignore_attribute_locks: true). For an agent, keeping the user's manual edits seemed the safer default. Happy to flip it if you'd rather match the UI.
  • AI-backed actions are not available (auto_categorize, auto_detect_merchants). They cost money per transaction, and the UI shows a cost estimate first. They're left out of get_rule_options and rejected by create_rule. update_rule and apply_rule refuse to change or apply a rule that already has one, and send the user to Settings → Rules. They can be added later with the estimate in the preview.
  • Validation before saving. Unknown condition or action types, operators the filter doesn't support, missing or non-numeric values, nested compound conditions and ids outside the user's reach all come back together as invalid_rule with a problems list. Validation also builds (without running) each condition's query, which catches an operator a filter lists but cannot apply. For example, the tag filter offers != but raises on it. get_rule_options only lists = / is_null for tags.
  • Permissions. Rules are family-wide, like the web UI. Account ids (the condition and the transfer action) must be accounts the user can access. Merchant conditions use Family#available_merchants_for(user). match_count covers the whole family, because that's what the rule touches. The sample (and visible_match_count) only lists transactions in accounts the user can see. Account names the user can't see are never returned.
  • No delete_rule. update_rule active: false stops a rule and can be undone. Deleting stays in the UI.

Design notes

  • The shared code (definition parsing, validation, readable serialization, preview) is in Assistant::Function::RuleSupport. Allowed values are resolved from the requesting user rather than from the registry's option lists, because TransactionAccount#options and TransactionMerchant#options read Current.user, which is nil on the assistant/MCP paths.
  • Rule#matching_resources is a new public wrapper around the private matching_resources_scope, used by the preview to count and sample. It's next to matching_transaction_ids, which does the same for ids.
  • The tools are in the standard registry (not preview-gated), like create_transaction / delete_transaction. Gating them is a one-line move to PREVIEW_FUNCTION_CLASSES if you'd prefer.
  • docs/hosting/mcp.md lists the new tools.

Tests

  • Per tool, in test/models/assistant/function/:
    • readable output and name resolution, the active filter, pagination, search (name, grouped condition, action value, category name, a literal %), match count and last run, cross-family ids
    • options without AI actions, and tag operators limited to the ones that apply
    • preview of saved and unsaved rules (saves nothing, changes nothing), effective_date, compound or, all problems listed together, nested compounds, non-numeric amounts, unsupported tag operator, family-wide count with a user-scoped sample
    • create saves inactive (and ignores active), multi-tag action, duplicate actions, AI actions, foreign category, account the member can't see
    • update: rename keeps active, replacing conditions deactivates, actions replaced as a list, an invalid update changes nothing, can deactivate but not activate
    • apply: activates and categorises via RuleJob, stale count refused with nothing enqueued, locked values kept unless override_locked, AI actions refused
  • End to end over HTTP against a dev server, using a static MCP_API_TOKEN: tools/list, options, preview, create (inactive), stale apply_rule refused, narrowing with update_rule, apply → RuleJob categorises exactly the 2 matches, get_rules shows names and the last run, update_rule can deactivate but not activate.
  • Tried against a real family with 121 rules: an unpaginated get_rules returned about 68k characters, more than an MCP client takes in one tool result. That's why it's paginated and has search.
  • Full bin/rails test: 10,595 runs, 0 failures, 0 errors (33 skips). RuboCop and Brakeman are clean. There are no view, JS or UI changes, so no system tests, ERB lint or Biome changes.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Assistants can find and inspect transaction rules, review available rule options, and preview how rules would affect transactions.
    • Create rules in an inactive state, edit existing rules, and apply them through the assistant. Changes to a rule’s conditions or actions deactivate it; application is blocked if the rule or its matching transactions have changed since preview.
    • Applying a rule preserves manually locked values unless you choose to override them.
  • Documentation

    • Updated the available-tools guide with transaction rule capabilities and safeguards.