MCP tools in a job

Merged
JO
2d ago
+937-86

Replaces #5826, which came from a fork branch and so couldn't join the stack. Its earlier bot review threads are there.

What and why

tools/call ran AI-backed MCP tools inline on the web thread, holding a Puma request for the whole model call. This PR moves those calls to Ai::ToolJob on the tool's feature lane. The web thread polls Ai::SharedState rather than blocking on a Redis pop (which would hold a Sidekiq connection for the wait), caps concurrent waiters per process, and reports a busy tool error when workers are not polling or the wait cap is reached. It also makes import_bank_statement idempotent so a retry whose response was lost returns the same draft instead of extracting again.

Based on: #5784 (feat/ai-4c-typing-hold), the last part of the sequencer stack. This PR is a plain PR — it is not stacked on #5748 or on any other feature PR, and it will retarget to refactor/ai-plumbing when 4c lands.

Plan: delivery plan §1–§2/M1–M3, with the design in PR 3, the redesign and the Workbench comparison.

What changes

  • Ai::ToolJob enqueues an AI-backed tool on Ai::Routes.queue_for(feature), writes the answer to Ai::SharedState, and caps concurrent web waiters at two per process. Busy and timeout answers keep the existing tools/call envelope with isError: true and a model-facing retry hint.
  • Only functions that declare an ai_feature and have it available go through the job. Chat and tools without a route keep their inline paths. search_family_files declares :search_documents but stays listed so its metadata fallback remains available when AI is off.
  • The job rechecks the user's authorized function list and runs as that user, preserving tool-level permission checks. Exceptions are logged without exposing provider text to the client.
  • Migration: imports.source_import_id gets a self-referencing foreign key and a unique partial index. A completed import_bank_statement that finished after its client gave up returns the same draft with already_imported: true. Legacy drafts marked only by source_pdf_import_id still use the existing draft guard.
  • What MCP clients see change: import_bank_statement keeps one draft per statement.
    • The same statement with a different account_id returns account_mismatch, where it used to create a second import.
    • A failed draft with no entries returns draft_already_exists until the user deletes it, where it used to extract again.
    • When no job could be started (the waiter cap is full, or no worker polls the AI queues), the answer is "Busy, try again.". "Still extracting; call again…" means a job is running.
  • The import's in-flight claim lasts an hour; the job renews it when it starts and clears it when it ends, so a long AI queue can't let a retry start a second extraction.
  • Host and pipeline docs describe the worker path and the idempotent retry. Minitest covers lane routing, worker/unavailable/busy paths, the hand-off, authorization, the unique index and migration round-trip.

Validation

Review fixes: Claim races hardened and extraction check warnings repeated on already-imported retries. Round 2 (a179d5056): the not-started busy reply, and the longer, renewed in-flight claim.

Checks after round 2 (local, on this branch, merged up to 4c): full Rails suite 20,408 runs / 222,043 assertions / 0 failures / 0 errors / 32 skips. RuboCop, erb_lint, Brakeman, Biome lint and the node tests (323) are clean.

Checks (local, on this branch, after the editor pass): full Rails suite 19,339 runs / 212,910 assertions / 0 failures / 0 errors / 32 skips; focused Minitest for the job, hand-off, authorization and migration 128 runs / 3,172 assertions / 0 failures / 0 errors; system tests 514 runs / 2,832 assertions / 0 failures / 0 errors. RuboCop, erb_lint, Biome lint and Brakeman are clean. npm run format:check reports the same 77 pre-existing errors as the base commit, none in this diff. The first full run hit one unrelated SimplefinItem::ImporterSnapshotConcurrencyTest timeout; that test passed in isolation and the clean full rerun is reported above.

Editor pass: collapsed the in-flight claim to one shared inflight_key (only import_bank_statement claims one), stopped search from taking an in-flight slot, clarified the rescue path, corrected the hosting doc wording, and reduced the tool-job tests from 12 to 8.

sure-dev verification: MCP search_family_files returned the uploaded memo through Ai::ToolJob; import_bank_statement created one derived import carrying the new source_import_id; two concurrent calls with the same pdf_import_id returned the same import id and created only one derived row.

Live provider calls: none. Automated validation used the stubbed transport only; RubyLLM version on this base: 2.2.3 (from Gemfile.lock). The manual dev-pod checks used the pod's local llama.cpp/pgvector services, not a hosted provider.

🤖 Generated with Claude Code

https://claude.ai/code/session_016zAWUWiGdNK4xoU3JEzKbB


Summary by cubic

Moves AI-backed MCP tools off the web thread: tools/call runs tools with an available AI feature in Ai::ToolJob on the tool's feature lane, and the web thread polls Ai::SharedState instead of blocking on Redis, capped at two concurrent waiters per process. When no worker polls the AI queues or the wait cap is reached, the call answers a generic "busy" error; "Still extracting" now appears only when the import's job is actually running. Tools without a routed AI feature, including search_family_files' metadata fallback, keep their inline paths.

import_bank_statement is now idempotent: a retry whose response was lost returns the existing draft with already_imported: true, repeats stored extraction-check warnings, and answers account_mismatch for a different account. A successful enqueue keeps its in-flight claim through polling failures; the claim lasts an hour and is renewed when the job starts, so a retry facing a long AI queue joins the queued job instead of starting a second extraction. An unsettled claim is retried rather than mistaken for a win, and a retry joins a running job only after rechecking the caller's authorization.

Migration

  • Requires db:migrate: adds source_import_id to imports with a unique partial index; legacy drafts keep the source_pdf_import_id guard.

Summary by CodeRabbit

  • New Features
    • AI-backed search and bank-statement tools can run in the background, with clear busy or error responses when they can’t be processed.
    • Family file search remains available even when its AI feature isn’t enabled.
    • Repeating a bank-statement import for the same account reuses the existing result instead of extracting it again.
  • Bug Fixes
    • Bank-statement imports now detect account mismatches and existing drafts, helping prevent duplicate or conflicting imports.
  • Documentation
    • Updated guidance on AI tool processing and retrying bank-statement imports.