| 25 | } |
| 26 | |
| 27 | export function createSqlToolDefinition(def: SqlToolDef): ToolDefinition { |
| 28 | return { |
| 29 | name: def.name, |
| 30 | description: def.description, |
| 31 | inputSchema: def.parameters, |
| 32 | category: 'analysis', |
| 33 | handler: async (params: Record<string, unknown>, context: ToolExecutionContext): Promise<ToolResult> => { |
| 34 | const rows = await context.dataProvider!.executeParameterizedSql(def.execution.query, params) |
| 35 | |
| 36 | const fallback = resolveTemplate(def.name, 'fallback', def.execution.fallback, context.translateTemplate) |
| 37 | |
| 38 | if (!rows || rows.length === 0) { |
| 39 | return { |
| 40 | content: fallback, |
| 41 | data: { rows: [], rowCount: 0 }, |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | const rowTemplate = resolveTemplate(def.name, 'rowTemplate', def.execution.rowTemplate, context.translateTemplate) |
| 46 | const summaryTemplate = def.execution.summaryTemplate |
| 47 | ? resolveTemplate(def.name, 'summaryTemplate', def.execution.summaryTemplate, context.translateTemplate) |
| 48 | : undefined |
| 49 | |
| 50 | const lines: string[] = [] |
| 51 | |
| 52 | if (summaryTemplate) { |
| 53 | lines.push(summaryTemplate.replace(/\{rowCount\}/g, String(rows.length))) |
| 54 | lines.push('') |
| 55 | } |
| 56 | |
| 57 | for (const row of rows) { |
| 58 | lines.push(formatRow(rowTemplate, row as Record<string, unknown>)) |
| 59 | } |
| 60 | |
| 61 | return { |
| 62 | content: lines.join('\n'), |
| 63 | data: { rows, rowCount: rows.length }, |
| 64 | } |
| 65 | }, |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | export function createAllSqlToolDefinitions(defs: SqlToolDef[]): ToolDefinition[] { |
| 70 | return defs.map(createSqlToolDefinition) |