|
1 | 1 | import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' |
2 | 2 | import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js' |
| 3 | +import { isRecordLike } from '@sim/utils/object' |
| 4 | +import { truncate } from '@sim/utils/string' |
3 | 5 | import type { NextRequest } from 'next/server' |
| 6 | +import type { z } from 'zod' |
4 | 7 | import { |
5 | 8 | authenticateV2ApiKey, |
6 | 9 | V2ApiKeyUnauthenticatedError, |
7 | 10 | } from '@/lib/api/server/routes/v2-api-key-auth' |
8 | 11 | 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' |
9 | 18 | import { type OAuthAccessTokenOptions, parseBearerToken } from '@/lib/auth/oauth-access-token' |
10 | 19 | import { OAUTH_ACCESS_TOKEN_PREFIX } from '@/lib/auth/oauth-provider' |
| 20 | +import { describeResponseError, describeValidationError } from '@/lib/core/utils/response-error' |
11 | 21 |
|
12 | 22 | const NO_STORE = 'private, no-store' |
13 | 23 |
|
@@ -53,12 +63,63 @@ export async function serveStatelessMcp( |
53 | 63 | await server.connect(transport) |
54 | 64 | const response = await transport.handleRequest(request, { parsedBody }) |
55 | 65 | response.headers.set('Cache-Control', NO_STORE) |
| 66 | + if (response.status >= 400) await describeTransportRefusal(response, request) |
56 | 67 | return response |
57 | 68 | } finally { |
58 | 69 | await server.close() |
59 | 70 | } |
60 | 71 | } |
61 | 72 |
|
| 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 | + |
62 | 123 | /** Stateless servers take POST only; callers authenticate before answering 405. */ |
63 | 124 | export function mcpMethodNotAllowed(): Response { |
64 | 125 | return new Response(null, { status: 405, headers: { Allow: 'POST', 'Cache-Control': NO_STORE } }) |
|
0 commit comments