@@ -3,14 +3,15 @@ import { createLogger } from '@sim/logger'
33import { CLIENT_INFO_HEADER } from '@sim/utils/client-info'
44import { isPlainRecord } from '@sim/utils/object'
55import { NextRequest } from 'next/server'
6- import { callerHeaderNames , getMcpOperation } from '@/lib/api/mcp/catalog'
6+ import { callerHeaderNames , getMcpOperation , isReadOperation } from '@/lib/api/mcp/catalog'
77import type { V2McpOperationName } from '@/lib/api/mcp/generated/v2-operations'
88import { API_KEY_HEADER } from '@/lib/api/server/credential-headers'
99import type { V2CredentialHeaders } from '@/lib/api/server/routes/v2-credential-headers'
1010import {
1111 type OAuthAccessTokenOptions ,
1212 withOAuthAccessTokenAudience ,
1313} from '@/lib/auth/oauth-access-token'
14+ import { normalizeStringRecord } from '@/lib/core/utils/records'
1415import {
1516 consumeOrCancelBody ,
1617 isPayloadSizeLimitError ,
@@ -38,7 +39,7 @@ type V2RouteHandler = (
3839/** One tool call, as the read and write tools accept it. */
3940export interface McpOperationCall {
4041 operation : V2McpOperationName
41- params ?: Record < string , string >
42+ params ?: Record < string , string | number >
4243 query ?: Record < string , string | number | boolean >
4344 body ?: unknown
4445 headers ?: Record < string , string >
@@ -115,7 +116,31 @@ function buildHeaders(
115116type McpDispatchOutcome =
116117 | { rejected : string }
117118 | { status : number ; ok : boolean ; text : string }
118- | { status : number ; unreadable : string }
119+ | UnreadableAnswer
120+
121+ /** An answer the route gave that cannot be returned, and why. */
122+ interface UnreadableAnswer {
123+ status : number
124+ unreadable : string
125+ tooLarge : boolean
126+ }
127+
128+ /**
129+ * Explains an unreadable answer to the model. The operation ran either way, so a
130+ * write is never to be repeated; only a read that came back too large can be
131+ * retried, asking for less.
132+ */
133+ export function unreadableMessage (
134+ operation : V2McpOperationName ,
135+ answer : UnreadableAnswer ,
136+ isRead : boolean
137+ ) : string {
138+ const message = `${ operation } ran (HTTP ${ answer . status } ), but its answer cannot be returned. ${ answer . unreadable } `
139+ if ( ! isRead ) return `${ message } Do not repeat it; read the resource to see its state.`
140+ return answer . tooLarge
141+ ? `${ message } Request less, such as a smaller page with limit or cursor.`
142+ : message
143+ }
119144
120145/** Reads the route's JSON answer, bounded by {@link MAX_RESULT_BYTES}. */
121146async function readJsonAnswer (
@@ -126,8 +151,9 @@ async function readJsonAnswer(
126151 if ( ! / [ / + ] j s o n \b / i. test ( contentType ) ) {
127152 await consumeOrCancelBody ( response )
128153 return {
129- unreadable : `${ operation } answered with ${ contentType || 'an empty body' } (HTTP ${ response . status } ). Only JSON responses can be returned over MCP.` ,
130154 status : response . status ,
155+ unreadable : `The answer is ${ contentType || 'empty' } ; only JSON can be returned over MCP.` ,
156+ tooLarge : false ,
131157 }
132158 }
133159 try {
@@ -139,8 +165,9 @@ async function readJsonAnswer(
139165 } catch ( error ) {
140166 if ( ! isPayloadSizeLimitError ( error ) ) throw error
141167 return {
142- unreadable : 'Result is too large. Request a smaller page with limit or cursor.' ,
143168 status : response . status ,
169+ unreadable : 'The answer is too large to return.' ,
170+ tooLarge : true ,
144171 }
145172 }
146173}
@@ -162,7 +189,8 @@ export async function dispatchMcpRequest(
162189 const startedAt = performance . now ( )
163190 const { contract, handler } = getMcpOperation ( call . operation )
164191
165- const resolved = resolvePath ( contract . path , call . params ?? { } )
192+ const params = normalizeStringRecord ( call . params )
193+ const resolved = resolvePath ( contract . path , params )
166194 if ( 'error' in resolved ) return { rejected : resolved . error }
167195
168196 const url = new URL ( resolved . path , getBaseUrl ( ) )
@@ -195,7 +223,7 @@ export async function dispatchMcpRequest(
195223 signal : context . signal ,
196224 } )
197225 const response = await withOAuthAccessTokenAudience ( context . audience , ( ) =>
198- route ( request , { params : Promise . resolve ( call . params ?? { } ) } )
226+ route ( request , { params : Promise . resolve ( params ) } )
199227 )
200228 logger . info ( 'Sim MCP operation dispatched' , {
201229 operation : call . operation ,
@@ -213,6 +241,10 @@ export async function dispatchMcpOperation(
213241) : Promise < CallToolResult > {
214242 const outcome = await dispatchMcpRequest ( call , context )
215243 if ( 'rejected' in outcome ) return toolError ( outcome . rejected )
216- if ( 'unreadable' in outcome ) return toolError ( outcome . unreadable )
244+ if ( 'unreadable' in outcome ) {
245+ return toolError (
246+ unreadableMessage ( call . operation , outcome , await isReadOperation ( call . operation ) )
247+ )
248+ }
217249 return outcome . ok ? { content : [ { type : 'text' , text : outcome . text } ] } : toolError ( outcome . text )
218250}
0 commit comments