Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

create-snippet-management-tools.ts

298 lines10.0 KB

1import { toolDefinition } from '@tanstack/ai'
2import { toolsToBindings } from '@tanstack/ai-code-mode'
3import { z } from 'zod'
4import { createDefaultTrustStrategy } from './trust-strategies'
5import { snippetToTool } from './snippets-to-tools'
6import type { SchemaInput, ServerTool, ToolRegistry } from '@tanstack/ai'
7import type { CodeModeToolConfig, ToolBinding } from '@tanstack/ai-code-mode'
8import type { SnippetStorage } from './types'
9import type { TrustStrategy } from './trust-strategies'
10​
11interface CreateSnippetManagementToolsOptions {
12 /**
13 * Storage implementation for snippets
14 */
15 storage: SnippetStorage
16​
17 /**
18 * Trust strategy for determining initial trust level.
19 * If not provided, uses the storage's trustStrategy or falls back to default.
20 */
21 trustStrategy?: TrustStrategy
22​
23 /**
24 * Tool registry for adding newly registered snippets immediately.
25 * When provided, register_snippet will add the new snippet to this registry
26 * so it's available as a direct tool in the current chat session.
27 */
28 registry?: ToolRegistry
29​
30 /**
31 * Code mode config for creating snippet tools.
32 * Required when registry is provided.
33 */
34 config?: CodeModeToolConfig
35​
36 /**
37 * Pre-computed bindings for external_* functions.
38 * Required when registry is provided.
39 */
40 baseBindings?: Record<string, ToolBinding>
42​
43/**
44 * Create tools for searching, retrieving, and registering snippets.
45 * These tools allow the LLM to interact with the snippet library at runtime.
46 *
47 * When registry, config, and baseBindings are provided, newly registered snippets
48 * will be immediately added to the registry and available as direct tools.
49 */
50export function createSnippetManagementTools({
51 storage,
52 trustStrategy,
53 registry,
54 config,
55 baseBindings,
56}: CreateSnippetManagementToolsOptions): Array<
57 ServerTool<SchemaInput, SchemaInput, string>
58> {
59 // Use provided strategy, or storage's strategy, or default
60 const strategy =
61 trustStrategy ?? storage.trustStrategy ?? createDefaultTrustStrategy()
62​
63 // Compute bindings if not provided but config is available
64 const bindings =
65 baseBindings ?? (config ? toolsToBindings(config.tools, 'external_') : {})
66 return [
67 // Search for snippets
68 toolDefinition({
69 name: 'search_snippets',
70 description:
71 'Search the snippet library for reusable snippets. Use this to find snippets that can help accomplish a task. Returns matching snippets with their descriptions.',
72 inputSchema: z.object({
73 query: z
74 .string()
75 .describe('Search query describing what you want to accomplish'),
76 limit: z
77 .number()
78 .optional()
79 .default(5)
80 .describe('Maximum number of results (default: 5)'),
81 }),
82 outputSchema: z.array(
83 z.object({
84 name: z.string(),
85 description: z.string(),
86 usageHints: z.array(z.string()),
87 trustLevel: z.enum(['untrusted', 'provisional', 'trusted']),
88 }),
89 ),
90 }).server(async ({ query, limit }) => {
91 const results = await storage.search(query, { limit: limit ?? 5 })
92 return results.map((s) => ({
93 name: s.name,
94 description: s.description,
95 usageHints: s.usageHints,
96 trustLevel: s.trustLevel,
97 }))
98 }),
99​
100 // Get full snippet details
101 toolDefinition({
102 name: 'get_snippet',
103 description:
104 'Get the full implementation details of a snippet, including its code. Use this after search_snippets to see how a snippet works before using it.',
105 inputSchema: z.object({
106 name: z.string().describe('The snippet name (without snippet_ prefix)'),
107 }),
108 outputSchema: z.object({
109 name: z.string().optional(),
110 description: z.string().optional(),
111 code: z.string().optional(),
112 inputSchema: z.string().optional().describe('JSON Schema as string'),
113 outputSchema: z.string().optional().describe('JSON Schema as string'),
114 usageHints: z.array(z.string()).optional(),
115 dependsOn: z.array(z.string()).optional(),
116 trustLevel: z.enum(['untrusted', 'provisional', 'trusted']).optional(),
117 stats: z
118 .object({
119 executions: z.number(),
120 successRate: z.number(),
121 })
122 .optional(),
123 error: z.string().optional(),
124 }),
125 }).server(async ({ name }) => {
126 const snippet = await storage.get(name)
127 if (!snippet) {
128 return { error: `Snippet '${name}' not found` }
129 }
130 return {
131 name: snippet.name,
132 description: snippet.description,
133 code: snippet.code,
134 inputSchema: JSON.stringify(snippet.inputSchema),
135 outputSchema: JSON.stringify(snippet.outputSchema),
136 usageHints: snippet.usageHints,
137 dependsOn: snippet.dependsOn,
138 trustLevel: snippet.trustLevel,
139 stats: snippet.stats,
140 }
141 }),
142​
143 // Register a new snippet
144 toolDefinition({
145 name: 'register_snippet',
146 description:
147 'Save working TypeScript code as a reusable snippet for future use. Only register code that has been tested and works correctly. The snippet becomes available as a callable tool immediately.',
148 inputSchema: z.object({
149 name: z
150 .string()
151 .regex(
152 /^[a-z][a-z0-9_]*$/,
153 'Must be snake_case starting with a letter',
154 )
155 .describe(
156 'Unique snippet name in snake_case (e.g., fetch_github_stats)',
157 ),
158 description: z
159 .string()
160 .describe('Clear description of what the snippet does'),
161 code: z
162 .string()
163 .describe(
164 'The TypeScript code. Receives `input` variable, can call external_* and snippet_* functions, should return a value.',
165 ),
166 inputSchema: z
167 .string()
168 .describe(
169 'JSON Schema as a JSON string describing the input parameter, e.g. {"type":"object","properties":{"a":{"type":"number"}},"required":["a"]}',
170 ),
171 outputSchema: z
172 .string()
173 .describe(
174 'JSON Schema as a JSON string describing the return value, e.g. {"type":"object","properties":{"result":{"type":"number"}}}',
175 ),
176 usageHints: z
177 .array(z.string())
178 .describe(
179 'Hints about when to use this snippet, e.g. "Use when user asks about..."',
180 ),
181 dependsOn: z
182 .array(z.string())
183 .optional()
184 .default([])
185 .describe('Names of other snippets this snippet calls'),
186 }),
187 outputSchema: z.object({
188 success: z.boolean().optional(),
189 snippetId: z.string().optional(),
190 name: z.string().optional(),
191 message: z.string().optional(),
192 error: z.string().optional(),
193 }),
194 }).server(async (rawSnippetDef, context) => {
195 // Parse the JSON string schemas
196 let inputSchema: Record<string, unknown>
197 let outputSchema: Record<string, unknown>
198 try {
199 inputSchema = JSON.parse(rawSnippetDef.inputSchema) as Record<
200 string,
201 unknown
202 >
203 } catch {
204 return { error: 'inputSchema must be a valid JSON string' }
205 }
206 try {
207 outputSchema = JSON.parse(rawSnippetDef.outputSchema) as Record<
208 string,
209 unknown
210 >
211 } catch {
212 return { error: 'outputSchema must be a valid JSON string' }
213 }
214​
215 const snippetDef = {
216 ...rawSnippetDef,
217 inputSchema,
218 outputSchema,
219 }
220 try {
221 // Validate the snippet name isn't reserved
222 if (snippetDef.name.startsWith('external_')) {
223 return { error: "Snippet names cannot start with 'external_'" }
224 }
225 if (snippetDef.name.startsWith('snippet_')) {
226 return {
227 error:
228 "Snippet names should not include the 'snippet_' prefix - it will be added automatically",
229 }
230 }
231​
232 // Check if snippet already exists
233 const existing = await storage.get(snippetDef.name)
234 if (existing) {
235 return {
236 error: `Snippet '${snippetDef.name}' already exists. Use a different name or update the existing snippet.`,
237 }
238 }
239​
240 // Generate a unique ID
241 const id = crypto.randomUUID()
242​
243 // Get initial trust level from strategy
244 const initialTrustLevel = strategy.getInitialTrustLevel()
245​
246 // Save the snippet
247 const snippet = await storage.save({
248 id,
249 name: snippetDef.name,
250 description: snippetDef.description,
251 code: snippetDef.code,
252 inputSchema: snippetDef.inputSchema,
253 outputSchema: snippetDef.outputSchema,
254 usageHints: snippetDef.usageHints,
255 dependsOn: snippetDef.dependsOn ?? [],
256 trustLevel: initialTrustLevel,
257 stats: { executions: 0, successRate: 0 },
258 })
259​
260 // If registry and config are available, add the snippet as a tool immediately
261 if (registry && config) {
262 const snippetTool = snippetToTool({
263 snippet,
264 driver: config.driver,
265 bindings,
266 storage,
267 timeout: config.timeout,
268 memoryLimit: config.memoryLimit,
269 })
270 registry.add(snippetTool)
271 console.log(
272 `[register_snippet] Added snippet '${snippet.name}' to registry immediately`,
273 )
274 }
275​
276 // Emit event for UI notification
277 context?.emitCustomEvent('snippet:registered', {
278 id: snippet.id,
279 name: snippet.name,
280 description: snippet.description,
281 timestamp: Date.now(),
282 })
283​
284 return {
285 success: true,
286 snippetId: snippet.id,
287 name: snippet.name,
288 message: `Snippet '${snippet.name}' registered successfully and is now available as the '${snippet.name}' tool.`,
289 }
290 } catch (error) {
291 console.error('[register_snippet] Error:', error)
292 return {
293 error: `Failed to register snippet: ${error instanceof Error ? error.message : String(error)}`,
294 }
295 }
296 }),
297 ]