Repository navigation
Description
Problem
sequant_run is a long-running MCP tool (up to 30+ minutes for multi-issue runs). Today it:
- Buffers all stdout — no mid-execution updates reach the client
- Has a hardcoded 30-minute timeout — multi-issue runs regularly exceed this, causing the tool call to fail even though the underlying process completes successfully
- Returns everything at the end — the client (Claude) has no visibility into which issues/phases have completed
The polling workaround (sequant_status) exists but can't be used mid-tool-call — the client is blocked waiting for sequant_run to return.
Proposal — Hybrid Progress Notifications (Option C)
Use MCP's native notifications/progress protocol to emit phase-level updates during execution, while maintaining backward compatibility for clients that don't support progress tokens.
How it works
- Client sends a
progressTokenvia_meta.progressTokenin the tool request - Batch executor emits structured
SEQUANT_PROGRESS:{json}lines on stderr at each phase boundary - MCP server streams stderr line-by-line, parses progress lines, and emits
notifications/progress - Client receives updates in real-time and can display them inline
- Spawn timeout auto-resets on each progress notification, preventing timeout on long but progressing runs
- Structured summary still returned at the end (no change to final response format)
- Graceful fallback — if no
progressTokenis provided, behavior is identical to today
Progress notification payloads
// Phase started
{
method: "notifications/progress",
params: {
progressToken: token,
progress: 1, // phases completed so far
total: 12, // total phases across all issues (e.g. 4 issues × 3 phases)
message: "#325: spec started"
}
}
// Phase completed
{
method: "notifications/progress",
params: {
progressToken: token,
progress: 2,
total: 12,
message: "#325: spec ✓ (45s)"
}
}
// Phase failed
{
method: "notifications/progress",
params: {
progressToken: token,
progress: 3,
total: 12,
message: "#384: exec ✗ — QA verdict: AC_NOT_MET (retrying)"
}
}Structured progress line format (emitted by batch executor)
The batch executor emits structured lines on stderr at phase boundaries:
SEQUANT_PROGRESS:{"issue":325,"phase":"spec","event":"start"}
SEQUANT_PROGRESS:{"issue":325,"phase":"spec","event":"complete","durationSeconds":45}
SEQUANT_PROGRESS:{"issue":325,"phase":"spec","event":"failed","error":"timeout"}
This avoids fragile regex parsing of PhaseSpinner console output. The MCP layer is a consumer of these structured events.
Acceptance Criteria
- AC-1:
sequant_runhandler acceptsextra._meta?.progressTokenand usesextra.sendNotification()to emitnotifications/progressat phase boundaries - AC-2: stderr from the spawned process is consumed as a line stream (not buffered to completion) so progress events can be detected in real-time
- AC-3: Progress notifications include
progress(phases completed),total(total expected phases), andmessage(human-readable status like"#325: spec ✓ (45s)") - AC-4: The spawn timeout resets on each progress notification sent, preventing timeout on long but progressing runs. A
maxTotalTimeoutceiling (e.g. 2 hours) prevents infinite runs even with progress resets. - AC-5: When no
progressTokenis provided by the client, behavior is identical to current implementation (full buffer, structured response at end) — no breaking changes - AC-6: Final structured response format (
RunToolResponse) is unchanged — progress notifications supplement, not replace, the final result - AC-7:
extraparameter typing updated from{ signal: AbortSignal }to use the fullRequestHandlerExtrafrom the MCP SDK (includes_meta,sendNotification,signal) - AC-8: The batch executor (
src/lib/workflow/batch-executor.ts) emitsSEQUANT_PROGRESS:{json}lines on stderr at each phase start, completion, and failure — this is the source of progress events consumed by AC-2 - AC-9: The stdout/stderr parsing approach in the issue description uses the structured
SEQUANT_PROGRESS:prefix (not PhaseSpinner regex) — this is intentional to avoid fragile pattern matching against human-readable console output - AC-10: Unit tests cover: progress notification emission with token, no-op when token absent, line buffer handling of partial chunks, timeout reset on progress, and
SEQUANT_PROGRESSline parsing
Design Notes
Structured progress lines (AC-8)
The batch executor (src/lib/workflow/batch-executor.ts) already orchestrates phase execution per issue. At each phase boundary, it should emit a structured line to stderr:
// In batch-executor.ts, at phase start/complete/fail:
process.stderr.write(`SEQUANT_PROGRESS:${JSON.stringify({
issue: issueNumber,
phase: phaseName,
event: "start" | "complete" | "failed",
durationSeconds?: number, // on complete
error?: string, // on failed
})}\n`);Why stderr? Stdout is used for human-readable output (PhaseSpinner, summary tables). Stderr is the sideband for machine-readable progress. This separation avoids polluting the user-facing console output and keeps the rawOutput field clean.
Why not stdout parsing? PhaseSpinner output patterns (e.g. ✓ spec (1/3) (45s)) may change, use ANSI escape codes, or interleave unpredictably in concurrent mode. Structured lines are reliable and testable.
MCP-side consumption (AC-1, AC-2)
The MCP sequant_run handler:
- Extracts
progressTokenfromextra._meta?.progressToken - If present, creates a line buffer on the stderr stream
- Parses each line for the
SEQUANT_PROGRESS:prefix - Emits
notifications/progressviaextra.sendNotification() - Resets the spawn timeout on each notification
Timeout reset pattern (AC-4)
const PHASE_TIMEOUT = 1800000; // 30 min per-phase ceiling
const MAX_TOTAL_TIMEOUT = 7200000; // 2 hour absolute ceiling
const runStart = Date.now();
let timeoutHandle = setTimeout(killProcess, PHASE_TIMEOUT);
function resetTimeout() {
const elapsed = Date.now() - runStart;
if (elapsed >= MAX_TOTAL_TIMEOUT) {
killProcess();
return;
}
clearTimeout(timeoutHandle);
const remaining = Math.min(PHASE_TIMEOUT, MAX_TOTAL_TIMEOUT - elapsed);
timeoutHandle = setTimeout(killProcess, remaining);
}Each emitProgress() call invokes resetTimeout(). This means:
- A run that makes steady progress can exceed 30 minutes total
- A run stuck on a single phase for 30 minutes still times out
- No run can exceed 2 hours regardless of progress
extra typing (AC-7)
Current handler signature:
async (args, extra: { signal: AbortSignal }) => { ... }Should become:
type ToolHandlerExtra = RequestHandlerExtra<ServerRequest, ServerNotification>;
async (args, extra: ToolHandlerExtra) => { ... }This is the type that McpServer.registerTool() already passes — the current code just destructures it narrowly. Widening the type is non-breaking.
Phase count estimation for total
The total field in progress notifications requires knowing how many phases will run:
issues.length × phases.lengthgives the base count- Quality loop retries are additive (not predictable), so
totalshould update as retries are scheduled - If
totalcan't be determined upfront, omit it (the field is optional per MCP spec)
Potential Gaps
1. Claude Code client support
The MCP SDK protocol supports progressToken and resetTimeoutOnProgress. Whether Claude Code (as the MCP client) actually:
- Sends
progressTokenin tool requests - Displays progress notifications to the user
- Uses
resetTimeoutOnProgress
...is unknown without testing. The fallback (AC-5) ensures this isn't a blocker — if Claude Code doesn't send a token, nothing changes. But the feature only delivers value once the client participates.
Mitigation: Test with Claude Code after implementation. If Claude Code doesn't send progressToken, consider filing a feature request. The server-side implementation is correct regardless.
2. Concurrent issue interleaving
In non-sequential mode, multiple issues run in parallel. Their stderr lines interleave unpredictably. The SEQUANT_PROGRESS: line format includes the issue field explicitly, so the MCP layer can attribute phases correctly regardless of arrival order.
Mitigation: The structured line format handles this by design. The createLineBuffer handles partial chunks.
3. Notification ordering
MCP notifications are fire-and-forget (no ack). If the transport drops or reorders notifications, the client may see phases complete out of order.
Mitigation: Include monotonically increasing progress counter. Client should use progress value for ordering, not arrival order.
4. Memory — stderr still needed for error reporting
Even when streaming stderr for progress parsing, we still need the full stderr for error reporting in the final response. The streaming approach tees stderr into both the line-by-line parser and the existing buffer (already implemented via onStderr callback that runs alongside stderr += chunk).
5. Batch executor availability
The SEQUANT_PROGRESS: lines must be emitted by the batch executor in the spawned CLI process. If the CLI is an older version (e.g. globally installed) that doesn't emit these lines, no progress notifications will be sent — but the fallback (AC-5) ensures the run still completes normally.
Files to modify
src/mcp/tools/run.ts— MCP-side: streaming stderr, progress emission, timeout reset, extra typingsrc/lib/workflow/batch-executor.ts— CLI-side: emitSEQUANT_PROGRESS:{json}lines at phase boundariessrc/mcp/tools/run.test.ts— Tests for progress notification emission, fallback behavior, timeout reset, line parsingsrc/lib/workflow/batch-executor.test.ts— Tests forSEQUANT_PROGRESSline emission
References
- MCP SDK types:
@modelcontextprotocol/sdk/dist/esm/spec.types.d.ts—ProgressNotification,ProgressToken - MCP SDK handler extra:
@modelcontextprotocol/sdk/dist/esm/shared/protocol.d.ts—RequestHandlerExtra - Current run tool:
src/mcp/tools/run.ts - Batch executor:
src/lib/workflow/batch-executor.ts - Run log schema:
src/lib/workflow/run-log-schema.ts
Activity
admarble commentedon Mar 25, 2026
Spec Plan — #435 MCP Progress Notifications
Current State Analysis
7 of 10 ACs are already implemented in main. Remaining work:
spawnAsyncwith 30min/phase + 2hr ceilingeventfield to batch executorAC Checklist
Implementation Plan
Step 1: Extend
ProgressEventinterface andemitProgressLineto support event types (start,complete,failed) with optionaldurationSeconds/errorStep 2: Add completion/failure progress emissions in
batch-executor.tsat phase boundariesStep 3: Add
onProgresscallback toSpawnOptionsand implement resettable timeout inspawnAsync(30min per-phase + 2hr absolute ceiling)Step 4: Update
emitProgressmessage generation based on event typeStep 5: Add unit tests:
parseProgressLine,createLineBuffer, timeout reset, emission with/without tokenFiles to modify
src/mcp/tools/run.ts— ProgressEvent, parseProgressLine, spawnAsync timeout, emitProgress messagessrc/lib/workflow/batch-executor.ts— emitProgressLine with event types, completion/failure emissionssrc/mcp/tools/run.test.ts— New test suite for progress functionsRecommended Workflow
Phases: exec → qa
Quality Loop: disabled
feat(#435): add MCP progress notifications with timeout reset
admarble commentedon Mar 25, 2026
QA Review — #435 MCP Progress Notifications
Verdict: READY_FOR_MERGE
All 10/10 AC items fully met.
AC Coverage
Quality Metrics
Key Changes
ProgressEventextended withevent,durationSeconds,errorfieldsspawnAsyncinternally detects progress lines and resets timeoutemitProgressLineemits at phase start, completion, and failurePR: #449
fix(#435): add maxTotalTimeout test and make ceiling injectable
docs: update MCP server docs for #435 progress notification enhancements
admarble commentedon Mar 25, 2026
Documentation Updated
File:
docs/features/mcp-server.md(existing doc, updated)Sections Updated:
progress,total,message), timeout reset behavior (30min per-phase, 2hr ceiling), and backward-compatible fallbackNo new doc file needed — #435 enhances an existing feature already documented in
mcp-server.md.feat(#435): MCP progress notifications with timeout reset