Open History to see the last commit
1import { z } from 'zod'
2import { renderLazyCatalogEntry, toolDefinition } from '@tanstack/ai'
3import { toolToBinding } from './bindings/tool-to-binding'
4import { generateTypeStubs } from './type-generator/json-schema-to-ts'
5import type { LazyToolsConfig, ServerTool } from '@tanstack/ai'
6import type { CodeModeTool } from './types'
7
8const discoverInputSchema = z.object({
9 toolNames: z
10 .array(z.string())
11 .describe(
12 'Names of tools to discover, exactly as shown in the Discoverable APIs ' +
13 'catalog. The external_ prefix is optional — both "external_fetchStocks" ' +
14 'and "fetchStocks" resolve.',
15 ),
16})
17
18const discoverOutputSchema = z.object({
19 tools: z.array(
20 z.object({
21 name: z
22 .string()
23 .describe('The sandbox function name, e.g. external_fetchStocks'),
24 description: z.string(),
25 typeStub: z.string().describe('TypeScript declaration for the function'),
26 }),
27 ),
28 errors: z.array(z.string()).optional(),
29})
30
31const EXTERNAL_PREFIX = 'external_'
32
33/**
34 * Strip a single leading `external_` prefix so the model can pass either the
35 * catalog name (`external_fetchStocks`) or the bare name (`fetchStocks`).
36 */
37function stripExternalPrefix(name: string): string {
38 return name.startsWith(EXTERNAL_PREFIX)
39 ? name.slice(EXTERNAL_PREFIX.length)
40 : name
41}
42
43/**
44 * Build the `discover_tools` sibling tool for Code Mode lazy tools. The model
45 * calls it with lazy tool names and receives each one's TypeScript type stub +
46 * description, which it can then use to write correctly-typed `external_*`
47 * calls inside `execute_typescript`. The bindings themselves are always present
48 * in the sandbox — this only reveals documentation.
49 *
50 * Tools are catalogued in `external_<name>` form to match the "Discoverable
51 * APIs" section of the Code Mode system prompt; lookups tolerate either form.
52 * `lazyToolsConfig.includeDescription` controls how much of each tool's
53 * description appears in this tool's own catalog (mirroring the system prompt).
54 */
55export function createDiscoveryTool(
56 lazyTools: Array<CodeModeTool>,
57 lazyToolsConfig?: LazyToolsConfig,
58): ServerTool<
59 typeof discoverInputSchema,
60 typeof discoverOutputSchema,
61 'discover_tools'
62> {
63 const lazyMap = new Map(lazyTools.map((t) => [t.name, t]))
64 const include = lazyToolsConfig?.includeDescription ?? 'none'
65 const catalog = lazyTools
66 .map((t) =>
67 renderLazyCatalogEntry(
68 `${EXTERNAL_PREFIX}${t.name}`,
69 t.description,
70 include,
71 ),
72 )
73 .join(', ')
74
75 return toolDefinition({
76 name: 'discover_tools' as const,
77 description:
78 `Discover full TypeScript signatures for additional sandbox APIs before ` +
79 `using them inside execute_typescript. Discoverable tools: [${catalog}]. ` +
80 `Pass the names exactly as shown (the external_ prefix is optional).`,
81 inputSchema: discoverInputSchema,
82 outputSchema: discoverOutputSchema,
83 }).server(async ({ toolNames }) => {
84 const tools: Array<{
85 name: string
86 description: string
87 typeStub: string
88 }> = []
89 const errors: Array<string> = []
90
91 for (const name of toolNames) {
92 const tool = lazyMap.get(stripExternalPrefix(name))
93 if (!tool) {
94 errors.push(`Unknown tool: '${name}'. Discoverable tools: [${catalog}]`)
95 continue
96 }
97 const binding = toolToBinding(tool, EXTERNAL_PREFIX)
98 const typeStub = generateTypeStubs({ [binding.name]: binding })
99 tools.push({
100 name: binding.name,
101 description: tool.description,
102 typeStub,
103 })
104 }
105
106 return errors.length > 0 ? { tools, errors } : { tools }
107 })
108}