Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions apps/docs/content/docs/mcp/tools.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,52 @@ correct its request.
- **No file bytes.** Downloads, knowledge base exports, and multipart document
uploads are not available over MCP; use the [CLI](/cli/files) or the API.

## Code mode (beta)

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

| Tool | Does |
| --- | --- |
| `execute_read_code` | Runs a program that may call only operations `call_read_operation` could run. Anything that needs write access is refused. |
| `execute_write_code` | Runs a program that may call any operation. Changes apply as each call runs. |

`describe_operation` returns each operation's `signature`, a TypeScript
declaration of its input and response. The program is the body of an async
function. It calls operations through `sim.api` with the same `params`, `query`,
`body`, and `headers` a call tool takes, and returns a JSON value. TypeScript
is accepted; types are stripped, not checked.

```ts
const stale: string[] = []
let cursor: string | undefined
do {
const page = await sim.api.listTables({
query: { workspaceId: 'ws_91ab', limit: 100, ...(cursor ? { cursor } : {}) },
})
for (const table of page.data) {
if (table.rowCount === 0) stale.push(table.name)
}
cursor = page.nextCursor ?? undefined
} while (cursor)
return stale
```

The result holds `result` (the returned value), `calls` (each operation the
program called, with its HTTP status and duration), and `logs` (console output).
A failed API call throws a `SimApiError` with `status`, `code`, `message`, and
`details`, which the program can catch. If the program fails, the error comes
back with the calls it already made, so the agent can tell which changes
happened.

Each call runs through the API exactly as a call tool's would, with the same
credential, permissions, and rate limits. The program has no network access and
never sees your credential. A program runs for at most 60 seconds by default (up
to 120 with `timeoutMs`), makes at most 200 calls, and returns at most 1 MiB.

## Related docs

- [Authentication](/mcp/authentication) for scopes and credential access
Expand Down
7 changes: 7 additions & 0 deletions apps/docs/scripts/fixtures/content-baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -168306,6 +168306,13 @@
"sha256": "c41d2003c0cd831ef035cf57c15fb634765979cb94fb73e5c21118628943e584",
"bytes": 122,
"line": 40
},
{
"lang": "ts",
"meta": null,
"sha256": "fe8327354204841a48740ac7d74646438863ad94c0c7ab11762f25e0b2e2a1d0",
"bytes": 353,
"line": 90
}
],
"links": [
Expand Down
1 change: 1 addition & 0 deletions apps/sim/lib/api/application/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export const v2McpOperations = {
* The scope a tool call needs when it runs a raw v2 route, which declares no
* operation of its own (chat, workflow execution, resume); each changes
* something. Declared-operation routes are checked against their own scope.
* The write code tool needs it too: its programs may run any operation.
*/
// permission-group-exempt: a scope gate only; the dispatched v2 route enforces its own capability
rawRoute: defineOperation({
Expand Down
194 changes: 194 additions & 0 deletions apps/sim/lib/api/contracts/typescript.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
import { isRecordLike, toRecord } from '@sim/utils/object'
import { z } from 'zod'

/**
* TypeScript types for the JSON Schema `z.toJSONSchema` produces from the route
* contracts. The Sim CLI generator and the MCP server's `describe_operation`
* both render contract types through this one emitter, so the terminal and an
* agent read the same shape for the same operation.
*
* Imports no `@/` paths: the root CLI generator imports it by relative path.
*/

type JsonSchema = Record<string, unknown>

const ANNOTATION_KEYS: ReadonlySet<string> = new Set([
'$schema',
'description',
'title',
'default',
'examples',
])

function schemaList(value: unknown): JsonSchema[] | undefined {
return Array.isArray(value) ? value.filter(isRecordLike) : undefined
}

/**
* Hand-rolled rather than pulled from `json-schema-to-typescript`: the input is
* a known, narrow subset (no `patternProperties`, no draft-04 quirks), and the
* output is read by humans and models, so controlling the formatting is worth
* more than covering spec corners that never appear. An unhandled construct
* throws rather than degrading to `any`: silence is how a generated client
* drifts from its server.
*
* `refs` maps a `$defs` key to the alias hoisted for it. Zod factors a schema
* out into `$defs` when it is recursive, which the table filter grammar is.
*/
function toTypeScript(schema: JsonSchema, indent: number, refs?: Map<string, string>): string {
if (typeof schema.$ref === 'string') {
const name = refs?.get(schema.$ref.replace('#/$defs/', ''))
if (!name) throw new Error(`Unresolved $ref: ${schema.$ref}`)
return name
}

const pad = ' '.repeat(indent + 1)
const closePad = ' '.repeat(indent)

if (schema.const !== undefined) return JSON.stringify(schema.const)
if (Array.isArray(schema.enum)) return schema.enum.map((v) => JSON.stringify(v)).join(' | ')

const variants = schemaList(schema.anyOf) ?? schemaList(schema.oneOf)
if (variants) return variants.map((v) => toTypeScript(v, indent, refs)).join(' | ')

const parts = schemaList(schema.allOf)
if (parts) {
return parts
.map((part) => {
const type = toTypeScript(part, indent, refs)
return schemaList(part.anyOf) || schemaList(part.oneOf) || Array.isArray(part.enum)
? `(${type})`
: type
})
.join(' & ')
}

switch (schema.type) {
case 'string':
return 'string'
case 'number':
case 'integer':
return 'number'
case 'boolean':
return 'boolean'
case 'null':
return 'null'
case 'array': {
const tuple = schemaList(schema.prefixItems)
const rest = isRecordLike(schema.items) ? toTypeScript(schema.items, indent, refs) : null
if (tuple) {
const elements = tuple.map((item) => toTypeScript(item, indent, refs))
if (rest) elements.push(`...Array<${rest}>`)
return `[${elements.join(', ')}]`
}
return rest ? `Array<${rest}>` : 'unknown[]'
}
case 'object': {
const properties = toRecord(schema.properties)
const required = Array.isArray(schema.required) ? schema.required : []
const keys = Object.keys(properties)

if (keys.length === 0) {
if (schema.additionalProperties === false) return 'Record<string, never>'
const value = isRecordLike(schema.additionalProperties)
? toTypeScript(schema.additionalProperties, indent, refs)
: 'unknown'
return `Record<string, ${value}>`
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
}

const types: string[] = []
const lines = keys.map((key) => {
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
const property = properties[key]
const optional = required.includes(key) ? '' : '?'
const safeKey = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : JSON.stringify(key)
const type = isRecordLike(property) ? toTypeScript(property, indent + 1, refs) : 'unknown'
types.push(optional ? `${type} | undefined` : type)
return `${pad}${safeKey}${optional}: ${type}`
})
// Extra keys are allowed; an index signature must also cover the named properties' types.
if (isRecordLike(schema.additionalProperties)) {
const extra = toTypeScript(schema.additionalProperties, indent + 1, refs)
const value = extra === 'unknown' ? extra : [...new Set([extra, ...types])].join(' | ')
lines.push(`${pad}[key: string]: ${value}`)
}
return `{\n${lines.join('\n')}\n${closePad}}`
}
}

// `z.unknown()` renders as a schema with no constraints; `.describe()` adds
// annotation keys without narrowing the type.
if (Object.keys(schema).every((key) => ANNOTATION_KEYS.has(key))) return 'unknown'

throw new Error(`Unhandled JSON Schema construct: ${JSON.stringify(schema).slice(0, 200)}`)
}

/** `listTables` → `ListTables`: how generated type aliases are named after an operation or slot. */
export function pascal(name: string): string {
return name.charAt(0).toUpperCase() + name.slice(1)
}

/** A type plus the aliases that must be declared before it. */
interface GeneratedType {
type: string
declarations: string[]
}

/**
* Renders JSON Schema as a TypeScript type. A recursive schema cannot be
* written inline, so its `$defs` become aliases named `${name}Ref<n>`, after
* the owning type so two operations' aliases cannot collide.
*/
export function jsonSchemaToTypeScript(schema: JsonSchema, name: string): GeneratedType {
const { $defs, ...root } = schema
if (!isRecordLike($defs)) return { type: toTypeScript(root, 0), declarations: [] }

const refs = new Map(Object.keys($defs).map((key, index) => [key, `${name}Ref${index}`]))
const declarations = Object.entries($defs).map(
([key, def]) =>
`type ${refs.get(key)} = ${isRecordLike(def) ? toTypeScript(def, 0, refs) : 'unknown'}\n`
)
return { type: toTypeScript(root, 0, refs), declarations }
}

/**
* A contract schema as JSON Schema, the way it crosses the wire: a date is the
* ISO string JSON carries, rather than the unconstrained schema Zod falls back
* to for a type JSON Schema cannot represent.
*/
export function contractJsonSchema(schema: z.ZodType, io: 'input' | 'output'): JsonSchema {
return z.toJSONSchema(schema, {
io,
unrepresentable: 'any',
override: ({ zodSchema, jsonSchema }) => {
if (zodSchema._zod.def.type === 'date') {
jsonSchema.type = 'string'
jsonSchema.format = 'date-time'
}
},
}) as JsonSchema
}

/** Renders a contract schema as a TypeScript type; see {@link jsonSchemaToTypeScript}. */
export function schemaToTypeScript(
schema: z.ZodType,
io: 'input' | 'output',
name: string
): GeneratedType {
return jsonSchemaToTypeScript(contractJsonSchema(schema, io), name)
}

/**
* Whether a request part must be sent: its object requires a field, or every
* branch of its union does.
*/
export function isJsonSchemaRequired(schema: JsonSchema, defs = toRecord(schema.$defs)): boolean {
if (typeof schema.$ref === 'string') {
const target = defs[schema.$ref.replace('#/$defs/', '')]
return isRecordLike(target) && isJsonSchemaRequired(target, defs)
}
if (Array.isArray(schema.required) && schema.required.length > 0) return true
const variants = schemaList(schema.anyOf) ?? schemaList(schema.oneOf)
if (variants) return variants.every((variant) => isJsonSchemaRequired(variant, defs))
const parts = schemaList(schema.allOf)
return parts ? parts.some((part) => isJsonSchemaRequired(part, defs)) : false
}
Loading
Loading