🔒 Keep internal failures out of MCP tool results, as the HTTP API does

The HTTP API answers an unexpected failure with a generic message and
leaves the details to the server log. The MCP tools returned any
error's message to the client instead: a database, filesystem or
upstream failure could hand an agent client connection strings, table
names or internal paths.

MCP tool results now follow the HTTP API's rules: domain errors keep
their code, message and details, invalid input reports its validation
issues, and anything else is INTERNAL_ERROR with a pointer to the
server log, where the details are written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
eust-w 2026-10-26 14:54:01 +08:00
parent d4ea7c7626
commit 01acc236a0
2 changed files with 29 additions and 13 deletions

View File

@ -1,6 +1,6 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { z } from 'zod';
import { z, ZodError } from 'zod';
import type { Request, Response } from 'express';
import { DomainError, wishInput, type Actor, type Evidence, type Run } from '@wishforge/contracts';
import { auditContext } from './audit-context.js';
@ -43,6 +43,15 @@ export function createMcpServer(s: Services, actor: Actor) {
'Find the project with list_projects, then submit a wish with a goal and at least one verifiable acceptance criterion; reuse its idempotency_key when retrying. The run continues after the call returns: follow it with get_run and get_run_events, answer questions with answer_question, and report the result with get_delivery. A finished agent turn is not a verified delivery. Release approvals happen only in the web console at the returned URL.',
},
);
// Errors follow the HTTP API's rules: domain errors and invalid input explain themselves, anything
// else (a database, filesystem or upstream failure) stays in the server log, not in the client.
const failure = (error: unknown) => {
if (error instanceof DomainError) return { code: error.code, message: error.message, details: error.details };
if (error instanceof ZodError)
return { code: 'INVALID_INPUT', message: 'Request validation failed', details: error.flatten() };
console.error(error instanceof Error ? `${error.name}: ${error.message}` : 'MCP tool failure');
return { code: 'INTERNAL_ERROR', message: 'Tool failed. Consult the server audit log.' };
};
const result = async (fn: () => Promise<unknown>) => {
try {
const data = await fn();
@ -50,17 +59,7 @@ export function createMcpServer(s: Services, actor: Actor) {
} catch (error) {
return {
isError: true,
content: [
{
type: 'text' as const,
text: JSON.stringify({
error: {
code: error instanceof DomainError ? error.code : 'TOOL_ERROR',
message: error instanceof Error ? error.message : 'Tool failed',
},
}),
},
],
content: [{ type: 'text' as const, text: JSON.stringify({ error: failure(error) }) }],
};
}
};

View File

@ -1,4 +1,4 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
import type { Actor } from '@wishforge/contracts';
@ -106,6 +106,23 @@ describe('MCP tools for agent clients (FR-A3, FR-A6, journey J1)', () => {
error: { code: 'RELEASE_NOT_READY', message: expect.any(String) },
});
});
it('keeps internal failures out of tool results, as the HTTP API does', async () => {
// An unexpected failure, such as the database's, carries details meant for the server log only.
services.control.projects = async () => {
throw new Error('relation "entities" does not exist (postgres://wishforge_app@127.0.0.1:55432)');
};
const logged = vi.spyOn(console, 'error').mockImplementation(() => undefined);
try {
const failed = await call('list_projects');
expect(failed).toEqual({
error: { code: 'INTERNAL_ERROR', message: 'Tool failed. Consult the server audit log.' },
});
expect(JSON.stringify(failed)).not.toContain('postgres');
expect(logged).toHaveBeenCalledWith(expect.stringContaining('relation "entities" does not exist'));
} finally {
logged.mockRestore();
}
});
it('acts only within the user’s own permissions', async () => {
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
const viewer: Actor = { tenantId: 'alpha', userId: 'viewer', role: 'viewer', kind: 'connector' };