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
49 changes: 48 additions & 1 deletion apps/sim/app/api/mcp/serve/[serverId]/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -828,7 +828,25 @@ describe('MCP Serve Route', () => {
'a JSON-RPC 1.0 envelope',
JSON.stringify({ jsonrpc: '1.0', id: 1, method: 'ping' }),
ErrorCode.InvalidRequest,
'not_a_request',
'invalid_version',
],
[
'a JSON-RPC batch',
JSON.stringify([{ jsonrpc: '2.0', id: 1, method: 'ping' }]),
ErrorCode.InvalidRequest,
'batch',
],
[
'a message without a method',
JSON.stringify({ jsonrpc: '2.0', id: 1 }),
ErrorCode.InvalidRequest,
'missing_method',
],
[
'a request with a null id',
JSON.stringify({ jsonrpc: '2.0', id: null, method: 'ping' }),
ErrorCode.InvalidRequest,
'invalid_id',
],
])('names why it refuses %s on the route log line', async (_label, body, code, reason) => {
dbChainMockFns.limit.mockResolvedValueOnce([
Expand All @@ -853,6 +871,35 @@ describe('MCP Serve Route', () => {
expect(readResponseError(response)).toEqual({ errorCode: String(code), errorReason: reason })
})

it.each([
['result', { jsonrpc: '2.0', id: 'srv-1', result: {} }],
['error', { jsonrpc: '2.0', id: 'srv-1', error: { code: -32601, message: 'Unsupported' } }],
])(
'accepts a client-posted JSON-RPC %s response with 202 and no body',
async (_kind, message) => {
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: JSON.stringify(message),
})

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

expect(response.status).toBe(202)
expect(await response.text()).toBe('')
expect(fetchMock).not.toHaveBeenCalled()
}
)

it('rejects streamed MCP request bodies that exceed the cap without content-length', async () => {
const cancelSpy = vi.fn()
dbChainMockFns.limit.mockResolvedValueOnce([
Expand Down
41 changes: 39 additions & 2 deletions apps/sim/app/api/mcp/serve/[serverId]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,17 @@ import {
type CallToolResult,
ErrorCode,
type InitializeResult,
isJSONRPCErrorResponse,
isJSONRPCNotification,
isJSONRPCRequest,
isJSONRPCResultResponse,
type JSONRPCError,
type JSONRPCMessage,
type JSONRPCResultResponse,
LATEST_PROTOCOL_VERSION,
type ListToolsResult,
type RequestId,
RequestIdSchema,
SUPPORTED_PROTOCOL_VERSIONS,
type Tool,
} from '@modelcontextprotocol/sdk/types.js'
Expand Down Expand Up @@ -152,11 +155,35 @@ function createError(
}
}

type NotARequestReason =
| 'batch'
| 'not_an_object'
| 'invalid_response'
| 'missing_method'
| 'invalid_id'
| 'invalid_version'
| 'not_a_request'

/**
* Names the shape of a body that is neither a notification, a response, nor a request, so the
* log line says what a client sent without logging the body. JSON-RPC batches are refused: the
* 2025-06-18 transport removed them and this route answers one message per POST.
*/
function describeNotARequest(body: unknown): NotARequestReason {
if (Array.isArray(body)) return 'batch'
if (!isRecordLike(body)) return 'not_an_object'
if (body.jsonrpc !== '2.0') return 'invalid_version'
if (body.method === undefined && ('result' in body || 'error' in body)) return 'invalid_response'
if (typeof body.method !== 'string') return 'missing_method'
if ('id' in body && !RequestIdSchema.safeParse(body.id).success) return 'invalid_id'
return 'not_a_request'
}

/** 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'
reason: 'invalid_json' | 'invalid_notification' | 'invalid_request' | NotARequestReason
): NextResponse {
const response = NextResponse.json(createError(0, code, message), { status: 400 })
describeResponseError(response, { errorCode: String(code), errorReason: reason })
Expand Down Expand Up @@ -781,11 +808,21 @@ export const POST = withRouteHandler(
return new NextResponse(null, { status: 202 })
}

const responseKind = isJSONRPCResultResponse(message)
? 'result'
: isJSONRPCErrorResponse(message)
? 'error'
: null
if (responseKind) {
logger.info('Ignored client JSON-RPC response', { kind: responseKind })
return new NextResponse(null, { status: 202 })
}

if (!isJSONRPCRequest(message)) {
return malformedMessageResponse(
ErrorCode.InvalidRequest,
'Invalid JSON-RPC message',
'not_a_request'
describeNotARequest(body)
)
}

Expand Down
Loading