Skip to content

feat: MCP Execution Query Tools — async result polling (#19) - #167

Merged
vybe merged 1 commit into
Abilityai:mainfrom
webmixgamer:feature/19-mcp-execution-query-tools
Mar 25, 2026
Merged

vybe merged 1 commit into
Abilityai:mainfrom
webmixgamer:feature/19-mcp-execution-query-tools

Conversation

@webmixgamer

Copy link
Copy Markdown
Contributor

Summary

  • Three new MCP tools (list_recent_executions, get_execution_result, get_agent_activity_summary) enabling agents to query execution history and poll for async task results
  • Closes the async agent-to-agent collaboration loop: chat_with_agent(async=true) returns execution_id, then get_execution_result(id) polls until complete — bypassing the 60-second MCP timeout
  • No backend changes — all tools wrap existing REST endpoints with the same auth pattern as existing 59 tools
  • Total MCP tools: 59 → 62

Changes

MCP Server (5 files):

  • src/mcp-server/src/tools/executions.ts — NEW: 3 tools with agent-scoped access control
  • src/mcp-server/src/client.ts — Added getExecution(), getExecutionLog(), getActivityTimeline()
  • src/mcp-server/src/types.ts — Added ActivityTimelineResponse, ActivityEntry, extended ScheduleExecution
  • src/mcp-server/src/server.ts — Register 3 new tools
  • src/mcp-server/src/tools/index.ts — Export

Documentation (8 files):

  • docs/memory/changelog.md, requirements.md, architecture.md — Feature documented
  • docs/requirements/MCP_EXECUTION_QUERY_TOOLS.md — Status → Implemented
  • docs/memory/feature-flows/mcp-orchestration.md — Added MCP polling examples
  • docs/KNOWN_ISSUES.md — Updated 60s timeout workaround with get_execution_result
  • CLAUDE.md, README.md — Updated tool counts

Test plan

  • TypeScript compiles cleanly
  • MCP server starts with 62 tools registered
  • Level 1: All 3 tools return correct data via MCP Streamable HTTP protocol
  • Level 2: mem-agent async polls trinity-system through 90-second task (4 polls)
  • Level 2: mem-agent async polls trinity-system through 180-second task (6 polls, ~3.5 min total)
  • Auth: Agent-scoped keys can only access self or permitted agents

Closes #19

🤖 Generated with Claude Code

…aboration (Abilityai#19)

Three new MCP tools enabling agents to query execution history and poll
for async task results. Closes the async agent-to-agent collaboration
loop: chat_with_agent(async=true) → get_execution_result(id) polls
until complete, bypassing the 60-second MCP timeout limitation.

Tools:
- list_recent_executions: list executions across all trigger types
- get_execution_result: full execution details with optional transcript
- get_agent_activity_summary: aggregated activity counts for monitoring

Tested: Level 1 (direct MCP protocol calls) and Level 2 (mem-agent
async polling trinity-system through 90s and 180s tasks). No backend
changes — all tools wrap existing REST endpoints.

Closes Abilityai#19

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@vybe
vybe merged commit d4ecf47 into Abilityai:main Mar 25, 2026
@webmixgamer
webmixgamer deleted the feature/19-mcp-execution-query-tools branch March 25, 2026 17:05
webmixgamer added a commit that referenced this pull request Sep 23, 2026
…tured dependency; update_file containment via is_relative_to (#2915)

- tests: `TestRefusal` answered 401 under CI seed 12345 — an earlier module in
  that order leaves `routers.operator_queue` holding a different
  `get_current_user` object than a fresh `from dependencies import …` returns,
  so an override keyed on the fresh one is ignored and the real auth runs. The
  override now walks the router's dependant tree and keys off every captured
  `get_current_user`, asserting it found one. Mechanism reproduced locally with
  a reloaded `dependencies` module: old shape 401, new shape 409.
- agent server: `update_file` guards the workspace with resolved-path
  `is_relative_to`, the barrier `create_folder` already uses, instead of a
  string prefix that a sibling name such as `/home/developer2` satisfies.
  `test_update_file_containment_is_resolved_path_not_string_prefix` goes red
  with the string prefix restored (sibling case) and green on the branch.
- learnings fragment for the override-identity class.

CodeQL's 13 `py/path-injection` alerts on this handler are the unmodelled
containment-guard false positive of #167–#172 (create_folder); they need a
maintainer dismissal.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
vybe pushed a commit that referenced this pull request Sep 24, 2026
… delivery state, fingerprint reconcile, if_match write-back, 409 item_diverged, aging (#2915) (#2989)

* fix(operator-queue): the file sync tells the truth — per-row sync and delivery state, fingerprint reconcile, if_match write-back, 409 item_diverged, aging (#2915)

A pending approval sat unseen for six days because the agent rewrote and then closed its entry while the platform kept a create-only snapshot and read only the pending/acknowledged file statuses. The file contract stays; every way the two sides can disagree is now detected, recorded on the row, refused where it must be, and audited.

Backend
- Seven nullable operator_queue columns on both tracks (SQLite `operator_queue_sync_state`, Alembic `0071_operator_queue_sync_state`): sync_state/sync_detail/sync_updated_at/last_confirmed_at, delivery_state/delivery_detail/delivery_updated_at. No backfill: NULL renders as "not yet checked".
- The poller reconciles every file entry against its row through a pure content fingerprint (clamped title/question, canonical options, normalised expires_at): confirmed · changed · closed_by_filer · missing · stale_id · unconfirmed. One sync-index read per agent replaces the per-entry exists() probe (a pending entry re-using a terminal row's id was a phantom admit + a "new" broadcast every cycle). Writers are edge-triggered by rowcount; last_confirmed_at is refreshed once a minute per agent, batched.
- The cycle reads the tri-state agent_container_states() (Docker unreadable sweeps nothing), runs expiry BEFORE the no-running-agents return (an all-stopped fleet never expired anything), sweeps open rows of stopped agents to unconfirmed:agent_not_running, enters unconfirmed on a read failure only after three consecutive misses, and never writes back over an unparseable file (the old path overwrote the agent's file with the reconstructed responses alone).
- The write-back re-reads before writing and writes with if_match; the agent server's PUT /api/files is atomic (tmp + os.replace) and answers 412 on a mismatch. An answer is delivered only into a matching, still-pending entry (a rewritten one is undelivered:entry_changed); terminal flips are fetched by delivery state instead of a 168 h window; platform-minted rows are not_applicable and take no part in delivery.
- POST …/respond and the portal answer return 409 item_diverged while sync_state ∈ {changed, closed_by_filer} unless acknowledge_divergence is set (MCP respond_to_operator_queue takes the same parameter, only when given).
- operator_queue_aging_hours ops setting (default 24, 0 disables, validated 0–8760, admin-gated ops/config): aging/aged_since are computed once server-side on every list/get and in the portal projection; the receipt platform.aging_since is written into the file entry once at the crossing, taught in the prompt (both copies).
- Audit rows for the accountability transitions only (ingested · diverged · reconciled · written_back · undeliverable); the confirmed↔unconfirmed flap is never audited. One thin operator_queue_sync WS trigger per cycle (allow-listed as fleet-level, no payload).

Frontend
- ONE badge rule (utils/operatorQueue.js::queueSyncBadge) rendered as a BaseBadge by QueueCard, ResolvedCard and PortalAsks, and as a currentColor pill in /m. The store turns 409 item_diverged into a refetch + InlineError beside the controls; the next Send carries the acknowledgement (desktop, /m and the portal). The list's undelivered_count / closed_by_filer_count render in the Operations header with one-click cancel of closed items through the existing ConfirmDialog. The aging bound is a BaseInput in its own component under Settings → Operations.

Tests (the fix reverted from a scratch copy, 7 mutations, 7 red): tests/unit/test_2915_operator_queue_sync_honesty.py (divergence fixtures, hysteresis, no write on invalid JSON, tri-state cycle, one broadcast per cycle, write-back gating + if_match, re-read, receipt once, fingerprint stability, the accessors on a real migrated SQLite, both refusal entry points through the real router and service), tests/unit/test_2915_agent_server_files_if_match.py, operatorQueueSyncBadge / queueCardSyncBadge / operatorQueueAgingSetting specs (two mounted), a workspaceAsks case, and a /m e2e case; test_1632/1525 fakes made explicit; ent#467 allowlist.

Docs: requirements §26.8 OPS-001-HONEST, operating-room.md "Sync honesty", background-services / api-endpoints / database / workspace / frontend area files, the flows index, two learnings fragments.

Residuals registered in the debt inbox (trinity-enterprise#619/#611 own them): closed_by_filer rows still count toward the depth cap until cancelled; a response undelivered because the entry changed after the answer has no re-answer path; a re-ask with a reused id after acknowledged is swallowed by #1631's design.

Fixes #2915

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(operator-queue): fold the agent-authored type before it reaches the ingested audit row; cso diff report (#2915)

The new `ingested` audit row copied the entry's `type` — agent-authored and unbounded at ingest and at the DB sink — into audit_log.details, a hash-chained table that cannot be pruned for a year. It now carries the folded token or `other` (`_fold_agent_status`), pinned by a hostile-input test. Verified LOW by an independent verifier and fixed in-branch; the pre-existing unbounded `operator_queue.type` column is registered in the debt inbox. The cso --diff report for the branch is saved beside the prior ones: 0 open findings, 1 found-and-fixed, 7/7 mutations red.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(operator-queue): key the test's auth override off the routes' captured dependency; update_file containment via is_relative_to (#2915)

- tests: `TestRefusal` answered 401 under CI seed 12345 — an earlier module in
  that order leaves `routers.operator_queue` holding a different
  `get_current_user` object than a fresh `from dependencies import …` returns,
  so an override keyed on the fresh one is ignored and the real auth runs. The
  override now walks the router's dependant tree and keys off every captured
  `get_current_user`, asserting it found one. Mechanism reproduced locally with
  a reloaded `dependencies` module: old shape 401, new shape 409.
- agent server: `update_file` guards the workspace with resolved-path
  `is_relative_to`, the barrier `create_folder` already uses, instead of a
  string prefix that a sibling name such as `/home/developer2` satisfies.
  `test_update_file_containment_is_resolved_path_not_string_prefix` goes red
  with the string prefix restored (sibling case) and green on the branch.
- learnings fragment for the override-identity class.

CodeQL's 13 `py/path-injection` alerts on this handler are the unmodelled
containment-guard false positive of #167–#172 (create_folder); they need a
maintainer dismissal.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(operator-queue): review round 2 — wrong-shape files are unconfirmed, an acknowledged answer is delivered, a stopped agent is undelivered, platform alarms are never "missing" (#2915)

Blockers from the PR #2989 review, each pinned by a test that was red first:

- Wrong-shape JSON (`{"requests": {...}}`, a top-level array) is `unconfirmed:wrong_shape`
  at both reads and never a write — it used to read as an empty list, mark every row
  `missing`, overwrite the agent's file and record `delivered`.
- `acknowledge_divergence` reaches the file: the operator route and the portal answer stamp
  `divergence_acknowledged_at` (eighth column, same unshipped migration), and the write-back
  delivers into the entry as it is now — a rewritten entry, or one the agent closed (status
  → responded). A landed answer is recognised by its own `responded_at`, never by entry
  status, and `mark_acknowledged` flips a responded row only when `delivery_state = delivered`,
  so an entry the agent closed itself is no longer read as an ack of an answer never seen.
- The "rows the file no longer carries" loop skips platform-minted alarms (they were never
  in the file) and responded rows (the write-back re-appends them the same cycle); the
  `unconfirmed` sweeps exclude reserved id prefixes in SQL.

Warnings addressed:
- a duplicated id is reconciled once, first entry wins (no confirmed ↔ changed flip-flop);
- `if_match_holds` decodes with errors="replace", the same text the download endpoint serves;
- the fingerprint also covers type / priority / context / addressee (addressee only when the
  row resolved one — that value is a roster decision, not a copy);
- an answer or terminal flip owed to a non-running agent is `undelivered:agent_not_running`
  (edge-triggered, audited once) — AC3 on the row, not only the sync state;
- the terminal retry set excludes `entry_missing` (it can never land) and goes oldest first;
  the header's undelivered count excludes a dropped cancellation; the card copy stops
  promising a retry for it and names when it last tried;
- a file present at the cycle-start read and gone at the re-read is left alone that cycle.

Docs: operating-room.md, feature-flows.md, security.md §26.8, database/background-services/
api-endpoints area files.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MCP Execution Query Tools (MCP-007)

2 participants