/** * CustomToolScanner — discovers standalone tool files in a directory and * extracts their metadata so that ProxyTool instances can be registered * with the YAML loader. * * Convention over Configuration: * • Each file in the custom-tools folder must export a default metadata * object conforming to CustomToolMetadata (see standalone tool wrapper docs). * • The exported class name (or `name` field in metadata) MUST match the * file's basename (without extension). E.g. `WeatherLookup.ts` → name: "WeatherLookup". * • The tool is referenced in YAML by that same name. * * Metadata Extraction (zero-import approach): * We read the file as text and use a lightweight regex to pull the * `TOOL_METADATA` export block. This keeps the scanner decoupled from * Bun/ESM and lets it run purely in the Node.js main process. * The metadata block must be a single JSON object assigned to * `export const TOOL_METADATA = { ... };` */ import * as fs from 'fs'; import * as path from 'path'; import type { ToolInputs } from '../types.js'; import { ProxyTool, ProxyToolConfig } from './ProxyTool.js'; export interface CustomToolMetadata { /** Must match the file's basename (sans extension) */ name: string; /** Human-readable description shown to the LLM */ description: string; /** Input schema identical to Tool.inputs */ inputs: ToolInputs; /** Output type label */ outputType: string; /** Optional execution timeout in ms */ timeout?: number; } export interface DiscoveredTool { /** Absolute path to the tool file */ filePath: string; /** Parsed metadata */ metadata: CustomToolMetadata; } // Regex: captures everything between the braces of `export const TOOL_METADATA = { ... };` // This is intentionally lenient — it matches the first `TOOL_METADATA = ` and grabs until the // matching closing brace followed by an optional semicolon. const METADATA_REGEX = /export\s+const\s+TOOL_METADATA\s*=\s*(\{[\s\S]*?\});\s*$/m; /** * Scan a directory for custom tool files and extract their metadata. * * @param folderPath Absolute path to the custom-tools directory. * @returns Array of discovered tools with parsed metadata. * @throws If any file fails metadata extraction. */ export function scanCustomTools(folderPath: string): DiscoveredTool[] { if (!fs.existsSync(folderPath)) { throw new Error( `Custom tools folder not found: ${folderPath}. ` + 'Create the directory or check your --custom-tools-folder path.' ); } const entries = fs.readdirSync(folderPath, { withFileTypes: true }); const discovered: DiscoveredTool[] = []; for (const entry of entries) { if (entry.isDirectory()) continue; const ext = path.extname(entry.name).toLowerCase(); if (ext !== '.ts' && ext !== '.js') continue; const filePath = path.resolve(folderPath, entry.name); const baseName = path.basename(entry.name, ext); let metadata: CustomToolMetadata; try { metadata = extractMetadata(filePath); } catch (err) { throw new Error( `Failed to extract TOOL_METADATA from "${entry.name}": ${(err as Error).message}\n` + 'Ensure the file exports `export const TOOL_METADATA = { name, description, inputs, outputType };`' ); } // Enforce: metadata.name must match the file's base name if (metadata.name !== baseName) { throw new Error( `Tool metadata name mismatch in "${entry.name}": ` + `file is "${baseName}" but TOOL_METADATA.name is "${metadata.name}". ` + 'They must match (Convention over Configuration).' ); } discovered.push({ filePath, metadata }); } return discovered; } /** * Read a tool file and extract the TOOL_METADATA export via regex. */ function extractMetadata(filePath: string): CustomToolMetadata { const source = fs.readFileSync(filePath, 'utf8'); const match = source.match(METADATA_REGEX); if (!match) { throw new Error( 'No `export const TOOL_METADATA = { ... };` block found. ' + 'Add the metadata export at the bottom of your tool file.' ); } let parsed: CustomToolMetadata; try { // Use Function constructor to safely evaluate the object literal. // This handles JS object syntax (unquoted keys, trailing commas) that // strict JSON.parse would reject. parsed = new Function(`"use strict"; return (${match[1]});`)() as CustomToolMetadata; } catch (err) { throw new Error( `Could not parse TOOL_METADATA object: ${(err as Error).message}. ` + 'Ensure it is a valid JavaScript object literal.' ); } // Validate required fields if (!parsed.name || typeof parsed.name !== 'string') { throw new Error('TOOL_METADATA.name must be a non-empty string.'); } if (!parsed.description || typeof parsed.description !== 'string') { throw new Error('TOOL_METADATA.description must be a non-empty string.'); } if (!parsed.inputs || typeof parsed.inputs !== 'object') { throw new Error('TOOL_METADATA.inputs must be an object mapping parameter names to their schemas.'); } if (!parsed.outputType || typeof parsed.outputType !== 'string') { throw new Error('TOOL_METADATA.outputType must be a non-empty string.'); } return parsed; } /** * Scan a folder and return a Map ready for registration * with YAMLLoader. */ export function loadCustomTools(folderPath: string): Map { const discovered = scanCustomTools(folderPath); const tools = new Map(); for (const { filePath, metadata } of discovered) { const config: ProxyToolConfig = { toolPath: filePath, name: metadata.name, description: metadata.description, inputs: metadata.inputs, outputType: metadata.outputType, timeout: metadata.timeout, }; tools.set(metadata.name, new ProxyTool(config)); } return tools; }