Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions apps/sim/app/api/mcp/serve/[serverId]/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ vi.mock('@/lib/workflows/executor/execute-service', () => ({
}))

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

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

it.each([
['an unparseable body', '{ this is not json', ErrorCode.ParseError, 'invalid_json'],
[
'a JSON-RPC 1.0 envelope',
JSON.stringify({ jsonrpc: '1.0', id: 1, method: 'ping' }),
ErrorCode.InvalidRequest,
'not_a_request',
],
])('names why it refuses %s on the route log line', async (_label, body, code, reason) => {
dbChainMockFns.limit.mockResolvedValueOnce([
{
id: 'server-1',
name: 'Public Server',
workspaceId: 'ws-1',
isPublic: true,
createdBy: 'owner-1',
},
])

const req = new NextRequest('http://localhost:3000/api/mcp/serve/server-1', {
method: 'POST',
body,
})

const response = await POST(req, createRouteContext({ serverId: 'server-1' }))

expect(response.status).toBe(400)
expect((await response.clone().json()).error.code).toBe(code)
expect(readResponseError(response)).toEqual({ errorCode: String(code), errorReason: reason })
})

it('rejects streamed MCP request bodies that exceed the cap without content-length', async () => {
const cancelSpy = vi.fn()
dbChainMockFns.limit.mockResolvedValueOnce([
Expand Down
43 changes: 25 additions & 18 deletions apps/sim/app/api/mcp/serve/[serverId]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ import {
import { getMaxExecutionTimeout } from '@/lib/core/execution-limits'
import { acceptsMediaType } from '@/lib/core/utils/media-types'
import { generateRequestId } from '@/lib/core/utils/request'
import { describeResponseError } from '@/lib/core/utils/response-error'
import { encodeSSE, encodeSSEComment, SSE_HEADERS } from '@/lib/core/utils/sse'
import {
assertContentLengthWithinLimit,
Expand Down Expand Up @@ -151,6 +152,17 @@ function createError(
}
}

/** A 400 for a body that is not a usable JSON-RPC message, with its reason kept for the route's log line. */
function malformedMessageResponse(
code: ErrorCode,
message: string,
reason: 'invalid_json' | 'invalid_notification' | 'not_a_request' | 'invalid_request'
): NextResponse {
const response = NextResponse.json(createError(0, code, message), { status: 400 })
describeResponseError(response, { errorCode: String(code), errorReason: reason })
return response
}

const SESSION_SIGNAL_STATUSES = new Set([400, 401, 404])

/**
Expand Down Expand Up @@ -751,20 +763,17 @@ export const POST = withRouteHandler(
)
}
if (request.signal.aborted) return clientCancelledJsonRpcResponse(0)
return NextResponse.json(createError(0, ErrorCode.ParseError, 'Invalid JSON body'), {
status: 400,
})
return malformedMessageResponse(ErrorCode.ParseError, 'Invalid JSON body', 'invalid_json')
}
const message = body as JSONRPCMessage

if (isJSONRPCNotification(message)) {
const notificationValidation = mcpJsonRpcNotificationSchema.safeParse(message)
if (!notificationValidation.success) {
return NextResponse.json(
createError(0, ErrorCode.InvalidRequest, 'Invalid JSON-RPC message'),
{
status: 400,
}
return malformedMessageResponse(
ErrorCode.InvalidRequest,
'Invalid JSON-RPC message',
'invalid_notification'
)
}

Expand All @@ -773,21 +782,19 @@ export const POST = withRouteHandler(
}

if (!isJSONRPCRequest(message)) {
return NextResponse.json(
createError(0, ErrorCode.InvalidRequest, 'Invalid JSON-RPC message'),
{
status: 400,
}
return malformedMessageResponse(
ErrorCode.InvalidRequest,
'Invalid JSON-RPC message',
'not_a_request'
)
}

const requestValidation = mcpJsonRpcRequestSchema.safeParse(message)
if (!requestValidation.success) {
return NextResponse.json(
createError(0, ErrorCode.InvalidRequest, 'Invalid JSON-RPC message'),
{
status: 400,
}
return malformedMessageResponse(
ErrorCode.InvalidRequest,
'Invalid JSON-RPC message',
'invalid_request'
)
}

Expand Down
Loading