UNPKG

@utcp/sdk

Version:

Universal Tool Calling Protocol (UTCP) client library for TypeScript

249 lines 9.87 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.TextTransport = void 0; const fs_1 = require("fs"); const path_1 = require("path"); const utcp_manual_1 = require("../../shared/utcp-manual"); const openapi_converter_1 = require("../openapi-converter"); const yaml = __importStar(require("js-yaml")); /** * Transport implementation for text file-based tool providers. * * This transport reads tool definitions from local text files. The file should * contain a JSON object with a 'tools' array containing tool definitions. * * Since tools are defined statically in text files, tool calls are not supported * and will raise a ValueError. */ class TextTransport { /** * Initialize the text transport. * * @param basePath The base path to resolve relative file paths from. */ constructor(basePath) { this.basePath = basePath; } /** * Log informational messages. */ _logInfo(message) { console.log(`[TextTransport] ${message}`); } /** * Log error messages. */ _logError(message) { console.error(`[TextTransport Error] ${message}`); } /** * Register a text provider and discover its tools. * * @param manual_provider The TextProvider to register * @returns List of tools defined in the text file * @throws Error if provider is not a TextProvider * @throws Error if the specified file doesn't exist * @throws Error if the file contains invalid JSON */ async register_tool_provider(manual_provider) { if (manual_provider.provider_type !== 'text') { throw new Error('TextTransport can only be used with TextProvider'); } const textProvider = manual_provider; let filePath = textProvider.file_path; // Resolve relative paths using base_path if (!this.isAbsolutePath(filePath) && this.basePath) { filePath = (0, path_1.resolve)(this.basePath, filePath); } this._logInfo(`Reading tool definitions from '${filePath}'`); try { // Check if file exists try { await fs_1.promises.access(filePath); } catch { throw new Error(`Tool definition file not found: ${filePath}`); } // Read the file content const fileContent = await fs_1.promises.readFile(filePath, 'utf-8'); // Parse based on file extension const ext = (0, path_1.extname)(filePath).toLowerCase(); let data; try { if (ext === '.yaml' || ext === '.yml') { data = yaml.load(fileContent); } else { data = JSON.parse(fileContent); } } catch (e) { this._logError(`Failed to parse file '${filePath}': ${e.message}`); throw new Error(`Failed to parse file '${filePath}': ${e.message}`); } // Check if the data is a UTCP manual, an OpenAPI spec, or neither let utcpManual; if (typeof data === 'object' && data !== null && 'version' in data && 'tools' in data) { this._logInfo(`Detected UTCP manual in '${filePath}'.`); const manualParseResult = utcp_manual_1.UtcpManualSchema.safeParse(data); if (!manualParseResult.success) { this._logError(`Invalid UTCP manual format in '${filePath}': ${JSON.stringify(manualParseResult.error)}`); return []; } utcpManual = manualParseResult.data; } else if (typeof data === 'object' && data !== null && ('openapi' in data || 'swagger' in data || 'paths' in data)) { this._logInfo(`Assuming OpenAPI spec in '${filePath}'. Converting to UTCP manual.`); try { const fileUri = this.pathToUri(filePath); const converter = new openapi_converter_1.OpenApiConverter(data, { specUrl: fileUri, providerName: textProvider.name }); utcpManual = converter.convert(); } catch (e) { this._logError(`Failed to convert OpenAPI spec: ${e.message}`); return []; } } else { throw new Error(`File '${filePath}' is not a valid OpenAPI specification or UTCP manual`); } this._logInfo(`Successfully loaded ${utcpManual.tools.length} tools from '${filePath}'`); return utcpManual.tools; } catch (error) { if (error.message.includes('not found')) { this._logError(`Tool definition file not found: ${filePath}`); throw error; } if (error.message.includes('Failed to parse')) { // Already logged in the catch block above throw error; } this._logError(`Unexpected error reading file '${filePath}': ${error.message}`); return []; } } /** * Deregister a text provider. * * This is a no-op for text providers since they are stateless. * * @param manual_provider The provider to deregister */ async deregister_tool_provider(manual_provider) { if (manual_provider.provider_type === 'text') { this._logInfo(`Deregistering text provider '${manual_provider.name}' (no-op)`); } } /** * Call a tool on a text provider. * * For text providers, this returns the content of the text file. * * @param tool_name Name of the tool to call (ignored for text providers) * @param args Arguments for the tool call (ignored for text providers) * @param tool_provider The TextProvider containing the file * @returns The content of the text file as a string * @throws Error if provider is not a TextProvider * @throws Error if the specified file doesn't exist */ async call_tool(tool_name, args, tool_provider) { if (tool_provider.provider_type !== 'text') { throw new Error('TextTransport can only be used with TextProvider'); } const textProvider = tool_provider; let filePath = textProvider.file_path; // Resolve relative paths using base_path if (this.basePath && !(0, path_1.resolve)(filePath).startsWith('/') && !filePath.includes(':')) { filePath = (0, path_1.resolve)(this.basePath, filePath); } this._logInfo(`Reading content from '${filePath}' for tool '${tool_name}'`); try { // Check if file exists try { await fs_1.promises.access(filePath); } catch { throw new Error(`File not found: ${filePath}`); } // Read and return the file content const content = await fs_1.promises.readFile(filePath, 'utf-8'); this._logInfo(`Successfully read ${content.length} characters from '${filePath}'`); return content; } catch (error) { if (error.message.includes('not found')) { this._logError(`File not found: ${filePath}`); throw error; } this._logError(`Error reading file '${filePath}': ${error.message}`); throw error; } } /** * Close the transport. * * This is a no-op for text transports since they don't maintain connections. */ async close() { this._logInfo("Closing text transport (no-op)"); } /** * Check if a path is absolute. * @param path The path to check * @returns True if the path is absolute, false otherwise */ isAbsolutePath(path) { return (0, path_1.resolve)(path) === path; } /** * Convert a file path to a URI. * @param path The file path * @returns The file URI */ pathToUri(path) { // Convert to URL format with file:// protocol const normalized = path.replace(/\\/g, '/'); return `file://${normalized.startsWith('/') ? '' : '/'}${normalized}`; } } exports.TextTransport = TextTransport; //# sourceMappingURL=text-transport.js.map