Skip to content

MCP: add progress notifications for sequant_run with graceful fallback #435

Closed

Description

@admarble

Problem

sequant_run is a long-running MCP tool (up to 30+ minutes for multi-issue runs). Today it:

  1. Buffers all stdout — no mid-execution updates reach the client
  2. 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
  3. 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

  1. Client sends a progressToken via _meta.progressToken in the tool request
  2. Batch executor emits structured SEQUANT_PROGRESS:{json} lines on stderr at each phase boundary
  3. MCP server streams stderr line-by-line, parses progress lines, and emits notifications/progress
  4. Client receives updates in real-time and can display them inline
  5. Spawn timeout auto-resets on each progress notification, preventing timeout on long but progressing runs
  6. Structured summary still returned at the end (no change to final response format)
  7. Graceful fallback — if no progressToken is 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_run handler accepts extra._meta?.progressToken and uses extra.sendNotification() to emit notifications/progress at 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), and message (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 maxTotalTimeout ceiling (e.g. 2 hours) prevents infinite runs even with progress resets.
  • AC-5: When no progressToken is 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: extra parameter typing updated from { signal: AbortSignal } to use the full RequestHandlerExtra from the MCP SDK (includes _meta, sendNotification, signal)
  • AC-8: The batch executor (src/lib/workflow/batch-executor.ts) emits SEQUANT_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_PROGRESS line 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:

  1. Extracts progressToken from extra._meta?.progressToken
  2. If present, creates a line buffer on the stderr stream
  3. Parses each line for the SEQUANT_PROGRESS: prefix
  4. Emits notifications/progress via extra.sendNotification()
  5. 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.length gives the base count
  • Quality loop retries are additive (not predictable), so total should update as retries are scheduled
  • If total can'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 progressToken in 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 typing
  • src/lib/workflow/batch-executor.ts — CLI-side: emit SEQUANT_PROGRESS:{json} lines at phase boundaries
  • src/mcp/tools/run.test.ts — Tests for progress notification emission, fallback behavior, timeout reset, line parsing
  • src/lib/workflow/batch-executor.test.ts — Tests for SEQUANT_PROGRESS line 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

  1. admarble commented on Mar 25, 2026

    @admarble
    ContributorAuthor

    Spec Plan — #435 MCP Progress Notifications

    Current State Analysis

    7 of 10 ACs are already implemented in main. Remaining work:

    AC Gap Work
    AC-4 Timeout reset on progress Add resettable timeout to spawnAsync with 30min/phase + 2hr ceiling
    AC-8 Only start events emitted Add completion/failure events + event field to batch executor
    AC-3 Message always says "started" Event-appropriate messages (started/✓/✗)
    AC-10 No progress tests Tests for parseProgressLine, createLineBuffer, timeout reset, emission

    AC Checklist

    • AC-1: progressToken extraction + sendNotification (done)
    • AC-2: Streaming stderr via createLineBuffer (done)
    • AC-3: Event-appropriate progress messages (start/complete/failed)
    • AC-4: Spawn timeout resets on progress (30min/phase, 2hr ceiling)
    • AC-5: No-op fallback without progressToken (done)
    • AC-6: RunToolResponse unchanged (done)
    • AC-7: RequestHandlerExtra typing (done)
    • AC-8: Batch executor emits start + complete + failed events
    • AC-9: Structured SEQUANT_PROGRESS prefix (done)
    • AC-10: Unit tests for all progress functions

    Implementation Plan

    Step 1: Extend ProgressEvent interface and emitProgressLine to support event types (start, complete, failed) with optional durationSeconds/error

    Step 2: Add completion/failure progress emissions in batch-executor.ts at phase boundaries

    Step 3: Add onProgress callback to SpawnOptions and implement resettable timeout in spawnAsync (30min per-phase + 2hr absolute ceiling)

    Step 4: Update emitProgress message generation based on event type

    Step 5: Add unit tests: parseProgressLine, createLineBuffer, timeout reset, emission with/without token

    Files to modify

    • src/mcp/tools/run.ts — ProgressEvent, parseProgressLine, spawnAsync timeout, emitProgress messages
    • src/lib/workflow/batch-executor.ts — emitProgressLine with event types, completion/failure emissions
    • src/mcp/tools/run.test.ts — New test suite for progress functions

    Recommended Workflow

    Phases: exec → qa
    Quality Loop: disabled

  2. added a commit that references this issue on Mar 25, 2026
  3. admarble commented on Mar 25, 2026

    @admarble
    ContributorAuthor

    QA Review — #435 MCP Progress Notifications

    Verdict: READY_FOR_MERGE

    All 10/10 AC items fully met.

    AC Coverage

    AC Status Evidence
    AC-1 ✅ MET progressToken extraction + sendNotification
    AC-2 ✅ MET createLineBuffer streams stderr line-by-line
    AC-3 ✅ MET formatProgressMessage with start/complete/failed variants
    AC-4 ✅ MET spawnAsync resettable timeout (30min phase, 2hr ceiling)
    AC-5 ✅ MET No-op guard when no progressToken
    AC-6 ✅ MET RunToolResponse unchanged
    AC-7 ✅ MET ToolHandlerExtra typing from MCP SDK
    AC-8 ✅ MET emitProgressLine with start/complete/failed at all phase boundaries
    AC-9 ✅ MET Structured SEQUANT_PROGRESS: prefix
    AC-10 ✅ MET 29 new unit tests + updated integration tests

    Quality Metrics

    • Type issues: 0 | Deleted tests: 0 | Files: 6 | +648/-90 lines
    • Test coverage: 2/2 changed source files have tests
    • CHANGELOG: Updated

    Key Changes

    • ProgressEvent extended with event, durationSeconds, error fields
    • spawnAsync internally detects progress lines and resets timeout
    • emitProgressLine emits at phase start, completion, and failure
    • Only complete/failed events increment progress counter

    PR: #449

  4. added 2 commits that reference this issue on Mar 25, 2026
  5. admarble commented on Mar 25, 2026

    @admarble
    ContributorAuthor

    Documentation Updated

    File: docs/features/mcp-server.md (existing doc, updated)

    Sections Updated:

    • What to Expect → During a run — progress notifications now cover start, complete, and failed events with timing/error details
    • sequant_run → Progress notifications — documented payload fields (progress, total, message), timeout reset behavior (30min per-phase, 2hr ceiling), and backward-compatible fallback
    • Troubleshooting → Client reports a timeout — added guidance for 2-hour ceiling and multi-issue batch splitting

    No new doc file needed — #435 enhances an existing feature already documented in mcp-server.md.

  6. added a commit that references this issue on Mar 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions