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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/codemode-validate-tool-args.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@cloudflare/codemode": patch
---

Validate tool arguments against Zod schema before execution in codemode sandbox
26 changes: 23 additions & 3 deletions packages/codemode/src/tool.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { tool, type Tool } from "ai";
import { tool, type Tool, asSchema } from "ai";
import { z } from "zod";
import type { ToolSet } from "ai";
import * as acorn from "acorn";
Expand Down Expand Up @@ -98,7 +98,9 @@ export function createCodeTool(
description,
inputSchema: codeSchema,
execute: async ({ code }) => {
// Extract execute functions from tools, keyed by name
// Extract execute functions from tools, keyed by name.
// Wrap each with its schema so arguments from the sandbox
// are validated before reaching the tool function.
const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};

for (const [name, t] of Object.entries(tools)) {
Expand All @@ -107,7 +109,25 @@ export function createCodeTool(
? (t.execute as (args: unknown) => Promise<unknown>)
: undefined;
if (execute) {
fns[sanitizeToolName(name)] = execute;
const rawSchema =
"inputSchema" in t
? t.inputSchema
: "parameters" in t
? (t as Record<string, unknown>).parameters
: undefined;

// Use AI SDK's asSchema() to normalize any schema type
// (Zod v3/v4, Standard Schema, JSON Schema) into a unified
// Schema with an optional .validate() method.
const schema = rawSchema != null ? asSchema(rawSchema) : undefined;

fns[sanitizeToolName(name)] = schema?.validate
? async (args: unknown) => {
const result = await schema.validate!(args);
if (!result.success) throw result.error;
return execute(result.value);
}
: execute;
}
}

Expand Down
Loading