Skip to content

MCP server: improve sequant_run output structure #391

Closed

Description

@admarble

Context

In #372, sequant_run returns output.slice(-2000) — the raw tail of stdout. For multi-issue workflows, this may only capture the end of the last issue with no summary of earlier ones.

Goal

Return structured output from sequant_run so MCP clients get a useful summary regardless of output length.

Acceptance Criteria

  • sequant_run returns structured JSON with per-issue summaries
  • Each issue includes: status, phases completed, verdict (if QA ran), duration
  • Raw output still available but as a secondary field
  • Total output respects MCP response size limits

Activity

  1. added
    enhancement
    multi-agent
    on Mar 23, 2026
  2. admarble commented on Mar 23, 2026

    @admarble
    ContributorAuthor

    Spec Plan — #391: MCP server: improve sequant_run output structure

    AC Quality Check

    ⚠️ AC items use plain checkbox format (no AC-N: identifiers). Renumbered below for tracking.

    • ✅ AC-1 (structured JSON): Clear and testable
    • ✅ AC-2 (per-issue fields): Clear — status, phases, verdict, duration are well-defined
    • ✅ AC-3 (raw output secondary): Clear and testable
    • ⚠️ AC-4 (MCP response size limits): "Respects MCP response size limits" — threshold not specified
      → Suggest: Define a concrete limit (e.g., total response ≤ 64 KB; truncate rawOutput to fit)

    Summary: 3/4 AC items clear; 1 flagged for threshold clarification.


    Scope Assessment

    Non-Goals (Required)

    ⚠️ Non-Goals section not found in issue. Recommended boundaries:

    Scope Metrics

    Metric Value Status
    Feature count 1 ✅
    AC items 4 ✅
    Directory spread 2 (src/mcp/tools/, src/lib/workflow/) ✅

    Scope Verdict

    ✅ SCOPE_OK — Single focused feature, modifying output format of one MCP tool.


    Acceptance Criteria

    AC-1: sequant_run returns structured JSON with per-issue summaries

    Verification Method: Unit Test + Integration Test

    Test Scenario:

    • Given: sequant_run completes a multi-issue run (mocked spawnAsync)
    • When: The tool handler parses stdout and builds the response
    • Then: Response JSON contains an issues array with one entry per issue processed, each containing summary fields

    Integration Points: spawnAsync, LogWriter JSON output, run-log-schema.ts types

    AC-2: Each issue includes status, phases completed, verdict (if QA ran), duration

    Verification Method: Unit Test

    Test Scenario:

    • Given: A completed run log with 2 issues (one success with QA verdict, one failure)
    • When: The structured response is built from the log
    • Then: Each issue entry has status, phases (array of {phase, status}), verdict (present only when QA ran), durationSeconds

    AC-3: Raw output still available but as a secondary field

    Verification Method: Unit Test

    Test Scenario:

    • Given: A completed run producing stdout output
    • When: The structured response is built
    • Then: Response includes a rawOutput field containing the tail of stdout (≤ 2000 chars), and the primary fields are the structured summary

    AC-4: Total output respects MCP response size limits

    Verification Method: Unit Test

    Test Scenario:

    • Given: A run producing very large stdout (e.g., 100 KB)
    • When: The structured response is built
    • Then: Total JSON response size ≤ 64 KB; rawOutput is truncated to fit; structured fields are preserved in full

    Assumptions to Validate:

    • 64 KB is an appropriate MCP response size target (MCP spec doesn't define a hard limit, but practical clients buffer ~100 KB)

    Implementation Plan

    Phase 1: Define structured response types

    1. Create response type in src/mcp/tools/run.ts (or a shared types file):

      interface RunToolIssueSummary {
        issueNumber: number;
        status: "success" | "failure" | "partial";
        phases: Array<{ phase: string; status: string; durationSeconds: number }>;
        verdict?: string;      // QA verdict if QA phase ran
        durationSeconds: number;
      }
      
      interface RunToolResponse {
        status: "success" | "failure";
        exitCode?: number;
        issues: RunToolIssueSummary[];
        summary: { total: number; passed: number; failed: number; durationSeconds: number };
        phases: string;
        rawOutput?: string;    // truncated tail of stdout
        error?: string;        // truncated stderr on failure
      }
    2. These types align with the existing RunLog / IssueLog / PhaseLog schemas in run-log-schema.ts — we reuse the same shape.

    Phase 2: Parse structured data from run output

    1. Add a log-file reader to the tool handler. Since --log-json is always passed, after spawnAsync completes:

      • Read the most recent log file from .sequant/logs/
      • Parse it with RunLogSchema.parse()
      • Extract per-issue summaries

      Why read the log file instead of parsing stdout? The LogWriter already produces validated, structured JSON. Parsing stdout is fragile (mixed with human-readable output). The log file is the authoritative structured record.

    2. Fallback: If log file is missing or unparseable (e.g., process crashed before finalizing), fall back to the current output.slice(-2000) behavior with issues: [].

    Phase 3: Build and return structured response

    1. Replace the current response construction (lines 89–119 in run.ts) with:

      • Map RunLog.issues → RunToolIssueSummary[]
      • Compute summary stats from RunLog.summary
      • Include rawOutput: result.stdout.slice(-2000) as secondary field
      • Enforce size limit: if total JSON > 64 KB, progressively truncate rawOutput
    2. Size guard: JSON.stringify() the response, check .length, and shrink rawOutput if needed.

    Phase 4: Tests

    1. Unit tests in src/mcp/server.test.ts or a new src/mcp/tools/run.test.ts:
      • Mock spawnAsync to return known stdout
      • Mock log file reads to return known RunLog data
      • Verify structured response shape
      • Verify size limit enforcement
      • Verify fallback when no log file exists

    Feature Quality Planning

    Completeness Check

    • All AC items have corresponding implementation steps
    • Integration points: LogWriter (produces log files), spawnAsync (produces stdout), run-log-schema.ts (types)
    • No partial implementations planned
    • State management: N/A
    • Data flow: spawnAsync → read log file → map to response type → size guard → return

    Error Handling

    • Log file missing → fallback to raw output with issues: []
    • Log file corrupt/unparseable → same fallback
    • Process crash before log finalization → same fallback
    • Oversized response → progressive rawOutput truncation

    Code Quality

    • Types fully defined (reuses existing Zod schemas)
    • Follows existing MCP tool patterns (sequant_logs already reads log files)
    • No magic strings — size limit as named constant

    Test Coverage Plan

    • Unit tests for response construction from RunLog
    • Unit test for size limit enforcement
    • Unit test for fallback when log unavailable
    • Edge: empty run (0 issues), single issue, multi-issue

    Best Practices

    • No new dependencies needed
    • Security: no user input in file paths (log dir is hardcoded)
    • Backwards compatible: MCP clients parsing old format get same status/output fields

    Derived ACs

    Source Derived AC Priority
    Error Handling AC-5: Graceful fallback to raw output when log file is unavailable High
    Best Practices AC-6: Response includes same top-level status field for backwards compatibility Medium

    Conflict Risk Analysis

    In-flight work detected: Issue #389 (feature/389-mcp-server-prevent-nested-npx-version-mismatch-in-)
    Overlapping files:

    Recommended approach:

    Selected: Option A recommended — #389 is a small targeted fix.


    Open Questions

    1. MCP response size limit threshold
      • Recommendation: 64 KB (conservative; most MCP clients handle 100 KB+)
      • Impact: Too small → useful output truncated; too large → client buffering issues

    Recommended Workflow

    Phases: spec → testgen → exec → qa
    Quality Loop: disabled
    Reasoning: New feature with 4 AC items and Unit Test verification methods. testgen will create test stubs before implementation. Single-feature scope, no browser testing needed.


    Label Review

    Current: enhancement, multi-agent
    Recommended: enhancement, multi-agent, mcp
    Reason: All MCP server issues should share a label for filtering.

    → gh issue edit 391 --add-label mcp


    Verification Methods Summary

    AC Method Automated?
    AC-1: Structured JSON with per-issue summaries Unit + Integration Test ✅
    AC-2: Per-issue status/phases/verdict/duration Unit Test ✅
    AC-3: Raw output as secondary field Unit Test ✅
    AC-4: MCP response size limits Unit Test ✅
    AC-5 (derived): Fallback when log unavailable Unit Test ✅
    AC-6 (derived): Backwards-compatible status field Unit Test ✅
  3. added
    planned
    on Mar 23, 2026
  4. added a commit that references this issue on Mar 23, 2026
  5. admarble commented on Mar 23, 2026

    @admarble
    ContributorAuthor

    Exec Phase — Progress Update

    AC Coverage

    AC Source Description Status
    AC-1 Original Structured JSON with per-issue summaries ✅ Implemented
    AC-2 Original Per-issue status/phases/verdict/duration ✅ Implemented
    AC-3 Original Raw output as secondary field ✅ Implemented
    AC-4 Original MCP response size limits (64KB) ✅ Implemented
    AC-5 Derived Graceful fallback when log unavailable ✅ Implemented
    AC-6 Derived Backwards-compatible status field ✅ Implemented

    Key Files Changed

    File Change
    src/mcp/tools/run.ts Structured response builder, log reader, size guard
    src/mcp/tools/run.test.ts 16 unit tests for structured output
    src/mcp/server-extended.test.ts Updated assertions for new response shape
    CHANGELOG.md Added [Unreleased] entry

    Quality Results

    Check Status
    npm run build ✅ Pass
    npm run lint ✅ Pass (0 errors, 0 warnings)
    npm test ✅ 1773 tests pass (76 files)

    Quality Plan Alignment

    Quality Dimension Items Addressed Notes
    Error Handling 3/3 Missing log, corrupt log, process crash fallback
    Test Coverage 4/4 Unit tests for all AC items + edge cases
    Code Quality 2/2 Types defined, reuses existing RunLog schema
    Best Practices 1/1 Size limit as named constant, no magic strings

    Derived ACs: 2/2 addressed

    PR

    ✅ Created: #407

  6. admarble commented on Mar 23, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #391

    AC Coverage

    AC Source Description Status Notes
    AC-1 Original Structured JSON with per-issue summaries MET issues array with RunToolIssueSummary objects, summary aggregate stats. Verified in 16 unit tests + integration test.
    AC-2 Original Per-issue status/phases/verdict/duration MET Each issue has status, phases[] (with per-phase duration), conditional verdict (only when QA ran), durationSeconds. Test verifies verdict omission when no QA.
    AC-3 Original Raw output as secondary field MET rawOutput field with 2000-char tail truncation. Primary fields are structured issues/summary.
    AC-4 Original MCP response size limits MET 64 KB limit enforced via enforceResponseSizeLimit() with progressive truncation (rawOutput first, then error). Test creates 100 KB input and verifies output ≤ 64 KB.
    Derived ACs
    AC-5 Derived (Error Handling) Graceful fallback when log unavailable MET readLatestRunLog() returns null on missing dir, empty dir, or corrupt JSON. buildFallbackResponse() returns empty issues[] with raw output. 4 tests cover fallback paths.
    AC-6 Derived (Best Practices) Backwards-compatible status field MET Top-level `status: "success"

    Coverage: 6/6 AC items fully met
    Original ACs: 4/4 met
    Derived ACs: 2/2 met


    Quality Plan Verification

    Quality Plan found: Yes (from spec comment)

    Dimension Items Planned Items Addressed Status
    Completeness 4 4 ✅ Complete
    Error Handling 3 3 ✅ Complete (missing log, corrupt log, process crash)
    Code Quality 3 3 ✅ Complete (types defined, reuses RunLog schema, named constants)
    Test Coverage 4 4 ✅ Complete (response construction, size limit, fallback, edge cases)
    Best Practices 3 3 ✅ Complete (no new deps, no user input in paths, backwards compat)
    Polish N/A N/A - (not UI feature)

    Derived ACs: 2/2 addressed
    Quality Plan Status: Complete


    CI Status

    No CI checks configured for this repository.

    CI-related AC items: None


    Quality Metrics

    Metric Value Status
    Type issues (any) 2 (test-only as any for fs mock typing) OK
    Deleted tests 0 OK
    Files changed 4 OK
    Lines added +589 OK
    Lines deleted -26 OK

    Stale Branch Check

    Check Value
    Commits behind main 4
    Threshold 5
    Status ⚠️ Warning

    Feature branch is 4 commits behind main. Consider rebasing before merge.


    Test Coverage Analysis

    Changed File Tier Has Tests? Test File
    src/mcp/tools/run.ts Standard ✅ Yes src/mcp/tools/run.test.ts (16 tests)
    src/mcp/server-extended.test.ts - Test file itself -
    CHANGELOG.md Optional N/A -

    Coverage: 1/1 changed source files have corresponding tests
    Critical paths without tests: None


    Code Review

    Strengths:

    • Clean separation: buildStructuredResponse, buildFallbackResponse, enforceResponseSizeLimit as focused functions
    • Reuses existing RunLogSchema and RunLog types — no type duplication
    • Progressive truncation strategy is well-designed (rawOutput → error → done)
    • Test coverage is thorough: 16 unit tests covering happy path, edge cases, size limits, and all fallback paths
    • Integration test updated to validate new response shape
    • CHANGELOG entry is well-structured with correct format

    Issues:

    • Stale log risk (minor): readLatestRunLog() reads the most recent log file by filename sort but doesn't verify the log belongs to the run that just completed. If a previous run's log exists and the current run crashes before writing its log, stale data would be returned. Mitigation: The fallback path handles this gracefully (empty issues array), and in practice the most recent log should match since --log-json always writes. Consider correlating by timestamp window in a follow-up.

    Suggestions (non-blocking):

    • Lines 282/291: overallStatus as "success" | "failure" is a redundant cast — the ternary already produces that type
    • enforceResponseSizeLimit mutates the response object directly. Consider returning a new object for purity, though this is minor since it's called at the end of construction

    Test Quality Review

    Category Status Notes
    Behavior vs Implementation ✅ OK Tests assert on output shape, not internals
    Coverage Depth ✅ OK Error paths (null log, corrupt log, empty dir), edge cases (0 issues, single issue, huge output)
    Mock Hygiene ✅ OK Only fs module mocked (external dependency)
    Test Reliability ✅ OK Deterministic, no timing dependencies

    Issues Found: None


    Anti-Pattern Detection

    Dependency Audit

    N/A - No dependency changes

    Code Patterns

    File:Line Category Pattern Suggestion
    run.ts:87 Error Handling Empty catch block Acceptable — intentional fallback for AC-5 (returns null on any error)

    Critical Issues: 0
    Warnings: 0


    Call-Site Review

    New exported functions detected: 2

    Function Call Sites Loop? Conditions AC Match
    readLatestRunLog() run.ts:275 No After spawnSync completes ✅ Matches AC-5 (fallback path)
    buildStructuredResponse() run.ts:279 No if (runLog) guard ✅ Matches AC-1 (structured output when log available)

    Findings: All call sites match AC constraints correctly. Fallback path correctly uses buildFallbackResponse when readLatestRunLog returns null.


    Execution Evidence

    N/A - No scripts/ or CLI command changes


    Skill Command Verification

    N/A - No skill files changed


    CLI Registration Verification

    N/A - No option interface changes


    CHANGELOG Verification

    Check Status
    CHANGELOG.md exists ✅ Found
    User-facing changes ✅ Yes (feat: commit)
    [Unreleased] entry ✅ Present
    Entry format ✅ Valid (includes #391, action verb, sub-items)

    Result: CHANGELOG requirements met


    Self-Evaluation

    • Verified working: Yes — build passes, all 1773 tests pass (including 16 new + updated integration tests)
    • Test efficacy: High — tests cover structured response shape, size limits, fallback paths, edge cases (0 issues, single issue, no QA verdict)
    • Likely failure mode: Stale log file from a previous run being read instead of the current run's log. Mitigated by fallback path returning empty issues, and in practice the most recent log should match.
    • Verdict confidence: High — all AC items verified literally against implementation and tests

    Verdict: READY_FOR_MERGE

    All 6 AC items (4 original + 2 derived) are fully met. Implementation is clean, well-tested, and follows existing patterns. The stale-log-risk is minor and non-blocking (graceful fallback exists). Branch is 4 commits behind main — recommend rebasing before merge.

    Documentation

    • CHANGELOG entry added
    • N/A - No new user-facing CLI flags or config options requiring README update

    Next Steps

    1. Rebase on main to pick up the 4 commits behind
    2. Merge PR feat(#391): improve sequant_run MCP tool output structure #407

    QA completed: 6/6 AC items met

  7. added
    ready-for-review
    on Mar 23, 2026
  8. admarble commented on Mar 24, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #391 (Re-run)

    AC Coverage

    AC Source Description Status Notes
    AC-1 Original Structured JSON with per-issue summaries MET issues array with RunToolIssueSummary objects, summary aggregate stats. 16 unit tests + integration test.
    AC-2 Original Per-issue status/phases/verdict/duration MET Each issue has status, phases[] (with per-phase duration), conditional verdict (only when QA ran), durationSeconds.
    AC-3 Original Raw output as secondary field MET rawOutput field with 2000-char tail truncation. Primary fields are structured issues/summary.
    AC-4 Original MCP response size limits (64KB) MET enforceResponseSizeLimit() with progressive truncation. Test verifies 100KB input → ≤64KB output.
    Derived ACs
    AC-5 Derived (Error Handling) Graceful fallback when log unavailable MET readLatestRunLog() returns null on missing/empty/corrupt. buildFallbackResponse() returns empty issues with raw output.
    AC-6 Derived (Best Practices) Backwards-compatible status field MET Top-level `status: "success"

    Coverage: 6/6 AC items fully met
    Original ACs: 4/4 met
    Derived ACs: 2/2 met


    Quality Plan Verification

    Quality Plan found: Yes

    Dimension Items Planned Items Addressed Status
    Completeness 4 4 ✅ Complete
    Error Handling 3 3 ✅ Complete
    Code Quality 3 3 ✅ Complete
    Test Coverage 4 4 ✅ Complete
    Best Practices 3 3 ✅ Complete
    Polish N/A N/A - (not UI)

    Derived ACs: 2/2 addressed
    Quality Plan Status: Complete


    CI Status

    No CI checks configured for this repository.


    Stale Branch Check

    Check Value
    Commits behind main 5
    Threshold 5
    Status ⚠️ Warning

    ⚠️ MERGE RISK: Main now uses spawnAsync (commit 9aba881, #388) and resolveCliBinary (#389). This branch still uses spawnSync. Rebase will require adapting the structured output code to the async API — not a trivial merge.


    Quality Metrics

    Metric Value Status
    Type issues (any) 2 (test-only as any for fs mock) OK
    Deleted tests 0 OK
    Files changed 4 OK
    Lines added +589 OK
    Lines deleted -26 OK

    Test Coverage Analysis

    Changed File Tier Has Tests? Test File
    src/mcp/tools/run.ts Standard ✅ Yes src/mcp/tools/run.test.ts (16 tests)
    src/mcp/server-extended.test.ts - Test file itself -
    CHANGELOG.md Optional N/A -

    Coverage: 1/1 changed source files have corresponding tests
    Critical paths without tests: None


    Code Review

    Strengths:

    • Clean separation of concerns: buildStructuredResponse, buildFallbackResponse, enforceResponseSizeLimit, readLatestRunLog as focused functions
    • Reuses existing RunLogSchema and RunLog types — no duplication
    • Progressive truncation strategy (rawOutput → error) is well-designed
    • Test coverage is thorough: happy path, edge cases (0/1/N issues), size limits, all fallback paths
    • Verdict conditionally included via ...(verdict ? { verdict } : {}) — verified absent when no QA phase

    Issues:

    • Stale log risk (minor): readLatestRunLog() reads the most recent file by filename sort without verifying it belongs to the current run. If a previous run's log exists and the current run crashes before writing, stale data could be returned. Mitigated by the fallback path and in-practice --log-json always writing.
    • Redundant cast (cosmetic): Lines 282/291 — overallStatus as "success" | "failure" is unnecessary since the ternary already produces that type.
    • Mutation in enforceResponseSizeLimit (cosmetic): Mutates the response object in-place. Non-issue since called at end of construction.

    Suggestions (non-blocking):

    • Remove redundant as "success" | "failure" casts
    • Consider correlating log file to current run by timestamp window in a follow-up

    Test Quality Review

    Category Status Notes
    Behavior vs Implementation ✅ OK Tests assert on output shape, not internals
    Coverage Depth ✅ OK Error paths, edge cases, size limits all covered
    Mock Hygiene ✅ OK Only fs module mocked
    Test Reliability ✅ OK Deterministic, no timing dependencies

    Anti-Pattern Detection

    Dependency Audit

    N/A — No dependency changes

    Code Patterns

    File:Line Category Pattern Suggestion
    run.ts:87 Error Handling Empty catch block Acceptable — intentional fallback for AC-5

    Critical Issues: 0
    Warnings: 0


    Call-Site Review

    New exported functions detected: 2

    Function Call Sites Loop? Conditions AC Match
    readLatestRunLog() run.ts:275 No After spawnSync completes ✅ AC-5
    buildStructuredResponse() run.ts:279 No if (runLog) guard ✅ AC-1

    Execution Evidence

    N/A — No scripts/ or CLI command changes


    Skill Command Verification

    N/A — No skill files changed


    CLI Registration Verification

    N/A — No option interface changes


    CHANGELOG Verification

    Check Status
    CHANGELOG.md exists ✅ Found
    User-facing changes ✅ Yes
    [Unreleased] entry ✅ Present
    Entry format ✅ Valid (includes #391, sub-items)

    Result: CHANGELOG requirements met


    Self-Evaluation

    • Verified working: Yes — build passes, all 1773 tests pass (76 files)
    • Test efficacy: High — tests cover structured shape, size limits, fallback paths, edge cases
    • Likely failure mode: Stale log file from previous run returned. Mitigated by fallback path.
    • Verdict confidence: High — all AC items verified literally against implementation and tests

    Verdict: READY_FOR_MERGE

    All 6 AC items (4 original + 2 derived) are fully met. Implementation is clean, well-tested, and follows existing patterns.

    ⚠️ IMPORTANT: Branch is 5 commits behind main. Main has replaced spawnSync with spawnAsync (#388) and added resolveCliBinary (#389). Rebase will require adapting the structured output code to the async spawn API — plan for non-trivial merge resolution.

    Documentation

    • CHANGELOG entry added
    • N/A — No new CLI flags or config options

    Next Steps

    1. Rebase on main — adapt structured output to spawnAsync API (exitCode vs status, signal support)
    2. Merge PR feat(#391): improve sequant_run MCP tool output structure #407

    QA completed: 6/6 AC items met

  9. added 3 commits that reference this issue on Mar 24, 2026
  10. added 2 commits that reference this issue on Mar 24, 2026
  11. admarble commented on Mar 24, 2026

    @admarble
    ContributorAuthor

    Documentation Complete

    File: docs/features/mcp-server.md (updated, not new — documentation lives with the existing MCP server docs)

    What was documented:

    The sequant_run response format was added to the Tools Reference section:

    • Response fields — status, exitCode, issues, summary, phases, rawOutput, error
    • Per-issue summary fields — issueNumber, status, phases, verdict, durationSeconds
    • Fallback behavior — what happens when the run log is unavailable

    No separate doc file needed:

    This feature enhances an existing MCP tool (sequant_run), not a new tool. The response format documentation was added inline to the existing docs/features/mcp-server.md under the sequant_run section.


    Documentation complete.

  12. added a commit that references this issue on Mar 24, 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

    enhancementmulti-agentplannedready-for-review

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions