### Migration Guide for Users Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/IMPORTS-GUIDE.md Illustrates the minimal change required for existing users when migrating to the new import pattern. The example shows that importing from the package root is now the standard, simplifying the update process. ```typescript // Before import { ToolDefinition } from '@utcp/sdk'; // After import { ToolDefinition } from '@utcp/sdk'; ``` -------------------------------- ### Install @utcp/http Package Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/http/README.md Instructions for installing the @utcp/http package and its core dependency @utcp/sdk using npm or bun. ```bash npm install @utcp/http @utcp/sdk # Or with bun bun add @utcp/http @utcp/sdk ``` -------------------------------- ### GitHub API Integration Example Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/http/README.md A comprehensive example showing how to integrate with the GitHub API to fetch repository issues. ```APIDOC ## HTTP GET GitHub Repository Issues ### Description This example demonstrates integrating with the GitHub API to retrieve a list of issues for a specific repository. It uses a bearer token for authorization, passed via headers and resolved from environment variables or client configuration. ### Method GET ### Endpoint `https://api.github.com/repos/${owner}/${repo}/issues` ### Parameters #### Path Parameters - **owner** (string) - Required - The owner of the repository. - **repo** (string) - Required - The name of the repository. #### Query Parameters None specified. #### Request Body Not applicable for GET method. #### Headers - **Authorization**: `Bearer ${TOKEN}` (Requires a `TOKEN` variable, typically prefixed like `github__api_TOKEN`) ### Request Example ```typescript const serializer = new HttpCallTemplateSerializer(); const githubTemplate = serializer.validateDict({ name: 'github_api', call_template_type: 'http', http_method: 'GET', url: 'https://api.github.com/repos/${owner}/${repo}/issues', headers: { 'Authorization': 'Bearer ${TOKEN}' } }); const client = await UtcpClient.create(process.cwd(), { variables: { 'github__api_TOKEN': process.env.GITHUB_TOKEN || '' }, manual_call_templates: [githubTemplate] }); const issues = await client.callTool('github_api.get_issues', { owner: 'utcp', repo: 'typescript-utcp' }); ``` ### Response #### Success Response (200) Returns an array of issue objects for the repository. #### Response Example ```json [ { "url": "https://api.github.com/repos/utcp/typescript-utcp/issues/1", "title": "Bug in issue parsing", "user": { "login": "contributor" } } ] ``` ``` -------------------------------- ### TypeScript Example: Git Workflow Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/cli/README.md Demonstrates a Git workflow setup using UTCP in TypeScript. This example configures `git add`, `git commit`, and `git push` commands, utilizing argument placeholders for the commit message and branch name. ```typescript const serializer = new CliCallTemplateSerializer(); const gitWorkflow = serializer.validateDict({ name: 'git_commit_push', call_template_type: 'cli', commands: [ { command: 'git add .', append_to_final_output: false }, { command: 'git commit -m "UTCP_ARG_message_UTCP_END"', append_to_final_output: false }, { command: 'git push origin UTCP_ARG_branch_UTCP_END', append_to_final_output: true } ] }); const result = await client.callTool('git_commit_push', { message: 'feat: add new feature', branch: 'main' }); ``` -------------------------------- ### Install @utcp/sdk with npm or bun Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/core/README.md This code snippet demonstrates how to install the @utcp/sdk package using either npm or bun, the recommended package managers for Node.js environments. ```bash npm install @utcp/sdk # Or with bun bun add @utcp/sdk ``` -------------------------------- ### TypeScript Example: Build and Test Pipeline Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/cli/README.md Illustrates setting up a build and test pipeline using UTCP in TypeScript. This example configures multiple npm commands (`lint`, `test`, `build`) with specific `append_to_final_output` settings and defines environment variables. ```typescript const serializer = new CliCallTemplateSerializer(); const buildPipeline = serializer.validateDict({ name: 'build_and_test', call_template_type: 'cli', commands: [ { command: 'npm run lint', append_to_final_output: false }, { command: 'npm test', append_to_final_output: true }, { command: 'npm run build', append_to_final_output: true } ], env_vars: { NODE_ENV: 'production', CI: 'true' } }); ``` -------------------------------- ### Install @utcp/mcp and @utcp/sdk using Bun or npm Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/mcp/README.md These commands show how to install the necessary packages for the @utcp/mcp plugin and its peer dependency, @utcp/sdk. The MCP SDK dependencies are included automatically. ```bash bun add @utcp/mcp @utcp/sdk # Or using npm npm install @utcp/mcp @utcp/sdk ``` -------------------------------- ### Running HTTP Protocol Tests with Bun Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/http/README.md This command demonstrates how to execute the tests specifically for the HTTP protocol using the Bun runtime. It points to the test directory within the packages/http/tests/ path, indicating a testing setup managed by Bun. ```bash # Run HTTP protocol tests bun test packages/http/tests/ ``` -------------------------------- ### Build and Test Pipeline Example Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/cli/README.md Illustrates a multi-command CLI template for a build and test pipeline, including environment variables. ```APIDOC ## Build and Test Pipeline Example Illustrates a multi-command CLI template for a build and test pipeline, including environment variables. ### Request Example ```typescript const serializer = new CliCallTemplateSerializer(); const buildPipeline = serializer.validateDict({ name: 'build_and_test', call_template_type: 'cli', commands: [ { command: 'npm run lint', append_to_final_output: false }, { command: 'npm test', append_to_final_output: true }, { command: 'npm run build', append_to_final_output: true } ], env_vars: { NODE_ENV: 'production', CI: 'true' } }); ``` ### Description This example defines a `build_and_test` CLI template. It includes three commands: `npm run lint`, `npm test`, and `npm run build`. The `append_to_final_output` flag is set to `false` for the linting step, meaning its output won't be included in the final result, while the test and build outputs will be included. Additionally, it sets environment variables `NODE_ENV` to `production` and `CI` to `true` for the execution context. ``` -------------------------------- ### Install @utcp/cli and @utcp/sdk Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/cli/README.md Installs the necessary packages for using the @utcp/cli plugin with the UTCP SDK. It supports both Bun and npm package managers. ```bash bun add @utcp/cli @utcp/sdk # Or using npm npm install @utcp/cli @utcp/sdk ``` -------------------------------- ### TypeScript: Multi-Command Workflow Execution Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/cli/README.md Illustrates how to define and execute a multi-command workflow using @utcp/cli. This example demonstrates changing directories, pulling changes, installing dependencies, and running tests sequentially within a single subprocess. ```typescript const serializer = new CliCallTemplateSerializer(); const multiStepTemplate = serializer.validateDict({ name: 'multi_step_workflow', call_template_type: 'cli', commands: [ { command: 'cd UTCP_ARG_target_dir_UTCP_END', append_to_final_output: false // Don't include this output in final result }, { command: 'git pull origin main', append_to_final_output: false // Don't include this output }, { command: 'npm install', append_to_final_output: false // Don't include this output }, { command: 'npm test', append_to_final_output: true // Include this output in final result } ] }); // Call with arguments const result = await client.callTool('multi_step_workflow', { target_dir: '/path/to/project' }); ``` -------------------------------- ### Set Up UTCP Monorepo for Development Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/README.md Clones the UTCP TypeScript monorepo from GitHub, navigates into the directory, installs project dependencies using bun, and builds all packages within the monorepo. ```bash # Clone the repository git clone https://github.com/universal-tool-calling-protocol/typescript-utcp.git cd typescript-utcp # Install dependencies (requires bun) bun install # Build all packages bun run build ``` -------------------------------- ### Implement Custom Tool Search Strategy (Semantic Search Example) Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/README.md Demonstrates implementing a custom `ToolSearchStrategy` for searching tools, using semantic search as an example. This allows for advanced, context-aware tool discovery. ```typescript import { ToolSearchStrategy } from '@utcp/sdk'; class SemanticSearchStrategy implements ToolSearchStrategy { async searchTools( repository: ConcurrentToolRepository, query: string, limit?: number ): Promise { // Custom semantic search implementation } } ``` -------------------------------- ### Install @utcp/code-mode using npm Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/code-mode/README.md This command installs the @utcp/code-mode package, which is required to use the code execution features. Ensure you have Node.js and npm installed in your environment. ```bash npm install @utcp/code-mode ``` -------------------------------- ### Example of Generated TypeScript Interfaces Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/code-mode/README.md An example output of generated TypeScript interfaces for UTCP tools, demonstrating how input and output types are defined within namespaces that mirror the tool's hierarchical structure. ```typescript // Auto-generated TypeScript interfaces for UTCP tools namespace math_tools { interface addInput { /** First number */ a: number; /** Second number */ b: number; } interface addOutput { /** The sum result */ result: number; } } /** * Adds two numbers * Tags: math, arithmetic * Access as: math_tools.add(args) */ ``` -------------------------------- ### Implement Custom Tool Repository (Redis Example) Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/README.md Shows how to implement a custom `ConcurrentToolRepository` for storing and retrieving tools, using Redis as an example backend. This allows for dynamic tool management. ```typescript import { ConcurrentToolRepository } from '@utcp/sdk'; class RedisToolRepository implements ConcurrentToolRepository { // Implement required methods async getTools(): Promise { /* ... */ } async getTool(name: string): Promise { /* ... */ } // ... other methods } ``` -------------------------------- ### Initialize UTCP Client with Configuration Source: https://context7.com/universal-tool-calling-protocol/typescript-utcp/llms.txt Initializes a new UTCP client instance, automatically registering all protocol plugins. It accepts configuration for manuals, variables (including dotenv loading), and repositories. The example demonstrates setting up an HTTP API call template for GitHub. ```typescript import { UtcpClient } from '@utcp/sdk'; import { HttpCallTemplateSerializer } from '@utcp/http'; async function initializeClient() { const httpSerializer = new HttpCallTemplateSerializer(); const githubTemplate = httpSerializer.validateDict({ name: 'github_api', call_template_type: 'http', http_method: 'GET', url: 'https://api.github.com/users/${username}', headers: { 'Authorization': 'Bearer ${TOKEN}' } }); const client = await UtcpClient.create(process.cwd(), { variables: { github__api_TOKEN: process.env.GITHUB_TOKEN || 'your-token', github__api_username: 'octocat' }, load_variables_from: [ { variable_loader_type: 'dotenv', env_file_path: './.env' } ], manual_call_templates: [githubTemplate] }); console.log('Client initialized successfully'); return client; } // Output: Client initialized successfully, tools registered ``` -------------------------------- ### Install @utcp/file and @utcp/sdk Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/file/README.md Installs the @utcp/file package and its peer dependency @utcp/sdk. Also notes that @utcp/http and js-yaml are automatically included for OpenAPI conversion and YAML parsing. ```bash bun add @utcp/file @utcp/sdk # Or using npm npm install @utcp/file @utcp/sdk ``` -------------------------------- ### Dynamic Tool Discovery with CLI Provider in TypeScript Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/cli/README.md Explains how to create a CLI tool that dynamically discovers its available tools using a UTCP discovery flag ('--utcp-discover') in TypeScript. The example shows both the client-side setup for discovering tools and the server-side (CLI tool) implementation for outputting its manual. ```typescript // Client-side setup const serializer = new CliCallTemplateSerializer(); const discoveryTemplate = serializer.validateDict({ name: 'my_cli_tools', call_template_type: 'cli', commands: [ { command: 'node my-cli-tool.js --utcp-discover', append_to_final_output: true } ] }); const client = await UtcpClient.create(process.cwd(), { manual_call_templates: [discoveryTemplate] }); // Tools are automatically discovered and registered const tools = await client.searchTools('my_cli_tools'); console.log('Discovered tools:', tools.map(t => t.name)); ``` ```typescript // my-cli-tool.ts if (process.argv.includes('--utcp-discover')) { const manual = { utcp_version: "1.0.0", manual_version: "1.0.0", tools: [ { name: "echo_cli", description: "Echoes a message via CLI.", inputs: { type: "object", properties: { message: { type: "string" } }, required: ["message"] }, outputs: { type: "string" }, tags: ["cli", "echo"], tool_call_template: { name: "my_cli_tools", call_template_type: "cli" } } ] }; console.log(JSON.stringify(manual)); process.exit(0); } // Handle other commands... ``` -------------------------------- ### Git Workflow Example Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/cli/README.md Shows a CLI template for a common Git workflow involving add, commit, and push operations. ```APIDOC ## Git Workflow Example Shows a CLI template for a common Git workflow involving add, commit, and push operations. ### Request Example ```typescript const serializer = new CliCallTemplateSerializer(); const gitWorkflow = serializer.validateDict({ name: 'git_commit_push', call_template_type: 'cli', commands: [ { command: 'git add .', append_to_final_output: false }, { command: 'git commit -m "UTCP_ARG_message_UTCP_END"', append_to_final_output: false }, { command: 'git push origin UTCP_ARG_branch_UTCP_END', append_to_final_output: true } ] }); const result = await client.callTool('git_commit_push', { message: 'feat: add new feature', branch: 'main' }); ``` ### Description This example defines a `git_commit_push` CLI template. It orchestrates a Git workflow: first, `git add .` stages all changes (output not appended to final result). Second, `git commit -m "UTCP_ARG_message_UTCP_END"` creates a commit with a message provided via the `message` argument (output not appended). Finally, `git push origin UTCP_ARG_branch_UTCP_END` pushes the changes to the specified branch (output appended to final result). The placeholders `UTCP_ARG_message_UTCP_END` and `UTCP_ARG_branch_UTCP_END` are dynamically replaced with the values passed to `client.callTool`. ``` -------------------------------- ### Basic File Operations Example Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/cli/README.md Demonstrates a basic CLI call to read the content of a file using UTCP. ```APIDOC ## Basic File Operations Example Demonstrates a basic CLI call to read the content of a file using UTCP. ### Request Example ```typescript const serializer = new CliCallTemplateSerializer(); const fileOpsTemplate = serializer.validateDict({ name: 'file_operations', call_template_type: 'cli', commands: [ { command: 'cat UTCP_ARG_filename_UTCP_END' } ] }); const content = await client.callTool('file_operations', { filename: '/path/to/file.txt' }); ``` ### Description This example defines a CLI template named `file_operations`. It consists of a single command that uses an argument placeholder `UTCP_ARG_filename_UTCP_END` to specify the file to be read by the `cat` command. When `client.callTool` is invoked with the `filename` argument, the placeholder is substituted, and the `cat` command is executed. ``` -------------------------------- ### Basic HTTP Usage Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/http/README.md Demonstrates how to make a standard HTTP GET request to a weather API using the UTCP SDK. It shows setting up the client, defining a manual HTTP call template, and invoking a tool. ```APIDOC ## GET /v1/current.json (weather_api) ### Description Retrieves the current weather information for a specified location. ### Method GET ### Endpoint `https://api.weatherapi.com/v1/current.json` ### Parameters #### Query Parameters - **q** (string) - Required - The location (e.g., city name, zip code) to get weather information for. #### Headers - **X-API-Key** (string) - Required - Your unique API key for accessing the weather service. ### Request Example ```json { "name": "weather_api", "call_template_type": "http", "http_method": "GET", "url": "https://api.weatherapi.com/v1/current.json", "headers": { "X-API-Key": "${API_KEY}" } } ``` ### Response #### Success Response (200) - **data** (object) - The weather data for the specified location. - **location** (object) - Details about the location. - **current** (object) - Current weather conditions. #### Response Example ```json { "location": { "name": "London", "region": "City of London, Greater London", "country": "United Kingdom", "lat": 51.52, "lon": -0.11, "tz_id": "Europe/London", "localtime_epoch": 1678886400, "localtime": "2023-03-15 10:00" }, "current": { "temp_c": 8.0, "condition": { "text": "Partly cloudy", "icon": "//cdn.weatherapi.com/weather/64x64/day/116.png", "code": 1003 }, "wind_kph": 11.2, "wind_dir": "SW", "pressure_mb": 1015.0, "precip_mm": 0.1, "humidity": 70, "cloud": 75, "feelslike_c": 5.0 } } ``` ``` -------------------------------- ### UTCP CLI Protocol Configuration in TypeScript Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/README.md Configures a CLI call template for executing command-line tools. This example defines a 'git status' command and specifies the working directory for its execution. ```typescript import { CliCallTemplateSerializer } from '@utcp/cli'; const serializer = new CliCallTemplateSerializer(); const cliTemplate = serializer.validateDict({ name: 'system_commands', call_template_type: 'cli', commands: [ { command: 'git status' } ], working_dir: './my-repo' }); ``` -------------------------------- ### Discover Tools from OpenAPI Specification with UTCP TypeScript Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/http/README.md This example demonstrates how to automatically discover tools from an OpenAPI specification using the UTCP SDK. A HTTP call template is created pointing to the OpenAPI JSON URL, and then tools can be searched and called by name. Dependencies include '@utcp/sdk' and '@utcp/http'. ```typescript import { UtcpClient } from '@utcp/sdk'; import { HttpCallTemplateSerializer } from '@utcp/http'; const serializer = new HttpCallTemplateSerializer(); const petstoreTemplate = serializer.validateDict({ name: 'petstore_api', call_template_type: 'http', http_method: 'GET', url: 'https://petstore.swagger.io/v2/swagger.json', // Tools will be auto-discovered from the OpenAPI spec }); const client = await UtcpClient.create(process.cwd(), { manual_call_templates: [petstoreTemplate] }); // Search for discovered tools const tools = await client.searchTools('pet'); console.log('Available tools:', tools.map(t => t.name)); // Call a discovered tool const pets = await client.callTool('petstore_api.findPetsByStatus', { status: 'available' }); ``` -------------------------------- ### Basic HTTP Request with UTCP TypeScript SDK Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/http/README.md This snippet shows how to make a basic HTTP GET request using the UTCP SDK. It involves creating an HTTP call template, configuring the client with variables, and then calling the tool. Dependencies include '@utcp/sdk' and '@utcp/http'. ```typescript import { UtcpClient } from '@utcp/sdk'; import { HttpCallTemplateSerializer } from '@utcp/http'; async function main() { const serializer = new HttpCallTemplateSerializer(); const weatherTemplate = serializer.validateDict({ name: 'weather_api', call_template_type: 'http', http_method: 'GET', url: 'https://api.weatherapi.com/v1/current.json', headers: { 'X-API-Key': '${API_KEY}' } }); const client = await UtcpClient.create(process.cwd(), { variables: { // Namespaced variables for security 'weather__api_API_KEY': process.env.WEATHER_API_KEY || '' }, manual_call_templates: [weatherTemplate] }); // Call the API const weather = await client.callTool('weather_api.get_current', { q: 'London' }); console.log('Weather:', weather); await client.close(); } ``` -------------------------------- ### AI Agent System Prompt with UTCP Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/code-mode/README.md Provides the necessary TypeScript code snippet to integrate the UTCP CodeMode client into an AI agent's system prompt. It includes the `CodeModeUtcpClient.AGENT_PROMPT_TEMPLATE` to guide the AI on tool discovery, access patterns, and best practices for using UTCP. ```typescript import { CodeModeUtcpClient } from '@utcp/code-mode'; // Add this to your AI agent's system prompt const systemPrompt = ` You are an AI assistant with access to tools via UTCP CodeMode. ${CodeModeUtcpClient.AGENT_PROMPT_TEMPLATE} Additional instructions... `; ``` -------------------------------- ### Basic UtcpClient Usage with HTTP Protocol Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/core/README.md Illustrates the basic setup and usage of UtcpClient, including importing and registering the HTTP protocol plugin, defining an API call template with variable substitution for authentication, and performing a tool search and call. It also shows client initialization with custom variables and manual call templates. ```typescript import { UtcpClient } from '@utcp/sdk'; import '@utcp/http'; // Auto-registers HTTP protocol import { HttpCallTemplateSerializer } from '@utcp/http'; async function main() { // Create client const serializer = new HttpCallTemplateSerializer(); const apiTemplate = serializer.validateDict({ name: 'api_manual', call_template_type: 'http', http_method: 'GET', url: 'https://api.example.com/data', headers: { 'Authorization': 'Bearer ${API_KEY}' // Resolves to api__manual_API_KEY } }); const client = await UtcpClient.create(process.cwd(), { variables: { // Namespaced format: manual_name_VARIABLE api__manual_API_KEY: process.env.API_KEY || '' }, manual_call_templates: [apiTemplate] }); // Search for tools const tools = await client.searchTools('data'); // Call a tool const result = await client.callTool('api_manual.get_data', {}); await client.close(); } ``` -------------------------------- ### UTCP HTTP Protocol Configuration in TypeScript Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/README.md Configures an HTTP call template for UTCP, supporting RESTful APIs and automatic OpenAPI specification conversion. This example shows setting up a GET request for weather data, including header authentication. ```typescript import { HttpCallTemplateSerializer } from '@utcp/http'; const serializer = new HttpCallTemplateSerializer(); const weatherTemplate = serializer.validateDict({ name: 'weather_api', call_template_type: 'http', http_method: 'GET', url: 'https://api.weather.com/v1/forecast', headers: { 'X-API-Key': '${API_KEY}' }, // Optional: Basic, API Key, or OAuth2 authentication auth: { auth_type: 'api_key', var_name: 'X-API-Key', api_key_value: '${API_KEY}', in: 'header' } }); // Features include path parameter substitution, header/body templates, multiple auth methods, and OpenAPI to UTCP conversion. ``` -------------------------------- ### Correct Import from Main Entry Point (TypeScript) Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/IMPORTS-GUIDE.md Demonstrates the correct way to import UTCP SDK, MCP, Text, HTTP, and CLI packages from their main entry points. This ensures compatibility with the standard library pattern and modern bundlers. ```typescript import { UtcpClient, ToolDefinition, CallTemplate } from '@utcp/sdk'; import { McpCommunicationProtocol } from '@utcp/mcp'; import { TextCallTemplate } from '@utcp/text'; import { HttpCommunicationProtocol } from '@utcp/http'; import { CliCallTemplate } from '@utcp/cli'; ``` -------------------------------- ### Basic UTCP Client Usage in TypeScript Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/README.md Demonstrates the basic usage of the UTCP SDK in TypeScript. It shows how to create a client instance, automatically registering plugins, define an HTTP call template, set namespace-isolated variables, search for tools, call a tool, and properly close the client connection. ```typescript import { UtcpClient } from '@utcp/sdk'; import { HttpCallTemplateSerializer } from '@utcp/http'; async function main() { // Create client - plugins auto-register const serializer = new HttpCallTemplateSerializer(); const githubTemplate = serializer.validateDict({ name: 'github_api', call_template_type: 'http', http_method: 'GET', url: 'https://api.github.com/users/${username}', }); const client = await UtcpClient.create(process.cwd(), { manual_call_templates: [githubTemplate], variables: { // Namespace format: manual_name_VARIABLE github__api_username: 'octocat' } }); // Search for tools const tools = await client.searchTools('github user'); console.log('Found tools:', tools.map(t => t.name)); // Call a tool const result = await client.callTool('github_api.get_user', {}); console.log('Result:', result); await client.close(); } main().catch(console.error); ``` -------------------------------- ### Install @utcp/dotenv-loader using npm Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/dotenv-loader/README.md This command installs the dotenv-loader plugin for UTCP using the Node Package Manager (npm). It is a prerequisite for using the plugin in your project. ```bash npm install @utcp/dotenv-loader ``` -------------------------------- ### UtcpClient.create() Configuration in TypeScript Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/README.md Details the static `create` method of `UtcpClient` for initializing the SDK. It outlines the parameters `root_dir` and `config`, with a deep dive into the `UtcpClientConfig` interface, including options for variables, variable loaders, and manual call templates. ```typescript static async create( root_dir: string, config: Partial ): Promise interface UtcpClientConfig { // Direct variable definitions (highest priority) variables?: Record; // External variable loaders (e.g., .env files) load_variables_from?: Array<{ variable_loader_type: 'dotenv'; env_file_path: string; }>; // Manual call templates to register at startup manual_call_templates?: CallTemplate[]; // Tool repository configuration (defaults to in-memory) tool_repository?: ConcurrentToolRepository; // Search strategy configuration (defaults to tag_and_description_word_match) tool_search_strategy?: ToolSearchStrategy; // Post-processing configurations post_processing?: ToolPostProcessor[]; } ``` -------------------------------- ### UtcpClient.create() Static Method Signature Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/core/README.md Provides the TypeScript signature for the static `create` method of `UtcpClient`, outlining its parameters for initializing a new client instance. It specifies the `root_dir` and optional `config` object. ```typescript static async create( root_dir: string, config?: Partial ): Promise ``` -------------------------------- ### Build Script Execution Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/core/scripts/README.md Shows the commands to execute the build process for the project using npm or bun. The build process includes cleaning, TypeScript compilation, and version replacement. ```bash npm run build # or bun run build ``` -------------------------------- ### Install UTCP Packages via npm or bun Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/README.md Installs the core UTCP SDK and various protocol plugins using either npm or bun package managers. The dotenv loader is an optional dependency for Node.js environments. ```bash npm install @utcp/sdk @utcp/http @utcp/mcp @utcp/text @utcp/file @utcp/code-mode # Optional: Add dotenv variable loader for Node.js npm install @utcp/dotenv-loader # Or using bun bun add @utcp/sdk @utcp/http @utcp/mcp @utcp/text @utcp/file @utcp/code-mode ``` -------------------------------- ### TypeScript IntelliSense Hint Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/IMPORTS-GUIDE.md A reminder that IDEs provide auto-completion for imports from '@utcp/sdk', helping developers discover available exports quickly. ```typescript import { /* Ctrl+Space to see all exports */ } from '@utcp/sdk'; ``` -------------------------------- ### TypeScript: Integrate and Use @utcp/file Plugin Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/file/README.md This snippet shows how to import and utilize the @utcp/file plugin in a TypeScript application. It demonstrates creating dummy files, setting up the UTCP client with a file-based manual, searching for and calling tools that read file content, and cleaning up generated files. This example requires Node.js environment and access to the file system. ```typescript // From your application's entry point import { UtcpClient } from '@utcp/sdk'; import { FileCallTemplateSerializer } from '@utcp/file'; import * as path from 'path'; import * as fs from 'fs/promises'; // For creating dummy files async function main() { // Create a dummy UTCP manual file for demonstration const manualContent = { "utcp_version": "1.0.0", "manual_version": "1.0.0", "tools": [ { "name": "read_static_data", "description": "Reads static data from a local file.", "inputs": {}, "outputs": { "type": "string", "description": "The content of the file." }, "tags": ["file", "static"], "tool_call_template": { "name": "static_file_reader", "call_template_type": "file", "file_path": "./config/static_data.txt" // The file path for the tool's content } }, { "name": "describe_project", "description": "Provides a description of the project from a local markdown file.", "inputs": {}, "outputs": { "type": "string" }, "tags": ["documentation"], "tool_call_template": { "name": "project_readme_reader", "call_template_type": "file", "file_path": "./README.md" // Example: reads the project's README } } ] }; const configDirPath = path.resolve(process.cwd(), './config'); await fs.mkdir(configDirPath, { recursive: true }); const dummyManualPath = path.resolve(configDirPath, './my_local_manual.json'); await fs.writeFile(dummyManualPath, JSON.stringify(manualContent, null, 2)); const staticDataPath = path.resolve(configDirPath, './static_data.txt'); await fs.writeFile(staticDataPath, 'Hello from UTCP File Plugin static data!'); // Define a CallTemplate to load the local UTCP manual from the 'config' directory const serializer = new FileCallTemplateSerializer(); const fileCallTemplate = serializer.validateDict({ name: 'local_manual_loader', call_template_type: 'file', file_path: './config/my_local_manual.json', // Path relative to client's root_path }); const client = await UtcpClient.create(process.cwd(), { manual_call_templates: [fileCallTemplate] // Register the file manual at client startup }); console.log('File Plugin active. Searching for tools...'); // Example: Call 'read_static_data' tool. This will return the content of 'static_data.txt'. try { const staticDataReaderTool = await client.searchTools('read static data'); if (staticDataReaderTool.length > 0) { const result = await client.callTool(staticDataReaderTool.name, {}); console.log('Result from "read_static_data" tool:', result); } } catch (error) { console.error('Error calling "read_static_data" tool:', error); } // Example: Call 'describe_project' tool. This will return the content of the project's README.md. try { const projectDescTool = await client.searchTools('project description'); if (projectDescTool.length > 0) { const result = await client.callTool(projectDescTool.name, {}); console.log('Result from "describe_project" tool (first 100 chars):', String(result).substring(0, 100) + '...'); } } catch (error) { console.error('Error calling "describe_project" tool:', error); } finally { // Clean up dummy files await fs.unlink(dummyManualPath); await fs.unlink(staticDataPath); await fs.rmdir(configDirPath); // Remove the config directory } await client.close(); // No-op for file protocol, but good practice } main().catch(console.error); ``` -------------------------------- ### UTCP SDK Package Exports (TypeScript) Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/IMPORTS-GUIDE.md Lists all available exports from the core '@utcp/sdk' package, including client configurations, data models, interfaces, implementations, and plugin loaders. This provides a comprehensive overview for developers. ```typescript import { // Client UtcpClient, UtcpClientConfig, // Data Models Auth, CallTemplate, Tool, ToolDefinition, UtcpManual, RegisterManualResult, // Interfaces CommunicationProtocol, ConcurrentToolRepository, Serializer, ToolSearchStrategy, VariableSubstitutor, // Implementations InMemConcurrentToolRepository, TagSearchStrategy, // Plugins PluginLoader } from '@utcp/sdk'; ``` -------------------------------- ### UtcpClient.create() Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/core/README.md Creates a new instance of the UtcpClient. This is the primary entry point for interacting with the UTCP ecosystem. It allows for custom configuration of variables, manual call templates, tool repositories, and search strategies. ```APIDOC ## UtcpClient.create() ### Description Creates a new instance of the UtcpClient. This is the primary entry point for interacting with the UTCP ecosystem. It allows for custom configuration of variables, manual call templates, tool repositories, and search strategies. ### Method `static async create(root_dir: string, config?: Partial): Promise` ### Parameters #### Path Parameters * **root_dir** (string) - Required - Base directory for resolving relative paths (typically `process.cwd()`) #### Query Parameters * **config** (Partial) - Optional - Configuration object for the UtcpClient. **Configuration (`UtcpClientConfig`)**: - **variables** (Record) - Optional - Direct variable definitions (highest priority). - **load_variables_from** (VariableLoader[]) - Optional - External variable loaders for loading variables from sources like `.env` files. - **manual_call_templates** (CallTemplate[]) - Optional - Initial manuals to register with the client. - **tool_repository** (ConcurrentToolRepository) - Optional - Tool storage implementation (default: in-memory). - **tool_search_strategy** (ToolSearchStrategy) - Optional - Tool search algorithm implementation (default: tag and description matching). - **post_processing** (ToolPostProcessor[]) - Optional - Array of result post-processors. ### Request Example ```typescript import { UtcpClient } from '@utcp/sdk'; import '@utcp/http'; // Auto-registers HTTP protocol async function main() { const client = await UtcpClient.create(process.cwd(), { variables: { api__manual_API_KEY: process.env.API_KEY || '' }, manual_call_templates: [ // ... your CallTemplate objects ] }); // ... use client await client.close(); } ``` ### Response #### Success Response (UtcpClient) - **UtcpClient** - An initialized UtcpClient instance. ``` -------------------------------- ### TypeScript Example: Basic File Operations Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/cli/README.md Demonstrates a basic file operation using UTCP in TypeScript. It shows how to serialize a `CliCallTemplate` for a 'cat' command and execute it with a provided filename argument using `client.callTool`. ```typescript const serializer = new CliCallTemplateSerializer(); const fileOpsTemplate = serializer.validateDict({ name: 'file_operations', call_template_type: 'cli', commands: [ { command: 'cat UTCP_ARG_filename_UTCP_END' } ] }); const content = await client.callTool('file_operations', { filename: '/path/to/file.txt' }); ``` -------------------------------- ### CodeModeUtcpClient.create Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/code-mode/README.md Documentation for the static `create` method of `CodeModeUtcpClient`, used for instantiating the client with optional root directory and configuration. ```APIDOC ## CodeModeUtcpClient.create ### Description Asynchronously creates and returns a new instance of `CodeModeUtcpClient`. Allows specifying a root directory for path resolution and custom client configuration. ### Method `CodeModeUtcpClient.create(root_dir?: string, config?: UtcpClientConfig): Promise` ### Parameters - **root_dir** (string) - Optional - The root directory to use for resolving relative paths. - **config** (UtcpClientConfig) - Optional - Configuration options for the UTCP client. ### Returns - **Promise** - A promise that resolves to a new `CodeModeUtcpClient` instance. ``` -------------------------------- ### Getting Required Variables for a Tool Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/core/README.md Demonstrates the `getRequiredVariablesForTool` asynchronous method, which returns an array of strings representing the names of variables required by a specified tool. This can be useful for pre-flight checks or user input prompts. ```typescript async getRequiredVariablesForTool(toolName: string): Promise ``` -------------------------------- ### Re-Publishing Commands Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/IMPORTS-GUIDE.md Provides the necessary commands using 'bun' to rebuild packages and publish new versions after configuration changes. This includes updating the version in 'package.json' and executing the publish script. ```bash # Update version in each package.json (1.0.1 -> 1.0.2) bun run rebuild bun run publish:all ``` -------------------------------- ### UTCP Text Protocol Configuration in TypeScript Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/README.md Configures a Text call template for handling direct text/string content, compatible with browsers. This example shows how to stringify JSON content containing UTCP manuals or OpenAPI specs. ```typescript import { TextCallTemplateSerializer } from '@utcp/text'; const serializer = new TextCallTemplateSerializer(); const textTemplate = serializer.validateDict({ name: 'inline_tools', call_template_type: 'text', content: JSON.stringify({ tools: [ // UTCP manual or OpenAPI spec as string ] }) }); ``` -------------------------------- ### TypeScript: Output Chaining Between Commands Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/cli/README.md Shows how to chain the output of one command as input to another using special variables like `$CMD_0_OUTPUT`. This example builds a Docker image tagged with a Git commit hash. ```typescript const serializer = new CliCallTemplateSerializer(); const outputChainingTemplate = serializer.validateDict({ name: 'chained_commands', call_template_type: 'cli', commands: [ { command: 'git rev-parse --short HEAD', append_to_final_output: false }, { command: 'echo "Building version: $CMD_0_OUTPUT"', append_to_final_output: false }, { command: 'docker build -t myapp:$CMD_0_OUTPUT .', append_to_final_output: true } ] }); ``` -------------------------------- ### UtcpClient.create() Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/README.md Initializes and creates a new instance of the UtcpClient. This is the primary entry point for interacting with the UTCP SDK. ```APIDOC ## UtcpClient.create() ### Description Initializes and creates a new instance of the UtcpClient. This is the primary entry point for interacting with the UTCP SDK. It allows configuration of variables, loading them from external sources, and registering manual call templates. ### Method `static async create(root_dir: string, config: Partial): Promise` ### Parameters #### Path Parameters * `root_dir` (string) - Required - Base directory for resolving relative paths (usually `process.cwd()`) #### Query Parameters * `config` (Partial) - Required - Client configuration object #### Request Body * `variables` (Record) - Optional - Direct variable definitions (highest priority) * `load_variables_from` (Array<{ variable_loader_type: 'dotenv'; env_file_path: string; }>)- Optional - External variable loaders (e.g., .env files) * `manual_call_templates` (CallTemplate[]) - Optional - Manual call templates to register at startup * `tool_repository` (ConcurrentToolRepository) - Optional - Tool repository configuration (defaults to in-memory) * `tool_search_strategy` (ToolSearchStrategy) - Optional - Search strategy configuration (defaults to tag_and_description_word_match) * `post_processing` (ToolPostProcessor[]) - Optional - Post-processing configurations ### Response #### Success Response (200) - `UtcpClient` - An instance of the UtcpClient. #### Response Example ```typescript // Example of response object structure (actual instance) { // ... client instance properties ... } ``` ``` -------------------------------- ### UTCP MCP Protocol Configuration in TypeScript Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/README.md Sets up a Model Context Protocol (MCP) call template for connecting to MCP servers. This example demonstrates configuring an MCP server using the 'stdio' transport and specifying the command to run. ```typescript import { McpCallTemplateSerializer } from '@utcp/mcp'; const serializer = new McpCallTemplateSerializer(); const mcpTemplate = serializer.validateDict({ name: 'mcp_manual', call_template_type: 'mcp', config: { mcpServers: { server_name: { transport: 'stdio', // or 'http' command: 'bun', args: ['run', './mcp-server.ts'], cwd: './servers', env: { DEBUG: 'true' } } } } }); // Tool naming convention: `manual_name.server_name.tool_name`. // Features include stdio/HTTP transports, persistent sessions, retries, and multiple servers. ``` -------------------------------- ### Custom Tool Repository Implementation Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/packages/core/README.md Provides an example of implementing a custom tool repository by extending the `ConcurrentToolRepository` interface. This allows users to integrate their own tool management systems with UTCP, defining how tools are retrieved, saved, and removed. ```typescript import { ConcurrentToolRepository, Tool } from '@utcp/sdk'; class CustomRepository implements ConcurrentToolRepository { tool_repository_type = 'custom' as const; async getTools(): Promise { /* ... */ } async getTool(name: string): Promise { /* ... */ } async saveManual(callTemplate: CallTemplate, manual: UtcpManual): Promise { /* ... */ } async removeManual(manualName: string): Promise { /* ... */ } // ... implement other required methods } const client = await UtcpClient.create(process.cwd(), { tool_repository: new CustomRepository() }); ``` -------------------------------- ### Initialize UTCP Client with Multiple Protocols in TypeScript Source: https://github.com/universal-tool-calling-protocol/typescript-utcp/blob/main/README.md Demonstrates how to create an UtcpClient instance in TypeScript, registering various call templates for HTTP, MCP, and file-based tools. It shows how to configure variables and load them from environment files. ```typescript import { UtcpClient } from '@utcp/sdk'; import { HttpCallTemplateSerializer } from '@utcp/http'; import { McpCallTemplateSerializer } from '@utcp/mcp'; import { FileCallTemplateSerializer } from '@utcp/file'; async function main() { // Create serializers for each protocol const httpSerializer = new HttpCallTemplateSerializer(); const mcpSerializer = new McpCallTemplateSerializer(); const fileSerializer = new FileCallTemplateSerializer(); // Validate and create call templates const httpTemplate = httpSerializer.validateDict({ name: 'api_manual', call_template_type: 'http', http_method: 'GET', url: 'https://api.example.com/data', headers: { 'Authorization': 'Bearer ${API_KEY}' } }); const mcpTemplate = mcpSerializer.validateDict({ name: 'mcp_tools', call_template_type: 'mcp', config: { mcpServers: { my_mcp_server: { transport: 'stdio', command: 'node', args: ['./mcp-server.js'], cwd: './servers' } } } }); const fileTemplate = fileSerializer.validateDict({ name: 'local_tools', call_template_type: 'file', file_path: './config/tools.json' }); const client = await UtcpClient.create(process.cwd(), { variables: { // Namespaced variables for security api__manual_API_KEY: process.env.API_KEY || 'default-key', }, load_variables_from: [ { variable_loader_type: 'dotenv', env_file_path: './.env' } ], manual_call_templates: [ httpTemplate, // HTTP API mcpTemplate, // MCP Server fileTemplate // Local file-based tools ] }); // Tools are namespaced: manual_name.tool_name // For MCP: manual_name.server_name.tool_name const allTools = await client.getTools(); console.log('Registered tools:', allTools.map(t => t.name)); // Examples: // - 'api_manual.get_data' // - 'mcp_tools.my_mcp_server.echo' // - 'local_tools.my_function' await client.close(); } ```