Skip to content

feat: run_agent_loop MCP tool — sequential bounded task execution with configurable stop conditions #740

Closed

Description

@vybe

Summary

Add a run_agent_loop MCP tool that executes an agent task sequentially N times — either exactly N times (fixed mode) or up to N times with an early-exit signal from the agent (until mode). Loop state is managed server-side so the caller can disconnect after firing.

Context

Trinity has chat_with_agent (single turn) and fan_out (parallel batch) but no primitive for sequential bounded repetition — running the same task one after another, each run optionally informed by the previous.

Client-side looping breaks on tasks exceeding the 60-second MCP timeout. Server-side management lets the caller fire and disconnect.

Use cases: iterative refinement, agentic retry loops, multi-step pipelines where each step depends on the previous output, polling until a condition is met.

Proposed Design

Tool signature

run_agent_loop({
  agent_name: string,

  // Supports template vars: {{run}} (1-indexed), {{previous_response}} (last run's response)
  message: string,

  max_runs: number,         // required; hard cap; range 1–100

  // If set, enables "until" mode: stop early when response contains this string.
  // Recommended sentinel: "[[DONE]]"
  stop_signal?: string,

  delay_seconds?: number,   // pause between runs; default 0
  timeout_per_run?: number, // per-run timeout; defaults to agent's configured timeout
  model?: string,
  allowed_tools?: string[],
})
→ { loop_id: string, status: "queued", agent_name: string, max_runs: number }

Companion tools:

get_loop_status(loop_id: string)
→ { loop_id, status, runs_completed, stop_reason, runs: [{run_number, status, response_preview, cost, duration_ms}], last_response }

stop_loop(loop_id: string)   // graceful: waits for current run to finish
→ { status: "stopping" | "already_done" }

Execution model

Each loop iteration is a standard sequential task execution — same path as POST /api/internal/execute-task used by the scheduler. Loop fires iteration, waits for completion, checks stop signal, fires next. No parallelism.

Iteration 1 → execute-task → wait for done
Iteration 2 → execute-task → wait for done
Iteration 3 → execute-task → [[DONE]] in response → exit

Exit signal protocol

Agent includes [[DONE]] (or whatever stop_signal is set to) anywhere in its response. Loop runner checks after every run.

Acceptance Criteria

  • run_agent_loop tool: accepts agent_name, message, max_runs (required, 1–100), optional stop_signal, delay_seconds, timeout_per_run, model, allowed_tools
  • Message template supports {{run}} and {{previous_response}} substitution ({{previous_response}} truncated to last 2000 chars)
  • Each iteration dispatches through standard sequential task execution path (not parallel/stateless)
  • Loop runs server-side; caller receives loop_id immediately and can disconnect
  • Fixed mode (no stop_signal): runs exactly max_runs times
  • Until mode (stop_signal set): stops early when agent response contains the signal
  • get_loop_status returns status, runs completed, stop reason, per-run summaries, last full response
  • stop_loop signals graceful stop after current run completes
  • Loop state persisted in SQLite: new agent_loops + agent_loop_runs tables
  • WebSocket events: loop_run_completed, loop_completed
  • Same checkAgentAccess permission rules as chat_with_agent

Technical Notes

New files: src/mcp-server/src/tools/loops.ts, src/backend/routers/loops.py, src/backend/services/loop_service.py, src/backend/db/loops.py

Open question before build: should loop iterations appear as individual execution rows on the Timeline linked by loop_id, or as a collapsed loop group?

Activity

  1. added
    priority-p2
    type-feature
    on May 8, 2026
  2. added
    status-in-progress
    on May 20, 2026
  3. self-assigned this
    on May 20, 2026
  4. dolho commented on May 20, 2026

    @dolho
    Contributor

    Phase 1 implementation up for review: #902 (draft). Covers run_agent_loop/get_loop_status/stop_loop MCP tools, backend LoopService with cooperative stop + restart recovery, schema + migration for agent_loops + agent_loop_runs (plus loop_id on schedule_executions for timeline tagging), and 16 unit tests covering fixed/until modes, template substitution, graceful stop, and failure paths.

    Deferred: dedicated dashboard surface (timeline tagging is the Phase 1 affordance), auto-resume after restart, cross-agent loops.

  5. Keesan12 commented on May 23, 2026

    @Keesan12

    Phase 1 looks like the right shape. One field I would strongly consider before the schema settles is a compact loop receipt per run, not just counters in get_loop_status.

    For each iteration, I would want: run_number, input_template_hash, previous_response_hash, status, stop_reason, duration_ms, cost if known, and next_run_admitted: true/false with a short reason. That last bit matters because fixed and until loops fail differently: a timeout, a missing [[DONE]], and a policy denial should not all look like "run N did not finish".

    It also helps after disconnect/restart. The caller can see whether the loop stopped because the agent met the sentinel, exhausted the cap, hit a transient worker failure, or was deliberately denied another attempt. I am testing a similar receipt/admission pattern in MartinLoop, and this is the exact place I would want it if I were consuming the MCP tool from another orchestrator.

  6. 2 remaining items

  7. added
    status-in-dev
    and removed
    status-in-progress
    on Jun 3, 2026
  8. added a commit that references this issue on Jul 8, 2026
  9. removed
    status-in-dev
    on Aug 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

priority-p2theme-devextype-feature

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions