UNPKG

@utcp/sdk

Version:
1,203 lines (1,181 loc) 56.6 kB
import z$1, { z } from 'zod'; declare function setPluginInitializer(fn: () => void): void; declare abstract class Serializer<T> { constructor(); abstract toDict(obj: T): { [key: string]: any; }; abstract validateDict(obj: { [key: string]: any; }): T; copy(obj: T): T; } interface Auth { /** Authentication type identifier */ auth_type: string; } declare class AuthSerializer extends Serializer<Auth> { private static serializers; static registerAuth(authType: string, serializer: Serializer<Auth>, override?: boolean): boolean; toDict(obj: Auth): Record<string, unknown>; validateDict(obj: Record<string, unknown>): Auth; } declare const AuthSchema: z.ZodType<Auth, z.ZodTypeDef, Auth>; /** * Base interface for all CallTemplates. Each protocol plugin will implement this structure. * It provides the common fields every call template must have. */ interface CallTemplate { /** * Unique identifier for the CallTemplate/Manual. Recommended to be a human-readable name. */ name?: string; /** * The transport protocol type used by this call template (e.g., 'http', 'mcp', 'text'). */ call_template_type: string; /** * Optional authentication configuration for the provider. */ auth?: Auth; /** * Optional list of allowed communication protocol types for tools within this manual. * * Behavior: * - If undefined, null, or empty array → defaults to only allowing the manual's own call_template_type * - If set to a non-empty array → only those protocol types are allowed * * This provides secure-by-default behavior where a manual can only register/call tools * that use its own protocol unless explicitly configured otherwise. */ allowed_communication_protocols?: string[]; [key: string]: any; } declare class CallTemplateSerializer extends Serializer<CallTemplate> { private static serializers; static registerCallTemplate(callTemplateType: string, serializer: Serializer<CallTemplate>, override?: boolean): boolean; toDict(obj: CallTemplate): Record<string, unknown>; validateDict(obj: Record<string, unknown>): CallTemplate; } declare const CallTemplateSchema: z.ZodType<CallTemplate, z.ZodTypeDef, CallTemplate>; /** * A recursive type representing any valid JSON value: string, number, boolean, null, object, or array. */ type JsonValue = string | number | boolean | null | { [key: string]: JsonValue; } | JsonValue[]; /** * Zod type for basic JSON primitive or recursive structure. */ declare const JsonTypeSchema: z.ZodType<JsonValue>; type JsonType = z.infer<typeof JsonTypeSchema>; /** * Interface for a JSON Schema definition (based on draft-07). * This defines the structure for tool inputs and outputs. */ interface JsonSchema { /** * Optional schema identifier. */ $schema?: string; /** * Optional schema identifier. */ $id?: string; /** * Optional schema title. */ title?: string; /** * Optional schema description. */ description?: string; /** * The JSON data type (e.g., 'object', 'string', 'number'). */ type?: 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array' | 'null' | string[]; /** * Defines properties if type is 'object'. */ properties?: { [key: string]: JsonSchema; }; /** * Defines item structure if type is 'array'. */ items?: JsonSchema | JsonSchema[]; /** * List of required properties if type is 'object'. */ required?: string[]; /** * List of allowable values. */ enum?: JsonType[]; /** * The exact required value. */ const?: JsonType; /** * A default value for the property. */ default?: JsonType; /** * Optional format hint (e.g., 'date-time', 'email'). */ format?: string; /** * Allows or specifies schema for additional properties. */ additionalProperties?: boolean | JsonSchema; /** * Regex pattern for string validation. */ pattern?: string; /** * Minimum numeric value. */ minimum?: number; /** * Maximum numeric value. */ maximum?: number; /** * Minimum string length. */ minLength?: number; /** * Maximum string length. */ maxLength?: number; [k: string]: unknown; } /** * Zod schema corresponding to the JsonSchema interface. */ declare const JsonSchemaSchema: z.ZodType<JsonSchema>; /** * Interface for a UTCP Tool. * Represents a callable tool with its metadata, input/output schemas, * and associated call template. Tools are the fundamental units of * functionality in the UTCP ecosystem. */ interface Tool { /** * Unique identifier for the tool, typically in format "manual_name.tool_name". */ name: string; /** * Human-readable description of what the tool does. */ description: string; /** * JSON Schema defining the tool's input parameters. */ inputs: JsonSchema; /** * JSON Schema defining the tool's return value structure. */ outputs: JsonSchema; /** * List of tags for categorization and search. */ tags: string[]; /** * Optional hint about typical response size in bytes. */ average_response_size?: number; /** * CallTemplate configuration for accessing this tool. */ tool_call_template: CallTemplate; } /** * Zod schema corresponding to the Tool interface. */ declare const ToolSchema: z.ZodType<Tool>; /** * Serializer for JsonSchema objects. * Since JsonSchema is a standard format without subtypes, this is a simple passthrough serializer. */ declare class JsonSchemaSerializer extends Serializer<JsonSchema> { toDict(obj: JsonSchema): Record<string, unknown>; validateDict(obj: Record<string, unknown>): JsonSchema; } /** * Serializer for Tool objects. * Handles serialization and deserialization of complete tool definitions. */ declare class ToolSerializer extends Serializer<Tool> { toDict(obj: Tool): Record<string, unknown>; validateDict(obj: Record<string, unknown>): Tool; } /** * The default UTCP protocol version used throughout the library. * This is replaced at build time with the actual package version. * Use this constant when creating UtcpManual objects to ensure version consistency. */ declare const UTCP_PACKAGE_VERSION = "1.0.0"; /** * Interface for the standard format for tool provider responses during discovery. * Represents the complete set of tools available from a provider, along * with version information for compatibility checking. */ interface UtcpManual { /** * The UTCP protocol version supported by the provider. */ utcp_version: string; /** * The version of this specific manual/specification. */ manual_version: string; /** * List of available tools with their complete configurations. */ tools: Tool[]; } /** * The standard format for tool provider responses during discovery. * This schema is used for runtime validation and parsing of UTCP manuals. */ declare const UtcpManualSchema: z.ZodType<UtcpManual>; /** * Serializer for UtcpManual objects. * Handles serialization and deserialization of complete UTCP manual definitions. */ declare class UtcpManualSerializer extends Serializer<UtcpManual> { toDict(obj: UtcpManual): Record<string, unknown>; validateDict(obj: Record<string, unknown>): UtcpManual; } /** * Result of a manual registration operation. */ interface RegisterManualResult { manualCallTemplate: CallTemplate; manual: UtcpManual; success: boolean; errors: string[]; } /** * Defines the contract for tool repositories that store and manage UTCP tools * and their associated call templates. * * Repositories are responsible for: * - Persisting call template configurations and their associated tools. * - Providing efficient lookup and retrieval operations. * - Managing relationships between call templates and tools. * - Ensuring data consistency across concurrent asynchronous calls. */ interface ConcurrentToolRepository { /** * A string identifying the type of this tool repository (e.g., 'in_memory', 'database'). * This is used for configuration and plugin lookup. */ tool_repository_type: string; /** * Saves a manual's call template and its associated tools in the repository. * This operation replaces any existing manual with the same name. * * @param manualCallTemplate The call template associated with the manual to save. * @param manual The complete UTCP Manual object to save. * @returns A Promise that resolves when the operation is complete. */ saveManual(manualCallTemplate: CallTemplate, manual: UtcpManual): Promise<void>; /** * Removes a manual and its tools from the repository. * * @param manualName The name of the manual (which corresponds to the CallTemplate name) to remove. * @returns A Promise resolving to true if the manual was removed, False otherwise. */ removeManual(manualName: string): Promise<boolean>; /** * Removes a specific tool from the repository. * * @param toolName The full namespaced name of the tool to remove (e.g., "my_manual.my_tool"). * @returns A Promise resolving to true if the tool was removed, False otherwise. */ removeTool(toolName: string): Promise<boolean>; /** * Retrieves a tool by its full namespaced name. * * @param toolName The full namespaced name of the tool to retrieve. * @returns A Promise resolving to the tool if found, otherwise undefined. */ getTool(toolName: string): Promise<Tool | undefined>; /** * Retrieves all tools from the repository. * * @returns A Promise resolving to a list of all registered tools. */ getTools(): Promise<Tool[]>; /** * Retrieves all tools associated with a specific manual. * * @param manualName The name of the manual. * @returns A Promise resolving to a list of tools associated with the manual, or undefined if the manual is not found. */ getToolsByManual(manualName: string): Promise<Tool[] | undefined>; /** * Retrieves a complete UTCP Manual object by its name. * * @param manualName The name of the manual to retrieve. * @returns A Promise resolving to the manual if found, otherwise undefined. */ getManual(manualName: string): Promise<UtcpManual | undefined>; /** * Retrieves all registered manuals from the repository. * * @returns A Promise resolving to a list of all registered UtcpManual objects. */ getManuals(): Promise<UtcpManual[]>; /** * Retrieves a manual's CallTemplate by its name. * * @param manualCallTemplateName The name of the manual's CallTemplate to retrieve. * @returns A Promise resolving to the CallTemplate if found, otherwise undefined. */ getManualCallTemplate(manualCallTemplateName: string): Promise<CallTemplate | undefined>; /** * Retrieves all registered manual CallTemplates from the repository. * * @returns A Promise resolving to a list of all registered CallTemplateBase objects. */ getManualCallTemplates(): Promise<CallTemplate[]>; } declare class ConcurrentToolRepositoryConfigSerializer extends Serializer<ConcurrentToolRepository> { private static implementations; static default_strategy: string; static registerRepository(type: string, serializer: Serializer<ConcurrentToolRepository>, override?: boolean): boolean; toDict(obj: ConcurrentToolRepository): Record<string, unknown>; validateDict(data: Record<string, unknown>): ConcurrentToolRepository; } declare const ConcurrentToolRepositorySchema: z$1.ZodType<ConcurrentToolRepository, z$1.ZodTypeDef, ConcurrentToolRepository>; /** * Defines the contract for tool search strategies that can be plugged into * the UTCP client. Implementations provide algorithms for searching and ranking tools. */ interface ToolSearchStrategy { /** * A string identifying the type of this tool search strategy (e.g., 'tag_and_description_word_match', 'in_mem_embeddings'). * This is used for configuration and plugin lookup. */ tool_search_strategy_type: string; /** * Searches for tools relevant to the query within a given tool repository. * * @param toolRepository The repository to search within. * @param query The search query string. Format depends on the strategy (e.g., keywords, natural language). * @param limit Maximum number of tools to return. Use 0 for no limit. * @param anyOfTagsRequired Optional list of tags where one of them must be present in the tool's tags. * @returns A Promise resolving to a list of Tool objects ranked by relevance. */ searchTools(toolRepository: ConcurrentToolRepository, query: string, limit?: number, anyOfTagsRequired?: string[]): Promise<Tool[]>; } declare class ToolSearchStrategyConfigSerializer extends Serializer<ToolSearchStrategy> { private static implementations; static default_strategy: string; static registerStrategy(type: string, serializer: Serializer<ToolSearchStrategy>, override?: boolean): boolean; toDict(obj: ToolSearchStrategy): Record<string, unknown>; validateDict(data: Record<string, unknown>): ToolSearchStrategy; } declare const ToolSearchStrategySchema: z$1.ZodType<ToolSearchStrategy, z$1.ZodTypeDef, ToolSearchStrategy>; /** * Base interface for all VariableLoaders. * Variable loaders are responsible for loading configuration variables from external sources. */ interface VariableLoader { /** * The type identifier for this variable loader (e.g., 'dotenv'). */ variable_loader_type: string; [key: string]: any; /** * Retrieves a variable value by key. * @abstract * @param key Variable name to retrieve. * @returns Variable value if found, None otherwise. */ get(key: string): Promise<string | null>; } /** * Serializer for VariableLoader objects. * Uses a registry pattern to delegate to type-specific serializers. */ declare class VariableLoaderSerializer extends Serializer<VariableLoader> { private static serializers; /** * Registers a variable loader serializer for a specific type. * @param type The variable_loader_type identifier * @param serializer The serializer instance for this type * @param override Whether to override an existing registration * @returns true if registration succeeded, false if already exists and override is false */ static registerVariableLoader(type: string, serializer: Serializer<VariableLoader>, override?: boolean): boolean; toDict(obj: VariableLoader): Record<string, unknown>; validateDict(obj: Record<string, unknown>): VariableLoader; } /** * Zod schema for VariableLoader using custom validation. */ declare const VariableLoaderSchema: z.ZodType<VariableLoader, z.ZodTypeDef, VariableLoader>; /** * REQUIRED * Abstract interface for UTCP client implementations. * * Defines the core contract for UTCP clients, including CallTemplate management, * tool execution, search capabilities, and variable handling. This interface * allows for different client implementations while maintaining consistency. */ interface IUtcpClient { /** * The client's complete and immutable configuration object. */ readonly config: UtcpClientConfig; /** * The root directory for the client to resolve relative paths from. */ readonly root_dir: string | null; /** * REQUIRED * Register a tool CallTemplate and its tools. * * @param manualCallTemplate The CallTemplate to register. * @returns A Promise resolving to a RegisterManualResult object containing the registered CallTemplate and its tools. */ registerManual(manualCallTemplate: CallTemplate): Promise<RegisterManualResult>; /** * REQUIRED * Register multiple tool CallTemplates and their tools. * * @param manualCallTemplates List of CallTemplates to register. * @returns A Promise resolving to a list of RegisterManualResult objects containing the registered CallTemplates and their tools. Order is not preserved. */ registerManuals(manualCallTemplates: CallTemplate[]): Promise<RegisterManualResult[]>; /** * REQUIRED * Deregister a tool CallTemplate. * * @param manualCallTemplateName The name of the CallTemplate to deregister. * @returns A Promise resolving to true if the CallTemplate was deregistered, false otherwise. */ deregisterManual(manualCallTemplateName: string): Promise<boolean>; /** * REQUIRED * Call a tool. * * @param toolName The name of the tool to call. * @param toolArgs The arguments to pass to the tool. * @returns A Promise resolving to the result of the tool call. */ callTool(toolName: string, toolArgs: Record<string, any>): Promise<any>; /** * REQUIRED * Call a tool streamingly. * * @param toolName The name of the tool to call. * @param toolArgs The arguments to pass to the tool. * @returns An async generator that yields the result of the tool call. */ callToolStreaming(toolName: string, toolArgs: Record<string, any>): AsyncGenerator<any, void, unknown>; /** * REQUIRED * Search for tools relevant to the query. * * @param query The search query. * @param limit The maximum number of tools to return. 0 for no limit. * @param anyOfTagsRequired Optional list of tags where one of them must be present in the tool's tags * @returns A Promise resolving to a list of tools that match the search query. */ searchTools(query: string, limit?: number, anyOfTagsRequired?: string[]): Promise<Tool[]>; /** * REQUIRED * Gets the required namespaced variables for a manual CallTemplate and its discovered tools. * * @param manualCallTemplate The CallTemplate instance of the manual. * @returns A Promise resolving to a list of required, fully-qualified variable names. */ getRequiredVariablesForManualAndTools(manualCallTemplate: CallTemplate): Promise<string[]>; /** * REQUIRED * Gets the required namespaced variables for an already registered tool. * * @param toolName The full namespaced name of the registered tool (e.g., 'manual_name.tool_name'). * @returns A Promise resolving to a list of required, fully-qualified variable names. */ getRequiredVariablesForRegisteredTool(toolName: string): Promise<string[]>; } /** * Defines the contract for tool post-processors that can modify the result of a tool call. * Implementations can apply transformations, filtering, or other logic to the raw tool output. * Post-processors are configured in the UtcpClientConfig and executed in order after a successful tool call. */ interface ToolPostProcessor { /** * A string identifying the type of this tool post-processor (e.g., 'filter_dict', 'limit_strings'). * This is used for configuration and plugin lookup. */ tool_post_processor_type: string; /** * Processes the result of a tool call. * * @param caller The UTCP client instance that initiated the tool call. * @param tool The Tool object that was called. * @param manualCallTemplate The CallTemplateBase object of the manual that owns the tool. * @param result The raw result returned by the tool's communication protocol (can be a final result or a chunk from a stream). * @returns The processed result, which is then passed to the next processor in the chain or returned to the caller. */ postProcess(caller: IUtcpClient, tool: Tool, manualCallTemplate: CallTemplate, result: any): any; } declare class ToolPostProcessorConfigSerializer extends Serializer<ToolPostProcessor> { private static implementations; static registerPostProcessor(type: string, serializer: Serializer<ToolPostProcessor>, override?: boolean): boolean; toDict(obj: ToolPostProcessor): Record<string, unknown>; validateDict(data: Record<string, unknown>): ToolPostProcessor; } declare const ToolPostProcessorSchema: z$1.ZodType<ToolPostProcessor, z$1.ZodTypeDef, ToolPostProcessor>; /** * REQUIRED * Configuration model for UTCP client setup. * * Provides comprehensive configuration options for UTCP clients including * variable definitions, provider file locations, and variable loading * mechanisms. Supports hierarchical variable resolution with multiple * sources. * * Variable Resolution Order: * 1. Direct variables dictionary * 2. Custom variable loaders (in order) * 3. Environment variables * * Attributes: * variables: A dictionary of directly-defined * variables for substitution. * load_variables_from: A list of * variable loader configurations for loading variables from external * sources like .env files or remote services. * tool_repository: Configuration for the tool * repository, which manages the storage and retrieval of tools. * Defaults to an in-memory repository. * tool_search_strategy: Configuration for the tool * search strategy, defining how tools are looked up. Defaults to a * tag and description-based search. * post_processing: A list of tool post-processor * configurations to be applied after a tool call. * manual_call_templates: A list of manually defined * call templates for registering tools that don't have a provider. * * Example: * ```typescript * const config: UtcpClientConfig = { * variables: {"MANUAL__NAME_API_KEY_NAME": "$REMAPPED_API_KEY"}, * load_variables_from: [ * new VariableLoaderSerializer().validateDict({"variable_loader_type": "dotenv", "env_file_path": ".env"}) * ], * tool_repository: new ConcurrentToolRepositoryConfigSerializer().validateDict({ * "tool_repository_type": "in_memory" * }), * tool_search_strategy: new ToolSearchStrategyConfigSerializer().validateDict({ * "tool_search_strategy_type": "tag_and_description_word_match" * }), * post_processing: [], * manual_call_templates: [] * }; * ``` */ interface UtcpClientConfig { /** * A dictionary of directly-defined variables for substitution. */ variables: Record<string, string>; /** * A list of variable loader configurations for loading variables from external * sources like .env files. Loaders are processed in order. */ load_variables_from: VariableLoader[] | null; /** * Configuration for the tool repository. * Defaults to an in-memory repository. */ tool_repository: ConcurrentToolRepository; /** * Configuration for the tool search strategy. * Defaults to a tag and description-based search. */ tool_search_strategy: ToolSearchStrategy; /** * A list of tool post-processor configurations to be applied after a tool call. */ post_processing: ToolPostProcessor[]; /** * A list of manually defined call templates for registering tools at client initialization. */ manual_call_templates: CallTemplate[]; } /** * The main configuration schema for the UTCP client. */ declare const UtcpClientConfigSchema: z.ZodObject<{ variables: z.ZodDefault<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>; load_variables_from: z.ZodEffects<z.ZodDefault<z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodType<VariableLoader, z.ZodTypeDef, VariableLoader>, "many">>>>, VariableLoader[] | null, VariableLoader[] | null | undefined>; tool_repository: z.ZodDefault<z.ZodOptional<z.ZodEffects<z.ZodAny, ConcurrentToolRepository, any>>>; tool_search_strategy: z.ZodDefault<z.ZodOptional<z.ZodEffects<z.ZodAny, ToolSearchStrategy, any>>>; post_processing: z.ZodDefault<z.ZodOptional<z.ZodEffects<z.ZodArray<z.ZodAny, "many">, ToolPostProcessor[], any[]>>>; manual_call_templates: z.ZodDefault<z.ZodOptional<z.ZodEffects<z.ZodArray<z.ZodType<CallTemplate, z.ZodTypeDef, CallTemplate>, "many">, CallTemplate[], CallTemplate[]>>>; }, "strict", z.ZodTypeAny, { variables: Record<string, string>; load_variables_from: VariableLoader[] | null; tool_repository: ConcurrentToolRepository; tool_search_strategy: ToolSearchStrategy; post_processing: ToolPostProcessor[]; manual_call_templates: CallTemplate[]; }, { variables?: Record<string, string> | undefined; load_variables_from?: VariableLoader[] | null | undefined; tool_repository?: any; tool_search_strategy?: any; post_processing?: any[] | undefined; manual_call_templates?: CallTemplate[] | undefined; }>; /** * REQUIRED * Serializer for UTCP client configurations. * * Defines the contract for serializers that convert UTCP client configurations to and from * dictionaries for storage or transmission. Serializers are responsible for: * - Converting UTCP client configurations to dictionaries for storage or transmission * - Converting dictionaries back to UTCP client configurations * - Ensuring data consistency during serialization and deserialization */ declare class UtcpClientConfigSerializer extends Serializer<UtcpClientConfig> { /** * REQUIRED * Convert a UtcpClientConfig object to a dictionary. * * @param obj The UtcpClientConfig object to convert. * @returns The dictionary converted from the UtcpClientConfig object. */ toDict(obj: UtcpClientConfig): Record<string, unknown>; /** * REQUIRED * Validate a dictionary and convert it to a UtcpClientConfig object. * * @param data The dictionary to validate and convert. * @returns The UtcpClientConfig object converted from the dictionary. * @throws Error if validation fails */ validateDict(data: Record<string, unknown>): UtcpClientConfig; } /** * Defines the contract for variable substitution implementations. * Implementations are responsible for replacing placeholders in configuration data * with actual values from various sources (e.g., config, environment variables). */ interface VariableSubstitutor { /** * Recursively substitutes variables in the given object. * * @param obj The object (can be string, array, or object) containing potential variable references to substitute. * @param config The UTCP client configuration containing variable definitions and loaders. * @param namespace An optional namespace (e.g., manual name) to prefix variable lookups for isolation. * @returns The object with all variable references replaced by their values. * @throws UtcpVariableNotFoundError if a referenced variable cannot be resolved. */ substitute<T>(obj: T, config: UtcpClientConfig, namespace?: string): Promise<T>; /** * Recursively finds all variable references in the given object. * * @param obj The object (can be string, array, or object) to scan for variable references. * @param namespace An optional namespace (e.g., manual name) to prefix variable lookups for isolation. * @returns A list of fully-qualified variable names found in the object. */ findRequiredVariables(obj: any, namespace?: string): string[]; } /** * REQUIRED * Abstract interface for UTCP client implementations. * * Defines the core contract for UTCP clients, including CallTemplate management, * tool execution, search capabilities, and variable handling. This interface * allows for different client implementations while maintaining consistency. */ declare class UtcpClient implements IUtcpClient { readonly config: UtcpClientConfig; readonly variableSubstitutor: VariableSubstitutor; readonly root_dir: string | null; private _registeredCommProtocols; readonly postProcessors: ToolPostProcessor[]; protected constructor(config: UtcpClientConfig, variableSubstitutor: VariableSubstitutor, root_dir?: string | null); /** * REQUIRED * Create a new instance of UtcpClient. * * @param root_dir The root directory for the client to resolve relative paths from. Defaults to the current working directory. * @param config The configuration for the client. Can be a path to a configuration file, a dictionary, or UtcpClientConfig object. * @returns A new instance of UtcpClient. */ static create(root_dir?: string, config?: UtcpClientConfig | null): Promise<UtcpClient>; /** * Retrieves a tool by its full namespaced name. * @param toolName The full namespaced name of the tool to retrieve. * @returns A Promise resolving to the tool if found, otherwise undefined. */ getTool(toolName: string): Promise<Tool | undefined>; /** * Retrieves all tools from the repository. * @returns A Promise resolving to a list of all registered tools. */ getTools(): Promise<Tool[]>; /** * Registers a single tool manual. * @param manualCallTemplate The call template describing how to discover and connect to the manual. * @returns A promise that resolves to a result object indicating success or failure. */ registerManual(manualCallTemplate: CallTemplate): Promise<RegisterManualResult>; /** * Registers a list of tool manuals in parallel. * @param manualCallTemplates An array of call templates to register. * @returns A promise that resolves to an array of registration results. */ registerManuals(manualCallTemplates: CallTemplate[]): Promise<RegisterManualResult[]>; /** * Deregisters a tool manual and all of its associated tools. * @param manualName The name of the manual to deregister. * @returns A promise that resolves to true if the manual was found and removed, otherwise false. */ deregisterManual(manualName: string): Promise<boolean>; /** * Calls a registered tool by its full namespaced name. * @param toolName The full name of the tool (e.g., 'my_manual.my_tool'). * @param toolArgs A JSON object of arguments for the tool call. * @returns A promise that resolves to the result of the tool call, with post-processing applied. */ callTool(toolName: string, toolArgs: Record<string, any>): Promise<any>; /** * Calls a registered tool and streams the results. * @param toolName The full name of the tool (e.g., 'my_manual.my_tool'). * @param toolArgs A JSON object of arguments for the tool call. * @returns An async generator that yields chunks of the tool's response, with post-processing applied to each chunk. */ callToolStreaming(toolName: string, toolArgs: Record<string, any>): AsyncGenerator<any, void, unknown>; /** * Searches for relevant tools based on a task description. * @param query A natural language description of the task. * @param limit The maximum number of tools to return. * @param anyOfTagsRequired An optional list of tags, where at least one must be present on a tool for it to be included. * @returns A promise that resolves to a list of relevant `Tool` objects. */ searchTools(query: string, limit?: number, anyOfTagsRequired?: string[]): Promise<Tool[]>; /** * Gets the required variables for a manual CallTemplate and its tools. * * @param manualCallTemplate The manual CallTemplate. * @returns A list of required variables for the manual CallTemplate and its tools. */ getRequiredVariablesForManualAndTools(manualCallTemplate: CallTemplate): Promise<string[]>; /** * Gets the required variables for a registered tool. * * @param toolName The name of a registered tool. * @returns A list of required variables for the tool. */ getRequiredVariablesForRegisteredTool(toolName: string): Promise<string[]>; /** * Substitutes variables in a given call template. * @param callTemplate The call template to process. * @param namespace An optional namespace for variable lookup. * @returns A new call template instance with all variables substituted. */ substituteCallTemplateVariables<T extends CallTemplate>(callTemplate: T, namespace?: string): Promise<T>; /** * Closes the UTCP client and releases any resources held by its communication protocols. */ close(): Promise<void>; } interface ApiKeyAuth extends Auth { auth_type: "api_key"; api_key: string; var_name: string; location: "header" | "query" | "cookie"; } declare class ApiKeyAuthSerializer extends Serializer<ApiKeyAuth> { toDict(obj: ApiKeyAuth): { [key: string]: any; }; validateDict(obj: { [key: string]: any; }): ApiKeyAuth; } /** * Interface for Basic authentication details. */ interface BasicAuth extends Auth { auth_type: 'basic'; username: string; password: string; } declare class BasicAuthSerializer extends Serializer<BasicAuth> { toDict(obj: BasicAuth): { [key: string]: any; }; validateDict(obj: { [key: string]: any; }): BasicAuth; } /** * Interface for OAuth2 authentication details (Client Credentials Flow). */ interface OAuth2Auth extends Auth { auth_type: 'oauth2'; token_url: string; client_id: string; client_secret: string; scope?: string; } declare class OAuth2AuthSerializer extends Serializer<OAuth2Auth> { toDict(obj: OAuth2Auth): { [key: string]: any; }; validateDict(obj: { [key: string]: any; }): OAuth2Auth; } /** * Abstract interface for UTCP client transport implementations (Communication Protocols). * * Defines the contract that all transport implementations must follow to * integrate with the UTCP client. Each transport handles communication * with a specific type of provider (HTTP, CLI, WebSocket, etc.). */ declare abstract class CommunicationProtocol { /** * Mapping of communication protocol types to their respective implementations. */ static communicationProtocols: { [type: string]: CommunicationProtocol; }; /** * Registers a manual and its tools. * * Connects to the provider and retrieves the list of tools it offers. * This may involve making discovery requests, parsing configuration files, * or initializing connections depending on the provider type. * * @param caller The UTCP client that is calling this method. (Type will be properly defined in UtcpClient). * @param manualCallTemplate The call template of the manual to register. * @returns A RegisterManualResult object containing the call template and manual. */ abstract registerManual(caller: IUtcpClient, manualCallTemplate: CallTemplate): Promise<RegisterManualResult>; /** * Deregisters a manual and its tools. * * Cleanly disconnects from the provider and releases any associated * resources such as connections, processes, or file handles. * * @param caller The UTCP client that is calling this method. * @param manualCallTemplate The call template of the manual to deregister. */ abstract deregisterManual(caller: IUtcpClient, manualCallTemplate: CallTemplate): Promise<void>; /** * Executes a tool call through this transport. * * Sends a tool invocation request to the provider using the appropriate * protocol and returns the result. Handles serialization of arguments * and deserialization of responses according to the transport type. * * @param caller The UTCP client that is calling this method. * @param toolName Name of the tool to call (may include provider prefix). * @param toolArgs Dictionary of arguments to pass to the tool. * @param toolCallTemplate Call template of the tool to call. * @returns The tool's response. */ abstract callTool(caller: IUtcpClient, toolName: string, toolArgs: Record<string, any>, toolCallTemplate: CallTemplate): Promise<any>; /** * Executes a tool call through this transport streamingly. * * Sends a tool invocation request to the provider using the appropriate * protocol and returns an async generator for streaming results. * * @param caller The UTCP client that is calling this method. * @param toolName Name of the tool to call. * @param toolArgs Arguments to pass to the tool. * @param toolCallTemplate Call template of the tool to call. * @returns An async generator that yields chunks of the tool's response. */ abstract callToolStreaming(caller: IUtcpClient, toolName: string, toolArgs: Record<string, any>, toolCallTemplate: CallTemplate): AsyncGenerator<any, void, unknown>; /** * Closes any persistent connections or resources held by the communication protocol. * This is a cleanup method that should be called when the client is shut down. */ close(): Promise<void>; } /** * An in-memory implementation of the ConcurrentToolRepository. * Stores tools, manuals, and manual call templates in local maps. * Uses an `AsyncMutex` to serialize write operations, ensuring data consistency * across concurrent asynchronous calls, and returns deep copies to prevent * external modification of internal state. */ declare class InMemConcurrentToolRepository implements ConcurrentToolRepository { readonly tool_repository_type: string; private _config; private _toolsByName; private _manuals; private _manualCallTemplates; private _writeMutex; /** * The constructor must accept the config type to match the factory signature, * even if the implementation does not use it. */ constructor(config?: InMemConcurrentToolRepositoryConfig); /** * Converts the repository instance's configuration to a dictionary. */ toDict(): InMemConcurrentToolRepositoryConfig; /** * Saves a manual's call template and its associated tools in the repository. * This operation replaces any existing manual with the same name. * @param manualCallTemplate The call template associated with the manual to save. * @param manual The complete UTCP Manual object to save. */ saveManual(manualCallTemplate: CallTemplate, manual: UtcpManual): Promise<void>; /** * Removes a manual and its tools from the repository. * @param manualName The name of the manual to remove. * @returns True if the manual was removed, False otherwise. */ removeManual(manualName: string): Promise<boolean>; /** * Removes a specific tool from the repository. * Note: This also attempts to remove the tool from any associated manual. * @param toolName The full namespaced name of the tool to remove. * @returns True if the tool was removed, False otherwise. */ removeTool(toolName: string): Promise<boolean>; /** * Retrieves a tool by its full namespaced name. * @param toolName The full namespaced name of the tool to retrieve. * @returns The tool if found, otherwise undefined. */ getTool(toolName: string): Promise<Tool | undefined>; /** * Retrieves all tools from the repository. * @returns A list of all registered tools. */ getTools(): Promise<Tool[]>; /** * Retrieves all tools associated with a specific manual. * @param manualName The name of the manual. * @returns A list of tools associated with the manual, or undefined if the manual is not found. */ getToolsByManual(manualName: string): Promise<Tool[] | undefined>; /** * Retrieves a complete UTCP Manual object by its name. * @param manualName The name of the manual to retrieve. * @returns The manual if found, otherwise undefined. */ getManual(manualName: string): Promise<UtcpManual | undefined>; /** * Retrieves all registered manuals from the repository. * @returns A list of all registered UtcpManual objects. */ getManuals(): Promise<UtcpManual[]>; /** * Retrieves a manual's CallTemplate by its name. * @param manualCallTemplateName The name of the manual's CallTemplate to retrieve. * @returns The CallTemplate if found, otherwise undefined. */ getManualCallTemplate(manualCallTemplateName: string): Promise<CallTemplate | undefined>; /** * Retrieves all registered manual CallTemplates from the repository. * @returns A list of all registered CallTemplateBase objects. */ getManualCallTemplates(): Promise<CallTemplate[]>; } declare class InMemConcurrentToolRepositorySerializer extends Serializer<InMemConcurrentToolRepository> { toDict(obj: InMemConcurrentToolRepository): { [key: string]: any; }; validateDict(data: { [key: string]: any; }): InMemConcurrentToolRepository; } /** * Schema for the InMemConcurrentToolRepository configuration. */ declare const InMemConcurrentToolRepositoryConfigSchema: z.ZodObject<{ tool_repository_type: z.ZodLiteral<"in_memory">; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ tool_repository_type: z.ZodLiteral<"in_memory">; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ tool_repository_type: z.ZodLiteral<"in_memory">; }, z.ZodTypeAny, "passthrough">>; type InMemConcurrentToolRepositoryConfig = z.infer<typeof InMemConcurrentToolRepositoryConfigSchema>; /** * Implements a tool search strategy based on tag and description matching. * Tools are scored based on the occurrence of query words in their tags and description. */ declare class TagSearchStrategy implements ToolSearchStrategy { readonly tool_search_strategy_type: 'tag_and_description_word_match'; readonly descriptionWeight: number; readonly tagWeight: number; private readonly _config; /** * Creates an instance of TagSearchStrategy. * * @param descriptionWeight The weight to apply to words found in the tool's description. * @param tagWeight The weight to apply to words found in the tool's tags. */ constructor(config: TagSearchStrategyConfig); /** * Converts the search strategy instance's configuration to a dictionary. */ toDict(): TagSearchStrategyConfig; /** * Searches for tools by matching tags and description content against a query. * * @param concurrentToolRepository The repository to search for tools. * @param query The search query string. * @param limit The maximum number of tools to return. If 0, all matched tools are returned. * @param anyOfTagsRequired Optional list of tags where one of them must be present in the tool's tags. * @returns A promise that resolves to a list of tools ordered by relevance. */ searchTools(concurrentToolRepository: ConcurrentToolRepository, query: string, limit?: number, anyOfTagsRequired?: string[]): Promise<Tool[]>; } declare class TagSearchStrategyConfigSerializer extends Serializer<TagSearchStrategy> { toDict(obj: TagSearchStrategy): { [key: string]: any; }; validateDict(data: { [key: string]: any; }): TagSearchStrategy; } /** * Schema for the TagSearchStrategy configuration. */ declare const TagSearchStrategyConfigSchema: z.ZodObject<{ tool_search_strategy_type: z.ZodLiteral<"tag_and_description_word_match">; description_weight: z.ZodDefault<z.ZodOptional<z.ZodNumber>>; tag_weight: z.ZodDefault<z.ZodOptional<z.ZodNumber>>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ tool_search_strategy_type: z.ZodLiteral<"tag_and_description_word_match">; description_weight: z.ZodDefault<z.ZodOptional<z.ZodNumber>>; tag_weight: z.ZodDefault<z.ZodOptional<z.ZodNumber>>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ tool_search_strategy_type: z.ZodLiteral<"tag_and_description_word_match">; description_weight: z.ZodDefault<z.ZodOptional<z.ZodNumber>>; tag_weight: z.ZodDefault<z.ZodOptional<z.ZodNumber>>; }, z.ZodTypeAny, "passthrough">>; type TagSearchStrategyConfig = z.infer<typeof TagSearchStrategyConfigSchema>; /** * Default implementation of the VariableSubstitutor interface. * Provides a hierarchical variable resolution system that searches for * variables in the following order: * 1. Configuration variables (exact match from config.variables) * 2. Custom variable loaders (in order, from config.load_variables_from) * 3. Environment variables (process.env) * * It supports variable placeholders using ${VAR_NAME} or $VAR_NAME syntax * and applies namespacing (e.g., manual__name__VAR_NAME) for isolation, * mirroring the Python UTCP SDK's convention. */ declare class DefaultVariableSubstitutor implements VariableSubstitutor { /** * Retrieves a variable value from configured sources, respecting namespaces. * * @param key The variable name to look up (without namespace prefix). * @param config The UTCP client configuration. * @param namespace An optional namespace to prepend to the variable name for lookup. * @returns The resolved variable value. * @throws UtcpVariableNotFoundError if the variable cannot be found. */ private _getVariable; /** * Recursively substitutes variables in the given object. * * @param obj The object (can be string, array, or object) containing potential variable references to substitute. * @param config The UTCP client configuration containing variable definitions and loaders. * @param namespace An optional namespace (e.g., manual name) to prefix variable lookups for isolation. * @returns The object with all variable references replaced by their values. * @throws UtcpVariableNotFoundError if a referenced variable cannot be resolved. */ substitute<T>(obj: T, config: UtcpClientConfig, namespace?: string): Promise<T>; /** * Recursively finds all variable references in the given object. * * @param obj The object (can be string, array, or object) to scan for variable references. * @param namespace An optional namespace (e.g., manual name) to prefix variable lookups for isolation. * @returns A list of fully-qualified variable names found in the object. */ findRequiredVariables(obj: any, namespace?: string): string[]; } /** * Implements a tool post-processor that filters dictionary keys from tool results. * It can recursively process nested dictionaries and arrays. * Filtering can be configured to exclude specific keys, or only include specific keys. * Processing can also be conditional based on the tool's or manual's name. */ declare class FilterDictPostProcessor implements ToolPostProcessor { readonly tool_post_processor_type: 'filter_dict'; private readonly excludeKeys?; private readonly onlyIncludeKeys?; private readonly excludeTools?; private readonly onlyIncludeTools?; private readonly excludeManuals?; private readonly onlyIncludeManuals?; private readonly _config; constructor(config: FilterDictPostProcessorConfig); /** * Converts the post-processor instance's configuration to a dictionary. */ toDict(): FilterDictPostProcessorConfig; /** * Processes the result of a tool call, applying filtering logic. * @param caller The UTCP client instance. * @param tool The Tool object that was called. * @param manualCallTemplate The CallTemplateBase object of the manual that owns the tool. * @param result The raw result returned by the tool's communication protocol. * @returns The processed result. */ postProcess(caller: IUtcpClient, tool: Tool, manualCallTemplate: CallTemplate, result: any): any; /** * Determines if processing should be skipped based on tool and manual filters. * @param tool The Tool object. * @param manualCallTemplate The CallTemplateBase object of the manual. * @returns True if processing should be skipped, false otherwise. */ private shouldSkipProcessing; /** * Recursively filters a dictionary, keeping only specified keys. * @param data The data to filter. * @returns The filtered data. */ private _filterDictOnlyIncludeKeys; /** * Recursively filters a dictionary, excluding specified keys. * @param data The data to filter. * @returns The filtered data. */ private _filterDictExcludeKeys; } /** * Schema for the FilterDictPostProcessor configuration. */ declare const FilterDictPostProcessorConfigSchema: z.ZodObject<{ tool_post_processor_type: z.ZodLiteral<"filter_dict">; exclude_keys: z.ZodOptional<z.ZodArray<z.ZodString, "many">>; only_include_keys: z.ZodOptional<z.ZodArray<z.ZodString, "many">>; exclude_tools: z.ZodOptional<z.ZodArray<z.ZodString, "many">>; only_include_tools: z.ZodOptional<z.ZodArray<z.ZodString, "many">>; exclude_manuals: z.ZodOptional<z.ZodArray<z.ZodString, "many">>; only_include_manuals: z.ZodOptional<z.ZodArray<z.ZodString, "many">>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ tool_post_processor_type: z.ZodLiteral<"filter_dict">; exclude_keys: z.ZodOptional<z.ZodArray<z.ZodString, "many">>; only_include_keys: z.ZodOptional<z.ZodArray<z.ZodString, "many">>; exclude_tools: z.ZodOptional<z.ZodArray<z.ZodString, "many">>; only_include_tools: z.ZodOptional<z.ZodArray<z.ZodString, "many">>; exclude_manuals: z.ZodOptional<z.ZodArray<z.ZodString, "many">>; only_include_manuals: z.ZodOptional<z.ZodArray<z.ZodString, "many">>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ tool_post_processor_t