Skip to content

Commit 395212f

Browse files
authored
fix(mcp): accept numeric path params, read-aware unreadable advice, report unsent code-mode calls (#10211)
1 parent 627d213 commit 395212f

5 files changed

Lines changed: 97 additions & 22 deletions

File tree

‎apps/sim/lib/api/mcp/__integration__/code-mode.integration.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,20 @@ describe('Sim MCP code mode in PostgreSQL and the isolate pool', () => {
272272
})
273273
})
274274

275+
it('passes a numeric path parameter, as signatures declare it, through to its route', async () => {
276+
const result = await runCode(
277+
'execute_read_code',
278+
`
279+
try {
280+
await sim.api.getFileVersion({ params: { fileId: 'wf_${generateId().replaceAll('-', '')}', version: 1 }, query: { workspaceId: ${JSON.stringify(workspaceId)} } })
281+
} catch (error) {
282+
return { status: error.status, code: error.code }
283+
}
284+
`
285+
)
286+
expect(result.structuredContent?.result).toEqual({ status: 404, code: 'NOT_FOUND' })
287+
})
288+
275289
it('gives the program no network and no credential', async () => {
276290
const result = await runCode(
277291
'execute_read_code',
@@ -320,7 +334,9 @@ describe('Sim MCP code mode in PostgreSQL and the isolate pool', () => {
320334
expect(failed.error.message).toBe('stopped while writes were queued')
321335
await sleep(3000)
322336
const created = (await tableNames()).filter((name) => name.startsWith(prefix))
323-
expect(created.length).toBeLessThan(40)
337+
const sent = failed.calls.filter((call) => call.refused === undefined)
338+
expect(sent.length).toBeLessThan(failed.calls.length)
339+
expect(created.length).toBeLessThanOrEqual(sent.length)
324340
for (const call of failed.calls) {
325341
expect(
326342
call.status !== undefined || call.refused !== undefined || call.unreadable !== undefined

‎apps/sim/lib/api/mcp/catalog.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ const REQUEST_SLOTS = ['params', 'query', 'body', 'headers'] as const
3535
export const operationRequestInput = z
3636
.object({
3737
params: z
38-
.record(z.string(), z.string())
38+
.record(z.string(), z.union([z.string(), z.number()]))
3939
.optional()
4040
.describe(
4141
'Values for the bracketed segments of the operation’s path, by name, e.g. { "tableId": "..." }. IDs come from list operations such as listTables.'

‎apps/sim/lib/api/mcp/code-mode.ts‎

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,11 @@ import {
1212
operationRequestInput,
1313
resolveOperation,
1414
} from '@/lib/api/mcp/catalog'
15-
import { dispatchMcpRequest, type McpDispatchContext } from '@/lib/api/mcp/dispatch'
15+
import {
16+
dispatchMcpRequest,
17+
type McpDispatchContext,
18+
unreadableMessage,
19+
} from '@/lib/api/mcp/dispatch'
1620
import { createConcurrencyLimit } from '@/lib/core/utils/concurrency'
1721
import { runSandboxTask, SandboxUserCodeError } from '@/lib/execution/sandbox/run-task'
1822
import { loadTypeScript } from '@/lib/execution/typescript'
@@ -27,6 +31,7 @@ const MAX_CALLS_PER_RUN = 200
2731
/** Calls one program may have in flight at once, so a `Promise.all` cannot fan out a whole page of requests. */
2832
const MAX_CONCURRENT_CALLS = 8
2933
const MAX_CODE_CHARS = 100_000
34+
const NOT_SENT = 'The program ended before this call was sent.'
3035

3136
export const codeModeInput = z
3237
.object({
@@ -164,6 +169,8 @@ export async function runCodeMode(
164169
const startedAt = performance.now()
165170
const runId = generateShortId(12)
166171
const calls: CallRecord[] = []
172+
/** Calls handed to the dispatcher; the rest of an unfinished run's calls were never sent. */
173+
const sent = new Set<CallRecord>()
167174
let writes = 0
168175
const limit = createConcurrencyLimit(MAX_CONCURRENT_CALLS)
169176
/** Ends the run's in-flight calls once the program is over, whether it returned, threw, or timed out. */
@@ -223,14 +230,14 @@ export async function runCodeMode(
223230
)
224231
}
225232
if (!isRead) writes++
226-
const outcome = await limit(async () =>
227-
signal.aborted
228-
? { rejected: 'The program ended before this call was sent.' }
229-
: dispatchMcpRequest(
230-
{ ...parsed.data.input, operation: resolved.operation },
231-
{ ...context, signal, logMetadata: { codeRunId: runId, callIndex } }
232-
)
233-
)
233+
const outcome = await limit(async () => {
234+
if (signal.aborted) return { rejected: NOT_SENT }
235+
sent.add(record)
236+
return dispatchMcpRequest(
237+
{ ...parsed.data.input, operation: resolved.operation },
238+
{ ...context, signal, logMetadata: { codeRunId: runId, callIndex } }
239+
)
240+
})
234241
if ('rejected' in outcome) {
235242
record.refused = outcome.rejected
236243
return apiFailure(400, 'INVALID_CALL', outcome.rejected)
@@ -241,7 +248,7 @@ export async function runCodeMode(
241248
return apiFailure(
242249
outcome.status,
243250
'UNREADABLE_RESPONSE',
244-
`${resolved.operation} ran (HTTP ${outcome.status}), but its answer cannot be returned: ${outcome.unreadable} Do not repeat it; read the resource to see its state.`
251+
unreadableMessage(resolved.operation, outcome, isRead)
245252
)
246253
}
247254
return outcome.ok ? { dataJson: outcome.text } : envelopeFailure(outcome.status, outcome.text)
@@ -268,8 +275,11 @@ export async function runCodeMode(
268275
}
269276
runEnded.abort()
270277
for (const record of calls) {
271-
if (record.status === undefined && record.refused === undefined) {
278+
if (record.status !== undefined || record.refused !== undefined) continue
279+
if (sent.has(record)) {
272280
record.unreadable = 'The program ended before this call answered; it may still complete.'
281+
} else {
282+
record.refused = NOT_SENT
273283
}
274284
}
275285

‎apps/sim/lib/api/mcp/dispatch.test.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ vi.mock('@/lib/api/mcp/catalog', () => {
2828
handler: async () => mocks.route,
2929
}),
3030
callerHeaderNames: (name: string) => (name === 'completeFileUpload' ? ['upload-token'] : []),
31+
isReadOperation: async (name: string) => name === 'getTableRow',
3132
}
3233
})
3334

@@ -168,6 +169,22 @@ describe('dispatchMcpOperation', () => {
168169
context
169170
)
170171
expect(result.isError).toBe(true)
171-
expect(result.content[0]).toMatchObject({ text: expect.stringContaining('too large') })
172+
expect(result.content[0]).toMatchObject({ text: expect.stringContaining('Request less') })
173+
})
174+
175+
it('never asks for a write that answered too large to be retried', async () => {
176+
mocks.route.mockResolvedValue(jsonResponse({ data: 'x'.repeat(1024 * 1024) }))
177+
const result = await dispatchMcpOperation(
178+
{
179+
operation: 'completeFileUpload',
180+
params: { uploadId: 'u' },
181+
body: { workspaceId: 'w' },
182+
headers: { 'upload-token': 't' },
183+
},
184+
context
185+
)
186+
expect(result.isError).toBe(true)
187+
expect(result.content[0]).toMatchObject({ text: expect.stringContaining('Do not repeat it') })
188+
expect(result.content[0]).not.toMatchObject({ text: expect.stringContaining('Request less') })
172189
})
173190
})

‎apps/sim/lib/api/mcp/dispatch.ts‎

Lines changed: 40 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,15 @@ import { createLogger } from '@sim/logger'
33
import { CLIENT_INFO_HEADER } from '@sim/utils/client-info'
44
import { isPlainRecord } from '@sim/utils/object'
55
import { NextRequest } from 'next/server'
6-
import { callerHeaderNames, getMcpOperation } from '@/lib/api/mcp/catalog'
6+
import { callerHeaderNames, getMcpOperation, isReadOperation } from '@/lib/api/mcp/catalog'
77
import type { V2McpOperationName } from '@/lib/api/mcp/generated/v2-operations'
88
import { API_KEY_HEADER } from '@/lib/api/server/credential-headers'
99
import type { V2CredentialHeaders } from '@/lib/api/server/routes/v2-credential-headers'
1010
import {
1111
type OAuthAccessTokenOptions,
1212
withOAuthAccessTokenAudience,
1313
} from '@/lib/auth/oauth-access-token'
14+
import { normalizeStringRecord } from '@/lib/core/utils/records'
1415
import {
1516
consumeOrCancelBody,
1617
isPayloadSizeLimitError,
@@ -38,7 +39,7 @@ type V2RouteHandler = (
3839
/** One tool call, as the read and write tools accept it. */
3940
export 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(
115116
type 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}. */
121146
async function readJsonAnswer(
@@ -126,8 +151,9 @@ async function readJsonAnswer(
126151
if (!/[/+]json\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

Comments
 (0)