Skip to content

Commit e1d814a

Browse files
authored
fix(mcp): name the reason on MCP route 400 log lines (#10475)
* fix(mcp): name the reason on MCP route 400 log lines * fix(mcp): log only the slice for MCP validation failures * fix(mcp): pass a route context in the test-connection route tests
1 parent 155e03c commit e1d814a

9 files changed

Lines changed: 160 additions & 29 deletions

File tree

‎apps/sim/app/api/mcp/servers/test-connection/route.test.ts‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { createMockRequest, loggerMock } from '@sim/testing'
2+
import { createRouteContext } from '@sim/testing/helpers/http'
23
import { mcpOauthMock, mcpOauthMockFns } from '@sim/testing/mocks/mcp-oauth.mock'
34
import type { NextRequest } from 'next/server'
45
import { beforeEach, describe, expect, it, vi } from 'vitest'
@@ -129,7 +130,7 @@ describe('MCP server test-connection route', () => {
129130
new McpDnsResolutionError('example.invalid', hostNotFound)
130131
)
131132

132-
const response = await POST(createTestRequest())
133+
const response = await POST(createTestRequest(), createRouteContext({}))
133134

134135
expect(response.status).toBe(status)
135136
expect(await response.json()).toEqual({
@@ -141,7 +142,10 @@ describe('MCP server test-connection route', () => {
141142
)
142143

143144
it('tests configured bearer headers before treating OAuth discovery as mandatory', async () => {
144-
const response = await POST(createTestRequest({ Authorization: 'Bearer static-api-token' }))
145+
const response = await POST(
146+
createTestRequest({ Authorization: 'Bearer static-api-token' }),
147+
createRouteContext({})
148+
)
145149
const body = await response.json()
146150

147151
expect(response.status).toBe(200)
@@ -162,7 +166,10 @@ describe('MCP server test-connection route', () => {
162166
it('returns a header-auth failure when the configured token is rejected', async () => {
163167
mockConnect.mockRejectedValueOnce(new Error('HTTP 401: Unauthorized'))
164168

165-
const response = await POST(createTestRequest({ Authorization: 'Bearer invalid-static-token' }))
169+
const response = await POST(
170+
createTestRequest({ Authorization: 'Bearer invalid-static-token' }),
171+
createRouteContext({})
172+
)
166173
const body = await response.json()
167174

168175
expect(response.status).toBe(400)
@@ -182,7 +189,10 @@ describe('MCP server test-connection route', () => {
182189
const token = 'opaque-static-token'
183190
mockConnect.mockRejectedValueOnce(new Error(`Upstream rejected ${token}`))
184191

185-
const response = await POST(createTestRequest({ Authorization: `Bearer ${token}` }))
192+
const response = await POST(
193+
createTestRequest({ Authorization: `Bearer ${token}` }),
194+
createRouteContext({})
195+
)
186196
const body = await response.json()
187197

188198
expect(response.status).toBe(400)
@@ -194,7 +204,7 @@ describe('MCP server test-connection route', () => {
194204
})
195205

196206
it('preserves OAuth discovery when no static headers are configured', async () => {
197-
const response = await POST(createTestRequest())
207+
const response = await POST(createTestRequest(), createRouteContext({}))
198208
const body = await response.json()
199209

200210
expect(response.status).toBe(200)
@@ -227,7 +237,10 @@ describe('MCP server test-connection route', () => {
227237
return '203.0.113.10'
228238
})
229239

230-
const response = await POST(createTestRequest({ Authorization: `Bearer ${token}` }))
240+
const response = await POST(
241+
createTestRequest({ Authorization: `Bearer ${token}` }),
242+
createRouteContext({})
243+
)
231244
const responseText = await response.text()
232245

233246
expect(response.status).toBe(403)

‎apps/sim/app/api/v2/lib/response.ts‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ import {
2222
type OrchestrationErrorCode,
2323
} from '@/lib/core/orchestration/types'
2424
import type { HttpError } from '@/lib/core/utils/http-error'
25-
import { describeResponseError } from '@/lib/core/utils/response-error'
25+
import { describeResponseError, describeValidationError } from '@/lib/core/utils/response-error'
2626
import type { RateLimitResult } from '@/app/api/v1/middleware'
2727

2828
/**
@@ -280,13 +280,7 @@ export function v2ValidationError(error: ZodError, slice?: RequestSlice): NextRe
280280
const response = v2Error('BAD_REQUEST', location ? `${location}: ${message}` : message, {
281281
details: serializeZodIssues(error),
282282
})
283-
// Deeper segments can be record keys the caller wrote (an import's CSV headers); no slice is itself a record.
284-
const field = [slice, path[0]].filter((part) => part !== undefined && part !== '').join('.')
285-
describeResponseError(response, {
286-
errorCode: 'BAD_REQUEST',
287-
...(field ? { errorField: field } : {}),
288-
...(error.issues[0] ? { errorReason: error.issues[0].code } : {}),
289-
})
283+
describeValidationError(response, error, slice)
290284
return response
291285
}
292286

‎apps/sim/lib/api/mcp/route-handler.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { createSimMcpServer } from '@/lib/api/mcp/server'
1414
import { getSimMcpUrl } from '@/lib/api/mcp/urls'
1515
import { parseRequest } from '@/lib/api/server'
1616
import {
17+
MCP_PARSE_ERROR_RESPONSES,
1718
mcpCredentialAuth,
1819
mcpMethodNotAllowed,
1920
readMcpCredentialHeaders,
@@ -103,7 +104,7 @@ export function createSimMcpHandlers() {
103104
simMcpContract,
104105
request,
105106
{},
106-
{ maxBodyBytes: MAX_MCP_BODY_BYTES }
107+
{ ...MCP_PARSE_ERROR_RESPONSES, maxBodyBytes: MAX_MCP_BODY_BYTES }
107108
)
108109
if (!parsed.success) return parsed.response
109110
const operation = await toolCallOperation(parsed.data.body)

‎apps/sim/lib/api/server/routes/mcp-server-route.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,23 @@
11
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
22
import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'
3+
import { isRecordLike } from '@sim/utils/object'
4+
import { truncate } from '@sim/utils/string'
35
import type { NextRequest } from 'next/server'
6+
import type { z } from 'zod'
47
import {
58
authenticateV2ApiKey,
69
V2ApiKeyUnauthenticatedError,
710
} from '@/lib/api/server/routes/v2-api-key-auth'
811
import type { V2CredentialHeaders } from '@/lib/api/server/routes/v2-credential-headers'
12+
import {
13+
invalidJsonBodyResponse,
14+
type ParseRequestOptions,
15+
type RequestSlice,
16+
validationErrorResponse,
17+
} from '@/lib/api/server/validation'
918
import { type OAuthAccessTokenOptions, parseBearerToken } from '@/lib/auth/oauth-access-token'
1019
import { OAUTH_ACCESS_TOKEN_PREFIX } from '@/lib/auth/oauth-provider'
20+
import { describeResponseError, describeValidationError } from '@/lib/core/utils/response-error'
1121

1222
const NO_STORE = 'private, no-store'
1323

@@ -53,12 +63,63 @@ export async function serveStatelessMcp(
5363
await server.connect(transport)
5464
const response = await transport.handleRequest(request, { parsedBody })
5565
response.headers.set('Cache-Control', NO_STORE)
66+
if (response.status >= 400) await describeTransportRefusal(response, request)
5667
return response
5768
} finally {
5869
await server.close()
5970
}
6071
}
6172

73+
const UNSUPPORTED_PROTOCOL_VERSION = 'Bad Request: Unsupported protocol version'
74+
75+
/**
76+
* Records why the SDK transport refused a request (an unsupported
77+
* `mcp-protocol-version`, a malformed JSON-RPC message) for the route's log
78+
* line. The SDK's messages are fixed text, except for a value after a second
79+
* `: `, which is dropped; an unsupported protocol version is kept, bounded, as
80+
* the detail instead.
81+
*/
82+
async function describeTransportRefusal(response: Response, request: Request): Promise<void> {
83+
let body: unknown
84+
try {
85+
body = await response.clone().json()
86+
} catch {
87+
return
88+
}
89+
const error = isRecordLike(body) ? body.error : undefined
90+
if (!isRecordLike(error)) return
91+
const reason =
92+
typeof error.message === 'string'
93+
? truncate(error.message.split(': ', 2).join(': '), 200)
94+
: undefined
95+
const protocolVersion = request.headers.get('mcp-protocol-version')
96+
describeResponseError(response, {
97+
errorCode: String(error.code),
98+
...(reason ? { errorReason: reason } : {}),
99+
...(protocolVersion && reason === UNSUPPORTED_PROTOCOL_VERSION
100+
? { errorDetail: truncate(protocolVersion, 40) }
101+
: {}),
102+
})
103+
}
104+
105+
/**
106+
* `parseRequest` options for an MCP route: the default 400 bodies, described
107+
* for the route's log line. A JSON-RPC message keeps keys the caller chose, so
108+
* a validation failure names only the slice.
109+
*/
110+
export const MCP_PARSE_ERROR_RESPONSES = {
111+
validationErrorResponseBySlice(error: z.ZodError, slice: RequestSlice) {
112+
const response = validationErrorResponse(error)
113+
describeValidationError(response, error, slice, { sliceOnly: true })
114+
return response
115+
},
116+
invalidJsonResponse() {
117+
const response = invalidJsonBodyResponse()
118+
describeResponseError(response, { errorCode: 'BAD_REQUEST', errorReason: 'invalid_json' })
119+
return response
120+
},
121+
} satisfies ParseRequestOptions
122+
62123
/** Stateless servers take POST only; callers authenticate before answering 405. */
63124
export function mcpMethodNotAllowed(): Response {
64125
return new Response(null, { status: 405, headers: { Allow: 'POST', 'Cache-Control': NO_STORE } })

‎apps/sim/lib/api/server/validation.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,11 @@ export function isZodError(error: unknown): error is z.ZodError {
138138
return error instanceof ZodError
139139
}
140140

141+
/** The default 400 for a request body that is not valid JSON. */
142+
export function invalidJsonBodyResponse(): NextResponse<{ error: string }> {
143+
return NextResponse.json({ error: 'Request body must be valid JSON' }, { status: 400 })
144+
}
145+
141146
export function validationErrorResponse(
142147
error: z.ZodError,
143148
message = 'Validation error',
@@ -219,7 +224,7 @@ export async function parseJsonBody(
219224
return {
220225
success: false,
221226
reason: 'invalid_json',
222-
response: NextResponse.json({ error: 'Request body must be valid JSON' }, { status: 400 }),
227+
response: invalidJsonBodyResponse(),
223228
}
224229
}
225230
}
@@ -272,7 +277,7 @@ export async function parseOptionalJsonBody(
272277
return {
273278
success: false,
274279
reason: 'invalid_json',
275-
response: NextResponse.json({ error: 'Request body must be valid JSON' }, { status: 400 }),
280+
response: invalidJsonBodyResponse(),
276281
}
277282
}
278283
}

‎apps/sim/lib/core/utils/response-error.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import type { z } from 'zod'
2+
13
/**
24
* The machine-readable part of an error response, kept beside the response so
35
* the route handler's closing log line can be grouped by why a request was
@@ -11,6 +13,8 @@ export interface ResponseErrorSummary {
1113
errorField?: string
1214
/** The cause the refusal named (`READ_ONLY_API_KEY`) or the validation issue kind (`invalid_type`). */
1315
errorReason?: string
16+
/** A short, bounded header value the reason turns on, e.g. the protocol version a client asked for. */
17+
errorDetail?: string
1418
}
1519

1620
/**
@@ -28,3 +32,26 @@ export function describeResponseError(response: Response, summary: ResponseError
2832
export function readResponseError(response: Response): ResponseErrorSummary | undefined {
2933
return summaries.get(response)
3034
}
35+
36+
/**
37+
* Records a contract validation failure: the request slice, its top-level field
38+
* (deeper segments can be record keys the caller wrote) unless `sliceOnly` says
39+
* the slice accepts caller-chosen keys, and the first issue's kind.
40+
*/
41+
export function describeValidationError(
42+
response: Response,
43+
error: z.ZodError,
44+
slice?: string,
45+
{ sliceOnly = false }: { sliceOnly?: boolean } = {}
46+
): void {
47+
const issue = error.issues[0]
48+
const field = [slice, sliceOnly ? undefined : issue?.path[0]]
49+
.filter((part) => part !== undefined && part !== '')
50+
.map(String)
51+
.join('.')
52+
describeResponseError(response, {
53+
errorCode: 'BAD_REQUEST',
54+
...(field ? { errorField: field } : {}),
55+
...(issue ? { errorReason: issue.code } : {}),
56+
})
57+
}

‎apps/sim/lib/knowledge/mcp/route-handler.protocol.test.ts‎

Lines changed: 40 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -51,16 +51,17 @@ vi.mock('@/lib/sim-search/live/application', async (importOriginal) => ({
5151
searchLiveKnowledge: { execute: mocks.liveSearch },
5252
}))
5353

54+
import { readResponseError } from '@/lib/core/utils/response-error'
5455
import { createKnowledgeMcpHandlers } from '@/lib/knowledge/mcp/route-handler'
5556

5657
urlsMockFns.mockGetBaseUrl.mockReturnValue('http://localhost')
5758

5859
const handlers = createKnowledgeMcpHandlers()
5960
const principal = createPersonalApiKeyPrincipal({ userId: 'person-1' })
6061

61-
/** Calls a tool over the real route, SDK transport, and Search MCP server. */
62-
async function callTool(name: string, args: Record<string, unknown>) {
63-
const response = await handlers.POST(
62+
/** Posts one message over the real route, SDK transport, and Search MCP server. */
63+
function post(body: unknown, headers: Record<string, string> = {}) {
64+
return handlers.POST(
6465
createMockRequest({
6566
method: 'POST',
6667
url: 'http://localhost/api/mcp/search/organizations/org-1',
@@ -69,16 +70,21 @@ async function callTool(name: string, args: Record<string, unknown>) {
6970
accept: 'application/json, text/event-stream',
7071
'x-forwarded-for': '127.0.0.1',
7172
'x-api-key': 'personal-key',
73+
...headers,
7274
},
73-
body: {
74-
jsonrpc: '2.0',
75-
id: 1,
76-
method: 'tools/call',
77-
params: { name, arguments: args },
78-
},
75+
body,
7976
}),
8077
createRouteContext({ organizationId: 'org-1' })
8178
)
79+
}
80+
81+
async function callTool(name: string, args: Record<string, unknown>) {
82+
const response = await post({
83+
jsonrpc: '2.0',
84+
id: 1,
85+
method: 'tools/call',
86+
params: { name, arguments: args },
87+
})
8288
return { status: response.status, body: await response.json() }
8389
}
8490

@@ -194,3 +200,28 @@ describe('Search MCP tool arguments with one possible reading', () => {
194200
}
195201
)
196202
})
203+
204+
describe('Search MCP refusals name their reason on the route log line', () => {
205+
it('names the SDK refusal and the protocol version a client asked for', async () => {
206+
const response = await post(
207+
{ jsonrpc: '2.0', id: 1, method: 'tools/list' },
208+
{ 'mcp-protocol-version': '2099-01-01' }
209+
)
210+
expect(response.status).toBe(400)
211+
expect(readResponseError(response)).toEqual({
212+
errorCode: '-32000',
213+
errorReason: 'Bad Request: Unsupported protocol version',
214+
errorDetail: '2099-01-01',
215+
})
216+
})
217+
218+
it('names a JSON-RPC batch as a body that is not an object', async () => {
219+
const response = await post([{ jsonrpc: '2.0', id: 1, method: 'tools/list' }])
220+
expect(response.status).toBe(400)
221+
expect(readResponseError(response)).toEqual({
222+
errorCode: 'BAD_REQUEST',
223+
errorField: 'body',
224+
errorReason: 'invalid_type',
225+
})
226+
})
227+
})

‎apps/sim/lib/knowledge/mcp/route-handler.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import type { NextRequest } from 'next/server'
55
import { organizationKnowledgeMcpContract } from '@/lib/api/contracts/knowledge/mcp'
66
import { parseRequest } from '@/lib/api/server'
77
import {
8+
MCP_PARSE_ERROR_RESPONSES,
89
mcpCredentialAuth,
910
mcpMethodNotAllowed,
1011
serveStatelessMcp,
@@ -60,6 +61,7 @@ export function createKnowledgeMcpHandlers() {
6061
}
6162
try {
6263
const parsed = await parseRequest(organizationKnowledgeMcpContract, request, context, {
64+
...MCP_PARSE_ERROR_RESPONSES,
6365
maxBodyBytes: 64 * 1024,
6466
})
6567
if (!parsed.success) return parsed.response

‎scripts/check-test-types.baseline.json‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -196,9 +196,6 @@
196196
"apps/sim/app/api/mcp/servers/route.test.ts": {
197197
"TS2554": 2
198198
},
199-
"apps/sim/app/api/mcp/servers/test-connection/route.test.ts": {
200-
"TS2554": 5
201-
},
202199
"apps/sim/app/api/mothership/chat/stop/route.test.ts": {
203200
"TS18046": 2,
204201
"TS2345": 1,

0 commit comments

Comments
 (0)