MCP tools in a job

Closed
JO
9d ago
+910-87

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; a different account is an account_mismatch error. Legacy drafts marked only by source_pdf_import_id still use the existing draft guard.
  • 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.

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.


Summary by cubic

Moves AI-backed MCP tools and document upload indexing off the web thread: tools/call for AI tools now runs in Ai::ToolJob, and browser document uploads queue IndexFamilyDocumentJob instead of embedding inline. Web requests no longer hold a Puma request for the model call or embedding.

Key behaviors

  • The web thread polls Ai::SharedState instead of blocking on a Redis pop, caps concurrent waiters at two per process, and returns a busy tool error when workers aren't polling the AI queue or the wait cap is reached.
  • The tool job routes through the tool's feature lane, rechecks the user's authorized function list, and runs as that user. Tools without an available AI feature keep their inline paths and stay listed.
  • import_bank_statement returns the existing draft on a retry whose first response was lost (already_imported: true), repeats stored extraction-check warnings, and returns an account_mismatch error for a different account. A successful enqueue keeps its claim through polling failures, and an unsettled shared-state claim is retried rather than mistaken for a win.
  • Uploaded document bytes stay on a pending row until the embed job sends them; attachments purge only after a terminal status commits, a failed purge retries independently without re-indexing, and an enqueue failure keeps the bytes recoverable.
  • PDF imports can be stopped from the imports page: a Stop releases the processing claim, fences out a request already sent, and marks the import cancelled. A statement-less legacy import needs statement-manager permission to stop (guests can't).
  • Requires db:migrate: adds source_import_id to imports with a unique partial index; legacy drafts still use 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.