UNPKG

@tanstack/ai-code-mode

Version:

Secure TypeScript Code Mode for TanStack AI agents to execute sandboxed tool orchestration programs.

63 lines (62 loc) 2.41 kB
import { z } from "zod"; import { renderLazyCatalogEntry, toolDefinition } from "@tanstack/ai"; import { toolToBinding } from "./bindings/tool-to-binding.js"; import { generateTypeStubs } from "./type-generator/json-schema-to-ts.js"; const discoverInputSchema = z.object({ toolNames: z.array(z.string()).describe( 'Names of tools to discover, exactly as shown in the Discoverable APIs catalog. The external_ prefix is optional — both "external_fetchStocks" and "fetchStocks" resolve.' ) }); const discoverOutputSchema = z.object({ tools: z.array( z.object({ name: z.string().describe("The sandbox function name, e.g. external_fetchStocks"), description: z.string(), typeStub: z.string().describe("TypeScript declaration for the function") }) ), errors: z.array(z.string()).optional() }); const EXTERNAL_PREFIX = "external_"; function stripExternalPrefix(name) { return name.startsWith(EXTERNAL_PREFIX) ? name.slice(EXTERNAL_PREFIX.length) : name; } function createDiscoveryTool(lazyTools, lazyToolsConfig) { const lazyMap = new Map(lazyTools.map((t) => [t.name, t])); const include = lazyToolsConfig?.includeDescription ?? "none"; const catalog = lazyTools.map( (t) => renderLazyCatalogEntry( `${EXTERNAL_PREFIX}${t.name}`, t.description, include ) ).join(", "); return toolDefinition({ name: "discover_tools", description: `Discover full TypeScript signatures for additional sandbox APIs before using them inside execute_typescript. Discoverable tools: [${catalog}]. Pass the names exactly as shown (the external_ prefix is optional).`, inputSchema: discoverInputSchema, outputSchema: discoverOutputSchema }).server(async ({ toolNames }) => { const tools = []; const errors = []; for (const name of toolNames) { const tool = lazyMap.get(stripExternalPrefix(name)); if (!tool) { errors.push(`Unknown tool: '${name}'. Discoverable tools: [${catalog}]`); continue; } const binding = toolToBinding(tool, EXTERNAL_PREFIX); const typeStub = generateTypeStubs({ [binding.name]: binding }); tools.push({ name: binding.name, description: tool.description, typeStub }); } return errors.length > 0 ? { tools, errors } : { tools }; }); } export { createDiscoveryTool }; //# sourceMappingURL=create-discovery-tool.js.map