From c7c268ddf137162df2041c70960a408c24f93f21 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 28 Nov 2026 03:25:53 -0800 Subject: [PATCH 1/3] fix(mcp): name the reason on MCP route 400 log lines --- apps/sim/app/api/v2/lib/response.ts | 10 +--- apps/sim/lib/api/mcp/route-handler.ts | 3 +- .../lib/api/server/routes/mcp-server-route.ts | 60 +++++++++++++++++++ apps/sim/lib/api/server/validation.ts | 9 ++- apps/sim/lib/core/utils/response-error.ts | 26 ++++++++ .../mcp/route-handler.protocol.test.ts | 49 ++++++++++++--- apps/sim/lib/knowledge/mcp/route-handler.ts | 2 + 7 files changed, 139 insertions(+), 20 deletions(-) diff --git a/apps/sim/app/api/v2/lib/response.ts b/apps/sim/app/api/v2/lib/response.ts index 1e7117e4c72..0ea4d16c24b 100644 --- a/apps/sim/app/api/v2/lib/response.ts +++ b/apps/sim/app/api/v2/lib/response.ts @@ -22,7 +22,7 @@ import { type OrchestrationErrorCode, } from '@/lib/core/orchestration/types' import type { HttpError } from '@/lib/core/utils/http-error' -import { describeResponseError } from '@/lib/core/utils/response-error' +import { describeResponseError, describeValidationError } from '@/lib/core/utils/response-error' import type { RateLimitResult } from '@/app/api/v1/middleware' /** @@ -280,13 +280,7 @@ export function v2ValidationError(error: ZodError, slice?: RequestSlice): NextRe const response = v2Error('BAD_REQUEST', location ? `${location}: ${message}` : message, { details: serializeZodIssues(error), }) - // Deeper segments can be record keys the caller wrote (an import's CSV headers); no slice is itself a record. - const field = [slice, path[0]].filter((part) => part !== undefined && part !== '').join('.') - describeResponseError(response, { - errorCode: 'BAD_REQUEST', - ...(field ? { errorField: field } : {}), - ...(error.issues[0] ? { errorReason: error.issues[0].code } : {}), - }) + describeValidationError(response, error, slice) return response } diff --git a/apps/sim/lib/api/mcp/route-handler.ts b/apps/sim/lib/api/mcp/route-handler.ts index 442765b3db1..663d05e488b 100644 --- a/apps/sim/lib/api/mcp/route-handler.ts +++ b/apps/sim/lib/api/mcp/route-handler.ts @@ -14,6 +14,7 @@ import { createSimMcpServer } from '@/lib/api/mcp/server' import { getSimMcpUrl } from '@/lib/api/mcp/urls' import { parseRequest } from '@/lib/api/server' import { + MCP_PARSE_ERROR_RESPONSES, mcpCredentialAuth, mcpMethodNotAllowed, readMcpCredentialHeaders, @@ -103,7 +104,7 @@ export function createSimMcpHandlers() { simMcpContract, request, {}, - { maxBodyBytes: MAX_MCP_BODY_BYTES } + { ...MCP_PARSE_ERROR_RESPONSES, maxBodyBytes: MAX_MCP_BODY_BYTES } ) if (!parsed.success) return parsed.response const operation = await toolCallOperation(parsed.data.body) diff --git a/apps/sim/lib/api/server/routes/mcp-server-route.ts b/apps/sim/lib/api/server/routes/mcp-server-route.ts index b4aadc4fe5c..4c57fd9f5e3 100644 --- a/apps/sim/lib/api/server/routes/mcp-server-route.ts +++ b/apps/sim/lib/api/server/routes/mcp-server-route.ts @@ -1,13 +1,23 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js' +import { isRecordLike } from '@sim/utils/object' +import { truncate } from '@sim/utils/string' import type { NextRequest } from 'next/server' +import type { z } from 'zod' import { authenticateV2ApiKey, V2ApiKeyUnauthenticatedError, } from '@/lib/api/server/routes/v2-api-key-auth' import type { V2CredentialHeaders } from '@/lib/api/server/routes/v2-credential-headers' +import { + invalidJsonBodyResponse, + type ParseRequestOptions, + type RequestSlice, + validationErrorResponse, +} from '@/lib/api/server/validation' import { type OAuthAccessTokenOptions, parseBearerToken } from '@/lib/auth/oauth-access-token' import { OAUTH_ACCESS_TOKEN_PREFIX } from '@/lib/auth/oauth-provider' +import { describeResponseError, describeValidationError } from '@/lib/core/utils/response-error' const NO_STORE = 'private, no-store' @@ -53,12 +63,62 @@ export async function serveStatelessMcp( await server.connect(transport) const response = await transport.handleRequest(request, { parsedBody }) response.headers.set('Cache-Control', NO_STORE) + if (response.status >= 400) await describeTransportRefusal(response, request) return response } finally { await server.close() } } +const UNSUPPORTED_PROTOCOL_VERSION = 'Bad Request: Unsupported protocol version' + +/** + * Records why the SDK transport refused a request (an unsupported + * `mcp-protocol-version`, a malformed JSON-RPC message) for the route's log + * line. The SDK's messages are fixed text, except for a value after a second + * `: `, which is dropped; an unsupported protocol version is kept, bounded, as + * the detail instead. + */ +async function describeTransportRefusal(response: Response, request: Request): Promise { + let body: unknown + try { + body = await response.clone().json() + } catch { + return + } + const error = isRecordLike(body) ? body.error : undefined + if (!isRecordLike(error)) return + const reason = + typeof error.message === 'string' + ? truncate(error.message.split(': ', 2).join(': '), 200) + : undefined + const protocolVersion = request.headers.get('mcp-protocol-version') + describeResponseError(response, { + errorCode: String(error.code), + ...(reason ? { errorReason: reason } : {}), + ...(protocolVersion && reason === UNSUPPORTED_PROTOCOL_VERSION + ? { errorDetail: truncate(protocolVersion, 40) } + : {}), + }) +} + +/** + * `parseRequest` options for an MCP route: the default 400 bodies, described + * for the route's log line. + */ +export const MCP_PARSE_ERROR_RESPONSES = { + validationErrorResponseBySlice(error: z.ZodError, slice: RequestSlice) { + const response = validationErrorResponse(error) + describeValidationError(response, error, slice) + return response + }, + invalidJsonResponse() { + const response = invalidJsonBodyResponse() + describeResponseError(response, { errorCode: 'BAD_REQUEST', errorReason: 'invalid_json' }) + return response + }, +} satisfies ParseRequestOptions + /** Stateless servers take POST only; callers authenticate before answering 405. */ export function mcpMethodNotAllowed(): Response { return new Response(null, { status: 405, headers: { Allow: 'POST', 'Cache-Control': NO_STORE } }) diff --git a/apps/sim/lib/api/server/validation.ts b/apps/sim/lib/api/server/validation.ts index 0e0f8ea7cb5..dd1f1396932 100644 --- a/apps/sim/lib/api/server/validation.ts +++ b/apps/sim/lib/api/server/validation.ts @@ -138,6 +138,11 @@ export function isZodError(error: unknown): error is z.ZodError { return error instanceof ZodError } +/** The default 400 for a request body that is not valid JSON. */ +export function invalidJsonBodyResponse(): NextResponse<{ error: string }> { + return NextResponse.json({ error: 'Request body must be valid JSON' }, { status: 400 }) +} + export function validationErrorResponse( error: z.ZodError, message = 'Validation error', @@ -219,7 +224,7 @@ export async function parseJsonBody( return { success: false, reason: 'invalid_json', - response: NextResponse.json({ error: 'Request body must be valid JSON' }, { status: 400 }), + response: invalidJsonBodyResponse(), } } } @@ -272,7 +277,7 @@ export async function parseOptionalJsonBody( return { success: false, reason: 'invalid_json', - response: NextResponse.json({ error: 'Request body must be valid JSON' }, { status: 400 }), + response: invalidJsonBodyResponse(), } } } diff --git a/apps/sim/lib/core/utils/response-error.ts b/apps/sim/lib/core/utils/response-error.ts index a7445a0e68b..b112f139f91 100644 --- a/apps/sim/lib/core/utils/response-error.ts +++ b/apps/sim/lib/core/utils/response-error.ts @@ -1,3 +1,5 @@ +import type { z } from 'zod' + /** * The machine-readable part of an error response, kept beside the response so * the route handler's closing log line can be grouped by why a request was @@ -11,6 +13,8 @@ export interface ResponseErrorSummary { errorField?: string /** The cause the refusal named (`READ_ONLY_API_KEY`) or the validation issue kind (`invalid_type`). */ errorReason?: string + /** A short, bounded header value the reason turns on, e.g. the protocol version a client asked for. */ + errorDetail?: string } /** @@ -28,3 +32,25 @@ export function describeResponseError(response: Response, summary: ResponseError export function readResponseError(response: Response): ResponseErrorSummary | undefined { return summaries.get(response) } + +/** + * Records a contract validation failure: the request slice and its top-level + * field (deeper segments can be record keys the caller wrote) and the first + * issue's kind. + */ +export function describeValidationError( + response: Response, + error: z.ZodError, + slice?: string +): void { + const issue = error.issues[0] + const field = [slice, issue?.path[0]] + .filter((part) => part !== undefined && part !== '') + .map(String) + .join('.') + describeResponseError(response, { + errorCode: 'BAD_REQUEST', + ...(field ? { errorField: field } : {}), + ...(issue ? { errorReason: issue.code } : {}), + }) +} diff --git a/apps/sim/lib/knowledge/mcp/route-handler.protocol.test.ts b/apps/sim/lib/knowledge/mcp/route-handler.protocol.test.ts index a6be8a5ee7a..7440ae59ddc 100644 --- a/apps/sim/lib/knowledge/mcp/route-handler.protocol.test.ts +++ b/apps/sim/lib/knowledge/mcp/route-handler.protocol.test.ts @@ -51,6 +51,7 @@ vi.mock('@/lib/sim-search/live/application', async (importOriginal) => ({ searchLiveKnowledge: { execute: mocks.liveSearch }, })) +import { readResponseError } from '@/lib/core/utils/response-error' import { createKnowledgeMcpHandlers } from '@/lib/knowledge/mcp/route-handler' urlsMockFns.mockGetBaseUrl.mockReturnValue('http://localhost') @@ -58,9 +59,9 @@ urlsMockFns.mockGetBaseUrl.mockReturnValue('http://localhost') const handlers = createKnowledgeMcpHandlers() const principal = createPersonalApiKeyPrincipal({ userId: 'person-1' }) -/** Calls a tool over the real route, SDK transport, and Search MCP server. */ -async function callTool(name: string, args: Record) { - const response = await handlers.POST( +/** Posts one message over the real route, SDK transport, and Search MCP server. */ +function post(body: unknown, headers: Record = {}) { + return handlers.POST( createMockRequest({ method: 'POST', url: 'http://localhost/api/mcp/search/organizations/org-1', @@ -69,16 +70,21 @@ async function callTool(name: string, args: Record) { accept: 'application/json, text/event-stream', 'x-forwarded-for': '127.0.0.1', 'x-api-key': 'personal-key', + ...headers, }, - body: { - jsonrpc: '2.0', - id: 1, - method: 'tools/call', - params: { name, arguments: args }, - }, + body, }), createRouteContext({ organizationId: 'org-1' }) ) +} + +async function callTool(name: string, args: Record) { + const response = await post({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { name, arguments: args }, + }) return { status: response.status, body: await response.json() } } @@ -194,3 +200,28 @@ describe('Search MCP tool arguments with one possible reading', () => { } ) }) + +describe('Search MCP refusals name their reason on the route log line', () => { + it('names the SDK refusal and the protocol version a client asked for', async () => { + const response = await post( + { jsonrpc: '2.0', id: 1, method: 'tools/list' }, + { 'mcp-protocol-version': '2099-01-01' } + ) + expect(response.status).toBe(400) + expect(readResponseError(response)).toEqual({ + errorCode: '-32000', + errorReason: 'Bad Request: Unsupported protocol version', + errorDetail: '2099-01-01', + }) + }) + + it('names a JSON-RPC batch as a body that is not an object', async () => { + const response = await post([{ jsonrpc: '2.0', id: 1, method: 'tools/list' }]) + expect(response.status).toBe(400) + expect(readResponseError(response)).toEqual({ + errorCode: 'BAD_REQUEST', + errorField: 'body', + errorReason: 'invalid_type', + }) + }) +}) diff --git a/apps/sim/lib/knowledge/mcp/route-handler.ts b/apps/sim/lib/knowledge/mcp/route-handler.ts index 1f6b415829d..c0d7f44602a 100644 --- a/apps/sim/lib/knowledge/mcp/route-handler.ts +++ b/apps/sim/lib/knowledge/mcp/route-handler.ts @@ -5,6 +5,7 @@ import type { NextRequest } from 'next/server' import { organizationKnowledgeMcpContract } from '@/lib/api/contracts/knowledge/mcp' import { parseRequest } from '@/lib/api/server' import { + MCP_PARSE_ERROR_RESPONSES, mcpCredentialAuth, mcpMethodNotAllowed, serveStatelessMcp, @@ -60,6 +61,7 @@ export function createKnowledgeMcpHandlers() { } try { const parsed = await parseRequest(organizationKnowledgeMcpContract, request, context, { + ...MCP_PARSE_ERROR_RESPONSES, maxBodyBytes: 64 * 1024, }) if (!parsed.success) return parsed.response From a332db03d35d4a78434b4f73ad8f31c1f00fc3a9 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 28 Nov 2026 03:36:46 -0800 Subject: [PATCH 2/3] fix(mcp): log only the slice for MCP validation failures --- apps/sim/lib/api/server/routes/mcp-server-route.ts | 5 +++-- apps/sim/lib/core/utils/response-error.ts | 11 ++++++----- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/apps/sim/lib/api/server/routes/mcp-server-route.ts b/apps/sim/lib/api/server/routes/mcp-server-route.ts index 4c57fd9f5e3..4433e9c6e4d 100644 --- a/apps/sim/lib/api/server/routes/mcp-server-route.ts +++ b/apps/sim/lib/api/server/routes/mcp-server-route.ts @@ -104,12 +104,13 @@ async function describeTransportRefusal(response: Response, request: Request): P /** * `parseRequest` options for an MCP route: the default 400 bodies, described - * for the route's log line. + * for the route's log line. A JSON-RPC message keeps keys the caller chose, so + * a validation failure names only the slice. */ export const MCP_PARSE_ERROR_RESPONSES = { validationErrorResponseBySlice(error: z.ZodError, slice: RequestSlice) { const response = validationErrorResponse(error) - describeValidationError(response, error, slice) + describeValidationError(response, error, slice, { sliceOnly: true }) return response }, invalidJsonResponse() { diff --git a/apps/sim/lib/core/utils/response-error.ts b/apps/sim/lib/core/utils/response-error.ts index b112f139f91..3cc1aec70cb 100644 --- a/apps/sim/lib/core/utils/response-error.ts +++ b/apps/sim/lib/core/utils/response-error.ts @@ -34,17 +34,18 @@ export function readResponseError(response: Response): ResponseErrorSummary | un } /** - * Records a contract validation failure: the request slice and its top-level - * field (deeper segments can be record keys the caller wrote) and the first - * issue's kind. + * Records a contract validation failure: the request slice, its top-level field + * (deeper segments can be record keys the caller wrote) unless `sliceOnly` says + * the slice accepts caller-chosen keys, and the first issue's kind. */ export function describeValidationError( response: Response, error: z.ZodError, - slice?: string + slice?: string, + { sliceOnly = false }: { sliceOnly?: boolean } = {} ): void { const issue = error.issues[0] - const field = [slice, issue?.path[0]] + const field = [slice, sliceOnly ? undefined : issue?.path[0]] .filter((part) => part !== undefined && part !== '') .map(String) .join('.') From 908ee556b36553c262db16e033f0011f769ba06f Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 28 Nov 2026 03:43:59 -0800 Subject: [PATCH 3/3] fix(mcp): pass a route context in the test-connection route tests --- .../mcp/servers/test-connection/route.test.ts | 25 ++++++++++++++----- scripts/check-test-types.baseline.json | 3 --- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/apps/sim/app/api/mcp/servers/test-connection/route.test.ts b/apps/sim/app/api/mcp/servers/test-connection/route.test.ts index 03628f5ecfd..aedb419776d 100644 --- a/apps/sim/app/api/mcp/servers/test-connection/route.test.ts +++ b/apps/sim/app/api/mcp/servers/test-connection/route.test.ts @@ -1,4 +1,5 @@ import { createMockRequest, loggerMock } from '@sim/testing' +import { createRouteContext } from '@sim/testing/helpers/http' import { mcpOauthMock, mcpOauthMockFns } from '@sim/testing/mocks/mcp-oauth.mock' import type { NextRequest } from 'next/server' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -129,7 +130,7 @@ describe('MCP server test-connection route', () => { new McpDnsResolutionError('example.invalid', hostNotFound) ) - const response = await POST(createTestRequest()) + const response = await POST(createTestRequest(), createRouteContext({})) expect(response.status).toBe(status) expect(await response.json()).toEqual({ @@ -141,7 +142,10 @@ describe('MCP server test-connection route', () => { ) it('tests configured bearer headers before treating OAuth discovery as mandatory', async () => { - const response = await POST(createTestRequest({ Authorization: 'Bearer static-api-token' })) + const response = await POST( + createTestRequest({ Authorization: 'Bearer static-api-token' }), + createRouteContext({}) + ) const body = await response.json() expect(response.status).toBe(200) @@ -162,7 +166,10 @@ describe('MCP server test-connection route', () => { it('returns a header-auth failure when the configured token is rejected', async () => { mockConnect.mockRejectedValueOnce(new Error('HTTP 401: Unauthorized')) - const response = await POST(createTestRequest({ Authorization: 'Bearer invalid-static-token' })) + const response = await POST( + createTestRequest({ Authorization: 'Bearer invalid-static-token' }), + createRouteContext({}) + ) const body = await response.json() expect(response.status).toBe(400) @@ -182,7 +189,10 @@ describe('MCP server test-connection route', () => { const token = 'opaque-static-token' mockConnect.mockRejectedValueOnce(new Error(`Upstream rejected ${token}`)) - const response = await POST(createTestRequest({ Authorization: `Bearer ${token}` })) + const response = await POST( + createTestRequest({ Authorization: `Bearer ${token}` }), + createRouteContext({}) + ) const body = await response.json() expect(response.status).toBe(400) @@ -194,7 +204,7 @@ describe('MCP server test-connection route', () => { }) it('preserves OAuth discovery when no static headers are configured', async () => { - const response = await POST(createTestRequest()) + const response = await POST(createTestRequest(), createRouteContext({})) const body = await response.json() expect(response.status).toBe(200) @@ -227,7 +237,10 @@ describe('MCP server test-connection route', () => { return '203.0.113.10' }) - const response = await POST(createTestRequest({ Authorization: `Bearer ${token}` })) + const response = await POST( + createTestRequest({ Authorization: `Bearer ${token}` }), + createRouteContext({}) + ) const responseText = await response.text() expect(response.status).toBe(403) diff --git a/scripts/check-test-types.baseline.json b/scripts/check-test-types.baseline.json index 45ac99e6eee..b342963fbfa 100644 --- a/scripts/check-test-types.baseline.json +++ b/scripts/check-test-types.baseline.json @@ -196,9 +196,6 @@ "apps/sim/app/api/mcp/servers/route.test.ts": { "TS2554": 2 }, - "apps/sim/app/api/mcp/servers/test-connection/route.test.ts": { - "TS2554": 5 - }, "apps/sim/app/api/mothership/chat/stop/route.test.ts": { "TS18046": 2, "TS2345": 1,