Skip to content

Commit 8ea9ffc

Browse files
authored
feat(mcp): add code mode to the Sim MCP server (#10204)
* feat(mcp): add code mode to the Sim MCP server * fix(mcp): stop queued code-mode calls at run end, bound error output, and type union bodies * fix(mcp): render closed empty objects as Record<string, never> * fix(mcp): render tuples and open objects in generated contract types
1 parent 27a73ac commit 8ea9ffc

23 files changed

Lines changed: 1696 additions & 413 deletions

File tree

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

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,52 @@ correct its request.
6868
- **No file bytes.** Downloads, knowledge base exports, and multipart document
6969
uploads are not available over MCP; use the [CLI](/cli/files) or the API.
7070

71+
## Code mode (beta)
72+
73+
For a task that takes many calls, such as paging through a list, filtering, or
74+
updating every item that matches, the agent can write one program instead of
75+
making each call itself. Only the program's return value comes back, so
76+
intermediate results stay out of the model's context. Code mode is in beta and
77+
appears only for accounts where it is enabled.
78+
79+
| Tool | Does |
80+
| --- | --- |
81+
| `execute_read_code` | Runs a program that may call only operations `call_read_operation` could run. Anything that needs write access is refused. |
82+
| `execute_write_code` | Runs a program that may call any operation. Changes apply as each call runs. |
83+
84+
`describe_operation` returns each operation's `signature`, a TypeScript
85+
declaration of its input and response. The program is the body of an async
86+
function. It calls operations through `sim.api` with the same `params`, `query`,
87+
`body`, and `headers` a call tool takes, and returns a JSON value. TypeScript
88+
is accepted; types are stripped, not checked.
89+
90+
```ts
91+
const stale: string[] = []
92+
let cursor: string | undefined
93+
do {
94+
const page = await sim.api.listTables({
95+
query: { workspaceId: 'ws_91ab', limit: 100, ...(cursor ? { cursor } : {}) },
96+
})
97+
for (const table of page.data) {
98+
if (table.rowCount === 0) stale.push(table.name)
99+
}
100+
cursor = page.nextCursor ?? undefined
101+
} while (cursor)
102+
return stale
103+
```
104+
105+
The result holds `result` (the returned value), `calls` (each operation the
106+
program called, with its HTTP status and duration), and `logs` (console output).
107+
A failed API call throws a `SimApiError` with `status`, `code`, `message`, and
108+
`details`, which the program can catch. If the program fails, the error comes
109+
back with the calls it already made, so the agent can tell which changes
110+
happened.
111+
112+
Each call runs through the API exactly as a call tool's would, with the same
113+
credential, permissions, and rate limits. The program has no network access and
114+
never sees your credential. A program runs for at most 60 seconds by default (up
115+
to 120 with `timeoutMs`), makes at most 200 calls, and returns at most 1 MiB.
116+
71117
## Related docs
72118

73119
- [Authentication](/mcp/authentication) for scopes and credential access

‎apps/docs/scripts/fixtures/content-baseline.json‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168306,6 +168306,13 @@
168306168306
"sha256": "c41d2003c0cd831ef035cf57c15fb634765979cb94fb73e5c21118628943e584",
168307168307
"bytes": 122,
168308168308
"line": 40
168309+
},
168310+
{
168311+
"lang": "ts",
168312+
"meta": null,
168313+
"sha256": "fe8327354204841a48740ac7d74646438863ad94c0c7ab11762f25e0b2e2a1d0",
168314+
"bytes": 353,
168315+
"line": 90
168309168316
}
168310168317
],
168311168318
"links": [

‎apps/sim/lib/api/application/operations.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ export const v2McpOperations = {
3636
* The scope a tool call needs when it runs a raw v2 route, which declares no
3737
* operation of its own (chat, workflow execution, resume); each changes
3838
* something. Declared-operation routes are checked against their own scope.
39+
* The write code tool needs it too: its programs may run any operation.
3940
*/
4041
// permission-group-exempt: a scope gate only; the dispatched v2 route enforces its own capability
4142
rawRoute: defineOperation({
Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
import { isRecordLike, toRecord } from '@sim/utils/object'
2+
import { z } from 'zod'
3+
4+
/**
5+
* TypeScript types for the JSON Schema `z.toJSONSchema` produces from the route
6+
* contracts. The Sim CLI generator and the MCP server's `describe_operation`
7+
* both render contract types through this one emitter, so the terminal and an
8+
* agent read the same shape for the same operation.
9+
*
10+
* Imports no `@/` paths: the root CLI generator imports it by relative path.
11+
*/
12+
13+
type JsonSchema = Record<string, unknown>
14+
15+
const ANNOTATION_KEYS: ReadonlySet<string> = new Set([
16+
'$schema',
17+
'description',
18+
'title',
19+
'default',
20+
'examples',
21+
])
22+
23+
function schemaList(value: unknown): JsonSchema[] | undefined {
24+
return Array.isArray(value) ? value.filter(isRecordLike) : undefined
25+
}
26+
27+
/**
28+
* Hand-rolled rather than pulled from `json-schema-to-typescript`: the input is
29+
* a known, narrow subset (no `patternProperties`, no draft-04 quirks), and the
30+
* output is read by humans and models, so controlling the formatting is worth
31+
* more than covering spec corners that never appear. An unhandled construct
32+
* throws rather than degrading to `any`: silence is how a generated client
33+
* drifts from its server.
34+
*
35+
* `refs` maps a `$defs` key to the alias hoisted for it. Zod factors a schema
36+
* out into `$defs` when it is recursive, which the table filter grammar is.
37+
*/
38+
function toTypeScript(schema: JsonSchema, indent: number, refs?: Map<string, string>): string {
39+
if (typeof schema.$ref === 'string') {
40+
const name = refs?.get(schema.$ref.replace('#/$defs/', ''))
41+
if (!name) throw new Error(`Unresolved $ref: ${schema.$ref}`)
42+
return name
43+
}
44+
45+
const pad = ' '.repeat(indent + 1)
46+
const closePad = ' '.repeat(indent)
47+
48+
if (schema.const !== undefined) return JSON.stringify(schema.const)
49+
if (Array.isArray(schema.enum)) return schema.enum.map((v) => JSON.stringify(v)).join(' | ')
50+
51+
const variants = schemaList(schema.anyOf) ?? schemaList(schema.oneOf)
52+
if (variants) return variants.map((v) => toTypeScript(v, indent, refs)).join(' | ')
53+
54+
const parts = schemaList(schema.allOf)
55+
if (parts) {
56+
return parts
57+
.map((part) => {
58+
const type = toTypeScript(part, indent, refs)
59+
return schemaList(part.anyOf) || schemaList(part.oneOf) || Array.isArray(part.enum)
60+
? `(${type})`
61+
: type
62+
})
63+
.join(' & ')
64+
}
65+
66+
switch (schema.type) {
67+
case 'string':
68+
return 'string'
69+
case 'number':
70+
case 'integer':
71+
return 'number'
72+
case 'boolean':
73+
return 'boolean'
74+
case 'null':
75+
return 'null'
76+
case 'array': {
77+
const tuple = schemaList(schema.prefixItems)
78+
const rest = isRecordLike(schema.items) ? toTypeScript(schema.items, indent, refs) : null
79+
if (tuple) {
80+
const elements = tuple.map((item) => toTypeScript(item, indent, refs))
81+
if (rest) elements.push(`...Array<${rest}>`)
82+
return `[${elements.join(', ')}]`
83+
}
84+
return rest ? `Array<${rest}>` : 'unknown[]'
85+
}
86+
case 'object': {
87+
const properties = toRecord(schema.properties)
88+
const required = Array.isArray(schema.required) ? schema.required : []
89+
const keys = Object.keys(properties)
90+
91+
if (keys.length === 0) {
92+
if (schema.additionalProperties === false) return 'Record<string, never>'
93+
const value = isRecordLike(schema.additionalProperties)
94+
? toTypeScript(schema.additionalProperties, indent, refs)
95+
: 'unknown'
96+
return `Record<string, ${value}>`
97+
}
98+
99+
const types: string[] = []
100+
const lines = keys.map((key) => {
101+
const property = properties[key]
102+
const optional = required.includes(key) ? '' : '?'
103+
const safeKey = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : JSON.stringify(key)
104+
const type = isRecordLike(property) ? toTypeScript(property, indent + 1, refs) : 'unknown'
105+
types.push(optional ? `${type} | undefined` : type)
106+
return `${pad}${safeKey}${optional}: ${type}`
107+
})
108+
// Extra keys are allowed; an index signature must also cover the named properties' types.
109+
if (isRecordLike(schema.additionalProperties)) {
110+
const extra = toTypeScript(schema.additionalProperties, indent + 1, refs)
111+
const value = extra === 'unknown' ? extra : [...new Set([extra, ...types])].join(' | ')
112+
lines.push(`${pad}[key: string]: ${value}`)
113+
}
114+
return `{\n${lines.join('\n')}\n${closePad}}`
115+
}
116+
}
117+
118+
// `z.unknown()` renders as a schema with no constraints; `.describe()` adds
119+
// annotation keys without narrowing the type.
120+
if (Object.keys(schema).every((key) => ANNOTATION_KEYS.has(key))) return 'unknown'
121+
122+
throw new Error(`Unhandled JSON Schema construct: ${JSON.stringify(schema).slice(0, 200)}`)
123+
}
124+
125+
/** `listTables` → `ListTables`: how generated type aliases are named after an operation or slot. */
126+
export function pascal(name: string): string {
127+
return name.charAt(0).toUpperCase() + name.slice(1)
128+
}
129+
130+
/** A type plus the aliases that must be declared before it. */
131+
interface GeneratedType {
132+
type: string
133+
declarations: string[]
134+
}
135+
136+
/**
137+
* Renders JSON Schema as a TypeScript type. A recursive schema cannot be
138+
* written inline, so its `$defs` become aliases named `${name}Ref<n>`, after
139+
* the owning type so two operations' aliases cannot collide.
140+
*/
141+
export function jsonSchemaToTypeScript(schema: JsonSchema, name: string): GeneratedType {
142+
const { $defs, ...root } = schema
143+
if (!isRecordLike($defs)) return { type: toTypeScript(root, 0), declarations: [] }
144+
145+
const refs = new Map(Object.keys($defs).map((key, index) => [key, `${name}Ref${index}`]))
146+
const declarations = Object.entries($defs).map(
147+
([key, def]) =>
148+
`type ${refs.get(key)} = ${isRecordLike(def) ? toTypeScript(def, 0, refs) : 'unknown'}\n`
149+
)
150+
return { type: toTypeScript(root, 0, refs), declarations }
151+
}
152+
153+
/**
154+
* A contract schema as JSON Schema, the way it crosses the wire: a date is the
155+
* ISO string JSON carries, rather than the unconstrained schema Zod falls back
156+
* to for a type JSON Schema cannot represent.
157+
*/
158+
export function contractJsonSchema(schema: z.ZodType, io: 'input' | 'output'): JsonSchema {
159+
return z.toJSONSchema(schema, {
160+
io,
161+
unrepresentable: 'any',
162+
override: ({ zodSchema, jsonSchema }) => {
163+
if (zodSchema._zod.def.type === 'date') {
164+
jsonSchema.type = 'string'
165+
jsonSchema.format = 'date-time'
166+
}
167+
},
168+
}) as JsonSchema
169+
}
170+
171+
/** Renders a contract schema as a TypeScript type; see {@link jsonSchemaToTypeScript}. */
172+
export function schemaToTypeScript(
173+
schema: z.ZodType,
174+
io: 'input' | 'output',
175+
name: string
176+
): GeneratedType {
177+
return jsonSchemaToTypeScript(contractJsonSchema(schema, io), name)
178+
}
179+
180+
/**
181+
* Whether a request part must be sent: its object requires a field, or every
182+
* branch of its union does.
183+
*/
184+
export function isJsonSchemaRequired(schema: JsonSchema, defs = toRecord(schema.$defs)): boolean {
185+
if (typeof schema.$ref === 'string') {
186+
const target = defs[schema.$ref.replace('#/$defs/', '')]
187+
return isRecordLike(target) && isJsonSchemaRequired(target, defs)
188+
}
189+
if (Array.isArray(schema.required) && schema.required.length > 0) return true
190+
const variants = schemaList(schema.anyOf) ?? schemaList(schema.oneOf)
191+
if (variants) return variants.every((variant) => isJsonSchemaRequired(variant, defs))
192+
const parts = schemaList(schema.allOf)
193+
return parts ? parts.some((part) => isJsonSchemaRequired(part, defs)) : false
194+
}

0 commit comments

Comments
 (0)