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
25 changes: 19 additions & 6 deletions apps/sim/app/api/mcp/servers/test-connection/route.test.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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({
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
10 changes: 2 additions & 8 deletions apps/sim/app/api/v2/lib/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

/**
Expand Down Expand Up @@ -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
}

Expand Down
3 changes: 2 additions & 1 deletion apps/sim/lib/api/mcp/route-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down
61 changes: 61 additions & 0 deletions apps/sim/lib/api/server/routes/mcp-server-route.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand Down Expand Up @@ -53,12 +63,63 @@ 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<void> {
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. 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, { sliceOnly: true })
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 } })
Expand Down
9 changes: 7 additions & 2 deletions apps/sim/lib/api/server/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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(),
}
}
}
Expand Down Expand Up @@ -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(),
}
}
}
Expand Down
27 changes: 27 additions & 0 deletions apps/sim/lib/core/utils/response-error.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
}

/**
Expand All @@ -28,3 +32,26 @@ 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, 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,
{ sliceOnly = false }: { sliceOnly?: boolean } = {}
): void {
const issue = error.issues[0]
const field = [slice, sliceOnly ? undefined : issue?.path[0]]
.filter((part) => part !== undefined && part !== '')
.map(String)
.join('.')
describeResponseError(response, {
errorCode: 'BAD_REQUEST',
...(field ? { errorField: field } : {}),
...(issue ? { errorReason: issue.code } : {}),
})
}
49 changes: 40 additions & 9 deletions apps/sim/lib/knowledge/mcp/route-handler.protocol.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,16 +51,17 @@ 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')

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<string, unknown>) {
const response = await handlers.POST(
/** Posts one message over the real route, SDK transport, and Search MCP server. */
function post(body: unknown, headers: Record<string, string> = {}) {
return handlers.POST(
createMockRequest({
method: 'POST',
url: 'http://localhost/api/mcp/search/organizations/org-1',
Expand All @@ -69,16 +70,21 @@ async function callTool(name: string, args: Record<string, unknown>) {
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<string, unknown>) {
const response = await post({
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: { name, arguments: args },
})
return { status: response.status, body: await response.json() }
}

Expand Down Expand Up @@ -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',
})
})
})
2 changes: 2 additions & 0 deletions apps/sim/lib/knowledge/mcp/route-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
3 changes: 0 additions & 3 deletions scripts/check-test-types.baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading