Skip to content

Commit 82e19a3

Browse files
committed
feat(mcp): enable code mode for every caller and remove the mcp-code-mode flag
- Every Sim MCP caller gets execute_read_code and execute_write_code; the sandbox owner key comes from the principal (person, or workspace for workspace keys) - Default program timeout is 45s, under the 60s MCP client request default - A null query value is left out, so the last page's null cursor ends paging - The scope pre-check trims the operation name like the call tools do - Docs state the 256 KB per-call input limit and drop the beta note
1 parent b3e928f commit 82e19a3

9 files changed

Lines changed: 70 additions & 93 deletions

File tree

‎apps/docs/content/docs/mcp/tools.mdx‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ title: Tools
33
description: Discover an operation, inspect its request, and call it with the correct access.
44
---
55

6-
Sim MCP exposes four tools for discovering and calling its supported JSON API operations. Search for an operation, inspect its inputs, then call the read or write tool named in its description.
6+
Sim MCP exposes six tools for discovering and calling its supported JSON API operations. Search for an operation, inspect its inputs, then call the read or write tool named in its description, or run a program that makes many calls with a [code tool](#code-mode).
77

88
## Tools
99

@@ -72,13 +72,12 @@ correct its request.
7272

7373
`getWorkflowSource` returns a workflow as TypeScript source files with its `lock` and `base`. Edit the files and send them back, with the same `lock` and `base`, through `applyWorkflowSource`, first with `query: {"dryRun": true}`. One call replaces a batch of graph operations. Workflows as code is in preview; see [Workflows as code](/workflows/code).
7474

75-
## Code mode (beta)
75+
## Code mode
7676

7777
For a task that takes many calls, such as paging through a list, filtering, or
7878
updating every item that matches, the agent can write one program instead of
7979
making each call itself. Only the program's return value comes back, so
80-
intermediate results stay out of the model's context. Code mode is in beta and
81-
appears only for accounts where it is enabled.
80+
intermediate results stay out of the model's context.
8281

8382
| Tool | Does |
8483
| --- | --- |
@@ -115,8 +114,10 @@ happened.
115114

116115
Each call runs through the API exactly as a call tool's would, with the same
117116
credential, permissions, and rate limits. The program has no network access and
118-
never sees your credential. A program runs for at most 60 seconds by default (up
117+
never sees your credential. A program runs for at most 45 seconds by default (up
119118
to 120 with `timeoutMs`), makes at most 200 calls, and returns at most 1 MiB.
119+
One call's input may be at most 256 KB as JSON; send a larger body, such as a
120+
big batch of rows, with `call_write_operation`.
120121

121122
## Related docs
122123

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

Lines changed: 41 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,13 @@ import { db } from '@sim/db'
99
import { apiKey, permissions, user, userTableDefinitions, workspace } from '@sim/db/schema'
1010
import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
1111
import { authMock } from '@sim/testing/mocks/auth.mock'
12-
import { featureFlagsMock, featureFlagsMockFns } from '@sim/testing/mocks/feature-flags.mock'
1312
import { sleep } from '@sim/utils/helpers'
1413
import { generateId } from '@sim/utils/id'
15-
import { toRecord } from '@sim/utils/object'
1614
import { eq } from 'drizzle-orm'
1715
import { NextRequest } from 'next/server'
18-
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
16+
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
1917

2018
vi.mock('@/lib/auth', () => authMock)
21-
vi.mock('@/lib/core/config/feature-flags', () => featureFlagsMock)
2219

2320
import { hashApiKey } from '@/lib/api-key/crypto'
2421
import { POST as simMcpPost } from '@/app/api/mcp/route'
@@ -28,6 +25,7 @@ const userId = generateId()
2825
const workspaceId = generateId()
2926
const writeKey = `sk-sim-fixture-${generateId()}`
3027
const readKey = `sk-sim-fixture-${generateId()}`
28+
const workspaceKey = `sk-sim-fixture-${generateId()}`
3129

3230
interface ToolResult {
3331
isError?: boolean
@@ -130,44 +128,42 @@ describe('Sim MCP code mode in PostgreSQL and the isolate pool', () => {
130128
type: 'personal',
131129
access: 'read',
132130
},
131+
{
132+
id: generateId(),
133+
userId,
134+
workspaceId,
135+
name: 'Workspace',
136+
key: workspaceKey,
137+
keyHash: hashApiKey(workspaceKey),
138+
type: 'workspace',
139+
access: 'read',
140+
},
133141
])
134142
})
135143

136-
beforeEach(() => {
137-
featureFlagsMockFns.mockIsFeatureEnabled.mockImplementation(
138-
async (flag: string, target?: unknown) =>
139-
flag === 'mcp-code-mode' && toRecord(target).userId === userId
140-
)
141-
})
142-
143144
afterAll(async () => {
144145
await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId))
145146
await db.delete(user).where(eq(user.id, userId))
146147
await db.$client.end()
147148
})
148149

149-
it('lists the code tools only when the flag is on for the caller', async () => {
150-
const listed = await mcp(writeKey, { method: 'tools/list' })
150+
it('runs programs for a workspace key, which has no person to key the sandbox by', async () => {
151+
const listed = await mcp(workspaceKey, { method: 'tools/list' })
152+
expect(listed.status, JSON.stringify(listed.body)).toBe(200)
151153
const names = (listed.body.result as { tools: Array<{ name: string }> }).tools.map(
152154
(t) => t.name
153155
)
154156
expect(names).toEqual(expect.arrayContaining(['execute_read_code', 'execute_write_code']))
155157

156-
featureFlagsMockFns.mockIsFeatureEnabled.mockResolvedValue(false)
157-
const hidden = await mcp(writeKey, { method: 'tools/list' })
158-
const hiddenNames = (hidden.body.result as { tools: Array<{ name: string }> }).tools.map(
159-
(t) => t.name
158+
const read = await runCode(
159+
'execute_read_code',
160+
`const page = await sim.api.listTables({ query: { workspaceId: ${JSON.stringify(workspaceId)} } })
161+
return Array.isArray(page.data)`,
162+
{ key: workspaceKey }
160163
)
161-
expect(hiddenNames).not.toContain('execute_read_code')
162-
expect(hiddenNames).not.toContain('execute_write_code')
163-
const refused = await mcp(writeKey, {
164-
method: 'tools/call',
165-
params: { name: 'execute_read_code', arguments: { code: 'return 1' } },
166-
})
167-
expect(refused.body.result).toMatchObject({
168-
isError: true,
169-
content: [{ text: expect.stringContaining('Tool execute_read_code not found') }],
170-
})
164+
expect(read.isError, JSON.stringify(read)).toBeFalsy()
165+
expect(read.structuredContent?.result).toBe(true)
166+
expect(read.structuredContent?.calls).toMatchObject([{ operation: 'listTables', status: 200 }])
171167
})
172168

173169
it('writes through real routes and reads them back with paging, returning only the result', async () => {
@@ -195,9 +191,9 @@ describe('Sim MCP code mode in PostgreSQL and the isolate pool', () => {
195191
'execute_read_code',
196192
`
197193
const found = []
198-
let cursor
194+
let cursor = null
199195
do {
200-
const page = await sim.api.listTables({ query: { workspaceId: ${JSON.stringify(workspaceId)}, limit: 1, ...(cursor ? { cursor } : {}) } })
196+
const page = await sim.api.listTables({ query: { workspaceId: ${JSON.stringify(workspaceId)}, limit: 1, cursor } })
201197
found.push(...page.data.map((t) => t.name))
202198
cursor = page.nextCursor
203199
} while (cursor)
@@ -272,6 +268,22 @@ describe('Sim MCP code mode in PostgreSQL and the isolate pool', () => {
272268
})
273269
})
274270

271+
it('refuses an input key outside params, query, body, and headers instead of dropping it', async () => {
272+
const result = await runCode(
273+
'execute_read_code',
274+
`
275+
try {
276+
await sim.api.listTables({ query: { workspaceId: ${JSON.stringify(workspaceId)} }, limit: 1 })
277+
return 'sent without its limit'
278+
} catch (error) {
279+
return { status: error.status, code: error.code }
280+
}
281+
`
282+
)
283+
expect(result.structuredContent?.result).toEqual({ status: 400, code: 'INVALID_CALL' })
284+
expect(result.structuredContent?.calls).toEqual([])
285+
})
286+
275287
it('passes a numeric path parameter, as signatures declare it, through to its route', async () => {
276288
const result = await runCode(
277289
'execute_read_code',

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,10 @@ export const operationRequestInput = z
4141
'Values for the bracketed segments of the operation’s path, by name, e.g. { "tableId": "..." }. IDs come from list operations such as listTables.'
4242
),
4343
query: z
44-
.record(z.string(), z.union([z.string(), z.number(), z.boolean()]))
44+
.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.null()]))
4545
.optional()
4646
.describe(
47-
'Query-string values by name, as the query schema from describe_operation lists them, e.g. { "limit": 50 } or the cursor from the previous page.'
47+
'Query-string values by name, as the query schema from describe_operation lists them, e.g. { "limit": 50 } or the cursor from the previous page. A null value is left out, so the last page’s null cursor ends paging.'
4848
),
4949
headers: z
5050
.record(z.string(), z.string())

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ import { SIM_API_CODE_MAX_TIMEOUT_MS } from '@/sandboxes/sim-api-code'
2525

2626
const logger = createLogger('SimMcpCodeMode')
2727

28-
const DEFAULT_TIMEOUT_MS = 60_000
28+
/** Under the 60-second request timeout MCP clients default to, so a default run answers before its client gives up. */
29+
const DEFAULT_TIMEOUT_MS = 45_000
2930
/** API calls one program may make; each is a full v2 request against the caller's rate limit. */
3031
const MAX_CALLS_PER_RUN = 200
3132
/** Calls one program may have in flight at once, so a `Promise.all` cannot fan out a whole page of requests. */
@@ -40,7 +41,7 @@ export const codeModeInput = z
4041
.min(1)
4142
.max(MAX_CODE_CHARS)
4243
.describe(
43-
'The body of an async function. Call operations with `await sim.api.<operation>(input)`, where input is { params?, query?, body?, headers? } exactly as describe_operation’s signature declares, and `return` a JSON-serializable value: only that value comes back. TypeScript is accepted; types are stripped, not checked. A failed call throws SimApiError with status, code, message, and details.'
44+
'The body of an async function. Call operations with `await sim.api.<operation>(input)`, where input is { params?, query?, body?, headers? } exactly as describe_operation’s signature declares, and `return` a JSON-serializable value: only that value comes back. TypeScript is accepted; types are stripped, not checked. A failed call throws SimApiError with status, code, message, details, and requestId. One call’s input may be at most 256 KB as JSON; send a larger body with call_write_operation.'
4445
),
4546
timeoutMs: z
4647
.number()

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ type V2RouteHandler = (
4040
export interface McpOperationCall {
4141
operation: V2McpOperationName
4242
params?: Record<string, string | number>
43-
query?: Record<string, string | number | boolean>
43+
query?: Record<string, string | number | boolean | null>
4444
body?: unknown
4545
headers?: Record<string, string>
4646
}
@@ -195,7 +195,7 @@ export async function dispatchMcpRequest(
195195

196196
const url = new URL(resolved.path, getBaseUrl())
197197
for (const [name, value] of Object.entries(call.query ?? {})) {
198-
url.searchParams.set(name, String(value))
198+
if (value !== null) url.searchParams.set(name, String(value))
199199
}
200200

201201
const hasBody = contract.method !== 'GET' && contract.body !== undefined

‎apps/sim/lib/api/mcp/route-handler.ts‎

Lines changed: 8 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { type Principal, resolvePrincipalSubjectUserId } from '@sim/auth/principal'
1+
import { type Principal, requirePrincipalSubjectUserId } from '@sim/auth/principal'
22
import { isPlainRecord } from '@sim/utils/object'
33
import type { NextRequest } from 'next/server'
44
import { v2McpOperations } from '@/lib/api/application/operations'
@@ -26,7 +26,6 @@ import {
2626
} from '@/lib/api/server/routes/v2-json-route'
2727
import type { OAuthAccessTokenOptions } from '@/lib/auth/oauth-access-token'
2828
import { type ApplicationOperation, requireOAuthOperationScope } from '@/lib/core/application'
29-
import { isFeatureEnabled } from '@/lib/core/config/feature-flags'
3029
import { isSameOrigin } from '@/lib/core/utils/validation'
3130
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
3231
import { v2CaughtOrchestrationError, v2Error } from '@/app/api/v2/lib/response'
@@ -69,7 +68,7 @@ async function toolCallOperation(
6968
if (name !== TOOL_NAMES.read && name !== TOOL_NAMES.write) return null
7069
if (!isPlainRecord(args) || typeof args.operation !== 'string') return null
7170
const resolved = await resolveOperation(
72-
args.operation,
71+
args.operation.trim(),
7372
name === TOOL_NAMES.read ? 'read' : 'write'
7473
)
7574
if ('error' in resolved) return null
@@ -78,27 +77,12 @@ async function toolCallOperation(
7877
}
7978

8079
/**
81-
* Whether a message's answer depends on the code-mode flag: the instructions
82-
* and tool list mention the code tools, and a call may run one.
80+
* Names the caller for the sandbox pool's per-caller fairness: the person
81+
* calling, or the workspace a workspace key belongs to.
8382
*/
84-
function readsCodeMode(message: Record<string, unknown>): boolean {
85-
if (message.method === 'initialize' || message.method === 'tools/list') return true
86-
if (message.method !== 'tools/call' || !isPlainRecord(message.params)) return false
87-
const { name } = message.params
88-
return name === CODE_TOOL_NAMES.read || name === CODE_TOOL_NAMES.write
89-
}
90-
91-
/**
92-
* The code tools when the flag is on for this caller, keyed for the sandbox
93-
* pool's per-caller fairness by the person or workspace calling.
94-
*/
95-
async function codeModeFor(principal: Principal): Promise<{ ownerKey: string } | null> {
96-
const userId = resolvePrincipalSubjectUserId(principal)
97-
const workspaceId = principal.kind === 'workspace_api_key' ? principal.workspaceId : undefined
98-
if (!(await isFeatureEnabled('mcp-code-mode', { userId, workspaceId }))) return null
99-
if (userId) return { ownerKey: `user:${userId}` }
100-
if (workspaceId) return { ownerKey: `workspace:${workspaceId}` }
101-
return null
83+
function sandboxOwnerKey(principal: Principal): string {
84+
if (principal.kind === 'workspace_api_key') return `workspace:${principal.workspaceId}`
85+
return `user:${requirePrincipalSubjectUserId(principal)}`
10286
}
10387

10488
/** Browsers may only reach the server from Sim's own origins (DNS-rebinding protection). */
@@ -130,11 +114,7 @@ export function createSimMcpHandlers() {
130114
credential: readMcpCredentialHeaders(request.headers),
131115
audience: simMcpAudience(),
132116
},
133-
{
134-
codeMode: readsCodeMode(parsed.data.body)
135-
? await codeModeFor(admission.auth.principal)
136-
: null,
137-
}
117+
sandboxOwnerKey(admission.auth.principal)
138118
)
139119
return await serveStatelessMcp(server, request, parsed.data.body)
140120
} catch (error) {

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

Lines changed: 8 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,7 @@ const INSTRUCTIONS = `Sim is the AI workspace where teams build, deploy, and man
3434
2. Read its input schemas with describe_operation.
3535
3. Run it with the tool search_operations names: call_read_operation for operations that only read, call_write_operation for everything else.
3636
37-
Most operations take a workspaceId; listWorkspaces returns the workspaces you can use. Put path parameters in params, query-string values in query, and the JSON request body in body. Responses use the Sim API envelope ({ "data": ... }); list operations page with limit and cursor. Streaming options are not supported over MCP.`
38-
39-
const CODE_MODE_INSTRUCTIONS = `
37+
Most operations take a workspaceId; listWorkspaces returns the workspaces you can use. Put path parameters in params, query-string values in query, and the JSON request body in body. Responses use the Sim API envelope ({ "data": ... }); list operations page with limit and cursor. Streaming options are not supported over MCP.
4038
4139
For a task that takes more than one or two calls (paging, filtering, joining, or changing many items), write one program instead: describe_operation returns each operation's TypeScript signature, and ${CODE_TOOL_NAMES.read} or ${CODE_TOOL_NAMES.write} runs an async function body that calls await sim.api.<operation>(input) and returns only what you need. Intermediate results stay out of your context. ${CODE_TOOL_NAMES.read} refuses every operation that needs write access.`
4240

@@ -80,26 +78,20 @@ const describeInput = z.object({ operation: operationName }).strict()
8078
/** Shared because a read is not always a GET: searching and querying post their filter as JSON. */
8179
const callInput = operationRequestInput.extend({ operation: operationName }).strict()
8280

83-
interface SimMcpServerOptions {
84-
/**
85-
* Registers the code-mode tools for this caller; `ownerKey` names the caller
86-
* for the sandbox pool's per-caller fairness. `null` leaves them out.
87-
*/
88-
codeMode: { ownerKey: string } | null
89-
}
90-
9181
/**
9282
* The Sim MCP server for one HTTP request. A request owns its server, so no
9383
* credential outlives the request that presented it.
9484
*
95-
* Four tools cover the whole v2 API instead of one tool per operation: a
96-
* catalog of 200-odd tools would overflow most clients' tool limits and spend
85+
* A handful of tools cover the whole v2 API instead of one tool per operation:
86+
* a catalog of 200-odd tools would overflow most clients' tool limits and spend
9787
* the model's context on schemas it never uses. Reads and writes are separate
98-
* tools so a client can approve reads once and still confirm every change.
88+
* tools, for single calls and for programs alike, so a client can approve reads
89+
* once and still confirm every change. `ownerKey` names the caller for the
90+
* sandbox pool's per-caller fairness when it runs a program.
9991
*/
10092
export function createSimMcpServer(
10193
context: Omit<McpDispatchContext, 'signal'>,
102-
options: SimMcpServerOptions
94+
ownerKey: string
10395
): McpServer {
10496
const baseUrl = getBaseUrl()
10597
const server = new McpServer(
@@ -122,7 +114,7 @@ export function createSimMcpServer(
122114
},
123115
],
124116
},
125-
{ instructions: options.codeMode ? INSTRUCTIONS + CODE_MODE_INSTRUCTIONS : INSTRUCTIONS }
117+
{ instructions: INSTRUCTIONS }
126118
)
127119

128120
async function call(
@@ -224,9 +216,6 @@ export function createSimMcpServer(
224216
async (input, extra) => call('write', input, extra.signal)
225217
)
226218

227-
if (!options.codeMode) return server
228-
const { ownerKey } = options.codeMode
229-
230219
async function runCode(
231220
kind: 'read' | 'write',
232221
input: z.infer<typeof codeModeInput>,

‎apps/sim/lib/core/config/env.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -626,7 +626,6 @@ export const env = createEnv({
626626
CHANGELOG: z.boolean().optional(), // Fallback for the `changelog` feature flag off AppConfig
627627
SIM_LINKS: z.boolean().optional(), // Fallback for the `sim-links` feature flag off AppConfig
628628
PEOPLE: z.boolean().optional(), // Fallback for the `people` feature flag off AppConfig
629-
MCP_CODE_MODE: z.boolean().optional(), // Fallback for the `mcp-code-mode` feature flag off AppConfig
630629
ORGANIZATION_ACTIVITY_ROLLUP_READS: z.boolean().optional(), // Fallback for the `organization-activity-rollup-reads` feature flag off AppConfig
631630
ACTIVITY_ROLLUP_MAINTENANCE: z.boolean().optional(), // Fallback for the `activity-rollup-maintenance` feature flag off AppConfig
632631
ACTIVITY_ROLLUP_BACKFILL_ROWS_PER_SECOND: z.coerce.number().int().positive().optional(), // Source rows the activity rollup backfill reads per second (default 20000)

‎apps/sim/lib/core/config/feature-flags.ts‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -76,11 +76,6 @@ const FEATURE_FLAGS = {
7676
'Enable the organization People directory, org chart, profile imports, and directory sync. Supports organization rollout; disabled by default.',
7777
fallback: 'PEOPLE',
7878
},
79-
'mcp-code-mode': {
80-
description:
81-
'Add the code-mode tools (execute_read_code, execute_write_code) to the Sim MCP server. Supports user and workspace rollout; disabled by default.',
82-
fallback: 'MCP_CODE_MODE',
83-
},
8479
'mothership-model-selector': {
8580
description:
8681
'Show the Mothership model selector, model-specific effort levels, and Fast for supported ' +

0 commit comments

Comments
 (0)