From 56914aad8d05b95631da0162adefb35bed364c12 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 22 Nov 2026 21:06:41 +0000 Subject: [PATCH] fix(mcp): keep AutoCommit logs off JSON-RPC stdout Route phase auto-commit diagnostics to stderr and install an MCP stdio console guard so console.log/info/debug cannot corrupt the transport. Adds regression tests. Co-authored-by: Vinicius Lana --- CHANGELOG.md | 1 + .../planUpdateOrchestrator.autoCommit.test.ts | 97 +++++++++++++++++++ .../workflow/plans/planUpdateOrchestrator.ts | 4 +- src/mcp/server/mcpServer.ts | 2 + .../__tests__/stdioProtocolGuard.test.ts | 43 ++++++++ src/mcp/stdio/stdioProtocolGuard.ts | 40 ++++++++ 6 files changed, 185 insertions(+), 2 deletions(-) create mode 100644 src/harness/domain/workflow/plans/__tests__/planUpdateOrchestrator.autoCommit.test.ts create mode 100644 src/mcp/stdio/__tests__/stdioProtocolGuard.test.ts create mode 100644 src/mcp/stdio/stdioProtocolGuard.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index df4bc73..8a2ced7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Routed PREVC phase auto-commit diagnostics to stderr and installed an MCP stdio console guard so non-protocol output cannot corrupt JSON-RPC on stdout (fixes MCP client disconnect on phase completion). - Removed MCP response-body reparsing from action logging and replaced oversized response truncation risk with typed smaller-page or artifact-reference responses. - Applied the same bounded UTF-8 budget to every MCP resource, rejected oversized files before reading their bodies, enforced action-specific list maxima, and paginated `explore` file listings. - Bounded `explore` reads before file materialization and replaced whole-glob/whole-file code search with byte-capped streaming discovery, search, and cursor pages. diff --git a/src/harness/domain/workflow/plans/__tests__/planUpdateOrchestrator.autoCommit.test.ts b/src/harness/domain/workflow/plans/__tests__/planUpdateOrchestrator.autoCommit.test.ts new file mode 100644 index 0000000..33f7648 --- /dev/null +++ b/src/harness/domain/workflow/plans/__tests__/planUpdateOrchestrator.autoCommit.test.ts @@ -0,0 +1,97 @@ +import { execSync } from 'child_process'; +import * as fs from 'fs/promises'; +import * as os from 'os'; +import * as path from 'path'; +import { createPlanLinker } from '../planLinker'; +import { PlanTrackingStore } from '../planTrackingStore'; + +const PLAN_SLUG = 'autocommit-stdio'; + +async function setupGitRepo(): Promise { + const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'plan-autocommit-stdio-')); + await fs.mkdir(path.join(tempDir, '.context', 'plans'), { recursive: true }); + await fs.mkdir(path.join(tempDir, '.context', 'runtime', 'workflows'), { recursive: true }); + + const planPath = path.join(tempDir, '.context', 'plans', `${PLAN_SLUG}.md`); + await fs.writeFile( + planPath, + `--- +type: plan +name: "AutoCommit stdio" +description: "Regression for MCP stdout pollution" +generated: "2026-04-13" +status: filled +scaffoldVersion: "2.0.0" +planSlug: "${PLAN_SLUG}" +summary: "Test plan" +agents: + - type: "planner" + role: "Define scope" +docs: + - "README.md" +phases: + - id: "phase-1" + name: "Execute" + prevc: "E" + steps: + - order: 1 + description: "Finish" + deliverables: + - "done" +--- + +# AutoCommit stdio +` + ); + + execSync('git init', { cwd: tempDir, stdio: 'pipe' }); + execSync('git config user.email "test@example.com"', { cwd: tempDir, stdio: 'pipe' }); + execSync('git config user.name "Test User"', { cwd: tempDir, stdio: 'pipe' }); + execSync('git add -A', { cwd: tempDir, stdio: 'pipe' }); + execSync('git commit -m "init"', { cwd: tempDir, stdio: 'pipe' }); + + return tempDir; +} + +describe('PlanUpdateOrchestrator auto-commit stdio safety', () => { + let tempDir: string; + + beforeEach(async () => { + tempDir = await setupGitRepo(); + }); + + afterEach(async () => { + jest.restoreAllMocks(); + await fs.rm(tempDir, { recursive: true, force: true }); + }); + + it('does not log AutoCommit diagnostics via console.info when a phase auto-commits', async () => { + const infoSpy = jest.spyOn(console, 'info').mockImplementation(() => {}); + const stderrSpy = jest.spyOn(console, 'error').mockImplementation(() => {}); + + const linker = await createPlanLinker(tempDir, undefined, true); + await linker.linkPlan(PLAN_SLUG); + + const store = new PlanTrackingStore(path.join(tempDir, '.context', 'runtime', 'workflows')); + const tracking = (await store.load(PLAN_SLUG)) ?? store.createEmpty(PLAN_SLUG); + const now = new Date().toISOString(); + store.ensurePhase(tracking, 'phase-1', now); + const step = store.ensureStep(tracking, 'phase-1', 1, 'Finish', now); + step.status = 'in_progress'; + step.startedAt = now; + await store.save(PLAN_SLUG, tracking); + + const ok = await linker.updatePlanStep(PLAN_SLUG, 'phase-1', 1, 'completed'); + expect(ok).toBe(true); + + const autoCommitInfo = infoSpy.mock.calls.filter((args) => + String(args[0] ?? '').includes('[AutoCommit]') + ); + expect(autoCommitInfo).toHaveLength(0); + + const autoCommitStderr = stderrSpy.mock.calls.filter((args) => + String(args[0] ?? '').includes('[AutoCommit] Created commit') + ); + expect(autoCommitStderr.length).toBeGreaterThanOrEqual(1); + }); +}); \ No newline at end of file diff --git a/src/harness/domain/workflow/plans/planUpdateOrchestrator.ts b/src/harness/domain/workflow/plans/planUpdateOrchestrator.ts index 47d652a..49acead 100644 --- a/src/harness/domain/workflow/plans/planUpdateOrchestrator.ts +++ b/src/harness/domain/workflow/plans/planUpdateOrchestrator.ts @@ -323,7 +323,7 @@ export class PlanUpdateOrchestrator { try { const stagedFiles = gitService.stageFiles(['.context/**']); if (stagedFiles.length === 0) { - console.info('[AutoCommit] No files to commit - skipping'); + console.error('[AutoCommit] No files to commit - skipping'); return false; } @@ -336,7 +336,7 @@ export class PlanUpdateOrchestrator { committedBy: coAuthor, }); - console.info(`[AutoCommit] Created commit ${commitResult.shortHash} for phase ${phaseId}`); + console.error(`[AutoCommit] Created commit ${commitResult.shortHash} for phase ${phaseId}`); return true; } catch (error) { console.warn(`[AutoCommit] Failed to create commit for phase ${phaseId}:`, error); diff --git a/src/mcp/server/mcpServer.ts b/src/mcp/server/mcpServer.ts index 39c4878..62cb153 100644 --- a/src/mcp/server/mcpServer.ts +++ b/src/mcp/server/mcpServer.ts @@ -19,6 +19,7 @@ import { ContextCache } from '../../harness/adapters/out/semantic/contextCache'; import { VERSION } from '../../version'; import { WorkflowService } from '../../harness/application/workflow'; import { clearMcpActionSessionCache, logMcpAction } from '../logging/actionLogger'; +import { installMcpStdioProtocolGuard } from '../stdio/stdioProtocolGuard'; import { createBoundedResourceJson, createBoundedResourceText, @@ -1115,6 +1116,7 @@ Actions: * Start the MCP server with stdio transport */ async start(): Promise { + installMcpStdioProtocolGuard(); this.transport = new StdioServerTransport(); await this.server.connect(this.transport); this.log('MCP Server started on stdio'); diff --git a/src/mcp/stdio/__tests__/stdioProtocolGuard.test.ts b/src/mcp/stdio/__tests__/stdioProtocolGuard.test.ts new file mode 100644 index 0000000..6cbfa5b --- /dev/null +++ b/src/mcp/stdio/__tests__/stdioProtocolGuard.test.ts @@ -0,0 +1,43 @@ +import { + installMcpStdioProtocolGuard, + resetMcpStdioProtocolGuardForTests, +} from '../stdioProtocolGuard'; + +describe('installMcpStdioProtocolGuard', () => { + let stdoutWriteSpy: jest.SpyInstance; + let stderrWriteSpy: jest.SpyInstance; + + beforeEach(() => { + resetMcpStdioProtocolGuardForTests(); + stdoutWriteSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => true); + stderrWriteSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => true); + }); + + afterEach(() => { + resetMcpStdioProtocolGuardForTests(); + stdoutWriteSpy.mockRestore(); + stderrWriteSpy.mockRestore(); + }); + + it('routes console.info away from stdout', () => { + installMcpStdioProtocolGuard(); + + console.info('[AutoCommit] Created commit abc123 for phase phase-1'); + + const stdout = stdoutWriteSpy.mock.calls.map(([chunk]) => String(chunk)).join(''); + const stderr = stderrWriteSpy.mock.calls.map(([chunk]) => String(chunk)).join(''); + + expect(stdout).not.toContain('[AutoCommit]'); + expect(stderr).toContain('[AutoCommit] Created commit abc123 for phase phase-1'); + }); + + it('is idempotent', () => { + installMcpStdioProtocolGuard(); + installMcpStdioProtocolGuard(); + + console.log('diagnostic'); + + expect(stdoutWriteSpy).not.toHaveBeenCalled(); + expect(stderrWriteSpy.mock.calls.map(([chunk]) => String(chunk)).join('')).toContain('diagnostic'); + }); +}); \ No newline at end of file diff --git a/src/mcp/stdio/stdioProtocolGuard.ts b/src/mcp/stdio/stdioProtocolGuard.ts new file mode 100644 index 0000000..dbaaad2 --- /dev/null +++ b/src/mcp/stdio/stdioProtocolGuard.ts @@ -0,0 +1,40 @@ +import * as util from 'util'; + +const originalConsole = { + log: console.log, + info: console.info, + debug: console.debug, +}; + +let installed = false; + +function writeConsoleLineToStderr(...args: unknown[]): void { + process.stderr.write(`${util.format(...args)}\n`); +} + +/** + * Redirect casual console logging away from stdout while MCP stdio transport runs. + * JSON-RPC framing must be the only payload on stdout. + */ +export function installMcpStdioProtocolGuard(): void { + if (installed) { + return; + } + + installed = true; + console.log = writeConsoleLineToStderr as typeof console.log; + console.info = writeConsoleLineToStderr as typeof console.info; + console.debug = writeConsoleLineToStderr as typeof console.debug; +} + +/** Restores original console sinks; for unit tests only. */ +export function resetMcpStdioProtocolGuardForTests(): void { + if (!installed) { + return; + } + + console.log = originalConsole.log; + console.info = originalConsole.info; + console.debug = originalConsole.debug; + installed = false; +} \ No newline at end of file