Skip to content

Commit 5a4deba

Browse files
authored
fix(mcp): name the reason on the workflow MCP serve route's malformed-message 400s (#10482)
The serve route builds its own JSON-RPC 400s for an unparseable body, an invalid notification, a non-request message and an invalid request, so they reached the route log line with no reason. Record the JSON-RPC code and a fixed reason for each; response bodies and statuses are unchanged.
1 parent 3c2f25e commit 5a4deba

2 files changed

Lines changed: 57 additions & 18 deletions

File tree

‎apps/sim/app/api/mcp/serve/[serverId]/route.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ vi.mock('@/lib/workflows/executor/execute-service', () => ({
141141
}))
142142

143143
import { PERSONAL_KEY_DENIED } from '@/lib/api-key/policy-messages'
144+
import { readResponseError } from '@/lib/core/utils/response-error'
144145
import { DELETE, GET, POST } from '@/app/api/mcp/serve/[serverId]/route'
145146

146147
executionLimitsMockFns.mockGetMaxExecutionTimeout.mockReturnValue(60_000)
@@ -821,6 +822,37 @@ describe('MCP Serve Route', () => {
821822
expect(fetchMock).not.toHaveBeenCalled()
822823
})
823824

825+
it.each([
826+
['an unparseable body', '{ this is not json', ErrorCode.ParseError, 'invalid_json'],
827+
[
828+
'a JSON-RPC 1.0 envelope',
829+
JSON.stringify({ jsonrpc: '1.0', id: 1, method: 'ping' }),
830+
ErrorCode.InvalidRequest,
831+
'not_a_request',
832+
],
833+
])('names why it refuses %s on the route log line', async (_label, body, code, reason) => {
834+
dbChainMockFns.limit.mockResolvedValueOnce([
835+
{
836+
id: 'server-1',
837+
name: 'Public Server',
838+
workspaceId: 'ws-1',
839+
isPublic: true,
840+
createdBy: 'owner-1',
841+
},
842+
])
843+
844+
const req = new NextRequest('http://localhost:3000/api/mcp/serve/server-1', {
845+
method: 'POST',
846+
body,
847+
})
848+
849+
const response = await POST(req, createRouteContext({ serverId: 'server-1' }))
850+
851+
expect(response.status).toBe(400)
852+
expect((await response.clone().json()).error.code).toBe(code)
853+
expect(readResponseError(response)).toEqual({ errorCode: String(code), errorReason: reason })
854+
})
855+
824856
it('rejects streamed MCP request bodies that exceed the cap without content-length', async () => {
825857
const cancelSpy = vi.fn()
826858
dbChainMockFns.limit.mockResolvedValueOnce([

‎apps/sim/app/api/mcp/serve/[serverId]/route.ts‎

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ import {
6767
import { getMaxExecutionTimeout } from '@/lib/core/execution-limits'
6868
import { acceptsMediaType } from '@/lib/core/utils/media-types'
6969
import { generateRequestId } from '@/lib/core/utils/request'
70+
import { describeResponseError } from '@/lib/core/utils/response-error'
7071
import { encodeSSE, encodeSSEComment, SSE_HEADERS } from '@/lib/core/utils/sse'
7172
import {
7273
assertContentLengthWithinLimit,
@@ -151,6 +152,17 @@ function createError(
151152
}
152153
}
153154

155+
/** A 400 for a body that is not a usable JSON-RPC message, with its reason kept for the route's log line. */
156+
function malformedMessageResponse(
157+
code: ErrorCode,
158+
message: string,
159+
reason: 'invalid_json' | 'invalid_notification' | 'not_a_request' | 'invalid_request'
160+
): NextResponse {
161+
const response = NextResponse.json(createError(0, code, message), { status: 400 })
162+
describeResponseError(response, { errorCode: String(code), errorReason: reason })
163+
return response
164+
}
165+
154166
const SESSION_SIGNAL_STATUSES = new Set([400, 401, 404])
155167

156168
/**
@@ -751,20 +763,17 @@ export const POST = withRouteHandler(
751763
)
752764
}
753765
if (request.signal.aborted) return clientCancelledJsonRpcResponse(0)
754-
return NextResponse.json(createError(0, ErrorCode.ParseError, 'Invalid JSON body'), {
755-
status: 400,
756-
})
766+
return malformedMessageResponse(ErrorCode.ParseError, 'Invalid JSON body', 'invalid_json')
757767
}
758768
const message = body as JSONRPCMessage
759769

760770
if (isJSONRPCNotification(message)) {
761771
const notificationValidation = mcpJsonRpcNotificationSchema.safeParse(message)
762772
if (!notificationValidation.success) {
763-
return NextResponse.json(
764-
createError(0, ErrorCode.InvalidRequest, 'Invalid JSON-RPC message'),
765-
{
766-
status: 400,
767-
}
773+
return malformedMessageResponse(
774+
ErrorCode.InvalidRequest,
775+
'Invalid JSON-RPC message',
776+
'invalid_notification'
768777
)
769778
}
770779

@@ -773,21 +782,19 @@ export const POST = withRouteHandler(
773782
}
774783

775784
if (!isJSONRPCRequest(message)) {
776-
return NextResponse.json(
777-
createError(0, ErrorCode.InvalidRequest, 'Invalid JSON-RPC message'),
778-
{
779-
status: 400,
780-
}
785+
return malformedMessageResponse(
786+
ErrorCode.InvalidRequest,
787+
'Invalid JSON-RPC message',
788+
'not_a_request'
781789
)
782790
}
783791

784792
const requestValidation = mcpJsonRpcRequestSchema.safeParse(message)
785793
if (!requestValidation.success) {
786-
return NextResponse.json(
787-
createError(0, ErrorCode.InvalidRequest, 'Invalid JSON-RPC message'),
788-
{
789-
status: 400,
790-
}
794+
return malformedMessageResponse(
795+
ErrorCode.InvalidRequest,
796+
'Invalid JSON-RPC message',
797+
'invalid_request'
791798
)
792799
}
793800

0 commit comments

Comments
 (0)