diff --git a/apps/docs/content/docs/mcp/tools.mdx b/apps/docs/content/docs/mcp/tools.mdx index 600892d00e3..4bbdaa621a2 100644 --- a/apps/docs/content/docs/mcp/tools.mdx +++ b/apps/docs/content/docs/mcp/tools.mdx @@ -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 diff --git a/apps/docs/scripts/fixtures/content-baseline.json b/apps/docs/scripts/fixtures/content-baseline.json index b89569db304..addf8adb077 100644 --- a/apps/docs/scripts/fixtures/content-baseline.json +++ b/apps/docs/scripts/fixtures/content-baseline.json @@ -168306,6 +168306,13 @@ "sha256": "c41d2003c0cd831ef035cf57c15fb634765979cb94fb73e5c21118628943e584", "bytes": 122, "line": 40 + }, + { + "lang": "ts", + "meta": null, + "sha256": "fe8327354204841a48740ac7d74646438863ad94c0c7ab11762f25e0b2e2a1d0", + "bytes": 353, + "line": 90 } ], "links": [ diff --git a/apps/sim/lib/api/application/operations.ts b/apps/sim/lib/api/application/operations.ts index 8c5c1245476..13a18cd2894 100644 --- a/apps/sim/lib/api/application/operations.ts +++ b/apps/sim/lib/api/application/operations.ts @@ -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({ diff --git a/apps/sim/lib/api/contracts/typescript.ts b/apps/sim/lib/api/contracts/typescript.ts new file mode 100644 index 00000000000..1c07fda0bd8 --- /dev/null +++ b/apps/sim/lib/api/contracts/typescript.ts @@ -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 + +const ANNOTATION_KEYS: ReadonlySet = 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 { + 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' + const value = isRecordLike(schema.additionalProperties) + ? toTypeScript(schema.additionalProperties, indent, refs) + : 'unknown' + return `Record` + } + + const types: string[] = [] + const lines = keys.map((key) => { + 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`, 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 +} diff --git a/apps/sim/lib/api/mcp/__integration__/code-mode.integration.ts b/apps/sim/lib/api/mcp/__integration__/code-mode.integration.ts new file mode 100644 index 00000000000..b20b523f9b9 --- /dev/null +++ b/apps/sim/lib/api/mcp/__integration__/code-mode.integration.ts @@ -0,0 +1,388 @@ +/** + * Sim MCP code mode against real PostgreSQL and the real isolated-vm pool, + * through the `/api/mcp` route a client reaches: API-key authentication, the + * scope gate, the sandbox, and every `sim.api` call dispatched to its own v2 + * route. Each case is a way a program could exceed what its caller may do one + * call at a time, or lose the trail of what it already changed. + */ +import { db } from '@sim/db' +import { apiKey, permissions, user, userTableDefinitions, workspace } from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { authMock } from '@sim/testing/mocks/auth.mock' +import { featureFlagsMock, featureFlagsMockFns } from '@sim/testing/mocks/feature-flags.mock' +import { sleep } from '@sim/utils/helpers' +import { generateId } from '@sim/utils/id' +import { toRecord } from '@sim/utils/object' +import { eq } from 'drizzle-orm' +import { NextRequest } from 'next/server' +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@/lib/auth', () => authMock) +vi.mock('@/lib/core/config/feature-flags', () => featureFlagsMock) + +import { hashApiKey } from '@/lib/api-key/crypto' +import { POST as simMcpPost } from '@/app/api/mcp/route' + +const ORIGIN = 'http://localhost:3000' +const userId = generateId() +const workspaceId = generateId() +const writeKey = `sk-sim-fixture-${generateId()}` +const readKey = `sk-sim-fixture-${generateId()}` + +interface ToolResult { + isError?: boolean + content: Array<{ type: string; text: string }> + structuredContent?: { result: unknown; calls: Array>; logs?: string } +} + +async function mcp(key: string, message: Record) { + const request = new NextRequest(`${ORIGIN}/api/mcp`, { + method: 'POST', + headers: { + accept: 'application/json, text/event-stream', + 'content-type': 'application/json', + 'x-forwarded-for': '127.0.0.1', + 'x-api-key': key, + }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, ...message }), + }) + const response = await simMcpPost(request, { params: Promise.resolve({}) } as never) + return { status: response.status, body: (await response.json()) as Record } +} + +async function runCode( + tool: 'execute_read_code' | 'execute_write_code', + code: string, + options: { key?: string; timeoutMs?: number } = {} +): Promise { + const { status, body } = await mcp(options.key ?? writeKey, { + method: 'tools/call', + params: { + name: tool, + arguments: { code, ...(options.timeoutMs ? { timeoutMs: options.timeoutMs } : {}) }, + }, + }) + expect(status, JSON.stringify(body)).toBe(200) + return body.result as ToolResult +} + +/** A failed run's tool error, parsed: the error, and every call made before it. */ +function failureOf(result: ToolResult) { + expect(result.isError, JSON.stringify(result)).toBe(true) + return JSON.parse(result.content[0].text) as { + error: Record + calls: Array> + logs?: string + } +} + +async function tableNames(): Promise { + const rows = await db + .select({ name: userTableDefinitions.name }) + .from(userTableDefinitions) + .where(eq(userTableDefinitions.workspaceId, workspaceId)) + return rows.map((row) => row.name).sort() +} + +const TABLE_SCHEMA = { columns: [{ name: 'title', type: 'string' }] } + +describe('Sim MCP code mode in PostgreSQL and the isolate pool', () => { + beforeAll(async () => { + const now = new Date() + await db.insert(user).values({ + id: userId, + name: 'Code mode fixture', + email: `${userId}@code-mode.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await insertWorkspaceFixture(db, { + id: workspaceId, + name: 'Code mode fixture', + ownerId: userId, + billedAccountUserId: userId, + allowPersonalApiKeys: true, + }) + await db.insert(permissions).values({ + id: generateId(), + userId, + entityType: 'workspace', + entityId: workspaceId, + permissionType: 'admin', + }) + await db.insert(apiKey).values([ + { + id: generateId(), + userId, + name: 'Write', + key: writeKey, + keyHash: hashApiKey(writeKey), + type: 'personal', + access: 'write', + }, + { + id: generateId(), + userId, + name: 'Read', + key: readKey, + keyHash: hashApiKey(readKey), + type: 'personal', + access: 'read', + }, + ]) + }) + + beforeEach(() => { + featureFlagsMockFns.mockIsFeatureEnabled.mockImplementation( + async (flag: string, target?: unknown) => + flag === 'mcp-code-mode' && toRecord(target).userId === userId + ) + }) + + afterAll(async () => { + await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId)) + await db.delete(user).where(eq(user.id, userId)) + await db.$client.end() + }) + + it('lists the code tools only when the flag is on for the caller', async () => { + const listed = await mcp(writeKey, { method: 'tools/list' }) + const names = (listed.body.result as { tools: Array<{ name: string }> }).tools.map( + (t) => t.name + ) + expect(names).toEqual(expect.arrayContaining(['execute_read_code', 'execute_write_code'])) + + featureFlagsMockFns.mockIsFeatureEnabled.mockResolvedValue(false) + const hidden = await mcp(writeKey, { method: 'tools/list' }) + const hiddenNames = (hidden.body.result as { tools: Array<{ name: string }> }).tools.map( + (t) => t.name + ) + expect(hiddenNames).not.toContain('execute_read_code') + expect(hiddenNames).not.toContain('execute_write_code') + const refused = await mcp(writeKey, { + method: 'tools/call', + params: { name: 'execute_read_code', arguments: { code: 'return 1' } }, + }) + expect(refused.body.result).toMatchObject({ + isError: true, + content: [{ text: expect.stringContaining('Tool execute_read_code not found') }], + }) + }) + + it('writes through real routes and reads them back with paging, returning only the result', async () => { + const names = [`cm_a_${generateId().slice(0, 8)}`, `cm_b_${generateId().slice(0, 8)}`] + const written = await runCode( + 'execute_write_code', + ` + const created: string[] = [] + for (const name of ${JSON.stringify(names)}) { + const { data } = await sim.api.createTable({ body: { workspaceId: ${JSON.stringify(workspaceId)}, name, schema: ${JSON.stringify(TABLE_SCHEMA)} } }) + created.push(data.name) + } + return created + ` + ) + expect(written.isError, JSON.stringify(written)).toBeFalsy() + expect(written.structuredContent?.result).toEqual(names) + expect(written.structuredContent?.calls.map((c) => [c.operation, c.status])).toEqual([ + ['createTable', 201], + ['createTable', 201], + ]) + expect(await tableNames()).toEqual(expect.arrayContaining(names)) + + const read = await runCode( + 'execute_read_code', + ` + const found = [] + let cursor + do { + const page = await sim.api.listTables({ query: { workspaceId: ${JSON.stringify(workspaceId)}, limit: 1, ...(cursor ? { cursor } : {}) } }) + found.push(...page.data.map((t) => t.name)) + cursor = page.nextCursor + } while (cursor) + console.log('pages', found.length) + return found.sort() + ` + ) + expect(read.isError, JSON.stringify(read)).toBeFalsy() + expect(read.structuredContent?.result).toEqual(await tableNames()) + expect( + read.structuredContent?.calls.every((c) => c.operation === 'listTables' && c.status === 200) + ).toBe(true) + expect(read.structuredContent?.logs).toBe(`pages ${(await tableNames()).length}`) + }) + + it('refuses every write in a read program on the host, without changing a row', async () => { + const before = await tableNames() + const result = await runCode( + 'execute_read_code', + ` + try { + await sim.api.createTable({ body: { workspaceId: ${JSON.stringify(workspaceId)}, name: 'cm_refused', schema: ${JSON.stringify(TABLE_SCHEMA)} } }) + return 'created' + } catch (error) { + return { name: error.name, status: error.status, code: error.code } + } + ` + ) + expect(result.structuredContent?.result).toEqual({ + name: 'SimApiError', + status: 403, + code: 'WRITE_NOT_ALLOWED', + }) + expect(result.structuredContent?.calls).toEqual([ + expect.objectContaining({ operation: 'createTable', refused: expect.any(String) }), + ]) + expect(await tableNames()).toEqual(before) + }) + + it('refuses the write code tool to a read-only key before any program runs', async () => { + const before = await tableNames() + const { status, body } = await mcp(readKey, { + method: 'tools/call', + params: { + name: 'execute_write_code', + arguments: { + code: `await sim.api.createTable({ body: { workspaceId: ${JSON.stringify(workspaceId)}, name: 'cm_read_key', schema: ${JSON.stringify(TABLE_SCHEMA)} } })`, + }, + }, + }) + expect(status).toBe(403) + expect(body).toMatchObject({ error: { details: { code: 'READ_ONLY_API_KEY' } } }) + expect(await tableNames()).toEqual(before) + }) + + it('hands API errors to the program as catchable SimApiErrors with the v2 envelope', async () => { + const result = await runCode( + 'execute_read_code', + ` + try { + await sim.api.getTable({ params: { tableId: ${JSON.stringify(generateId())} }, query: { workspaceId: ${JSON.stringify(workspaceId)} } }) + } catch (error) { + return { name: error.name, status: error.status, code: error.code, isError: error instanceof SimApiError } + } + ` + ) + expect(result.structuredContent?.result).toMatchObject({ + name: 'SimApiError', + status: 404, + code: 'NOT_FOUND', + isError: true, + }) + }) + + it('gives the program no network and no credential', async () => { + const result = await runCode( + 'execute_read_code', + ` + const values = [] + const seen = new Set() + const visit = (value, depth) => { + if (value === null || value === undefined || depth > 5) return + if (typeof value === 'string') { values.push(value.slice(0, 2000)); return } + if (typeof value !== 'object' && typeof value !== 'function') return + if (seen.has(value)) return + seen.add(value) + if (typeof value === 'function') { try { values.push(String(value).slice(0, 2000)) } catch {} } + for (const key of Object.getOwnPropertyNames(value)) { + try { visit(value[key], depth + 1) } catch {} + } + } + visit(globalThis, 0) + return { fetch: typeof fetch, xhr: typeof XMLHttpRequest, process: typeof process, require: typeof require, globals: values.join('\\n').slice(0, 900000) } + ` + ) + const value = result.structuredContent?.result as Record + expect(value).toMatchObject({ + fetch: 'undefined', + xhr: 'undefined', + process: 'undefined', + require: 'undefined', + }) + expect(value.globals).not.toContain(writeKey) + expect(value.globals).not.toContain(hashApiKey(writeKey)) + }) + + it('sends no queued call once the program has ended, and marks every call’s outcome', async () => { + const prefix = `cm_q_${generateId().slice(0, 8)}` + const failed = failureOf( + await runCode( + 'execute_write_code', + ` + for (let i = 0; i < 40; i++) { + sim.api.createTable({ body: { workspaceId: ${JSON.stringify(workspaceId)}, name: '${prefix}_' + i, schema: ${JSON.stringify(TABLE_SCHEMA)} } }).catch(() => {}) + } + throw new Error('stopped while writes were queued') + ` + ) + ) + expect(failed.error.message).toBe('stopped while writes were queued') + await sleep(3000) + const created = (await tableNames()).filter((name) => name.startsWith(prefix)) + expect(created.length).toBeLessThan(40) + for (const call of failed.calls) { + expect( + call.status !== undefined || call.refused !== undefined || call.unreadable !== undefined + ).toBe(true) + } + }) + + it('reports an uncaught error with the calls that already ran', async () => { + const failed = failureOf( + await runCode( + 'execute_read_code', + ` + await sim.api.listWorkspaces() + throw new Error('stopped after listing') + ` + ) + ) + expect(failed.error).toMatchObject({ name: 'Error', message: 'stopped after listing' }) + expect(failed.calls).toEqual([ + expect.objectContaining({ operation: 'listWorkspaces', status: 200 }), + ]) + }) + + it('accepts TypeScript and reports syntax errors on the caller’s line', async () => { + const typed = await runCode( + 'execute_read_code', + ` + interface Row { id: string } + const rows: Row[] = [{ id: 'a' }] + return rows.map((row): string => row.id) + ` + ) + expect(typed.structuredContent?.result).toEqual(['a']) + + const broken = await runCode('execute_read_code', 'const a = 1\nconst = 2') + expect(broken.isError).toBe(true) + expect(broken.content[0].text).toMatch(/^The program does not parse\.\nLine 2: /) + }) + + it('stops a program at its timeout, at its call cap, and when its result is too large', async () => { + const timedOut = failureOf( + await runCode('execute_read_code', 'while (true) {}', { timeoutMs: 1000 }) + ) + expect(timedOut.error.name).toBe('TimeoutError') + + const capped = failureOf( + await runCode( + 'execute_read_code', + ` + for (let i = 0; i < 201; i++) { + try { await sim.api.notAnOperation() } catch (error) { if (error.name !== 'SimApiError') throw error } + } + ` + ) + ) + expect(capped.error.message).toContain('at most 200') + expect(capped.calls).toHaveLength(200) + + const large = failureOf( + await runCode('execute_read_code', "return 'x'.repeat(2 * 1024 * 1024)") + ) + expect(large.error.name).toBe('RangeError') + expect(String(large.error.message)).toContain('at most 1048576') + }) +}) diff --git a/apps/sim/lib/api/mcp/catalog.ts b/apps/sim/lib/api/mcp/catalog.ts index c89c18c1d1b..3b2957725b2 100644 --- a/apps/sim/lib/api/mcp/catalog.ts +++ b/apps/sim/lib/api/mcp/catalog.ts @@ -1,6 +1,13 @@ import { omit, toRecord } from '@sim/utils/object' import { z } from 'zod' import type { ApiSchema } from '@/lib/api/contracts/types' +import { + contractJsonSchema, + isJsonSchemaRequired, + jsonSchemaToTypeScript, + pascal, + schemaToTypeScript, +} from '@/lib/api/contracts/typescript' import { V2_MCP_OPERATIONS, type V2McpOperationName } from '@/lib/api/mcp/generated/v2-operations' import type { V2McpOperation } from '@/lib/api/mcp/types' import { v2RouteOperation } from '@/lib/api/server/routes/v2-json-route' @@ -19,8 +26,42 @@ const MANAGED_HEADERS: ReadonlySet = new Set([ export const TOOL_NAMES = { read: 'call_read_operation', write: 'call_write_operation' } as const type ToolKind = keyof typeof TOOL_NAMES +/** The code-mode tools, split the same way: the read tool's programs may run only read operations. */ +export const CODE_TOOL_NAMES = { read: 'execute_read_code', write: 'execute_write_code' } as const + const REQUEST_SLOTS = ['params', 'query', 'body', 'headers'] as const +/** The request parts of one operation call, as the call tools and `sim.api` both take them. */ +export const operationRequestInput = z + .object({ + params: z + .record(z.string(), z.string()) + .optional() + .describe( + 'Values for the bracketed segments of the operation’s path, by name, e.g. { "tableId": "..." }. IDs come from list operations such as listTables.' + ), + query: z + .record(z.string(), z.union([z.string(), z.number(), z.boolean()])) + .optional() + .describe( + '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.' + ), + headers: z + .record(z.string(), z.string()) + .optional() + .describe( + 'Headers the operation’s describe_operation schema lists, such as upload-token. Sim sets authentication and content headers itself.' + ), + body: z + .record(z.string(), z.unknown()) + .meta({ additionalProperties: true }) + .optional() + .describe( + 'JSON request body matching the body schema from describe_operation. Omit it when the operation takes no body.' + ), + }) + .strict() + const operationSummarySchema = z.object({ operation: z .string() @@ -54,6 +95,12 @@ export const searchOperationsOutput = z.object({ /** What describe_operation returns: everything needed to call one operation. */ export const describeOperationOutput = operationSummarySchema.extend({ description: z.string().optional().describe('Longer documentation, when the operation has it.'), + signature: z + .string() + .optional() + .describe( + `TypeScript declaration of the operation as a code-mode program calls it: sim.api.(input) with this input and response. Absent when the operation does not answer with JSON, so code cannot call it.` + ), input: z .object({ params: jsonSchema.optional(), @@ -194,7 +241,7 @@ export async function searchOperations(options: { } function toJsonSchema(schema: ApiSchema): JsonSchema { - const { $schema: _, ...json } = z.toJSONSchema(schema, { io: 'input', unrepresentable: 'any' }) + const { $schema: _, ...json } = contractJsonSchema(schema, 'input') return json } @@ -244,17 +291,65 @@ export function callerHeaderNames(name: V2McpOperationName): string[] { return Object.keys(toRecord(describeInput(name).headers?.properties)) } +/** Memo over a fixed catalog: at most one entry per operation, never evicted. */ +const signatures = new Map() + +/** + * The TypeScript declaration a code-mode program codes against, rendered from + * the same contract the route validates with, or `null` when the operation + * answers with something other than JSON. + */ +function renderSignature(name: V2McpOperationName): string | null { + const { contract, summary } = getMcpOperation(name) + if (contract.response.mode !== 'json' || !contract.response.schema) return null + const Name = pascal(name) + const declarations: string[] = [] + const fields: string[] = [] + let anyRequired = false + for (const [slot, schema] of Object.entries(describeInput(name))) { + if (!schema) continue + const generated = jsonSchemaToTypeScript(schema, `${Name}${pascal(slot)}`) + declarations.push(...generated.declarations) + const required = isJsonSchemaRequired(schema) + anyRequired ||= required + fields.push(` ${slot}${required ? '' : '?'}: ${generated.type.replace(/\n/g, '\n ')}`) + } + const response = schemaToTypeScript(contract.response.schema, 'output', `${Name}Response`) + declarations.push(...response.declarations) + const input = fields.length > 0 ? `{\n${fields.join('\n')}\n}` : 'Record' + return [ + ...declarations, + `/** ${summary ?? `${contract.method} ${contract.path}`} */`, + `function ${name}(input${anyRequired ? '' : '?'}: ${input}): Promise<${response.type}>`, + ].join('\n') +} + +function operationSignature(name: V2McpOperationName): string | null { + const cached = signatures.get(name) + if (cached !== undefined) return cached + const signature = renderSignature(name) + signatures.set(name, signature) + return signature +} + export async function describeOperation( name: V2McpOperationName ): Promise { const { description } = getMcpOperation(name) + const signature = operationSignature(name) return { ...(await withTool(summarize(name))), ...(description ? { description } : {}), input: describeInput(name), + ...(signature ? { signature } : {}), } } +/** Whether an operation needs nothing beyond read access, the same split the read and write tools apply. */ +export async function isReadOperation(name: V2McpOperationName): Promise { + return (await operationToolKind(name)) === 'read' +} + /** Catalog names close to an unknown one, found by searching its camelCase words. */ function suggestOperations(name: string): string[] { const words = name diff --git a/apps/sim/lib/api/mcp/code-mode.ts b/apps/sim/lib/api/mcp/code-mode.ts new file mode 100644 index 00000000000..d06eb12206c --- /dev/null +++ b/apps/sim/lib/api/mcp/code-mode.ts @@ -0,0 +1,301 @@ +import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js' +import { createLogger } from '@sim/logger' +import { sha256Hex } from '@sim/security/hash' +import { getErrorMessage } from '@sim/utils/errors' +import { generateShortId } from '@sim/utils/id' +import { z } from 'zod' +import { v2ErrorResponseSchema } from '@/lib/api/contracts/v2/shared' +import { + CODE_TOOL_NAMES, + getMcpOperation, + isReadOperation, + operationRequestInput, + resolveOperation, +} from '@/lib/api/mcp/catalog' +import { dispatchMcpRequest, type McpDispatchContext } from '@/lib/api/mcp/dispatch' +import { createConcurrencyLimit } from '@/lib/core/utils/concurrency' +import { runSandboxTask, SandboxUserCodeError } from '@/lib/execution/sandbox/run-task' +import { loadTypeScript } from '@/lib/execution/typescript' +import { structuredToolResult, toolError } from '@/lib/mcp/tool-result' +import { SIM_API_CODE_MAX_TIMEOUT_MS } from '@/sandboxes/sim-api-code' + +const logger = createLogger('SimMcpCodeMode') + +const DEFAULT_TIMEOUT_MS = 60_000 +/** API calls one program may make; each is a full v2 request against the caller's rate limit. */ +const MAX_CALLS_PER_RUN = 200 +/** Calls one program may have in flight at once, so a `Promise.all` cannot fan out a whole page of requests. */ +const MAX_CONCURRENT_CALLS = 8 +const MAX_CODE_CHARS = 100_000 + +export const codeModeInput = z + .object({ + code: z + .string() + .min(1) + .max(MAX_CODE_CHARS) + .describe( + 'The body of an async function. Call operations with `await sim.api.(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.' + ), + timeoutMs: z + .number() + .int() + .min(1000) + .max(SIM_API_CODE_MAX_TIMEOUT_MS) + .optional() + .describe( + `How long the program may run in milliseconds. Defaults to ${DEFAULT_TIMEOUT_MS}; at most ${SIM_API_CODE_MAX_TIMEOUT_MS}.` + ), + }) + .strict() + +const callRecord = z.object({ + operation: z.string(), + status: z.number().optional().describe('HTTP status the operation answered with.'), + durationMs: z.number(), + refused: z + .string() + .optional() + .describe('Why the call never reached the operation, such as a write in a read program.'), + unreadable: z + .string() + .optional() + .describe( + 'The operation ran, or may still be running, but its answer could not be returned: too large, not JSON, or not back before the program ended.' + ), +}) + +export const codeModeOutput = z.object({ + result: z.unknown().describe('The value the program returned.'), + calls: z.array(callRecord).describe('Every API call the program made, in order.'), + logs: z.string().optional().describe('Console output, truncated past 64 KB.'), +}) + +type CallRecord = z.infer +type CodeKind = keyof typeof CODE_TOOL_NAMES + +/** + * What `finalize` reports: the program's value or its error, with captured + * console output. The isolate already refused a result over the size cap. + */ +const outcomeSchema = z.discriminatedUnion('ok', [ + z.object({ ok: z.literal(true), result: z.unknown(), logs: z.string() }), + z.object({ ok: z.literal(false), error: z.record(z.string(), z.unknown()), logs: z.string() }), +]) + +const simApiCall = z.object({ operation: z.string(), input: operationRequestInput }).strict() + +/** + * A call's answer as the isolate reads it: the response body as JSON text, + * parsed in the isolate rather than on the request's event loop, or the + * failure its `SimApiError` carries. + */ +type SimApiAnswer = + | { dataJson: string } + | { + error: { + status: number + code: string + message: string + details?: unknown + requestId?: string + } + } + +function apiFailure(status: number, code: string, message: string): SimApiAnswer { + return { error: { status, code, message } } +} + +/** The v2 error envelope as the program's `SimApiError`, or the raw text when it is not one. */ +function envelopeFailure(status: number, text: string): SimApiAnswer { + try { + const parsed = v2ErrorResponseSchema.safeParse(JSON.parse(text)) + if (parsed.success) return { error: { status, ...parsed.data.error } } + } catch {} + return apiFailure(status, 'ERROR', text) +} + +/** + * Strips TypeScript from the program body and wraps it so its settlement, + * value or error, is recorded for `finalize` rather than lost to the worker. + * Syntax errors come back with lines numbered as the caller wrote them. + */ +async function compileProgram(code: string): Promise<{ script: string } | { error: string }> { + const ts = await loadTypeScript() + const { outputText, diagnostics } = ts.transpileModule( + `const __simProgram = async () => {\n${code}\n};`, + { + reportDiagnostics: true, + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }, + } + ) + const problems = (diagnostics ?? []).flatMap((diagnostic) => { + if (!diagnostic.file || diagnostic.start === undefined) return [] + const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n') + const { line } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start) + return [`Line ${Math.max(1, line)}: ${message}`] + }) + if (problems.length > 0) return { error: `The program does not parse.\n${problems.join('\n')}` } + return { + script: `${outputText}\ntry { __simCodeSettle(true, await __simProgram()); } catch (error) { __simCodeSettle(false, error); }`, + } +} + +function failure(error: Record, calls: CallRecord[], logs?: string) { + return toolError(JSON.stringify({ error, calls, ...(logs ? { logs } : {}) }, null, 2)) +} + +/** + * Runs one code-mode program for the read or write code tool. + * + * The program runs in a fresh isolate with no network. Each `sim.api` call + * crosses back to this request through the `simApi` broker and is dispatched + * exactly as the call tools dispatch one: the v2 route authenticates the + * request's own credential and applies its scope, workspace permissions, + * refusals, and rate limit. The read tool additionally refuses, here on the + * host, every operation the write tool would run. + */ +export async function runCodeMode( + kind: CodeKind, + input: z.infer, + context: McpDispatchContext, + ownerKey: string +): Promise { + const startedAt = performance.now() + const runId = generateShortId(12) + const calls: CallRecord[] = [] + let writes = 0 + const limit = createConcurrencyLimit(MAX_CONCURRENT_CALLS) + /** Ends the run's in-flight calls once the program is over, whether it returned, threw, or timed out. */ + const runEnded = new AbortController() + const signal = AbortSignal.any([context.signal, runEnded.signal]) + + const summary = (outcome: string) => + logger.info('Sim MCP code run finished', { + codeRunId: runId, + tool: CODE_TOOL_NAMES[kind], + ownerKey, + outcome, + calls: calls.length, + writes, + durationMs: Math.round(performance.now() - startedAt), + codeSha256: sha256Hex(input.code), + }) + + const compiled = await compileProgram(input.code) + if ('error' in compiled) { + summary('syntax_error') + return toolError(compiled.error) + } + + async function callSimApi(args: unknown): Promise { + const parsed = simApiCall.safeParse(args) + if (!parsed.success) { + return apiFailure(400, 'INVALID_CALL', `Invalid sim.api input: ${parsed.error.message}`) + } + if (calls.length >= MAX_CALLS_PER_RUN) { + throw new Error(`A program may make at most ${MAX_CALLS_PER_RUN} API calls.`) + } + const record: CallRecord = { operation: parsed.data.operation, durationMs: 0 } + const callIndex = calls.push(record) - 1 + const callStartedAt = performance.now() + try { + const resolved = await resolveOperation(parsed.data.operation, 'any') + if ('error' in resolved) { + record.refused = resolved.error + return apiFailure(404, 'UNKNOWN_OPERATION', resolved.error) + } + if (getMcpOperation(resolved.operation).contract.response.mode !== 'json') { + record.refused = 'answers with a non-JSON body' + return apiFailure( + 400, + 'NOT_CALLABLE', + `${resolved.operation} does not answer with JSON, so code cannot call it.` + ) + } + const isRead = await isReadOperation(resolved.operation) + if (!isRead && kind === 'read') { + record.refused = 'write operation in a read program' + return apiFailure( + 403, + 'WRITE_NOT_ALLOWED', + `${resolved.operation} needs write access; run this program with ${CODE_TOOL_NAMES.write}.` + ) + } + if (!isRead) writes++ + const outcome = await limit(async () => + signal.aborted + ? { rejected: 'The program ended before this call was sent.' } + : dispatchMcpRequest( + { ...parsed.data.input, operation: resolved.operation }, + { ...context, signal, logMetadata: { codeRunId: runId, callIndex } } + ) + ) + if ('rejected' in outcome) { + record.refused = outcome.rejected + return apiFailure(400, 'INVALID_CALL', outcome.rejected) + } + record.status = outcome.status + if ('unreadable' in outcome) { + record.unreadable = outcome.unreadable + return apiFailure( + outcome.status, + 'UNREADABLE_RESPONSE', + `${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.` + ) + } + return outcome.ok ? { dataJson: outcome.text } : envelopeFailure(outcome.status, outcome.text) + } finally { + record.durationMs = Math.round(performance.now() - callStartedAt) + } + } + + let bytes: Buffer | undefined + let runError: unknown + try { + bytes = await runSandboxTask( + 'sim-api-code', + { code: compiled.script }, + { + ownerKey, + callSimApi, + signal: context.signal, + timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS, + } + ) + } catch (error) { + runError = error + } + runEnded.abort() + for (const record of calls) { + if (record.status === undefined && record.refused === undefined) { + record.unreadable = 'The program ended before this call answered; it may still complete.' + } + } + + if (!bytes) { + if (context.signal.aborted) { + summary('cancelled') + return failure({ name: 'AbortError', message: 'The program was cancelled.' }, calls) + } + if (runError instanceof SandboxUserCodeError) { + summary(runError.name === 'TimeoutError' ? 'timeout' : 'error') + return failure({ name: runError.name, message: runError.message }, calls) + } + summary('system_error') + logger.error('Sim MCP code run failed', { codeRunId: runId, error: getErrorMessage(runError) }) + return failure( + { name: 'Error', message: 'Unable to run the program. Please try again.' }, + calls + ) + } + + const outcome = outcomeSchema.parse(JSON.parse(bytes.toString('utf8'))) + const logs = outcome.logs || undefined + if (!outcome.ok) { + summary('error') + return failure(outcome.error, calls, logs) + } + summary('ok') + return structuredToolResult({ result: outcome.result, calls, ...(logs ? { logs } : {}) }) +} diff --git a/apps/sim/lib/api/mcp/dispatch.ts b/apps/sim/lib/api/mcp/dispatch.ts index 06c71f1b7f8..24aa23c0a59 100644 --- a/apps/sim/lib/api/mcp/dispatch.ts +++ b/apps/sim/lib/api/mcp/dispatch.ts @@ -51,6 +51,8 @@ export interface McpDispatchContext { credential: V2CredentialHeaders audience: OAuthAccessTokenOptions signal: AbortSignal + /** Extra fields for the per-call log line, such as the code-mode run a call belongs to. */ + logMetadata?: Record } function isRouteHandler(value: unknown): value is V2RouteHandler { @@ -105,33 +107,47 @@ function buildHeaders( return headers } -/** Returns the route's JSON answer as tool content; a v2 error envelope becomes a tool error. */ -async function toToolResult( +/** + * What a call came to: rejected before it reached the route (a malformed call), + * the route's JSON answer, or an answer the route gave that cannot be returned + * (not JSON, or too large). An unreadable answer still means the operation ran. + */ +type McpDispatchOutcome = + | { rejected: string } + | { status: number; ok: boolean; text: string } + | { status: number; unreadable: string } + +/** Reads the route's JSON answer, bounded by {@link MAX_RESULT_BYTES}. */ +async function readJsonAnswer( operation: V2McpOperationName, response: Response -): Promise { +): Promise { const contentType = response.headers.get('content-type') ?? '' if (!/[/+]json\b/i.test(contentType)) { await consumeOrCancelBody(response) - return toolError( - `${operation} answered with ${contentType || 'an empty body'} (HTTP ${response.status}). Only JSON responses can be returned over MCP.` - ) + return { + unreadable: `${operation} answered with ${contentType || 'an empty body'} (HTTP ${response.status}). Only JSON responses can be returned over MCP.`, + status: response.status, + } } - let text: string try { - text = await readResponseTextWithLimit(response, { + const text = await readResponseTextWithLimit(response, { maxBytes: MAX_RESULT_BYTES, label: `${operation} result`, }) + return { status: response.status, ok: response.ok, text } } catch (error) { if (!isPayloadSizeLimitError(error)) throw error - return toolError('Result is too large. Request a smaller page with limit or cursor.') + return { + unreadable: 'Result is too large. Request a smaller page with limit or cursor.', + status: response.status, + } } - return response.ok ? { content: [{ type: 'text', text }] } : toolError(text) } /** - * Serves a tool call through the v2 route that owns the operation. + * Serves one operation call, from a call tool or `sim.api`, through the v2 + * route that owns the operation. * * The call becomes the HTTP request the route would receive — same path, query, * body, and credential — and the route handles it end to end: authentication, @@ -139,15 +155,15 @@ async function toToolResult( * envelope. MCP adds no authorization of its own, so no operation can be looser * here than over HTTP. */ -export async function dispatchMcpOperation( +export async function dispatchMcpRequest( call: McpOperationCall, context: McpDispatchContext -): Promise { +): Promise { const startedAt = performance.now() const { contract, handler } = getMcpOperation(call.operation) const resolved = resolvePath(contract.path, call.params ?? {}) - if ('error' in resolved) return toolError(resolved.error) + if ('error' in resolved) return { rejected: resolved.error } const url = new URL(resolved.path, getBaseUrl()) for (const [name, value] of Object.entries(call.query ?? {})) { @@ -156,15 +172,16 @@ export async function dispatchMcpOperation( const hasBody = contract.method !== 'GET' && contract.body !== undefined if (!hasBody && call.body !== undefined) { - return toolError(`${call.operation} takes no request body. Use params and query instead.`) + return { rejected: `${call.operation} takes no request body. Use params and query instead.` } } if (isPlainRecord(call.body) && call.body.stream === true) { - return toolError( - 'Streaming is not supported over MCP. Omit stream to wait for the result, or set async: true and poll getWorkflowRun.' - ) + return { + rejected: + 'Streaming is not supported over MCP. Omit stream to wait for the result, or set async: true and poll getWorkflowRun.', + } } const headers = buildHeaders(call, context, hasBody) - if ('error' in headers) return toolError(headers.error) + if ('error' in headers) return { rejected: headers.error } const route = await handler() if (!isRouteHandler(route)) { @@ -184,6 +201,18 @@ export async function dispatchMcpOperation( operation: call.operation, status: response.status, durationMs: Math.round(performance.now() - startedAt), + ...context.logMetadata, }) - return toToolResult(call.operation, response) + return readJsonAnswer(call.operation, response) +} + +/** {@link dispatchMcpRequest} as a tool result; a v2 error envelope becomes a tool error. */ +export async function dispatchMcpOperation( + call: McpOperationCall, + context: McpDispatchContext +): Promise { + const outcome = await dispatchMcpRequest(call, context) + if ('rejected' in outcome) return toolError(outcome.rejected) + if ('unreadable' in outcome) return toolError(outcome.unreadable) + return outcome.ok ? { content: [{ type: 'text', text: outcome.text }] } : toolError(outcome.text) } diff --git a/apps/sim/lib/api/mcp/route-handler.ts b/apps/sim/lib/api/mcp/route-handler.ts index 9f986ec701e..f0f40d9540a 100644 --- a/apps/sim/lib/api/mcp/route-handler.ts +++ b/apps/sim/lib/api/mcp/route-handler.ts @@ -1,8 +1,14 @@ +import { type Principal, resolvePrincipalSubjectUserId } from '@sim/auth/principal' import { isPlainRecord } from '@sim/utils/object' import type { NextRequest } from 'next/server' import { v2McpOperations } from '@/lib/api/application/operations' import { simMcpContract } from '@/lib/api/contracts/sim-mcp' -import { getMcpOperation, resolveOperation, TOOL_NAMES } from '@/lib/api/mcp/catalog' +import { + CODE_TOOL_NAMES, + getMcpOperation, + resolveOperation, + TOOL_NAMES, +} from '@/lib/api/mcp/catalog' import { withSimMcpAuthChallenge } from '@/lib/api/mcp/oauth-metadata' import { createSimMcpServer } from '@/lib/api/mcp/server' import { getSimMcpUrl } from '@/lib/api/mcp/urls' @@ -20,6 +26,7 @@ import { } from '@/lib/api/server/routes/v2-json-route' import type { OAuthAccessTokenOptions } from '@/lib/auth/oauth-access-token' import { type ApplicationOperation, requireOAuthOperationScope } from '@/lib/core/application' +import { isFeatureEnabled } from '@/lib/core/config/feature-flags' import { isSameOrigin } from '@/lib/core/utils/validation' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' import { v2CaughtOrchestrationError, v2Error } from '@/app/api/v2/lib/response' @@ -49,13 +56,16 @@ function admit(request: NextRequest) { * tool with a known operation. Its OAuth scope is checked before the SDK runs, * so a token without it gets the protocol's `insufficient_scope` step-up * challenge rather than a tool error. Raw routes declare no operation and all - * change something, so they need `api:write`. + * change something, so they need `api:write`, as does the write code tool, + * whose programs may run any operation. The read code tool needs only the + * `api:read` every connection already holds. */ async function toolCallOperation( message: Record ): Promise { if (message.method !== 'tools/call' || !isPlainRecord(message.params)) return null const { name, arguments: args } = message.params + if (name === CODE_TOOL_NAMES.write) return v2McpOperations.rawRoute if (name !== TOOL_NAMES.read && name !== TOOL_NAMES.write) return null if (!isPlainRecord(args) || typeof args.operation !== 'string') return null const resolved = await resolveOperation( @@ -67,6 +77,30 @@ async function toolCallOperation( return v2RouteOperation(route) ?? v2McpOperations.rawRoute } +/** + * Whether a message's answer depends on the code-mode flag: the instructions + * and tool list mention the code tools, and a call may run one. + */ +function readsCodeMode(message: Record): boolean { + if (message.method === 'initialize' || message.method === 'tools/list') return true + if (message.method !== 'tools/call' || !isPlainRecord(message.params)) return false + const { name } = message.params + return name === CODE_TOOL_NAMES.read || name === CODE_TOOL_NAMES.write +} + +/** + * The code tools when the flag is on for this caller, keyed for the sandbox + * pool's per-caller fairness by the person or workspace calling. + */ +async function codeModeFor(principal: Principal): Promise<{ ownerKey: string } | null> { + const userId = resolvePrincipalSubjectUserId(principal) + const workspaceId = principal.kind === 'workspace_api_key' ? principal.workspaceId : undefined + if (!(await isFeatureEnabled('mcp-code-mode', { userId, workspaceId }))) return null + if (userId) return { ownerKey: `user:${userId}` } + if (workspaceId) return { ownerKey: `workspace:${workspaceId}` } + return null +} + /** Browsers may only reach the server from Sim's own origins (DNS-rebinding protection). */ function isAllowedOrigin(origin: string | null): boolean { return !origin || isSameOrigin(origin) || isSameOrigin(origin, getSimMcpUrl()) @@ -90,11 +124,18 @@ export function createSimMcpHandlers() { if (!parsed.success) return parsed.response const operation = await toolCallOperation(parsed.data.body) if (operation) requireOAuthOperationScope(admission.auth.principal, operation) - const server = createSimMcpServer({ - inbound: request, - credential: readMcpCredentialHeaders(request.headers), - audience: simMcpAudience(), - }) + const server = createSimMcpServer( + { + inbound: request, + credential: readMcpCredentialHeaders(request.headers), + audience: simMcpAudience(), + }, + { + codeMode: readsCodeMode(parsed.data.body) + ? await codeModeFor(admission.auth.principal) + : null, + } + ) return await serveStatelessMcp(server, request, parsed.data.body) } catch (error) { const response = v2CaughtOrchestrationError(error) diff --git a/apps/sim/lib/api/mcp/server.ts b/apps/sim/lib/api/mcp/server.ts index dbcd2a481aa..2dbffeaa23b 100644 --- a/apps/sim/lib/api/mcp/server.ts +++ b/apps/sim/lib/api/mcp/server.ts @@ -4,14 +4,17 @@ import { createLogger } from '@sim/logger' import { SIM_DOCS_URL } from '@sim/utils/site' import { z } from 'zod' import { + CODE_TOOL_NAMES, describeOperation, describeOperationOutput, OPERATION_DOMAINS, + operationRequestInput, resolveOperation, searchOperations, searchOperationsOutput, TOOL_NAMES, } from '@/lib/api/mcp/catalog' +import { codeModeInput, codeModeOutput, runCodeMode } from '@/lib/api/mcp/code-mode' import { dispatchMcpOperation, type McpDispatchContext, @@ -33,6 +36,10 @@ const INSTRUCTIONS = `Sim is the AI workspace where teams build, deploy, and man 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.` +const CODE_MODE_INSTRUCTIONS = ` + +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.(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.` + const operationName = z .string() .trim() @@ -71,36 +78,15 @@ const searchInput = z const describeInput = z.object({ operation: operationName }).strict() /** Shared because a read is not always a GET: searching and querying post their filter as JSON. */ -const callInput = z - .object({ - operation: operationName, - params: z - .record(z.string(), z.string()) - .optional() - .describe( - 'Values for the bracketed segments of the operation’s path, by name, e.g. { "tableId": "..." }. IDs come from list operations such as listTables.' - ), - query: z - .record(z.string(), z.union([z.string(), z.number(), z.boolean()])) - .optional() - .describe( - '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.' - ), - headers: z - .record(z.string(), z.string()) - .optional() - .describe( - 'Headers the operation’s describe_operation schema lists, such as upload-token. Sim sets authentication and content headers itself.' - ), - body: z - .record(z.string(), z.unknown()) - .meta({ additionalProperties: true }) - .optional() - .describe( - 'JSON request body matching the body schema from describe_operation. Omit it when the operation takes no body.' - ), - }) - .strict() +const callInput = operationRequestInput.extend({ operation: operationName }).strict() + +interface SimMcpServerOptions { + /** + * Registers the code-mode tools for this caller; `ownerKey` names the caller + * for the sandbox pool's per-caller fairness. `null` leaves them out. + */ + codeMode: { ownerKey: string } | null +} /** * The Sim MCP server for one HTTP request. A request owns its server, so no @@ -111,7 +97,10 @@ const callInput = z * the model's context on schemas it never uses. Reads and writes are separate * tools so a client can approve reads once and still confirm every change. */ -export function createSimMcpServer(context: Omit): McpServer { +export function createSimMcpServer( + context: Omit, + options: SimMcpServerOptions +): McpServer { const baseUrl = getBaseUrl() const server = new McpServer( { @@ -133,7 +122,7 @@ export function createSimMcpServer(context: Omit): }, ], }, - { instructions: INSTRUCTIONS } + { instructions: options.codeMode ? INSTRUCTIONS + CODE_MODE_INSTRUCTIONS : INSTRUCTIONS } ) async function call( @@ -235,5 +224,59 @@ export function createSimMcpServer(context: Omit): async (input, extra) => call('write', input, extra.signal) ) + if (!options.codeMode) return server + const { ownerKey } = options.codeMode + + async function runCode( + kind: 'read' | 'write', + input: z.infer, + toolSignal: AbortSignal + ): Promise { + const signal = AbortSignal.any([context.inbound.signal, toolSignal]) + try { + return await runCodeMode(kind, input, { ...context, signal }, ownerKey) + } catch (error) { + if (signal.aborted) return toolError('The program was cancelled.') + logger.error('Sim MCP code run failed', { tool: CODE_TOOL_NAMES[kind], error }) + return toolError('Unable to run the program. Please try again.') + } + } + + server.registerTool( + CODE_TOOL_NAMES.read, + { + title: 'Run read-only code against Sim', + description: `Run a JavaScript or TypeScript program that reads from Sim through sim.api, for tasks that take many calls: paging through lists, filtering, counting, or joining results across operations. Only the returned value comes back, with a log of the calls made. Every operation the program calls must be one ${TOOL_NAMES.read} could run; anything needing write access is refused. Get each operation's signature from describe_operation first.`, + inputSchema: codeModeInput, + outputSchema: codeModeOutput, + annotations: { + title: 'Run read-only code against Sim', + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, + }, + }, + async (input, extra) => runCode('read', input, extra.signal) + ) + + server.registerTool( + CODE_TOOL_NAMES.write, + { + title: 'Run code that changes Sim', + description: `Run a JavaScript or TypeScript program that can read and change Sim through sim.api, for tasks that take many calls, such as updating or deleting every item that matches a filter. Changes apply immediately as each call runs, with no preview or undo; if the program fails partway, the calls log shows which changes already happened. Confirm what the program will change with the user first. Prefer ${CODE_TOOL_NAMES.read} when the task only reads.`, + inputSchema: codeModeInput, + outputSchema: codeModeOutput, + annotations: { + title: 'Run code that changes Sim', + readOnlyHint: false, + destructiveHint: true, + idempotentHint: false, + openWorldHint: true, + }, + }, + async (input, extra) => runCode('write', input, extra.signal) + ) + return server } diff --git a/apps/sim/lib/core/config/env.ts b/apps/sim/lib/core/config/env.ts index 1ffeff3b9e7..c62b3716655 100644 --- a/apps/sim/lib/core/config/env.ts +++ b/apps/sim/lib/core/config/env.ts @@ -625,6 +625,7 @@ export const env = createEnv({ CHANGELOG: z.boolean().optional(), // Fallback for the `changelog` feature flag off AppConfig SIM_LINKS: z.boolean().optional(), // Fallback for the `sim-links` feature flag off AppConfig PEOPLE: z.boolean().optional(), // Fallback for the `people` feature flag off AppConfig + MCP_CODE_MODE: z.boolean().optional(), // Fallback for the `mcp-code-mode` feature flag off AppConfig ORGANIZATION_ACTIVITY_ROLLUP_READS: z.boolean().optional(), // Fallback for the `organization-activity-rollup-reads` feature flag off AppConfig ACTIVITY_ROLLUP_MAINTENANCE: z.boolean().optional(), // Fallback for the `activity-rollup-maintenance` feature flag off AppConfig ACTIVITY_ROLLUP_BACKFILL_ROWS_PER_SECOND: z.coerce.number().int().positive().optional(), // Source rows the activity rollup backfill reads per second (default 20000) diff --git a/apps/sim/lib/core/config/feature-flags.ts b/apps/sim/lib/core/config/feature-flags.ts index f19bed44593..0bd999a4b51 100644 --- a/apps/sim/lib/core/config/feature-flags.ts +++ b/apps/sim/lib/core/config/feature-flags.ts @@ -71,6 +71,11 @@ const FEATURE_FLAGS = { 'Enable the organization People directory, org chart, profile imports, and directory sync. Supports organization rollout; disabled by default.', fallback: 'PEOPLE', }, + 'mcp-code-mode': { + description: + 'Add the code-mode tools (execute_read_code, execute_write_code) to the Sim MCP server. Supports user and workspace rollout; disabled by default.', + fallback: 'MCP_CODE_MODE', + }, 'mothership-model-selector': { description: 'Show the Mothership model selector, model-specific effort levels, and Fast for supported ' + diff --git a/apps/sim/lib/execution/sandbox/brokers/sim-api.ts b/apps/sim/lib/execution/sandbox/brokers/sim-api.ts new file mode 100644 index 00000000000..e53113fc634 --- /dev/null +++ b/apps/sim/lib/execution/sandbox/brokers/sim-api.ts @@ -0,0 +1,10 @@ +import type { SandboxBroker } from '@/lib/execution/sandbox/types' + +/** Isolate side: `__brokers.simApi({ operation, input })`, wrapped by the `sim-api-code` bootstrap as `sim.api.(input)`. */ +export const simApiBroker: SandboxBroker = { + name: 'simApi', + handle(ctx, args) { + if (!ctx.callSimApi) throw new Error('sim.api is not available in this run') + return ctx.callSimApi(args) + }, +} diff --git a/apps/sim/lib/execution/sandbox/run-task.ts b/apps/sim/lib/execution/sandbox/run-task.ts index 055c89c3443..6b86ef79648 100644 --- a/apps/sim/lib/execution/sandbox/run-task.ts +++ b/apps/sim/lib/execution/sandbox/run-task.ts @@ -27,6 +27,9 @@ export interface RunSandboxTaskOptions { filePrincipal?: SandboxBrokerContext['filePrincipal'] /** Run id that brokers see as `ctx.requestId`, for callers that keep per-run broker state. */ requestId?: string + callSimApi?: SandboxBrokerContext['callSimApi'] + /** A shorter budget than the task's own `timeoutMs`, which stays the ceiling. */ + timeoutMs?: number } /** @@ -66,6 +69,7 @@ export async function runSandboxTask( resolvePreparedFile: options.resolvePreparedFile, onWorkspaceFileAccess: options.onWorkspaceFileAccess, filePrincipal: options.filePrincipal, + callSimApi: options.callSimApi, } const brokers: Record = {} const runInCallerContext = AsyncLocalStorage.snapshot() @@ -89,7 +93,7 @@ export async function runSandboxTask( params: {}, envVars: {}, contextVariables: {}, - timeoutMs: task.timeoutMs, + timeoutMs: Math.min(options.timeoutMs ?? task.timeoutMs, task.timeoutMs), requestId, ownerKey: options.ownerKey, ownerWeight: 1, diff --git a/apps/sim/lib/execution/sandbox/types.ts b/apps/sim/lib/execution/sandbox/types.ts index 776e0a659dd..d713133d2c6 100644 --- a/apps/sim/lib/execution/sandbox/types.ts +++ b/apps/sim/lib/execution/sandbox/types.ts @@ -29,6 +29,8 @@ export interface SandboxBrokerContext { resolvePreparedFile?: (fileId: string) => { content: Buffer; contentType: string } /** Host-side identity used to authorize and admit each actual broker read. Never sent to the isolate. */ filePrincipal?: Principal + /** Serves one `sim.api` call from a code-mode program; it closes over the caller's credential, which stays on the host. */ + callSimApi?: (call: unknown) => Promise onWorkspaceFileAccess?: (identity: { fileId: string key: string diff --git a/apps/sim/lib/execution/typescript.ts b/apps/sim/lib/execution/typescript.ts new file mode 100644 index 00000000000..c42aeca2924 --- /dev/null +++ b/apps/sim/lib/execution/typescript.ts @@ -0,0 +1,19 @@ +type TypeScriptModule = typeof import('@typescript/typescript6') + +let typescriptModule: Promise | null = null + +/** + * The TypeScript compiler, imported on first use: it is large, and most + * requests never parse or transpile user code. A failed import is dropped so + * the next call retries it. + */ +export function loadTypeScript(): Promise { + typescriptModule ??= import('@typescript/typescript6').then( + (mod) => (mod?.default ?? mod) as TypeScriptModule, + (error) => { + typescriptModule = null + throw error + } + ) + return typescriptModule +} diff --git a/apps/sim/lib/function-execution/execute-request.ts b/apps/sim/lib/function-execution/execute-request.ts index 228060601f3..6642222e46a 100644 --- a/apps/sim/lib/function-execution/execute-request.ts +++ b/apps/sim/lib/function-execution/execute-request.ts @@ -100,6 +100,7 @@ import type { SandboxSessionRequest, } from '@/lib/execution/remote-sandbox/types' import { isExecutionResourceLimitError } from '@/lib/execution/resource-errors' +import { loadTypeScript } from '@/lib/execution/typescript' import { MAX_FUNCTION_REFERENCES } from '@/lib/function-execution/limits' import type { SandboxExportedFile } from '@/lib/function-execution/output' import { planUserFileMounts, resolveUserFileMounts } from '@/lib/function-execution/sandbox-mounts' @@ -385,24 +386,6 @@ const JS_RESERVED_WORDS = new Set([ 'public', ]) -type TypeScriptModule = typeof import('@typescript/typescript6') - -let typescriptModulePromise: Promise | null = null - -async function loadTypeScriptModule(): Promise { - if (!typescriptModulePromise) { - typescriptModulePromise = import('@typescript/typescript6').then( - (mod) => (mod?.default ?? mod) as TypeScriptModule, - (error) => { - typescriptModulePromise = null - throw error - } - ) - } - - return typescriptModulePromise -} - async function extractJavaScriptImports(code: string): Promise<{ imports: string remainingCode: string @@ -410,7 +393,7 @@ async function extractJavaScriptImports(code: string): Promise<{ identifierNames: ReadonlySet }> { try { - const tsModule = await loadTypeScriptModule() + const tsModule = await loadTypeScript() const sourceFile = tsModule.createSourceFile( 'user-code.js', diff --git a/apps/sim/sandboxes/index.ts b/apps/sim/sandboxes/index.ts index 89b76c97877..7e26b233968 100644 --- a/apps/sim/sandboxes/index.ts +++ b/apps/sim/sandboxes/index.ts @@ -14,6 +14,8 @@ * - `pdf-generate` → `apps/sim/sandboxes/pdf-generate.ts` * - `workflow-test-run`, `workflow-test-collect` → `apps/sim/sandboxes/workflow-test.ts` * (user code is an ES module importing only `vitest` and `sim:test`) + * - `sim-api-code` → `apps/sim/sandboxes/sim-api-code.ts` + * (Sim MCP code mode: an async function body calling the v2 API via `sim.api`) * * Tier 2 — Raw isolated-vm consumers. * Value-producing executions where the user supplies arbitrary JS and the diff --git a/apps/sim/sandboxes/registry.ts b/apps/sim/sandboxes/registry.ts index c76c6a73edb..d1cb36eb592 100644 --- a/apps/sim/sandboxes/registry.ts +++ b/apps/sim/sandboxes/registry.ts @@ -2,6 +2,7 @@ import type { SandboxTask } from '@/lib/execution/sandbox/types' import { docxGenerateTask } from '@/sandboxes/docx-generate' import { pdfGenerateTask } from '@/sandboxes/pdf-generate' import { pptxGenerateTask } from '@/sandboxes/pptx-generate' +import { simApiCodeTask } from '@/sandboxes/sim-api-code' import { workflowTestCollectTask, workflowTestRunTask } from '@/sandboxes/workflow-test' /** @@ -13,6 +14,7 @@ export const SANDBOX_TASKS = { 'pptx-generate': pptxGenerateTask, 'docx-generate': docxGenerateTask, 'pdf-generate': pdfGenerateTask, + 'sim-api-code': simApiCodeTask, 'workflow-test-run': workflowTestRunTask, 'workflow-test-collect': workflowTestCollectTask, } as const satisfies Record diff --git a/apps/sim/sandboxes/sim-api-code.ts b/apps/sim/sandboxes/sim-api-code.ts new file mode 100644 index 00000000000..8b840dfbedd --- /dev/null +++ b/apps/sim/sandboxes/sim-api-code.ts @@ -0,0 +1,176 @@ +import { simApiBroker } from '@/lib/execution/sandbox/brokers/sim-api' +import { defineSandboxTask } from '@/lib/execution/sandbox/define-task' + +/** The longest a code-mode program may run; a caller may ask for less. */ +export const SIM_API_CODE_MAX_TIMEOUT_MS = 120_000 + +/** The largest return value, as JSON, a program may hand back: the same bound as one call tool result. */ +const SIM_API_CODE_MAX_RESULT_CHARS = 1024 * 1024 + +/** + * Console output a program returns, beyond which lines are dropped with a marker. + * Captured in the isolate rather than read from the worker's stdout so the cap is + * per run and the logs travel with the result. + */ +const MAX_LOG_CHARS = 64 * 1024 + +/** Each text field of a failed program's error (message, stack, details as JSON) is cut to this. */ +const MAX_ERROR_FIELD_CHARS = 16 * 1024 + +/** + * Installs the program's view of Sim: a frozen `sim.api` whose every property + * is an operation that round-trips through the `simApi` broker, a + * `SimApiError` for API failures, and a console captured into the result. + * + * The program's settlement is recorded through `__simCodeSettle`, which the + * host-built wrapper calls, and read back by `finalize`. Results and response + * bodies cross the boundary as JSON text and are parsed on the side that uses + * them, and an oversized result is refused here, before it crosses. The task + * installs no `fetch`: the broker is the program's only way out of the isolate. + */ +const BOOTSTRAP = ` + const call = globalThis.__brokers.simApi; + const MAX_LOG_CHARS = ${MAX_LOG_CHARS}; + const MAX_RESULT_CHARS = ${SIM_API_CODE_MAX_RESULT_CHARS}; + const MAX_ERROR_FIELD_CHARS = ${MAX_ERROR_FIELD_CHARS}; + const cap = (text) => + text.length > MAX_ERROR_FIELD_CHARS ? text.slice(0, MAX_ERROR_FIELD_CHARS) + ' [truncated]' : text; + const logs = []; + let logChars = 0; + let logsTruncated = false; + const format = (value) => { + if (typeof value === 'string') return value; + if (value instanceof Error) return value.stack || String(value); + try { + const json = JSON.stringify(value); + return json === undefined ? String(value) : json; + } catch { + return String(value); + } + }; + const writer = (prefix) => (...args) => { + if (logsTruncated) return; + const line = prefix + args.map(format).join(' '); + if (logChars + line.length > MAX_LOG_CHARS) { + logs.push(line.slice(0, Math.max(0, MAX_LOG_CHARS - logChars)), '[logs truncated]'); + logsTruncated = true; + return; + } + logs.push(line); + logChars += line.length + 1; + }; + globalThis.console = Object.freeze({ + log: writer(''), + info: writer(''), + debug: writer(''), + warn: writer('WARN: '), + error: writer('ERROR: '), + }); + + class SimApiError extends Error { + constructor(info) { + super(info.message); + this.name = 'SimApiError'; + this.status = info.status; + this.code = info.code; + this.details = info.details; + this.requestId = info.requestId; + } + } + + const api = new Proxy(Object.freeze(Object.create(null)), { + get(_target, operation) { + if (typeof operation !== 'string' || operation === 'then') return undefined; + return async (input) => { + const answer = await call({ operation, input: input === undefined ? {} : input }); + if (answer.error) throw new SimApiError(answer.error); + return JSON.parse(answer.dataJson); + }; + }, + set: () => false, + defineProperty: () => false, + deleteProperty: () => false, + }); + const lock = (name, value) => + Object.defineProperty(globalThis, name, { value, writable: false, configurable: false }); + lock('sim', Object.freeze({ api })); + lock('SimApiError', SimApiError); + + const boundedDetails = (details) => { + if (details === undefined) return undefined; + let json; + try { + json = JSON.stringify(details); + } catch { + return undefined; + } + return json === undefined || json.length <= MAX_ERROR_FIELD_CHARS ? details : cap(json); + }; + const describeError = (error) => { + if (!(error instanceof Error)) return { name: 'Error', message: cap(String(error)) }; + const info = { + name: cap(String(error.name)), + message: cap(String(error.message)), + stack: typeof error.stack === 'string' ? cap(error.stack) : undefined, + }; + if (error instanceof SimApiError) { + const { status, code, requestId } = error; + Object.assign(info, { status, code, requestId, details: boundedDetails(error.details) }); + } + return info; + }; + let outcome = null; + lock('__simCodeSettle', (succeeded, value) => { + if (outcome) return; + if (!succeeded) { + outcome = { ok: false, error: describeError(value) }; + return; + } + let resultJson; + try { + resultJson = JSON.stringify(value === undefined ? null : value); + if (resultJson === undefined) throw new TypeError(typeof value + ' has no JSON form'); + } catch (error) { + outcome = { + ok: false, + error: { name: 'TypeError', message: 'The program returned a value that is not JSON-serializable: ' + describeError(error).message }, + }; + return; + } + outcome = resultJson.length > MAX_RESULT_CHARS + ? { + ok: false, + error: { + name: 'RangeError', + message: 'The returned value is ' + resultJson.length + ' characters; at most ' + MAX_RESULT_CHARS + ' can be returned. Return less, such as counts, ids, or a filtered subset.', + }, + } + : { ok: true, resultJson }; + }); + lock('__simCodeOutcomeJson', () => { + const logsJson = JSON.stringify(logs.join('\\n')); + if (outcome && outcome.ok) return '{"ok":true,"logs":' + logsJson + ',"result":' + outcome.resultJson + '}'; + const error = outcome ? outcome.error : { name: 'Error', message: 'The program did not finish' }; + return '{"ok":false,"logs":' + logsJson + ',"error":' + JSON.stringify(error) + '}'; + }); +` + +const FINALIZE = ` + return new TextEncoder().encode(globalThis.__simCodeOutcomeJson()); +` + +/** + * A code-mode program from the Sim MCP server: an async function body that + * calls the v2 API through `sim.api`. Every call is served on the host by the + * MCP request's own dispatcher, so the program holds no credential and can do + * only what its caller could do one call at a time. + */ +export const simApiCodeTask = defineSandboxTask({ + id: 'sim-api-code', + timeoutMs: SIM_API_CODE_MAX_TIMEOUT_MS, + bundles: [], + brokers: [simApiBroker], + bootstrap: BOOTSTRAP, + finalize: FINALIZE, + toResult: (bytes) => Buffer.from(bytes), +}) diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 68717b67b1e..3d2f5cfe08b 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -118,7 +118,7 @@ export type AbortProjectFileUploadParams = { uploadId: string } -export type AbortProjectFileUploadQuery = Record +export type AbortProjectFileUploadQuery = Record export type AbortProjectFileUploadHeaders = { 'upload-token': string @@ -171,9 +171,9 @@ export type ActivateWorkflowVersionParams = { workflowId: string } -export type ActivateWorkflowVersionQuery = Record +export type ActivateWorkflowVersionQuery = Record -export type ActivateWorkflowVersionBody = Record +export type ActivateWorkflowVersionBody = Record type ActivateWorkflowVersionResponseRef0 = { deploymentVersionId: string @@ -227,7 +227,7 @@ export type AddOrganizationDomainParams = { organizationId: string } -export type AddOrganizationDomainQuery = Record +export type AddOrganizationDomainQuery = Record export type AddOrganizationDomainBody = { domain: string @@ -250,7 +250,7 @@ export type AddPermissionGroupMemberParams = { groupId: string } -export type AddPermissionGroupMemberQuery = Record +export type AddPermissionGroupMemberQuery = Record export type AddPermissionGroupMemberBody = { userId: string @@ -274,7 +274,7 @@ export type AddTableColumnParams = { tableId: string } -export type AddTableColumnQuery = Record +export type AddTableColumnQuery = Record export type AddTableColumnBody = { workspaceId: string @@ -320,7 +320,7 @@ export type AddWorkflowGroupParams = { tableId: string } -export type AddWorkflowGroupQuery = Record +export type AddWorkflowGroupQuery = Record export type AddWorkflowGroupBody = { workspaceId: string @@ -405,7 +405,7 @@ export type AddWorkspaceFilesToKnowledgeBaseParams = { knowledgeBaseId: string } -export type AddWorkspaceFilesToKnowledgeBaseQuery = Record +export type AddWorkspaceFilesToKnowledgeBaseQuery = Record export type AddWorkspaceFilesToKnowledgeBaseBody = { workspaceId: string @@ -447,7 +447,9 @@ type ApplyWorkflowOperationsBodyRef0 = name: string inputs?: { tools?: ApplyWorkflowOperationsBodyRef1 + [key: string]: unknown } & Record + [key: string]: unknown } } | { @@ -456,7 +458,9 @@ type ApplyWorkflowOperationsBodyRef0 = params: { inputs?: { tools?: ApplyWorkflowOperationsBodyRef1 + [key: string]: unknown } & Record + [key: string]: unknown } & Record } | { @@ -472,7 +476,9 @@ type ApplyWorkflowOperationsBodyRef0 = name: string inputs?: { tools?: ApplyWorkflowOperationsBodyRef1 + [key: string]: unknown } & Record + [key: string]: unknown } } | { @@ -480,6 +486,7 @@ type ApplyWorkflowOperationsBodyRef0 = block_id: string params: { subflowId: string + [key: string]: unknown } } @@ -497,6 +504,7 @@ type ApplyWorkflowOperationsBodyRef3 = { usageControl?: 'auto' | 'force' | 'none' usageControlExpression?: string params?: Record + [key: string]: unknown } type ApplyWorkflowOperationsBodyRef4 = @@ -505,6 +513,7 @@ type ApplyWorkflowOperationsBodyRef4 = customToolId: string usageControl?: 'auto' | 'force' | 'none' usageControlExpression?: string + [key: string]: unknown } | { type: 'custom-tool' @@ -514,11 +523,14 @@ type ApplyWorkflowOperationsBodyRef4 = name: string description?: string parameters: Record + [key: string]: unknown } + [key: string]: unknown } code: string usageControl?: 'auto' | 'force' | 'none' usageControlExpression?: string + [key: string]: unknown } type ApplyWorkflowOperationsBodyRef5 = { @@ -526,9 +538,11 @@ type ApplyWorkflowOperationsBodyRef5 = { params: { serverId: string toolName: string + [key: string]: unknown } & Record usageControl?: 'auto' | 'force' | 'none' usageControlExpression?: string + [key: string]: unknown } type ApplyWorkflowOperationsBodyRef6 = { @@ -550,6 +564,7 @@ type ApplyWorkflowOperationsBodyRef6 = { } usageControl?: 'auto' | 'force' | 'none' usageControlExpression?: string + [key: string]: unknown } export type ApplyWorkflowOperationsBody = { @@ -696,7 +711,7 @@ export type ApplyWorkflowVariablesParams = { workflowId: string } -export type ApplyWorkflowVariablesQuery = Record +export type ApplyWorkflowVariablesQuery = Record export type ApplyWorkflowVariablesBody = { operations: Array< @@ -734,7 +749,7 @@ export type ArchiveProjectFileItemsParams = { projectId: string } -export type ArchiveProjectFileItemsQuery = Record +export type ArchiveProjectFileItemsQuery = Record export type ArchiveProjectFileItemsBody = { fileIds?: Array @@ -760,7 +775,7 @@ export type BulkAddPermissionGroupMembersParams = { groupId: string } -export type BulkAddPermissionGroupMembersQuery = Record +export type BulkAddPermissionGroupMembersQuery = Record export type BulkAddPermissionGroupMembersBody = { userIds?: Array @@ -777,7 +792,7 @@ export type BulkAddPermissionGroupMembersResponse = { } /** `POST /api/v2/files/bulk-delete` */ -export type BulkDeleteFilesQuery = Record +export type BulkDeleteFilesQuery = Record export type BulkDeleteFilesBody = { workspaceId: string @@ -795,7 +810,7 @@ export type BulkDeleteFilesResponse = { } /** `POST /api/v2/tables/bulk-delete` */ -export type BulkDeleteTablesQuery = Record +export type BulkDeleteTablesQuery = Record type BulkDeleteTablesBodyRef0 = string @@ -851,7 +866,7 @@ export type BulkSaveKnowledgeTagDefinitionsParams = { knowledgeBaseId: string } -export type BulkSaveKnowledgeTagDefinitionsQuery = Record +export type BulkSaveKnowledgeTagDefinitionsQuery = Record type BulkSaveKnowledgeTagDefinitionsBodyRef0 = { tagSlot: @@ -905,7 +920,7 @@ export type BulkUpdateKnowledgeChunksParams = { knowledgeBaseId: string } -export type BulkUpdateKnowledgeChunksQuery = Record +export type BulkUpdateKnowledgeChunksQuery = Record export type BulkUpdateKnowledgeChunksBody = { workspaceId: string @@ -928,7 +943,7 @@ export type BulkUpdateKnowledgeDocumentsParams = { knowledgeBaseId: string } -export type BulkUpdateKnowledgeDocumentsQuery = Record +export type BulkUpdateKnowledgeDocumentsQuery = Record export type BulkUpdateKnowledgeDocumentsBody = { workspaceId: string @@ -953,7 +968,7 @@ export type BulkUpdateTableRowsParams = { tableId: string } -export type BulkUpdateTableRowsQuery = Record +export type BulkUpdateTableRowsQuery = Record type BulkUpdateTableRowsBodyRef0 = Record @@ -1018,7 +1033,7 @@ export type CancelOrganizationAccessRequestParams = { requestId: string } -export type CancelOrganizationAccessRequestQuery = Record +export type CancelOrganizationAccessRequestQuery = Record type CancelOrganizationAccessRequestResponseRef0 = { id: string @@ -1248,7 +1263,7 @@ export type CancelTableRunsParams = { tableId: string } -export type CancelTableRunsQuery = Record +export type CancelTableRunsQuery = Record type CancelTableRunsBodyRef0 = | { @@ -1359,7 +1374,7 @@ export type CancelWorkflowRunParams = { runId: string } -export type CancelWorkflowRunQuery = Record +export type CancelWorkflowRunQuery = Record type CancelWorkflowRunResponseRef0 = { success: boolean @@ -1392,7 +1407,7 @@ export type CancelWorkspaceAccessRequestParams = { requestId: string } -export type CancelWorkspaceAccessRequestQuery = Record +export type CancelWorkspaceAccessRequestQuery = Record type CancelWorkspaceAccessRequestResponseRef0 = { id: string @@ -1490,7 +1505,7 @@ export type CancelWorkspaceAccessRequestResponse = { } /** `POST /api/v2/chat` */ -export type ChatQuery = Record +export type ChatQuery = Record export type ChatBody = { workspaceId: string @@ -1794,7 +1809,7 @@ export type CompleteProjectFileUploadParams = { uploadId: string } -export type CompleteProjectFileUploadQuery = Record +export type CompleteProjectFileUploadQuery = Record export type CompleteProjectFileUploadHeaders = { 'upload-token': string @@ -1848,9 +1863,9 @@ export type CompleteSourcePermissionImportParams = { importId: string } -export type CompleteSourcePermissionImportQuery = Record +export type CompleteSourcePermissionImportQuery = Record -export type CompleteSourcePermissionImportBody = Record +export type CompleteSourcePermissionImportBody = Record export type CompleteSourcePermissionImportResponse = { data: { @@ -1923,7 +1938,7 @@ export type CompleteTableImportResponse = { } /** `POST /api/v2/files/copy` */ -export type CopyFileItemsQuery = Record +export type CopyFileItemsQuery = Record export type CopyFileItemsBody = { source: { @@ -1984,7 +1999,7 @@ export type CopyFileItemsResponse = { } /** `POST /api/v2/credentials/connections` */ -export type CreateCredentialConnectionQuery = Record +export type CreateCredentialConnectionQuery = Record export type CreateCredentialConnectionBody = | { @@ -2089,7 +2104,7 @@ export type CreateCredentialConnectionResponse = { } /** `POST /api/v2/credentials/workload-identity/subjects` */ -export type CreateCredentialWorkloadIdentitySubjectQuery = Record +export type CreateCredentialWorkloadIdentitySubjectQuery = Record export type CreateCredentialWorkloadIdentitySubjectBody = { workspaceId: string @@ -2124,7 +2139,7 @@ export type CreateCredentialWorkloadIdentitySubjectResponse = { } /** `POST /api/v2/custom-tools` */ -export type CreateCustomToolQuery = Record +export type CreateCustomToolQuery = Record export type CreateCustomToolBody = { workspaceId: string @@ -2138,8 +2153,11 @@ export type CreateCustomToolBody = { type: string properties: Record required?: Array + [key: string]: unknown } + [key: string]: unknown } + [key: string]: unknown } code: string } @@ -2156,8 +2174,11 @@ type CreateCustomToolResponseRef0 = { type: string properties: Record required?: Array + [key: string]: unknown } + [key: string]: unknown } + [key: string]: unknown } code: string createdAt: string @@ -2169,7 +2190,7 @@ export type CreateCustomToolResponse = { } /** `POST /api/v2/files` */ -export type CreateFileQuery = Record +export type CreateFileQuery = Record type CreateFileBodyRef0 = string @@ -2202,7 +2223,7 @@ export type CreateFileResponse = { } /** `POST /api/v2/files/folders` */ -export type CreateFileFolderQuery = Record +export type CreateFileFolderQuery = Record type CreateFileFolderBodyRef0 = string @@ -2224,7 +2245,7 @@ export type CreateFileFolderResponse = { } /** `POST /api/v2/files/uploads` */ -export type CreateFileUploadQuery = Record +export type CreateFileUploadQuery = Record type CreateFileUploadBodyRef0 = string @@ -2325,7 +2346,7 @@ export type CreateFileUploadPartUrlsResponse = { } /** `POST /api/v2/knowledge` */ -export type CreateKnowledgeBaseQuery = Record +export type CreateKnowledgeBaseQuery = Record type CreateKnowledgeBaseBodyRef0 = { maxSize?: number @@ -2361,6 +2382,7 @@ type CreateKnowledgeBaseResponseRef0 = { recipe?: 'plain' | 'markdown' | 'code' strictBoundaries?: boolean } + [key: string]: unknown } type CreateKnowledgeBaseResponseRef1 = { @@ -2391,7 +2413,7 @@ export type CreateKnowledgeChunkParams = { knowledgeBaseId: string } -export type CreateKnowledgeChunkQuery = Record +export type CreateKnowledgeChunkQuery = Record export type CreateKnowledgeChunkBody = { workspaceId: string @@ -2428,7 +2450,7 @@ export type CreateKnowledgeConnectorParams = { knowledgeBaseId: string } -export type CreateKnowledgeConnectorQuery = Record +export type CreateKnowledgeConnectorQuery = Record export type CreateKnowledgeConnectorBody = { workspaceId: string @@ -2466,7 +2488,7 @@ export type CreateKnowledgeDocumentUploadParams = { knowledgeBaseId: string } -export type CreateKnowledgeDocumentUploadQuery = Record +export type CreateKnowledgeDocumentUploadQuery = Record export type CreateKnowledgeDocumentUploadBody = { workspaceId: string @@ -2581,7 +2603,7 @@ export type CreateKnowledgeDocumentUploadPartUrlsResponse = { } /** `POST /api/v2/knowledge/folders` */ -export type CreateKnowledgeFolderQuery = Record +export type CreateKnowledgeFolderQuery = Record type CreateKnowledgeFolderBodyRef0 = string @@ -2603,7 +2625,7 @@ export type CreateKnowledgeFolderResponse = { } /** `POST /api/v2/knowledge/imports` */ -export type CreateKnowledgeImportQuery = Record +export type CreateKnowledgeImportQuery = Record type CreateKnowledgeImportBodyRef0 = { type: 'upload' @@ -2699,7 +2721,7 @@ export type CreateKnowledgeTagParams = { knowledgeBaseId: string } -export type CreateKnowledgeTagQuery = Record +export type CreateKnowledgeTagQuery = Record export type CreateKnowledgeTagBody = { workspaceId: string @@ -2737,7 +2759,7 @@ export type CreateKnowledgeTagResponse = { } /** `POST /api/v2/mcp-servers` */ -export type CreateMcpServerQuery = Record +export type CreateMcpServerQuery = Record export type CreateMcpServerBody = { workspaceId: string @@ -2786,7 +2808,7 @@ export type CreateOrganizationAccessRequestParams = { organizationId: string } -export type CreateOrganizationAccessRequestQuery = Record +export type CreateOrganizationAccessRequestQuery = Record export type CreateOrganizationAccessRequestBody = { target: @@ -2965,7 +2987,7 @@ export type CreateOrganizationInvitationParams = { organizationId: string } -export type CreateOrganizationInvitationQuery = Record +export type CreateOrganizationInvitationQuery = Record export type CreateOrganizationInvitationBody = { email: string @@ -2993,7 +3015,7 @@ export type CreatePermissionGroupParams = { organizationId: string } -export type CreatePermissionGroupQuery = Record +export type CreatePermissionGroupQuery = Record export type CreatePermissionGroupBody = { name: string @@ -3120,7 +3142,7 @@ export type CreateProjectFileParams = { projectId: string } -export type CreateProjectFileQuery = Record +export type CreateProjectFileQuery = Record type CreateProjectFileBodyRef0 = string @@ -3159,7 +3181,7 @@ export type CreateProjectFileFolderParams = { projectId: string } -export type CreateProjectFileFolderQuery = Record +export type CreateProjectFileFolderQuery = Record export type CreateProjectFileFolderBody = { name: string @@ -3189,7 +3211,7 @@ export type CreateProjectFileUploadParams = { projectId: string } -export type CreateProjectFileUploadQuery = Record +export type CreateProjectFileUploadQuery = Record type CreateProjectFileUploadBodyRef0 = string @@ -3262,7 +3284,7 @@ export type CreateProjectFileUploadResponse = { } /** `POST /api/v2/sandboxes` */ -export type CreateSandboxQuery = Record +export type CreateSandboxQuery = Record export type CreateSandboxBody = { workspaceId: string @@ -3348,7 +3370,7 @@ export type CreateSearchSourceParams = { organizationId: string } -export type CreateSearchSourceQuery = Record +export type CreateSearchSourceQuery = Record export type CreateSearchSourceBody = { connectorType: string @@ -3401,7 +3423,7 @@ export type CreateSearchSourceResponse = { } /** `POST /api/v2/credentials` */ -export type CreateServiceAccountCredentialQuery = Record +export type CreateServiceAccountCredentialQuery = Record export type CreateServiceAccountCredentialBody = { workspaceId: string @@ -3431,7 +3453,7 @@ export type CreateServiceAccountCredentialResponse = { } /** `POST /api/v2/skills` */ -export type CreateSkillQuery = Record +export type CreateSkillQuery = Record export type CreateSkillBody = { workspaceId: string @@ -3460,7 +3482,7 @@ export type CreateSourcePermissionImportParams = { sourceId: string } -export type CreateSourcePermissionImportQuery = Record +export type CreateSourcePermissionImportQuery = Record export type CreateSourcePermissionImportBody = { provider: 'gitlab' @@ -3485,7 +3507,7 @@ export type CreateSourcePermissionImportResponse = { } /** `POST /api/v2/tables` */ -export type CreateTableQuery = Record +export type CreateTableQuery = Record type CreateTableBodyRef0 = string @@ -3564,7 +3586,7 @@ export type CreateTableDispatchParams = { tableId: string } -export type CreateTableDispatchQuery = Record +export type CreateTableDispatchQuery = Record type CreateTableDispatchBodyRef0 = | { @@ -3679,7 +3701,7 @@ export type CreateTableExportParams = { tableId: string } -export type CreateTableExportQuery = Record +export type CreateTableExportQuery = Record export type CreateTableExportBody = { workspaceId: string @@ -3704,7 +3726,7 @@ export type CreateTableExportResponse = { } /** `POST /api/v2/tables/folders` */ -export type CreateTableFolderQuery = Record +export type CreateTableFolderQuery = Record type CreateTableFolderBodyRef0 = string @@ -3726,7 +3748,7 @@ export type CreateTableFolderResponse = { } /** `POST /api/v2/tables/imports` */ -export type CreateTableImportQuery = Record +export type CreateTableImportQuery = Record type CreateTableImportBodyRef0 = { type: 'upload' @@ -3901,7 +3923,7 @@ export type CreateTableRowsParams = { tableId: string } -export type CreateTableRowsQuery = Record +export type CreateTableRowsQuery = Record type CreateTableRowsBodyRef0 = Record @@ -3957,7 +3979,7 @@ export type CreateTableViewParams = { tableId: string } -export type CreateTableViewQuery = Record +export type CreateTableViewQuery = Record type CreateTableViewBodyRef0 = | { @@ -4090,7 +4112,7 @@ export type CreateTableViewResponse = { } /** `POST /api/v2/workflows` */ -export type CreateWorkflowQuery = Record +export type CreateWorkflowQuery = Record type CreateWorkflowBodyRef0 = string @@ -4128,7 +4150,7 @@ export type CreateWorkflowResponse = { } /** `POST /api/v2/workflows/folders` */ -export type CreateWorkflowFolderQuery = Record +export type CreateWorkflowFolderQuery = Record type CreateWorkflowFolderBodyRef0 = string @@ -4151,7 +4173,7 @@ export type CreateWorkflowFolderResponse = { } /** `POST /api/v2/workflow-mcp-servers` */ -export type CreateWorkflowMcpServerQuery = Record +export type CreateWorkflowMcpServerQuery = Record export type CreateWorkflowMcpServerBody = { workspaceId: string @@ -4180,7 +4202,7 @@ export type CreateWorkspaceAccessRequestParams = { workspaceId: string } -export type CreateWorkspaceAccessRequestQuery = Record +export type CreateWorkspaceAccessRequestQuery = Record export type CreateWorkspaceAccessRequestBody = { target: @@ -4359,7 +4381,7 @@ export type CreateWorkspaceInvitationsParams = { workspaceId: string } -export type CreateWorkspaceInvitationsQuery = Record +export type CreateWorkspaceInvitationsQuery = Record export type CreateWorkspaceInvitationsBody = { emails: Array @@ -4675,7 +4697,7 @@ export type DeletePermissionGroupParams = { groupId: string } -export type DeletePermissionGroupQuery = Record +export type DeletePermissionGroupQuery = Record type DeletePermissionGroupResponseRef0 = { id: string @@ -4693,7 +4715,7 @@ export type DeleteProjectFileVersionParams = { version: number } -export type DeleteProjectFileVersionQuery = Record +export type DeleteProjectFileVersionQuery = Record export type DeleteProjectFileVersionResponse = { data: { @@ -4727,7 +4749,7 @@ export type DeleteSearchSourceParams = { sourceId: string } -export type DeleteSearchSourceQuery = Record +export type DeleteSearchSourceQuery = Record export type DeleteSearchSourceResponse = { data: { @@ -4780,7 +4802,7 @@ export type DeleteSsoProviderParams = { providerId: string } -export type DeleteSsoProviderQuery = Record +export type DeleteSsoProviderQuery = Record export type DeleteSsoProviderResponse = { data: { @@ -4812,7 +4834,7 @@ export type DeleteTableColumnParams = { tableId: string } -export type DeleteTableColumnQuery = Record +export type DeleteTableColumnQuery = Record export type DeleteTableColumnBody = { workspaceId: string @@ -4898,7 +4920,7 @@ export type DeleteTableRowsParams = { tableId: string } -export type DeleteTableRowsQuery = Record +export type DeleteTableRowsQuery = Record type DeleteTableRowsBodyRef0 = | { @@ -5029,7 +5051,7 @@ export type DeleteWorkflowParams = { workflowId: string } -export type DeleteWorkflowQuery = Record +export type DeleteWorkflowQuery = Record type DeleteWorkflowResponseRef0 = { id: string @@ -5046,7 +5068,7 @@ export type DeleteWorkflowChatDeploymentParams = { workflowId: string } -export type DeleteWorkflowChatDeploymentQuery = Record +export type DeleteWorkflowChatDeploymentQuery = Record type DeleteWorkflowChatDeploymentResponseRef0 = { id: string @@ -5096,7 +5118,7 @@ export type DeleteWorkflowGroupParams = { tableId: string } -export type DeleteWorkflowGroupQuery = Record +export type DeleteWorkflowGroupQuery = Record export type DeleteWorkflowGroupBody = { workspaceId: string @@ -5131,7 +5153,7 @@ export type DeleteWorkflowMcpServerParams = { serverId: string } -export type DeleteWorkflowMcpServerQuery = Record +export type DeleteWorkflowMcpServerQuery = Record type DeleteWorkflowMcpServerResponseRef0 = { id: string @@ -5147,7 +5169,7 @@ export type DeployWorkflowParams = { workflowId: string } -export type DeployWorkflowQuery = Record +export type DeployWorkflowQuery = Record export type DeployWorkflowBody = { name?: string @@ -5280,7 +5302,7 @@ export type DeployWorkflowMcpToolParams = { serverId: string } -export type DeployWorkflowMcpToolQuery = Record +export type DeployWorkflowMcpToolQuery = Record export type DeployWorkflowMcpToolBody = { workflowId: string @@ -5572,7 +5594,7 @@ export type DownloadRunFileParams = { fileId: string } -export type DownloadRunFileQuery = Record +export type DownloadRunFileQuery = Record /** Non-JSON response (`binary`). */ export type DownloadRunFileResponse = never @@ -5582,7 +5604,7 @@ export type DuplicateWorkflowParams = { workflowId: string } -export type DuplicateWorkflowQuery = Record +export type DuplicateWorkflowQuery = Record type DuplicateWorkflowBodyRef0 = string @@ -5615,7 +5637,7 @@ export type EditFileContentParams = { fileId: string } -export type EditFileContentQuery = Record +export type EditFileContentQuery = Record export type EditFileContentBody = { workspaceId: string @@ -5677,7 +5699,7 @@ export type ExecuteToolParams = { toolId: string } -export type ExecuteToolQuery = Record +export type ExecuteToolQuery = Record export type ExecuteToolBody = { workspaceId: string @@ -5704,7 +5726,7 @@ export type ExecuteWorkflowParams = { workflowId: string } -export type ExecuteWorkflowQuery = Record +export type ExecuteWorkflowQuery = Record export type ExecuteWorkflowBody = { input?: Record @@ -5805,7 +5827,7 @@ export type ExportProjectFileSnapshotParams = { fileId: string } -export type ExportProjectFileSnapshotQuery = Record +export type ExportProjectFileSnapshotQuery = Record export type ExportProjectFileSnapshotBody = { content: string @@ -5874,7 +5896,7 @@ export type ForkWorkspaceParams = { workspaceId: string } -export type ForkWorkspaceQuery = Record +export type ForkWorkspaceQuery = Record export type ForkWorkspaceBody = { name?: string @@ -6235,8 +6257,11 @@ type GetCustomToolResponseRef0 = { type: string properties: Record required?: Array + [key: string]: unknown } + [key: string]: unknown } + [key: string]: unknown } code: string createdAt: string @@ -6416,6 +6441,7 @@ type GetKnowledgeBaseResponseRef0 = { recipe?: 'plain' | 'markdown' | 'code' strictBoundaries?: boolean } + [key: string]: unknown } type GetKnowledgeBaseResponseRef1 = { @@ -6652,8 +6678,10 @@ type GetLogResponseRef1 = { startTime?: string endTime?: string duration?: number + [key: string]: unknown }> children?: Array + [key: string]: unknown } type GetLogResponseRef2 = { @@ -6798,7 +6826,7 @@ export type GetMcpServerResponse = { } /** `GET /api/v2/meta` */ -export type GetMetaQuery = Record +export type GetMetaQuery = Record type GetMetaResponseRef0 = { v2Enabled: boolean @@ -6846,7 +6874,7 @@ export type GetOrganizationParams = { organizationId: string } -export type GetOrganizationQuery = Record +export type GetOrganizationQuery = Record type GetOrganizationResponseRef0 = { id: string @@ -6866,7 +6894,7 @@ export type GetOrganizationAccessRequestSettingsParams = { organizationId: string } -export type GetOrganizationAccessRequestSettingsQuery = Record +export type GetOrganizationAccessRequestSettingsQuery = Record type GetOrganizationAccessRequestSettingsResponseRef0 = { allowRequests: boolean @@ -6882,7 +6910,7 @@ export type GetOrganizationInvitationParams = { invitationId: string } -export type GetOrganizationInvitationQuery = Record +export type GetOrganizationInvitationQuery = Record type GetOrganizationInvitationResponseRef0 = { id: string @@ -6906,7 +6934,7 @@ export type GetOrganizationMemberUsageLimitParams = { userId: string } -export type GetOrganizationMemberUsageLimitQuery = Record +export type GetOrganizationMemberUsageLimitQuery = Record type GetOrganizationMemberUsageLimitResponseRef0 = { creditsUsed: number @@ -7000,7 +7028,7 @@ export type GetPermissionGroupParams = { groupId: string } -export type GetPermissionGroupQuery = Record +export type GetPermissionGroupQuery = Record type GetPermissionGroupResponseRef0 = { id: string @@ -7073,7 +7101,7 @@ export type GetProjectFileMetadataParams = { fileId: string } -export type GetProjectFileMetadataQuery = Record +export type GetProjectFileMetadataQuery = Record type GetProjectFileMetadataResponseRef0 = { id: string @@ -7103,7 +7131,7 @@ export type GetProjectFileShareParams = { fileId: string } -export type GetProjectFileShareQuery = Record +export type GetProjectFileShareQuery = Record type GetProjectFileShareResponseRef0 = { id: string @@ -7127,7 +7155,7 @@ export type GetProjectFileUploadParams = { uploadId: string } -export type GetProjectFileUploadQuery = Record +export type GetProjectFileUploadQuery = Record export type GetProjectFileUploadHeaders = { 'upload-token': string @@ -7180,7 +7208,7 @@ export type GetProjectFileUploadPartUrlsParams = { uploadId: string } -export type GetProjectFileUploadPartUrlsQuery = Record +export type GetProjectFileUploadPartUrlsQuery = Record export type GetProjectFileUploadPartUrlsBody = { partNumbers: Array @@ -7212,7 +7240,7 @@ export type GetProjectFileVersionParams = { version: number } -export type GetProjectFileVersionQuery = Record +export type GetProjectFileVersionQuery = Record type GetProjectFileVersionResponseRef0 = GetProjectFileVersionResponseRef1 @@ -7351,7 +7379,7 @@ export type GetSearchSourceParams = { sourceId: string } -export type GetSearchSourceQuery = Record +export type GetSearchSourceQuery = Record export type GetSearchSourceResponse = { data: { @@ -7388,7 +7416,7 @@ export type GetSearchSourcePermissionsParams = { sourceId: string } -export type GetSearchSourcePermissionsQuery = Record +export type GetSearchSourcePermissionsQuery = Record type GetSearchSourcePermissionsResponseRef0 = { revision: number @@ -7399,7 +7427,7 @@ export type GetSearchSourcePermissionsResponse = { } /** `POST /api/v2/selectors/get` */ -export type GetSelectorQuery = Record +export type GetSelectorQuery = Record export type GetSelectorBody = { workspaceId: string @@ -7575,7 +7603,7 @@ export type GetSsoPolicyParams = { organizationId: string } -export type GetSsoPolicyQuery = Record +export type GetSsoPolicyQuery = Record export type GetSsoPolicyResponse = { data: { @@ -7591,7 +7619,7 @@ export type GetSsoProviderParams = { providerId: string } -export type GetSsoProviderQuery = Record +export type GetSsoProviderQuery = Record export type GetSsoProviderResponse = { data: { @@ -7925,7 +7953,7 @@ export type GetWorkflowParams = { workflowId: string } -export type GetWorkflowQuery = Record +export type GetWorkflowQuery = Record type GetWorkflowResponseRef0 = { name: string @@ -7937,6 +7965,7 @@ type GetWorkflowResponseRef1 = { type: string properties?: Record required?: Array + [key: string]: unknown } type GetWorkflowResponseRef2 = { @@ -7966,7 +7995,7 @@ export type GetWorkflowChatDeploymentParams = { workflowId: string } -export type GetWorkflowChatDeploymentQuery = Record +export type GetWorkflowChatDeploymentQuery = Record type GetWorkflowChatDeploymentResponseRef0 = { primaryColor?: string @@ -8009,7 +8038,7 @@ export type GetWorkflowDeploymentParams = { workflowId: string } -export type GetWorkflowDeploymentQuery = Record +export type GetWorkflowDeploymentQuery = Record type GetWorkflowDeploymentResponseRef0 = { deploymentVersionId: string @@ -8069,7 +8098,7 @@ export type GetWorkflowMcpServerParams = { serverId: string } -export type GetWorkflowMcpServerQuery = Record +export type GetWorkflowMcpServerQuery = Record type GetWorkflowMcpServerResponseRef0 = { id: string @@ -8090,7 +8119,7 @@ export type GetWorkflowOutlineParams = { workflowId: string } -export type GetWorkflowOutlineQuery = Record +export type GetWorkflowOutlineQuery = Record type GetWorkflowOutlineResponseRef0 = { type: string @@ -8232,7 +8261,7 @@ export type GetWorkflowStateParams = { workflowId: string } -export type GetWorkflowStateQuery = Record +export type GetWorkflowStateQuery = Record type GetWorkflowStateResponseRef0 = { id: string @@ -8337,7 +8366,7 @@ export type GetWorkflowVersionParams = { workflowId: string } -export type GetWorkflowVersionQuery = Record +export type GetWorkflowVersionQuery = Record type GetWorkflowVersionResponseRef0 = Record @@ -8360,7 +8389,7 @@ export type GetWorkspaceParams = { workspaceId: string } -export type GetWorkspaceQuery = Record +export type GetWorkspaceQuery = Record type GetWorkspaceResponseRef0 = { id: string @@ -8381,7 +8410,7 @@ export type GetWorkspaceForkAvailabilityParams = { workspaceId: string } -export type GetWorkspaceForkAvailabilityQuery = Record +export type GetWorkspaceForkAvailabilityQuery = Record type GetWorkspaceForkAvailabilityResponseRef0 = { available: boolean @@ -8396,7 +8425,7 @@ export type GetWorkspaceForkLineageParams = { workspaceId: string } -export type GetWorkspaceForkLineageQuery = Record +export type GetWorkspaceForkLineageQuery = Record type GetWorkspaceForkLineageResponseRef0 = { current: { @@ -8459,7 +8488,7 @@ export type GetWorkspaceOperationParams = { operationId: string } -export type GetWorkspaceOperationQuery = Record +export type GetWorkspaceOperationQuery = Record type GetWorkspaceOperationResponseRef0 = { operationId: string @@ -8512,7 +8541,7 @@ export type GetWorkspacePermissionConfigParams = { workspaceId: string } -export type GetWorkspacePermissionConfigQuery = Record +export type GetWorkspacePermissionConfigQuery = Record type GetWorkspacePermissionConfigResponseRef0 = { permissionGroupId: string | null @@ -8579,7 +8608,7 @@ export type GrantSkillEditorParams = { skillId: string } -export type GrantSkillEditorQuery = Record +export type GrantSkillEditorQuery = Record export type GrantSkillEditorBody = { workspaceId: string @@ -8598,7 +8627,7 @@ export type GrantSkillEditorResponse = { } /** `POST /api/v2/workflows/import` */ -export type ImportWorkflowQuery = Record +export type ImportWorkflowQuery = Record type ImportWorkflowBodyRef0 = string @@ -9113,8 +9142,11 @@ type ListCustomToolsResponseRef0 = { type: string properties: Record required?: Array + [key: string]: unknown } + [key: string]: unknown } + [key: string]: unknown } code: string createdAt: string @@ -9289,6 +9321,7 @@ type ListKnowledgeBasesResponseRef1 = { recipe?: 'plain' | 'markdown' | 'code' strictBoundaries?: boolean } + [key: string]: unknown } export type ListKnowledgeBasesResponse = { @@ -9614,8 +9647,10 @@ type ListLogsResponseRef2 = { startTime?: string endTime?: string duration?: number + [key: string]: unknown }> children?: Array + [key: string]: unknown } export type ListLogsResponse = { @@ -9678,11 +9713,13 @@ type ListMcpServerToolsResponseRef0 = { type: 'object' properties?: Record required?: Array + [key: string]: unknown } outputSchema?: { type: 'object' properties?: Record required?: Array + [key: string]: unknown } serverId: string serverName: string @@ -10631,7 +10668,7 @@ export type ListSecretsResponse = { } /** `POST /api/v2/selectors/list` */ -export type ListSelectorQuery = Record +export type ListSelectorQuery = Record export type ListSelectorBody = { workspaceId: string @@ -11183,7 +11220,7 @@ export type ListWorkflowMcpToolsParams = { serverId: string } -export type ListWorkflowMcpToolsQuery = Record +export type ListWorkflowMcpToolsQuery = Record type ListWorkflowMcpToolsResponseRef0 = { id: string @@ -11277,7 +11314,7 @@ export type ListWorkflowTriggersParams = { workflowId: string } -export type ListWorkflowTriggersQuery = Record +export type ListWorkflowTriggersQuery = Record type ListWorkflowTriggersResponseRef0 = { blockId: string @@ -11516,7 +11553,7 @@ export type ListWorkspaceSchedulesResponse = { } /** `POST /api/v2/files/move` */ -export type MoveFileItemsQuery = Record +export type MoveFileItemsQuery = Record type MoveFileItemsBodyRef0 = string @@ -11541,7 +11578,7 @@ export type MoveProjectFileItemsParams = { projectId: string } -export type MoveProjectFileItemsQuery = Record +export type MoveProjectFileItemsQuery = Record type MoveProjectFileItemsBodyRef0 = string @@ -11561,7 +11598,7 @@ export type MoveProjectFileItemsResponse = { } /** `POST /api/v2/tables/move` */ -export type MoveTablesQuery = Record +export type MoveTablesQuery = Record type MoveTablesBodyRef0 = string @@ -11600,7 +11637,7 @@ export type MoveTablesResponse = { } /** `POST /api/v2/workflows/move` */ -export type MoveWorkflowsQuery = Record +export type MoveWorkflowsQuery = Record type MoveWorkflowsBodyRef0 = string @@ -11625,7 +11662,7 @@ export type PrepareSearchSourcesParams = { organizationId: string } -export type PrepareSearchSourcesQuery = Record +export type PrepareSearchSourcesQuery = Record export type PrepareSearchSourcesBody = { connectorType: string @@ -11644,7 +11681,7 @@ export type PreviewOrganizationAccessRequestParams = { requestId: string } -export type PreviewOrganizationAccessRequestQuery = Record +export type PreviewOrganizationAccessRequestQuery = Record type PreviewOrganizationAccessRequestResponseRef0 = { newLimitCredits: number | null @@ -11966,7 +12003,7 @@ export type PreviewOrganizationAccessRequestResponse = { } /** `POST /api/v2/workflows/import/preview` */ -export type PreviewWorkflowImportQuery = Record +export type PreviewWorkflowImportQuery = Record type PreviewWorkflowImportBodyRef0 = string @@ -12116,7 +12153,7 @@ export type PreviewWorkspaceForkParams = { workspaceId: string } -export type PreviewWorkspaceForkQuery = Record +export type PreviewWorkspaceForkQuery = Record export type PreviewWorkspaceForkBody = { name?: string @@ -12151,7 +12188,7 @@ export type PreviewWorkspacePullParams = { workspaceId: string } -export type PreviewWorkspacePullQuery = Record +export type PreviewWorkspacePullQuery = Record export type PreviewWorkspacePullBody = { otherWorkspaceId: string @@ -12301,7 +12338,7 @@ export type PreviewWorkspacePushParams = { workspaceId: string } -export type PreviewWorkspacePushQuery = Record +export type PreviewWorkspacePushQuery = Record export type PreviewWorkspacePushBody = { otherWorkspaceId: string @@ -12451,7 +12488,7 @@ export type PullWorkspaceParams = { workspaceId: string } -export type PullWorkspaceQuery = Record +export type PullWorkspaceQuery = Record export type PullWorkspaceBody = { otherWorkspaceId: string @@ -12563,7 +12600,7 @@ export type PushWorkspaceParams = { workspaceId: string } -export type PushWorkspaceQuery = Record +export type PushWorkspaceQuery = Record export type PushWorkspaceBody = { otherWorkspaceId: string @@ -12678,7 +12715,7 @@ export type PutSourcePermissionImportPartParams = { partNumber: number } -export type PutSourcePermissionImportPartQuery = Record +export type PutSourcePermissionImportPartQuery = Record export type PutSourcePermissionImportPartBody = { field: 'userMapping' | 'projectPermissions' @@ -12696,7 +12733,7 @@ export type QueryRowsParams = { tableId: string } -export type QueryRowsQuery = Record +export type QueryRowsQuery = Record type QueryRowsBodyRef0 = | { @@ -12827,7 +12864,7 @@ export type QueryRowsCountParams = { tableId: string } -export type QueryRowsCountQuery = Record +export type QueryRowsCountQuery = Record type QueryRowsCountBodyRef0 = | { @@ -13007,7 +13044,7 @@ export type ReadProjectFileContentParams = { fileId: string } -export type ReadProjectFileContentQuery = Record +export type ReadProjectFileContentQuery = Record /** Non-JSON response (`binary`). */ export type ReadProjectFileContentResponse = never @@ -13019,13 +13056,13 @@ export type ReadProjectFileVersionContentParams = { version: number } -export type ReadProjectFileVersionContentQuery = Record +export type ReadProjectFileVersionContentQuery = Record /** Non-JSON response (`binary`). */ export type ReadProjectFileVersionContentResponse = never /** `PATCH /api/v2/files/folders` */ -export type RelocateFileFolderQuery = Record +export type RelocateFileFolderQuery = Record type RelocateFileFolderBodyRef0 = string @@ -13050,7 +13087,7 @@ export type RelocateFileFolderResponse = { } /** `PATCH /api/v2/knowledge/folders` */ -export type RelocateKnowledgeFolderQuery = Record +export type RelocateKnowledgeFolderQuery = Record type RelocateKnowledgeFolderBodyRef0 = string @@ -13075,7 +13112,7 @@ export type RelocateKnowledgeFolderResponse = { } /** `PATCH /api/v2/tables/folders` */ -export type RelocateTableFolderQuery = Record +export type RelocateTableFolderQuery = Record type RelocateTableFolderBodyRef0 = string @@ -13100,7 +13137,7 @@ export type RelocateTableFolderResponse = { } /** `PATCH /api/v2/workflows/folders` */ -export type RelocateWorkflowFolderQuery = Record +export type RelocateWorkflowFolderQuery = Record type RelocateWorkflowFolderBodyRef0 = string @@ -13148,7 +13185,7 @@ export type RemoveOrganizationDomainParams = { domainId: string } -export type RemoveOrganizationDomainQuery = Record +export type RemoveOrganizationDomainQuery = Record export type RemoveOrganizationDomainResponse = { data: { @@ -13163,7 +13200,7 @@ export type RemoveOrganizationMemberParams = { userId: string } -export type RemoveOrganizationMemberQuery = Record +export type RemoveOrganizationMemberQuery = Record type RemoveOrganizationMemberResponseRef0 = { userId: string @@ -13181,7 +13218,7 @@ export type RemovePermissionGroupMemberParams = { userId: string } -export type RemovePermissionGroupMemberQuery = Record +export type RemovePermissionGroupMemberQuery = Record type RemovePermissionGroupMemberResponseRef0 = { userId: string @@ -13198,7 +13235,7 @@ export type RemoveWorkspaceMemberParams = { userId: string } -export type RemoveWorkspaceMemberQuery = Record +export type RemoveWorkspaceMemberQuery = Record type RemoveWorkspaceMemberResponseRef0 = { userId: string @@ -13215,7 +13252,7 @@ export type RenameFileParams = { fileId: string } -export type RenameFileQuery = Record +export type RenameFileQuery = Record export type RenameFileBody = { workspaceId: string @@ -13246,7 +13283,7 @@ export type RenameProjectFileParams = { fileId: string } -export type RenameProjectFileQuery = Record +export type RenameProjectFileQuery = Record export type RenameProjectFileBody = { name: string @@ -13280,7 +13317,7 @@ export type ReplaceSearchSourcePermissionsParams = { sourceId: string } -export type ReplaceSearchSourcePermissionsQuery = Record +export type ReplaceSearchSourcePermissionsQuery = Record export type ReplaceSearchSourcePermissionsBody = { expectedRevision: number @@ -13310,7 +13347,7 @@ export type ReplaceWorkflowChatDeploymentParams = { workflowId: string } -export type ReplaceWorkflowChatDeploymentQuery = Record +export type ReplaceWorkflowChatDeploymentQuery = Record type ReplaceWorkflowChatDeploymentBodyRef0 = { primaryColor?: string @@ -13568,9 +13605,9 @@ export type ResendOrganizationInvitationParams = { invitationId: string } -export type ResendOrganizationInvitationQuery = Record +export type ResendOrganizationInvitationQuery = Record -export type ResendOrganizationInvitationBody = Record +export type ResendOrganizationInvitationBody = Record type ResendOrganizationInvitationResponseRef0 = { id: string @@ -13594,7 +13631,7 @@ export type ResolveOrganizationAccessRequestParams = { requestId: string } -export type ResolveOrganizationAccessRequestQuery = Record +export type ResolveOrganizationAccessRequestQuery = Record export type ResolveOrganizationAccessRequestBody = | { @@ -13707,7 +13744,7 @@ export type RestoreFileParams = { fileId: string } -export type RestoreFileQuery = Record +export type RestoreFileQuery = Record export type RestoreFileBody = { workspaceId: string @@ -13732,7 +13769,7 @@ export type RestoreFileResponse = { } /** `POST /api/v2/files/folders/restore` */ -export type RestoreFileFolderQuery = Record +export type RestoreFileFolderQuery = Record type RestoreFileFolderBodyRef0 = string @@ -13766,7 +13803,7 @@ export type RestoreKnowledgeBaseParams = { knowledgeBaseId: string } -export type RestoreKnowledgeBaseQuery = Record +export type RestoreKnowledgeBaseQuery = Record export type RestoreKnowledgeBaseBody = { workspaceId: string @@ -13783,6 +13820,7 @@ type RestoreKnowledgeBaseResponseRef0 = { recipe?: 'plain' | 'markdown' | 'code' strictBoundaries?: boolean } + [key: string]: unknown } type RestoreKnowledgeBaseResponseRef1 = { @@ -13813,9 +13851,9 @@ export type RestoreProjectFileParams = { fileId: string } -export type RestoreProjectFileQuery = Record +export type RestoreProjectFileQuery = Record -export type RestoreProjectFileBody = Record +export type RestoreProjectFileBody = Record type RestoreProjectFileResponseRef0 = { id: string @@ -13845,9 +13883,9 @@ export type RestoreProjectFileFolderParams = { folderId: string } -export type RestoreProjectFileFolderQuery = Record +export type RestoreProjectFileFolderQuery = Record -export type RestoreProjectFileFolderBody = Record +export type RestoreProjectFileFolderBody = Record export type RestoreProjectFileFolderResponse = { data: { @@ -13878,7 +13916,7 @@ export type RestoreTableParams = { tableId: string } -export type RestoreTableQuery = Record +export type RestoreTableQuery = Record export type RestoreTableBody = { workspaceId: string @@ -13933,7 +13971,7 @@ export type RestoreTableResponse = { } /** `POST /api/v2/tables/folders/restore` */ -export type RestoreTableFolderQuery = Record +export type RestoreTableFolderQuery = Record type RestoreTableFolderBodyRef0 = string @@ -13967,7 +14005,7 @@ export type RestoreWorkflowParams = { workflowId: string } -export type RestoreWorkflowQuery = Record +export type RestoreWorkflowQuery = Record type RestoreWorkflowResponseRef0 = { id: string @@ -13994,7 +14032,7 @@ export type ResumeWorkflowParams = { runId: string } -export type ResumeWorkflowQuery = Record +export type ResumeWorkflowQuery = Record export type ResumeWorkflowBody = { contextId: string @@ -14048,7 +14086,7 @@ export type RevertFileVersionParams = { version: number } -export type RevertFileVersionQuery = Record +export type RevertFileVersionQuery = Record export type RevertFileVersionBody = { workspaceId: string @@ -14105,7 +14143,7 @@ export type RevertProjectFileVersionParams = { version: number } -export type RevertProjectFileVersionQuery = Record +export type RevertProjectFileVersionQuery = Record export type RevertProjectFileVersionBody = { expectedCurrentVersion?: number @@ -14164,9 +14202,9 @@ export type RevertWorkflowVersionParams = { workflowId: string } -export type RevertWorkflowVersionQuery = Record +export type RevertWorkflowVersionQuery = Record -export type RevertWorkflowVersionBody = Record +export type RevertWorkflowVersionBody = Record type RevertWorkflowVersionResponseRef0 = { id: string @@ -14184,7 +14222,7 @@ export type RevokeOrganizationInvitationParams = { invitationId: string } -export type RevokeOrganizationInvitationQuery = Record +export type RevokeOrganizationInvitationQuery = Record type RevokeOrganizationInvitationResponseRef0 = { id: string @@ -14219,7 +14257,7 @@ export type RollbackWorkflowParams = { workflowId: string } -export type RollbackWorkflowQuery = Record +export type RollbackWorkflowQuery = Record export type RollbackWorkflowBody = { version?: number @@ -14275,7 +14313,7 @@ export type RollbackWorkspaceForkParams = { workspaceId: string } -export type RollbackWorkspaceForkQuery = Record +export type RollbackWorkspaceForkQuery = Record export type RollbackWorkspaceForkBody = { otherWorkspaceId: string @@ -14300,7 +14338,7 @@ export type RunRowEnrichmentParams = { groupId: string } -export type RunRowEnrichmentQuery = Record +export type RunRowEnrichmentQuery = Record export type RunRowEnrichmentBody = { workspaceId: string @@ -14319,7 +14357,7 @@ export type SaveSsoProviderParams = { organizationId: string } -export type SaveSsoProviderQuery = Record +export type SaveSsoProviderQuery = Record export type SaveSsoProviderBody = | { @@ -14420,7 +14458,7 @@ export type SearchFileContentResponse = { } /** `POST /api/v2/knowledge/search` */ -export type SearchKnowledgeQuery = Record +export type SearchKnowledgeQuery = Record type SearchKnowledgeBodyRef0 = { tagName: string @@ -14532,7 +14570,7 @@ export type SearchTableRowsParams = { tableId: string } -export type SearchTableRowsQuery = Record +export type SearchTableRowsQuery = Record type SearchTableRowsBodyRef0 = | { @@ -14652,9 +14690,9 @@ export type SetPrimarySsoProviderParams = { providerId: string } -export type SetPrimarySsoProviderQuery = Record +export type SetPrimarySsoProviderQuery = Record -export type SetPrimarySsoProviderBody = Record +export type SetPrimarySsoProviderBody = Record export type SetPrimarySsoProviderResponse = { data: { @@ -14668,7 +14706,7 @@ export type SetSecretParams = { name: string } -export type SetSecretQuery = Record +export type SetSecretQuery = Record export type SetSecretBody = { workspaceId: string @@ -14698,7 +14736,7 @@ export type SyncKnowledgeConnectorParams = { knowledgeBaseId: string } -export type SyncKnowledgeConnectorQuery = Record +export type SyncKnowledgeConnectorQuery = Record export type SyncKnowledgeConnectorBody = { workspaceId: string @@ -14739,7 +14777,7 @@ export type UndeployWorkflowParams = { workflowId: string } -export type UndeployWorkflowQuery = Record +export type UndeployWorkflowQuery = Record type UndeployWorkflowResponseRef0 = { deploymentVersionId: string @@ -14797,7 +14835,7 @@ export type UndeployWorkflowMcpToolParams = { workflowId: string } -export type UndeployWorkflowMcpToolQuery = Record +export type UndeployWorkflowMcpToolQuery = Record type UndeployWorkflowMcpToolResponseRef0 = { id: string @@ -14815,7 +14853,7 @@ export type UnlinkWorkspaceForkParams = { workspaceId: string } -export type UnlinkWorkspaceForkQuery = Record +export type UnlinkWorkspaceForkQuery = Record export type UnlinkWorkspaceForkBody = { otherWorkspaceId: string @@ -14834,7 +14872,7 @@ export type UnzipFileParams = { fileId: string } -export type UnzipFileQuery = Record +export type UnzipFileQuery = Record export type UnzipFileBody = { workspaceId: string @@ -14856,7 +14894,7 @@ export type UnzipProjectFileParams = { fileId: string } -export type UnzipProjectFileQuery = Record +export type UnzipProjectFileQuery = Record type UnzipProjectFileResponseRef0 = UnzipProjectFileResponseRef1 @@ -14927,7 +14965,7 @@ export type UpdateCustomToolParams = { customToolId: string } -export type UpdateCustomToolQuery = Record +export type UpdateCustomToolQuery = Record export type UpdateCustomToolBody = { workspaceId: string @@ -14941,8 +14979,11 @@ export type UpdateCustomToolBody = { type: string properties: Record required?: Array + [key: string]: unknown } + [key: string]: unknown } + [key: string]: unknown } code?: string } @@ -14959,8 +15000,11 @@ type UpdateCustomToolResponseRef0 = { type: string properties: Record required?: Array + [key: string]: unknown } + [key: string]: unknown } + [key: string]: unknown } code: string createdAt: string @@ -14976,7 +15020,7 @@ export type UpdateFileContentParams = { fileId: string } -export type UpdateFileContentQuery = Record +export type UpdateFileContentQuery = Record export type UpdateFileContentBody = { workspaceId: string @@ -15009,7 +15053,7 @@ export type UpdateKnowledgeBaseParams = { knowledgeBaseId: string } -export type UpdateKnowledgeBaseQuery = Record +export type UpdateKnowledgeBaseQuery = Record type UpdateKnowledgeBaseBodyRef0 = { maxSize?: number @@ -15045,6 +15089,7 @@ type UpdateKnowledgeBaseResponseRef0 = { recipe?: 'plain' | 'markdown' | 'code' strictBoundaries?: boolean } + [key: string]: unknown } type UpdateKnowledgeBaseResponseRef1 = { @@ -15076,7 +15121,7 @@ export type UpdateKnowledgeChunkParams = { knowledgeBaseId: string } -export type UpdateKnowledgeChunkQuery = Record +export type UpdateKnowledgeChunkQuery = Record export type UpdateKnowledgeChunkBody = { workspaceId: string @@ -15114,7 +15159,7 @@ export type UpdateKnowledgeConnectorParams = { knowledgeBaseId: string } -export type UpdateKnowledgeConnectorQuery = Record +export type UpdateKnowledgeConnectorQuery = Record export type UpdateKnowledgeConnectorBody = { workspaceId: string @@ -15151,7 +15196,7 @@ export type UpdateKnowledgeConnectorDocumentsParams = { knowledgeBaseId: string } -export type UpdateKnowledgeConnectorDocumentsQuery = Record +export type UpdateKnowledgeConnectorDocumentsQuery = Record export type UpdateKnowledgeConnectorDocumentsBody = { workspaceId: string @@ -15175,7 +15220,7 @@ export type UpdateKnowledgeDocumentParams = { knowledgeBaseId: string } -export type UpdateKnowledgeDocumentQuery = Record +export type UpdateKnowledgeDocumentQuery = Record export type UpdateKnowledgeDocumentBody = { workspaceId: string @@ -15233,7 +15278,7 @@ export type UpdateKnowledgeTagParams = { knowledgeBaseId: string } -export type UpdateKnowledgeTagQuery = Record +export type UpdateKnowledgeTagQuery = Record export type UpdateKnowledgeTagBody = { workspaceId: string @@ -15257,7 +15302,7 @@ export type UpdateMcpServerParams = { mcpServerId: string } -export type UpdateMcpServerQuery = Record +export type UpdateMcpServerQuery = Record export type UpdateMcpServerBody = { workspaceId: string @@ -15306,7 +15351,7 @@ export type UpdateOrganizationAccessRequestSettingsParams = { organizationId: string } -export type UpdateOrganizationAccessRequestSettingsQuery = Record +export type UpdateOrganizationAccessRequestSettingsQuery = Record export type UpdateOrganizationAccessRequestSettingsBody = { allowRequests: boolean @@ -15326,7 +15371,7 @@ export type UpdateOrganizationMemberParams = { userId: string } -export type UpdateOrganizationMemberQuery = Record +export type UpdateOrganizationMemberQuery = Record export type UpdateOrganizationMemberBody = { role: 'member' | 'admin' @@ -15350,7 +15395,7 @@ export type UpdateOrganizationMemberUsageLimitParams = { userId: string } -export type UpdateOrganizationMemberUsageLimitQuery = Record +export type UpdateOrganizationMemberUsageLimitQuery = Record export type UpdateOrganizationMemberUsageLimitBody = { creditLimit: number | null @@ -15370,7 +15415,7 @@ export type UpdatePermissionGroupParams = { groupId: string } -export type UpdatePermissionGroupQuery = Record +export type UpdatePermissionGroupQuery = Record export type UpdatePermissionGroupBody = { name?: string @@ -15498,7 +15543,7 @@ export type UpdateProjectFileContentParams = { fileId: string } -export type UpdateProjectFileContentQuery = Record +export type UpdateProjectFileContentQuery = Record export type UpdateProjectFileContentBody = { content: string @@ -15534,7 +15579,7 @@ export type UpdateProjectFileFolderParams = { folderId: string } -export type UpdateProjectFileFolderQuery = Record +export type UpdateProjectFileFolderQuery = Record export type UpdateProjectFileFolderBody = { name?: string @@ -15566,7 +15611,7 @@ export type UpdateProjectFileShareParams = { fileId: string } -export type UpdateProjectFileShareQuery = Record +export type UpdateProjectFileShareQuery = Record export type UpdateProjectFileShareBody = { isActive: boolean @@ -15596,7 +15641,7 @@ export type UpdateRowsByFilterParams = { tableId: string } -export type UpdateRowsByFilterQuery = Record +export type UpdateRowsByFilterQuery = Record type UpdateRowsByFilterBodyRef0 = | { @@ -15708,7 +15753,7 @@ export type UpdateSandboxParams = { sandboxId: string } -export type UpdateSandboxQuery = Record +export type UpdateSandboxQuery = Record export type UpdateSandboxBody = { workspaceId: string @@ -15795,7 +15840,7 @@ export type UpdateSearchSourceParams = { sourceId: string } -export type UpdateSearchSourceQuery = Record +export type UpdateSearchSourceQuery = Record export type UpdateSearchSourceBody = { apiKey?: string @@ -15850,7 +15895,7 @@ export type UpdateSkillParams = { skillId: string } -export type UpdateSkillQuery = Record +export type UpdateSkillQuery = Record export type UpdateSkillBody = { workspaceId: string @@ -15878,7 +15923,7 @@ export type UpdateSsoPolicyParams = { organizationId: string } -export type UpdateSsoPolicyQuery = Record +export type UpdateSsoPolicyQuery = Record export type UpdateSsoPolicyBody = { requireSso: boolean @@ -15897,7 +15942,7 @@ export type UpdateTableParams = { tableId: string } -export type UpdateTableQuery = Record +export type UpdateTableQuery = Record type UpdateTableBodyRef0 = string @@ -15961,7 +16006,7 @@ export type UpdateTableColumnParams = { tableId: string } -export type UpdateTableColumnQuery = Record +export type UpdateTableColumnQuery = Record export type UpdateTableColumnBody = { workspaceId: string @@ -16016,7 +16061,7 @@ export type UpdateTableRowParams = { rowId: string } -export type UpdateTableRowQuery = Record +export type UpdateTableRowQuery = Record type UpdateTableRowBodyRef0 = Record @@ -16055,7 +16100,7 @@ export type UpdateTableViewParams = { viewId: string } -export type UpdateTableViewQuery = Record +export type UpdateTableViewQuery = Record type UpdateTableViewBodyRef0 = | { @@ -16204,7 +16249,7 @@ export type UpdateWorkflowParams = { workflowId: string } -export type UpdateWorkflowQuery = Record +export type UpdateWorkflowQuery = Record type UpdateWorkflowBodyRef0 = string @@ -16238,7 +16283,7 @@ export type UpdateWorkflowGroupParams = { tableId: string } -export type UpdateWorkflowGroupQuery = Record +export type UpdateWorkflowGroupQuery = Record export type UpdateWorkflowGroupBody = { workspaceId: string @@ -16324,7 +16369,7 @@ export type UpdateWorkflowMcpServerParams = { serverId: string } -export type UpdateWorkflowMcpServerQuery = Record +export type UpdateWorkflowMcpServerQuery = Record export type UpdateWorkflowMcpServerBody = { name?: string @@ -16351,7 +16396,7 @@ export type UpdateWorkflowPublicApiParams = { workflowId: string } -export type UpdateWorkflowPublicApiQuery = Record +export type UpdateWorkflowPublicApiQuery = Record export type UpdateWorkflowPublicApiBody = { isPublicApi: boolean @@ -16372,7 +16417,7 @@ export type UpdateWorkflowTriggerParams = { blockId: string } -export type UpdateWorkflowTriggerQuery = Record +export type UpdateWorkflowTriggerQuery = Record export type UpdateWorkflowTriggerBody = { enabled: boolean @@ -16403,7 +16448,7 @@ export type UpdateWorkflowVersionParams = { workflowId: string } -export type UpdateWorkflowVersionQuery = Record +export type UpdateWorkflowVersionQuery = Record export type UpdateWorkflowVersionBody = { name?: string @@ -16425,7 +16470,7 @@ export type UpdateWorkspaceParams = { workspaceId: string } -export type UpdateWorkspaceQuery = Record +export type UpdateWorkspaceQuery = Record export type UpdateWorkspaceBody = { name?: string @@ -16451,7 +16496,7 @@ export type UpdateWorkspaceForkExclusionsParams = { workspaceId: string } -export type UpdateWorkspaceForkExclusionsQuery = Record +export type UpdateWorkspaceForkExclusionsQuery = Record export type UpdateWorkspaceForkExclusionsBody = { workflowIds: Array @@ -16471,7 +16516,7 @@ export type UpdateWorkspaceForkMappingsParams = { workspaceId: string } -export type UpdateWorkspaceForkMappingsQuery = Record +export type UpdateWorkspaceForkMappingsQuery = Record export type UpdateWorkspaceForkMappingsBody = { otherWorkspaceId: string @@ -16509,7 +16554,7 @@ export type UpdateWorkspaceMemberParams = { userId: string } -export type UpdateWorkspaceMemberQuery = Record +export type UpdateWorkspaceMemberQuery = Record export type UpdateWorkspaceMemberBody = { role: 'admin' | 'write' | 'read' @@ -16583,7 +16628,7 @@ export type UpsertFileShareParams = { fileId: string } -export type UpsertFileShareQuery = Record +export type UpsertFileShareQuery = Record export type UpsertFileShareBody = { workspaceId: string @@ -16614,7 +16659,7 @@ export type UpsertTableRowParams = { tableId: string } -export type UpsertTableRowQuery = Record +export type UpsertTableRowQuery = Record type UpsertTableRowBodyRef0 = Record @@ -16659,9 +16704,9 @@ export type VerifyOrganizationDomainParams = { domainId: string } -export type VerifyOrganizationDomainQuery = Record +export type VerifyOrganizationDomainQuery = Record -export type VerifyOrganizationDomainBody = Record +export type VerifyOrganizationDomainBody = Record export type VerifyOrganizationDomainResponse = { data: { diff --git a/scripts/check-utils-enforcement.ts b/scripts/check-utils-enforcement.ts index 514db36df08..b2c1bb82b51 100644 --- a/scripts/check-utils-enforcement.ts +++ b/scripts/check-utils-enforcement.ts @@ -42,6 +42,8 @@ const ALLOWLISTED_FILES = new Set([ 'apps/sim/lib/execution/isolated-vm-worker.cjs', // Emits the sandbox-side event filter as plain JS source, which cannot import @sim/utils 'apps/sim/executor/handlers/pi/cloud/event-filter-source.ts', + // Emits the code-mode isolate bootstrap as plain JS source, which cannot import @sim/utils + 'apps/sim/sandboxes/sim-api-code.ts', ]) /** `s.slice(0, n)` plus a suffix, by `+` or in a template literal; `\1` is `s` and `\2` is `n`. */ diff --git a/scripts/generate-v2-cli-api.ts b/scripts/generate-v2-cli-api.ts index c8c6d7f8654..e01fa9f5c25 100644 --- a/scripts/generate-v2-cli-api.ts +++ b/scripts/generate-v2-cli-api.ts @@ -31,6 +31,7 @@ import { readdirSync, readFileSync, writeFileSync } from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' import { z } from 'zod' +import { pascal, schemaToTypeScript } from '../apps/sim/lib/api/contracts/typescript' const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') const CONTRACTS_DIR = path.join(ROOT, 'apps/sim/lib/api/contracts/v2') @@ -232,10 +233,6 @@ function operationName(exportName: string): string { return stripped.charAt(0).toLowerCase() + stripped.slice(1) } -function pascal(name: string): string { - return name.charAt(0).toUpperCase() + name.slice(1) -} - /** Every v2 route contract, sorted by operation name. */ export async function collectOperations(): Promise { const operations: Operation[] = [] @@ -255,116 +252,6 @@ export async function collectOperations(): Promise { type JsonSchema = Record -/** - * Emits a TypeScript type for the subset of JSON Schema that `z.toJSONSchema` - * produces from these contracts. - * - * 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 committed and read by humans, so controlling the formatting is - * worth more here 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 TypeScript alias hoisted for it. Zod factors - * a schema out into `$defs` when it is recursive, which the table view's filter - * grammar is — a predicate holds predicates — so it cannot be inlined. - */ -function toTypeScript(schema: JsonSchema, indent = 0, refs?: Map): string { - if (typeof schema.$ref === 'string') { - const key = schema.$ref.replace('#/$defs/', '') - const name = refs?.get(key) - 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 (schema.enum) return schema.enum.map((v: unknown) => JSON.stringify(v)).join(' | ') - - const variants = schema.anyOf ?? schema.oneOf - if (variants) { - return variants.map((v: JsonSchema) => toTypeScript(v, indent, refs)).join(' | ') - } - - if (schema.allOf) { - return schema.allOf.map((v: JsonSchema) => toTypeScript(v, indent, refs)).join(' & ') - } - - switch (schema.type) { - case 'string': - return 'string' - case 'number': - case 'integer': - return 'number' - case 'boolean': - return 'boolean' - case 'null': - return 'null' - case 'array': - return schema.items ? `Array<${toTypeScript(schema.items, indent, refs)}>` : 'unknown[]' - case 'object': { - const properties: Record = schema.properties ?? {} - const required: string[] = schema.required ?? [] - const keys = Object.keys(properties) - - if (keys.length === 0) { - // A bare object with only `additionalProperties` is a record. - const value = - schema.additionalProperties && typeof schema.additionalProperties === 'object' - ? toTypeScript(schema.additionalProperties, indent, refs) - : 'unknown' - return `Record` - } - - const lines = keys.map((key) => { - const optional = required.includes(key) ? '' : '?' - const safeKey = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : JSON.stringify(key) - return `${pad}${safeKey}${optional}: ${toTypeScript(properties[key], indent + 1, refs)}` - }) - return `{\n${lines.join('\n')}\n${closePad}}` - } - } - - // `z.unknown()` / `z.any()` render as a schema carrying no constraints. A - // `.describe()` on one adds annotation keys without narrowing the type, so - // those are not constraints either. - const ANNOTATION_KEYS = new Set(['$schema', 'description', 'title', 'default', 'examples']) - if (Object.keys(schema).every((k) => ANNOTATION_KEYS.has(k))) return 'unknown' - - throw new Error(`Unhandled JSON Schema construct: ${JSON.stringify(schema).slice(0, 200)}`) -} - -/** - * A type plus any aliases that must be declared before it. - * - * A recursive schema cannot be written inline, so Zod lifts it into `$defs` and - * points at it; those become real named types, which TypeScript resolves - * recursively without complaint. - */ -interface GeneratedType { - type: string - declarations: string[] -} - -function schemaToType(schema: z.ZodType, io: 'input' | 'output', name: string): GeneratedType { - const json = z.toJSONSchema(schema, { io, unrepresentable: 'any' }) as JsonSchema - const defs = json.$defs as Record | undefined - if (!defs) return { type: toTypeScript(json), declarations: [] } - - // Named after the type that owns them, so two operations lifting their own - // `__schema0` cannot collide in the single generated module. - 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)} = ${toTypeScript(def, 0, refs)}\n` - ) - - const { $defs, ...root } = json - return { type: toTypeScript(root, 0, refs), declarations } -} - /** Path params the CLI must substitute, e.g. `/api/v2/workflows/[id]` → `['id']`. */ function pathParams(routePath: string): string[] { return [...routePath.matchAll(/\[([^\]]+)\]/g)].map((m) => m[1]) @@ -673,14 +560,14 @@ export function render(operations: Operation[], docs: Map) const schema = contract[slot] if (!schema) continue const slotName = `${Name}${pascal(slot)}` - const generated = schemaToType(schema, 'input', slotName) + const generated = schemaToTypeScript(schema, 'input', slotName) out.push(...generated.declarations) out.push(`export type ${slotName} = ${generated.type}`) out.push('') } if (contract.response.mode === 'json' && contract.response.schema) { - const generated = schemaToType(contract.response.schema, 'output', `${Name}Response`) + const generated = schemaToTypeScript(contract.response.schema, 'output', `${Name}Response`) out.push(...generated.declarations) out.push(`export type ${Name}Response = ${generated.type}`) } else {