### Install and Run CLI Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-cli/README.md Use this command to initiate the agent's self-configuration and usage guide. The agent will then read this guide to create its configuration file. ```bash npx -y @utcp/code-mode-cli prompt ``` -------------------------------- ### Local Development Setup Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-cli/README.md Commands to set up the local development environment for @utcp/code-mode-cli, including installing dependencies, building the project, and running the help command. ```bash npm install npm run build node dist/index.js --help ``` -------------------------------- ### Install @utcp/code-mode and Dependencies Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/typescript-library/README.md Install the necessary packages for code-mode, UTCP SDK, direct call, and isolated-vm. ```bash npm install @utcp/code-mode @utcp/sdk @utcp/direct-call isolated-vm ``` -------------------------------- ### Install code-mode Package Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/python-library/README.md Install the code-mode package using pip. This is the primary step to begin using the library. ```bash pip install code-mode ``` -------------------------------- ### Bootstrap UTCP Code Mode CLI Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-cli/SKILL.md Use this command to bootstrap the UTCP Code Mode CLI, which is useful for getting started or prompting for initial setup. ```bash npx @utcp/code-mode-cli prompt ``` -------------------------------- ### Quick Start: Execute TypeScript with Tool Access Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/typescript-library/README.md Demonstrates registering a UTCP manual and a tool implementation, then executing TypeScript code that calls the registered tool. ```typescript import { CodeModeUtcpClient } from '@utcp/code-mode'; import { addFunctionToUtcpDirectCall } from '@utcp/direct-call'; // Register a function that returns a UTCP manual addFunctionToUtcpDirectCall('getWeatherManual', async () => ({ utcp_version: '0.2.0', tools: [{ name: 'get_current', description: 'Get current weather for a city', inputs: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] }, tool_call_template: { call_template_type: 'direct-call', callable_name: 'getWeather' } }] })); // Register the actual tool implementation addFunctionToUtcpDirectCall('getWeather', async (city: string) => ({ city, temperature: 22, condition: 'sunny' })); // Create client and register manual const client = await CodeModeUtcpClient.create(); await client.registerManual({ name: 'weather', call_template_type: 'direct-call', callable_name: 'getWeatherManual' }); // Execute code with tool access const { result, logs } = await client.callToolChain(` const data = weather.get_current({ city: 'London' }); console.log('Weather:', data); return data; `); console.log(result); // { city: 'London', temperature: 22, condition: 'sunny' } ``` -------------------------------- ### Install @utcp/code-mode Package Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md Install the necessary package for using Code Mode. This is a prerequisite for both CLI and MCP server usage. ```bash npm install @utcp/code-mode ``` -------------------------------- ### UTCP Configuration File Example Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-mcp/README.md Example of a `.utcp_config.json` file to configure tools, services, and post-processing for the UTCP Code Mode bridge. It includes settings for environment variables, HTTP call templates, and tool repositories. ```json { "load_variables_from": [ { "variable_loader_type": "dotenv", "env_file_path": ".env" } ], "manual_call_templates": [ { "name": "openlibrary", "call_template_type": "http", "http_method": "GET", "url": "https://openlibrary.org/static/openapi.json", "content_type": "application/json" } ], "post_processing": [ { "tool_post_processor_type": "filter_dict", "only_include_keys": ["name", "description"], "only_include_tools": ["openlibrary.*"] } ], "tool_repository": { "tool_repository_type": "in_memory" }, "tool_search_strategy": { "tool_search_strategy_type": "tag_and_description_word_match" } } ``` -------------------------------- ### Discover Tools with UTCP CLI Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-cli/SKILL.md Commands to discover available tools, list their names, get detailed information, and check for required variables. ```bash utcp search "search for books" ``` ```bash utcp list ``` ```bash utcp info ``` ```bash utcp keys ``` -------------------------------- ### Example: Chaining Tools for Procurement and Pricing Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/typescript-library/README.md Illustrates chaining multiple tool calls within a single `callToolChain` execution, such as searching for parts and then getting their pricing. ```typescript const result = await client.callToolChain(` // Get parts from supplier const parts = procurement.search_parts({ mpn: 'LM358' }); // Get pricing for each part const pricing = parts.map(part => procurement.get_pricing({ part_id: part.id }) ); // Return combined result return { parts, pricing }; `); ``` -------------------------------- ### Connect to MCP Server with CodeModeUtcpClient Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/python-library/README.md Demonstrates how to create a CodeModeUtcpClient and connect to a GitHub MCP server. Ensure the 'utcp-mcp' plugin is installed and prerequisites like GITHUB_PERSONAL_ACCESS_TOKEN are met. ```python from utcp_code_mode import CodeModeUtcpClient from utcp.data.call_template import CallTemplateSerializer import os client = await CodeModeUtcpClient.create() # Connect to GitHub MCP server # Serialize the dict to CallTemplate object call_template = CallTemplateSerializer().validate_dict({ 'name': 'github', 'call_template_type': 'mcp', 'config': { 'mcpServers': { 'github': { 'command': 'docker', 'args': ['run', '-i', '--rm', '-e', 'GITHUB_PERSONAL_ACCESS_TOKEN', 'mcp/github'], 'env': {'GITHUB_PERSONAL_ACCESS_TOKEN': os.environ.get('GITHUB_TOKEN')} } } } }) await client.register_manual(call_template) ``` -------------------------------- ### Initialize, Register Tools, and Execute Code Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/python-library/README.md Initialize the CodeModeUtcpClient, register a manual call template for tools, and then execute a tool chain. This is the basic setup for using UTCP Code Mode. ```python from utcp_code_mode import CodeModeUtcpClient from utcp.data.call_template import CallTemplateSerializer client = await CodeModeUtcpClient.create() # 1. Initialize # Serialize the call template dict to CallTemplate object call_template = CallTemplateSerializer().validate_dict({ 'name': 'github', 'call_template_type': 'mcp', 'config': {...} }) await client.register_manual(call_template) # 2. Add tools result = await client.call_tool_chain("# Python code here") # 3. Execute code ``` -------------------------------- ### Run Tool-Chain with utcp CLI Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md Execute a tool-chain defined in JavaScript using the `utcp` CLI. This example maps search results to titles. ```javascript const r = await openlibrary.read_search_json_search_json_get({ q: "tolkien", limit: 3 }); return r.docs.map(b => b.title); ``` -------------------------------- ### Initiate Interactive OAuth Login Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-cli/SKILL.md Start an interactive OAuth sign-in process for a specified manual. This command initiates the flow and prints NDJSON instructions. ```bash utcp login ``` -------------------------------- ### Discover Tools Dynamically Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/python-library/README.md Agents can discover tools dynamically, loading only the necessary ones. This example shows searching for tools related to 'github pull request'. ```python # Agent discovers tools dynamically, loads only what it needs tools = await client.search_tools('github pull request') # Instead of 500 tool definitions → 3 relevant tools ``` -------------------------------- ### Install and Import MCP Transport Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md Install the MCP transport package and import it to register the 'mcp' call template. This is a prerequisite for connecting to an MCP server. ```bash npm install @utcp/mcp ``` -------------------------------- ### Configure UTCP with .utcp_config.json Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-cli/SKILL.md Define API and server configurations in a `.utcp_config.json` file. This example shows loading environment variables and configuring an HTTP call template for the Open Library API. ```json { "load_variables_from": [ { "variable_loader_type": "dotenv", "env_file_path": ".env" } ], "manual_call_templates": [ { "name": "openlibrary", "call_template_type": "http", "http_method": "GET", "url": "https://openlibrary.org/static/openapi.json", "content_type": "application/json" } ] } ``` -------------------------------- ### AI Agent Integration with OpenAI Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/python-library/README.md Use the `CodeModeUtcpClient.AGENT_PROMPT_TEMPLATE` with an AI client like OpenAI to enable tool access for your agent. The system prompt includes the template, guiding the AI on how to discover and use available tools. ```python from utcp_code_mode import CodeModeUtcpClient from openai import OpenAI system_prompt = f""" You are an AI assistant with access to tools via UTCP CodeMode. {CodeModeUtcpClient.AGENT_PROMPT_TEMPLATE} Additional instructions... """ # Works with any AI library client = OpenAI() response = client.chat.completions.create( model='gpt-4', messages=[ {'role': 'system', 'content': system_prompt}, {'role': 'user', 'content': 'Analyze the latest PR in microsoft/vscode'} ] ) ``` -------------------------------- ### Get Complete Tool Information Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-mcp/README.md Retrieve detailed information about a tool, including its TypeScript interface, using the `tool_info` MCP tool. ```bash tool_info ``` -------------------------------- ### Local Development Setup for @utcp/code-mode Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-mcp/README.md Use these npm scripts to build and register a local development version of the `@utcp/code-mode` library with Claude Code. After every edit, re-run `npm run dev:register` and restart Claude Code. Use `npm run dev:unregister` when finished. ```bash cd code-mode-mcp npm install npm run dev:register # builds lib + bridge, overlays the lib build into the bridge's node_modules, registers as 'utcp-codemode-dev' in Claude Code # restart Claude Code, then call mcp__utcp-codemode-dev__call_tool_chain to test # After every edit: npm run dev:register # rebuilds, re-registers; restart Claude Code # When done: npm run dev:unregister # removes the MCP entry and restores the registry @utcp/code-mode ``` -------------------------------- ### Get Required Environment Variables for a Tool Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-mcp/README.md Use `get_required_keys_for_tool` to determine which environment variables are necessary for a specific tool's operation. ```bash get_required_keys_for_tool ``` -------------------------------- ### Execute Multi-Step Workflow with Code Mode Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md This TypeScript code demonstrates executing a multi-step workflow using the Code Mode client. It replaces multiple API calls with a single code execution, allowing for in-sandbox data processing and analysis. The example retrieves pull request details, comments, reviews, and files, then summarizes them. ```typescript const { result, logs } = await client.callToolChain(` // Traditional: 4 separate API round trips → Code Mode: 1 execution const pr = await github.get_pull_request({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 }); const comments = await github.get_pull_request_comments({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 }); const reviews = await github.get_pull_request_reviews({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 }); const files = await github.get_pull_request_files({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 }); // Process data in-sandbox (no token overhead) const summary = { title: pr.title, state: pr.state, author: pr.user.login, stats: { comments: comments.length, reviews: reviews.length, filesChanged: files.length, approvals: reviews.filter(r => r.state === 'APPROVED').length }, topDiscussion: comments.slice(0, 3).map(c => ({ author: c.user.login, preview: c.body.substring(0, 100) + '...' })) }; console.log(\`PR " extbackslash${pr.title}\ ``` -------------------------------- ### Execute Natural Code Chains Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/python-library/README.md Chain multiple operations in a single request for efficient data processing. This example retrieves pull request details, comments, and reviews from GitHub. ```python result = await client.call_tool_chain(''' # Chain multiple operations in one request pr = await github.get_pull_request(owner='microsoft', repo='vscode', pull_number=1234) comments = await github.get_pull_request_comments(owner='microsoft', repo='vscode', pull_number=1234) reviews = await github.get_pull_request_reviews(owner='microsoft', repo='vscode', pull_number=1234) # Process data efficiently in-sandbox return { "title": pr["title"], "commentCount": len(comments), "approvals": len([r for r in reviews if r["state"] == "APPROVED"]) } ''') # Single API call replaces 15+ traditional tool calls ``` -------------------------------- ### Get Tool Interfaces Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/typescript-library/README.md Retrieve TypeScript interface definitions for all registered tools. This can be useful for understanding the expected input and output structures of tools. ```typescript const interfaces = await client.getToolInterfaces(); console.log(interfaces); // "interface Weather_get_current_Input { city: string; } ..." ``` -------------------------------- ### Execute TypeScript Code with Tool Chaining Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-mcp/README.md Use `call_tool_chain` to execute TypeScript code that chains multiple tool calls. This example retrieves user data, analyzes behavior, and generates a report. ```typescript // Example using call_tool_chain const result = await call_tool_chain(` // Get user data from an API const user = await user_service.getUserProfile({ userId: "123" }); console.log('User data:', user); // Process the data with another tool const processed = await data_processor.analyzeUserBehavior({ userData: user, timeframe: "30days" }); // Generate a report const report = await reporting.generateInsights({ analysis: processed, format: "summary" }); return { userId: user.id, totalActions: processed.actionCount, topInsight: report.insights[0] }; `); ``` -------------------------------- ### Execute Multi-Step Workflows with Code Mode Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/python-library/README.md Execute complex, multi-step workflows with a single code execution, replacing multiple API calls. This example shows fetching pull request data and processing it within the sandbox. ```python result = await client.call_tool_chain(''' # Traditional: 4 separate API round trips → Code Mode: 1 execution pr = await github.get_pull_request(owner='microsoft', repo='vscode', pull_number=1234) comments = await github.get_pull_request_comments(owner='microsoft', repo='vscode', pull_number=1234) reviews = await github.get_pull_request_reviews(owner='microsoft', repo='vscode', pull_number=1234) files = await github.get_pull_request_files(owner='microsoft', repo='vscode', pull_number=1234) # Process data in-sandbox (no token overhead) summary = { "title": pr["title"], "state": pr["state"], "author": pr["user"]["login"], "stats": { "comments": len(comments), "reviews": len(reviews), "filesChanged": len(files), "approvals": len([r for r in reviews if r["state"] == "APPROVED"]) }, "topDiscussion": [ { "author": c["user"]["login"], "preview": c["body"][:100] + "..." } for c in comments[:3] ] } print(f'PR "{pr["title"]}" analysis complete') return summary ''') print('Analysis Result:', result['result']) ``` -------------------------------- ### OAuth2 User Authentication (Remote MCP) Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-cli/README.md Example of an `oauth2_user` auth block for a remote MCP server like Notion. The token is provisioned by `utcp login` and injected on subsequent calls. The `dotenv` loader is required for `${VAR}` secrets. ```json "auth": { "auth_type": "oauth2_user", "access_token": "${NOTION_TOKEN}" } ``` -------------------------------- ### Auto-Generated Python TypedDict Interfaces Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/python-library/README.md Example of an auto-generated Python TypedDict interface for GitHub pull request input parameters. This provides type safety for tool inputs. ```python class GithubGetPullRequestInput(TypedDict): """Repository owner""" owner: str """Repository name""" repo: str """Pull request number""" pull_number: int ``` -------------------------------- ### Register New UTCP Manuals/APIs Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-mcp/README.md Use the `register_manual` MCP tool to add new UTCP manuals or APIs to your ecosystem. ```bash register_manual ``` -------------------------------- ### Initialize and Execute Code with UTCP Client Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md Initialize the UTCP client, register tools, and execute a TypeScript tool chain in three simple steps. This sets up your AI agent for complex workflow execution. ```typescript import { CodeModeUtcpClient } from '@utcp/code-mode'; const client = await CodeModeUtcpClient.create(); // 1. Initialize await client.registerManual({ name: 'github', /* MCP config */ }); // 2. Add tools const { result } = await client.callToolChain(`/* TypeScript */`); // 3. Execute code ``` -------------------------------- ### CodeModeUtcpClient.create Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/typescript-library/README.md Creates a new instance of the CodeModeUtcpClient. It can optionally take a root directory and configuration object. ```APIDOC ## CodeModeUtcpClient.create(root_dir?, config?) ### Description Creates a new client instance. ### Parameters #### Path Parameters - **root_dir** (string) - Optional - The root directory for the client. - **config** (UtcpClientConfig) - Optional - Configuration object for the client. ### Request Example ```typescript const client = await CodeModeUtcpClient.create( process.cwd(), // optional: root directory null // optional: UtcpClientConfig ); ``` ``` -------------------------------- ### Discover Tools with utcp CLI Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md Discover available tools and their TypeScript interfaces using the `utcp` CLI by providing a search query. ```bash npx -y @utcp/code-mode-cli search "" ``` -------------------------------- ### Register Manual from File with Text Template Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/typescript-library/README.md Shows how to register a UTCP manual from a file using the 'text' call template type, enabling the use of tools defined in that manual. ```typescript import { CodeModeUtcpClient } from '@utcp/code-mode'; import '@utcp/text'; // Enables text call template support const client = await CodeModeUtcpClient.create(); // Register from a UTCP manual file await client.registerManual({ name: 'myapi', call_template_type: 'text', file_path: './my-api-manual.utcp.json' }); // Use tools defined in the manual const result = await client.callToolChain(` return myapi.some_tool({ param: 'value' }); `); ``` -------------------------------- ### Create CodeModeUtcpClient Instance Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/typescript-library/README.md Instantiate the CodeModeUtcpClient, optionally providing a root directory and configuration. ```typescript const client = await CodeModeUtcpClient.create( process.cwd(), // optional: root directory null // optional: UtcpClientConfig ); ``` -------------------------------- ### Register Multiple Tool Sources for Multi-Protocol Chains Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/python-library/README.md Register tools from different ecosystems like GitHub (MCP), Slack (HTTP), and local files (Text) within a single client. This allows for seamless integration and execution of tool chains that span various protocols and services. ```python from utcp.data.call_template import CallTemplateSerializer serializer = CallTemplateSerializer() # Register multiple tool sources await client.register_manual(serializer.validate_dict({ 'name': 'github', 'call_template_type': 'mcp', 'config': {...} })) await client.register_manual(serializer.validate_dict({ 'name': 'slack', 'call_template_type': 'http', 'http_method': 'POST', 'url': 'https://api.slack.com/utcp' })) await client.register_manual(serializer.validate_dict({ 'name': 'db', 'call_template_type': 'text', 'file_path': './db-tools.json' })) result = await client.call_tool_chain(''' # Fetch PR data from GitHub (MCP) pr = await github.get_pull_request(owner='company', repo='api', pull_number=42) # Query deployment status from database (File) deployment = await db.get_deployment_status(pr_id=pr["id"]) # Send notification to Slack (HTTP) await slack.post_message( channel='#releases', text=f'PR #42 "{pr["title"]}" deployed to {deployment["environment"]}' ) return {"pr": pr["title"], "environment": deployment["environment"]} ''') ``` -------------------------------- ### Perform OAuth Login with utcp CLI Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md Initiate an interactive OAuth login process using the `utcp` CLI. The generated token is saved to a `.env` file. ```bash npx -y @utcp/code-mode-cli login ``` -------------------------------- ### Complete OAuth Login with Code/URL Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-cli/SKILL.md Provide the authorization code or pasted URL to complete the OAuth sign-in process after initiating it with `utcp login `. ```bash utcp login --code "" ``` -------------------------------- ### Discover Tools Dynamically with UTCP Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md Agents can discover tools dynamically, loading only the necessary ones. This optimizes performance by reducing the number of tool definitions loaded. ```typescript // Agent discovers tools dynamically, loads only what it needs const tools = await client.searchTools('github pull request'); // Instead of 500 tool definitions → 3 relevant tools ``` -------------------------------- ### Search Tools by Description Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-mcp/README.md Utilize the `search_tools` MCP tool to find available tools based on their descriptions, including their TypeScript interfaces. ```bash search_tools ``` -------------------------------- ### CLI Commands Reference Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-cli/README.md A table outlining the available commands for the code-mode-cli, their descriptions, and global options. ```markdown | Command | Description | | --- | --- | | `prompt` | Print the full agent guide (read first). | | `search [--limit N]` | Find tools; returns name + description + TS interface. | | `list` | List all registered tool names. | | `info ` | Print TypeScript interfaces for the named tools. | | `keys ` | List required variables (e.g. tokens) for a tool. | | `run [code] [-c ] [--file

] [--timeout ]` | Execute a tool-chain (also reads stdin). | | `login [--paste] [--code ]` | Interactive OAuth sign-in; writes the token to `.env`. | | `validate [--offline]` | Validate `.utcp_config.json` + its manuals (registers each unless `--offline`). | | `validate --manual ` | Validate standalone UTCP manual file(s). | | `--help` | Short usage. | Global: `--config ` to use a specific config file (default `./.utcp_config.json`). ``` -------------------------------- ### Initialize CodeModeUtcpClient and Register GitHub MCP Server Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md This TypeScript code initializes the CodeModeUtcpClient and registers a manual configuration for a GitHub MCP server. It specifies the transport type and the Docker command to run the GitHub MCP service, including setting the GITHUB_PERSONAL_ACCESS_TOKEN environment variable. ```typescript import '@utcp/mcp'; // registers the 'mcp' call template import { CodeModeUtcpClient } from '@utcp/code-mode'; const client = await CodeModeUtcpClient.create(); // Connect to GitHub MCP server await client.registerManual({ name: 'github', call_template_type: 'mcp', config: { mcpServers: { github: { transport: 'stdio', // required by @utcp/mcp command: 'docker', args: ['run', '-i', '--rm', '-e', 'GITHUB_PERSONAL_ACCESS_TOKEN', 'mcp/github'], env: { GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_TOKEN } } } } }); ``` -------------------------------- ### Register and Use Multi-Protocol Tool Chains Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md Register tools from different ecosystems (MCP, HTTP, file) and chain them in a single execution. Ensure correct `call_template_type` and configuration for each tool. ```typescript await client.registerManual({ name: 'github', call_template_type: 'mcp', /* config */ }); await client.registerManual({ name: 'slack', call_template_type: 'http', /* config */ }); await client.registerManual({ name: 'db', call_template_type: 'file', file_path: './db-tools.json' }); // This loads a UTCP manual from a json file const result = await client.callToolChain(` // Fetch PR data from GitHub (MCP) const pr = await github.get_pull_request({ owner: 'company', repo: 'api', pull_number: 42 }); // Query deployment status from database (File) const deployment = await db.get_deployment_status({ pr_id: pr.id }); // Send notification to Slack (HTTP) await slack.post_message({ channel: '#releases', text: `PR #${pr.pull_number} "${pr.title}" deployed to ${deployment.environment}` }); return { pr: pr.title, environment: deployment.environment }; `); ``` -------------------------------- ### Call Tool Chain and Monitor Logs Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/python-library/README.md Execute a chain of tools using the client and process the resulting logs. Ship error and warning logs to your monitoring system for observability. ```python result = await client.call_tool_chain(user_code) # Ship logs to your monitoring system for log in result['logs']: if '[ERROR]' in log: monitoring.error(log) if '[WARN]' in log: monitoring.warn(log) ``` -------------------------------- ### List All Registered Tool Names Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-mcp/README.md The `list_tools` MCP tool provides a comprehensive list of all currently registered tool names. ```bash list_tools ``` -------------------------------- ### Access Namespaced Tools Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/typescript-library/README.md Demonstrates how to access registered tools within the sandboxed environment using their respective namespaces and tool names. ```typescript // Namespaced tools (from manuals) manual_name.tool_name({ param: value }) // Examples weather.get_current({ city: 'Tokyo' }) procurement.search_parts({ mpn: 'ABC123' }) ``` -------------------------------- ### Run a Tool-Chain with UTCP CLI Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-cli/SKILL.md Execute a sequence of tool calls using TypeScript code. Supports top-level await and return. A heredoc can be used for multi-line code input. ```bash utcp run <<'EOF' const r = await openlibrary.read_search_json_search_json_get({ q: "tolkien", limit: 3 }); return (r.docs || []).map(b => b.title); EOF ``` -------------------------------- ### CodeModeUtcpClient.AGENT_PROMPT_TEMPLATE Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/typescript-library/README.md A static property providing a prompt template for AI agents, explaining how to utilize the code-mode functionality. ```APIDOC ## CodeModeUtcpClient.AGENT_PROMPT_TEMPLATE ### Description Static prompt template for AI agents explaining how to use code-mode. ### Request Example ```typescript const systemPrompt = CodeModeUtcpClient.AGENT_PROMPT_TEMPLATE; ``` ``` -------------------------------- ### Access Agent Prompt Template Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/typescript-library/README.md Retrieve the static prompt template used for AI agents, which explains how to utilize the code-mode functionality. ```typescript const systemPrompt = CodeModeUtcpClient.AGENT_PROMPT_TEMPLATE; ``` -------------------------------- ### Call Tool Chain and Process Logs Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md Execute a chain of tools with user-provided code and process the resulting logs. This snippet shows how to capture and route logs to a monitoring system based on their severity. ```typescript const { result, logs } = await client.callToolChain(userCode); // Ship logs to your monitoring system logs.forEach(log => { if (log.startsWith('[ERROR]')) monitoring.error(log); if (log.startsWith('[WARN]')) monitoring.warn(log); }); ``` -------------------------------- ### Configure Code Mode MCP Server Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md This JSON configuration is used to set up the Code Mode MCP server. It specifies the command to run and environment variables, including the path to your UTCP configuration file. ```json { "mcpServers": { "code-mode": { "command": "npx", "args": ["@utcp/code-mode-mcp"], "env": { "UTCP_CONFIG_FILE": "/path/to/your/.utcp_config.json" } } } } ``` -------------------------------- ### Generate Python Tool Interfaces Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/python-library/README.md Generate Python definitions for AI tools to enable full IntelliSense support in your IDE. Save these interfaces to a file and import them for type hinting. ```python # Generate tool interfaces interfaces = await client.get_all_tools_python_interfaces() with open('generated_tools.py', 'w') as f: f.write(interfaces) # Import in your code for type hints from generated_tools import * ``` -------------------------------- ### AI Agent System Prompt with CodeMode Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md Use this system prompt template when integrating AI agents with UTCP CodeMode. It includes the AGENT_PROMPT_TEMPLATE and allows for additional instructions. ```typescript import { CodeModeUtcpClient } from '@utcp/code-mode'; const systemPrompt = ` You are an AI assistant with access to tools via UTCP CodeMode. ${CodeModeUtcpClient.AGENT_PROMPT_TEMPLATE} Additional instructions... `; // Works with any AI library const response = await openai.chat.completions.create({ model: 'gpt-4', messages: [ { role: 'system', content: systemPrompt }, { role: 'user', content: 'Analyze the latest PR in microsoft/vscode' } ] }); ``` -------------------------------- ### searchTools Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md Discovers tools using natural language queries. It returns an array of relevant tools, each with a description and its associated interface. ```APIDOC ## searchTools(query: string) ### Description Discover tools using natural language queries. ### Method `searchTools` ### Parameters #### Path Parameters - **query** (string) - Required - The natural language query to search for tools. ### Returns - **Array** - An array of relevant tools, including their descriptions and interfaces. ``` -------------------------------- ### Generate TypeScript Tool Interfaces Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md Generate TypeScript definitions for tools to enable IntelliSense support in your IDE. This involves fetching interfaces and writing them to a .d.ts file. ```bash # Generate tool interfaces const interfaces = await client.getAllToolsTypeScriptInterfaces(); await fs.writeFile('generated-tools.d.ts', interfaces); # Add to tsconfig.json { "compilerOptions": { "typeRoots": ["./generated-tools.d.ts"] } } ``` -------------------------------- ### Runtime Interface Introspection for Dynamic Workflows Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/python-library/README.md Discover and utilize tool interfaces dynamically at runtime. The `interfaces` variable and `get_tool_interface` function allow tools to adapt to available functionalities, enabling more flexible and responsive workflows. Note that `interfaces` and `get_tool_interface` are exposed directly due to sandbox restrictions. ```python result = await client.call_tool_chain(''' # Discover available tools at runtime print('Available interfaces:', interfaces) # Get specific tool interface for validation pr_interface = get_tool_interface('github.get_pull_request') print('PR tool expects:', pr_interface) # Use interface info for dynamic workflows has_slack_tools = 'namespace slack' in interfaces if has_slack_tools: await slack.post_message(channel='#dev', text='Analysis complete') return {"toolsAvailable": has_slack_tools} ''') ``` -------------------------------- ### search_tools Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/python-library/README.md Discovers tools based on a natural language query. It returns a list of relevant tools, including their descriptions and available interfaces. ```APIDOC ## search_tools(query: str, limit: int = 10) ### Description Discover tools using natural language queries. ### Method ```python search_tools(query: str, limit: int = 10) ``` ### Parameters #### Path Parameters - None #### Query Parameters - **query** (str) - Required - The natural language query to search for tools. - **limit** (int) - Optional - The maximum number of tools to return. Defaults to 10. ### Returns - **tools** (List[ToolInfo]) - A list of relevant tools, each containing descriptions and interfaces. ``` -------------------------------- ### Context-Efficient Data Processing with Large Datasets Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/python-library/README.md Process large datasets efficiently by performing complex filtering and transformation within the sandbox, returning only a summarized result. This prevents bloating the model's context with excessive raw data, improving performance and reducing resource consumption. ```python result = await client.call_tool_chain(''' # Fetch large dataset all_issues = await github.list_repository_issues(owner='facebook', repo='react') print(f'Fetched {len(all_issues)} total issues') # Process efficiently in-sandbox critical_bugs = [ { "number": issue["number"], "title": issue["title"], "author": issue["user"]["login"], "daysOld": (datetime.now() - datetime.fromisoformat(issue["created_at"].replace('Z', '+00:00'))).days } for issue in all_issues if any(l["name"] == "bug" for l in issue["labels"]) and any(l["name"] == "high priority" for l in issue["labels"]) ] critical_bugs.sort(key=lambda x: x["daysOld"], reverse=True) # Only return processed summary (not 10,000 raw issues) return { "totalIssues": len(all_issues), "criticalBugs": critical_bugs[:10], # Top 10 oldest critical bugs "summary": f'Found {len(critical_bugs)} critical bugs, oldest is {critical_bugs[0]["daysOld"]} days old' } ''') ``` -------------------------------- ### getAllToolsTypeScriptInterfaces Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md Generates complete TypeScript interfaces for all available tools, which can be used for IDE integration and type safety. ```APIDOC ## getAllToolsTypeScriptInterfaces() ### Description Generate complete TypeScript interfaces for IDE integration. ### Method `getAllToolsTypeScriptInterfaces` ### Returns - **String** - A string containing all interface definitions, organized with namespaces. ``` -------------------------------- ### Error Handling and Observability in Tool Chains Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md Implement robust error handling using try-catch blocks within tool chains and leverage the returned `logs` for complete execution transparency. Ensure errors are caught and optionally re-thrown. ```typescript const { result, logs } = await client.callToolChain(` try { console.log('Starting multi-step workflow...'); const data = await external_api.fetch_data({ id: 'user-123' }); console.log('Data fetched successfully'); const processed = await data_processor.transform(data); console.warn('Processing completed with', processed.warnings.length, 'warnings'); return processed; } catch (error) { console.error('Workflow failed:', error.message); throw error; // Propagates to outer error handling } `, 30000); // 30-second timeout // Complete observability console.log('Result:', result); console.log('Execution logs:', logs); // ['Starting multi-step workflow...', 'Data fetched successfully', '[WARN] Processing completed with 2 warnings'] ``` -------------------------------- ### MCP Client Configuration for UTCP Code Mode Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-mcp/README.md Add this JSON configuration to your MCP client to enable the UTCP Code Mode bridge. It specifies the command to run and environment variables. ```json { "mcpServers": { "utcp-codemode": { "command": "npx", "args": ["@utcp/code-mode-mcp"], "env": { "UTCP_CONFIG_FILE": "/path/to/your/.utcp_config.json" } } } } ``` -------------------------------- ### get_all_tools_python_interfaces Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/python-library/README.md Generates a string containing Python TypedDict interfaces for all available tools. This is useful for IDEs to provide autocompletion and type checking for tool usage. ```APIDOC ## get_all_tools_python_interfaces() ### Description Generate complete Python TypedDict interfaces for IDE integration. ### Method ```python get_all_tools_python_interfaces() ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Returns - **interfaces** (str) - A string containing all interface definitions with proper typing. ``` -------------------------------- ### Context-Efficient Data Processing with Filtering and Mapping Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md Process large datasets efficiently within the sandbox by filtering, mapping, and slicing data. This avoids bloating the model's context by returning only a processed summary. ```typescript const result = await client.callToolChain(` // Fetch large dataset const allIssues = await github.list_repository_issues({ owner: 'facebook', repo: 'react' }); console.log('Fetched', allIssues.length, 'total issues'); // Process efficiently in-sandbox const criticalBugs = allIssues .filter(issue => issue.labels.some(l => l.name === 'bug')) .filter(issue => issue.labels.some(l => l.name === 'high priority')) .map(issue => ({ number: issue.number, title: issue.title, author: issue.user.login, daysOld: Math.floor((Date.now() - new Date(issue.created_at)) / (1000 * 60 * 60 * 24)) })) .sort((a, b) => b.daysOld - a.daysOld); // Only return processed summary (not 10,000 raw issues) return { totalIssues: allIssues.length, criticalBugs: criticalBugs.slice(0, 10), // Top 10 oldest critical bugs summary: `Found ${criticalBugs.length} critical bugs, oldest is ${criticalBugs[0]?.daysOld} days old` }; `); ``` -------------------------------- ### Configure Custom Timeouts for Tool Chain Execution Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/python-library/README.md Set custom timeout limits for tool chain executions to manage resource allocation and prevent indefinite waits. This allows for different timeout strategies for quick operations versus heavy data processing tasks. ```python # Quick operations (5 seconds) quick_result = await client.call_tool_chain('return await ping.check()', timeout=5) # Heavy data processing (2 minutes) heavy_result = await client.call_tool_chain(''' big_data = await database.export_full_dataset() return await analytics.process_dataset(big_data) ''', timeout=120) ``` -------------------------------- ### Execute TypeScript Code with Direct Tool Access Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-mcp/README.md The `call_tool_chain` MCP tool allows for the execution of TypeScript code, providing direct access to registered tools. ```bash call_tool_chain ``` -------------------------------- ### Registering UTCP Code Mode Bridge with Claude Code Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-mcp/README.md Command to add the UTCP Code Mode bridge as a user-scoped MCP server in Claude Code. This allows integration with the IDE extension. ```bash claude mcp add-json --scope user utcp-codemode '{"type":"stdio","command":"npx","args":["@utcp/code-mode-mcp"],"env":{"UTCP_CONFIG_FILE":"/absolute/path/to/.utcp_config.json"}}' ``` -------------------------------- ### Runtime Interface Introspection with `__interfaces` and `__getToolInterface` Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md Discover available tool interfaces at runtime using `__interfaces` and `__getToolInterface`. This allows for dynamic adaptation and validation of tool usage within workflows. ```typescript const result = await client.callToolChain(` // Discover available tools at runtime console.log('Available interfaces:', __interfaces); // Get specific tool interface for validation const prInterface = __getToolInterface('github.get_pull_request'); console.log('PR tool expects:', prInterface); // Use interface info for dynamic workflows const hasSlackTools = __interfaces.includes('namespace slack'); if (hasSlackTools) { await slack.post_message({ channel: '#dev', text: 'Analysis complete' }); } return { toolsAvailable: hasSlackTools }; `); ``` -------------------------------- ### Execute Natural Code Chains with UTCP Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md Chain multiple operations in a single request and process data efficiently in-sandbox. This replaces numerous traditional tool calls with a single API call. ```typescript const { result, logs } = await client.callToolChain(` // Chain multiple operations in one request const pr = await github.get_pull_request({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 }); const comments = await github.get_pull_request_comments({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 }); const reviews = await github.get_pull_request_reviews({ owner: 'microsoft', repo: 'vscode', pull_number: 1234 }); // Process data efficiently in-sandbox return { title: pr.title, commentCount: comments.length, approvals: reviews.filter(r => r.state === 'APPROVED').length }; `); // Single API call replaces 15+ traditional tool calls ``` -------------------------------- ### Remove Registered Manuals Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/code-mode-mcp/README.md Use the `deregister_manual` MCP tool to remove previously registered manuals. ```bash deregister_manual ``` -------------------------------- ### Error Handling and Observability in Workflows Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/python-library/README.md Implement robust error handling using try-except blocks within tool chains and gain complete execution transparency through detailed logs. The `result` object provides access to the execution outcome and logs, enabling effective debugging and monitoring. ```python result = await client.call_tool_chain(''' try: print('Starting multi-step workflow...') data = await external_api.fetch_data(id='user-123') print('Data fetched successfully') processed = await data_processor.transform(data) print(f'Processing completed with {len(processed.get("warnings", []))} warnings') return processed except Exception as error: print(f'Workflow failed: {str(error)}') raise error # Propagates to outer error handling ''', timeout=30) # 30-second timeout # Complete observability print('Result:', result['result']) print('Execution logs:', result['logs']) # ['Starting multi-step workflow...', 'Data fetched successfully', 'Processing completed with 2 warnings'] ``` -------------------------------- ### client.callToolChain Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/typescript-library/README.md Executes TypeScript code within a sandboxed environment, providing access to registered UTCP tools. It returns the result of the code execution and any captured console output. ```APIDOC ## client.callToolChain(code, options?) ### Description Executes TypeScript code with tool access. ### Parameters #### Path Parameters - **code** (string) - Required - The TypeScript code to execute. - **options** (object) - Optional - Configuration options for execution. - **timeout** (number) - Optional - Execution timeout in milliseconds (default: 30000). - **memoryLimit** (number) - Optional - Memory limit in MB (default: 128). ### Response #### Success Response (200) - **result** (any) - The return value from the executed code. - **consoleOutput** (string[]) - An array of captured console.log/error output. ### Request Example ```typescript const result = await client.callToolChain(code, { timeout: 30000, // execution timeout in ms (default: 30000) memoryLimit: 128 // memory limit in MB (default: 128) }); ``` ### Response Example ```typescript { result: any; // return value from code consoleOutput: string[]; // captured console.log/error output } ``` ``` -------------------------------- ### Execute TypeScript Code with Tool Access Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/typescript-library/README.md Call the `callToolChain` method to execute TypeScript code within the sandboxed environment, with options for timeout and memory limits. ```typescript const result = await client.callToolChain(code, { timeout: 30000, // execution timeout in ms (default: 30000) memoryLimit: 128 // memory limit in MB (default: 128) }); ``` -------------------------------- ### Configure Custom Timeouts for Tool Chain Execution Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md Set custom timeouts for `callToolChain` executions to manage resource usage and prevent indefinite waits. Different timeouts can be applied based on the expected workload duration. ```typescript // Quick operations (5 seconds) const quickResult = await client.callToolChain(`return await ping.check();`, 5000); // Heavy data processing (2 minutes) const heavyResult = await client.callToolChain(` const bigData = await database.export_full_dataset(); return await analytics.process_dataset(bigData); `, 120000); ``` -------------------------------- ### client.getToolInterfaces Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/typescript-library/README.md Retrieves TypeScript interface definitions for all tools that have been registered with the client. ```APIDOC ## client.getToolInterfaces() ### Description Returns TypeScript interface definitions for all registered tools. ### Response #### Success Response (200) - **interfaces** (string) - A string containing all TypeScript interface definitions. ### Request Example ```typescript const interfaces = await client.getToolInterfaces(); console.log(interfaces); // "interface Weather_get_current_Input { city: string; } ..." ``` ``` -------------------------------- ### call_tool_chain Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/python-library/README.md Executes Python code within a sandboxed environment, providing access to registered tools and capturing execution logs. It handles complex tool interactions and provides structured results. ```APIDOC ## call_tool_chain(code: str, timeout: int = 30) ### Description Execute Python code with full tool access and observability. ### Method ```python call_tool_chain(code: str, timeout: int = 30) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **code** (str) - Required - The Python code to execute. - **timeout** (int) - Optional - The maximum time in seconds to allow for execution. Defaults to 30 seconds. ### Returns - **result** (any) - The result of the code execution. - **logs** (List[str]) - A list of strings representing captured console output during execution. ``` -------------------------------- ### callToolChain Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md Executes TypeScript code with full tool access and observability. It returns the execution result along with any captured console output logs. A default timeout of 30 seconds is applied. ```APIDOC ## callToolChain(code: string, timeout?: number) ### Description Execute TypeScript code with full tool access and observability. ### Method `callToolChain` ### Parameters #### Path Parameters - **code** (string) - Required - The TypeScript code to execute. - **timeout** (number) - Optional - The maximum time in seconds to allow for execution. Defaults to 30 seconds. ### Returns - **result** (any) - The result of the code execution. - **logs** (string[]) - An array of strings representing captured console output. ``` -------------------------------- ### Auto-Generated TypeScript Interfaces for Tools Source: https://github.com/universal-tool-calling-protocol/code-mode/blob/main/README.md The UTCP Code Mode automatically generates TypeScript interfaces for tool inputs. This enhances type safety and developer experience when interacting with tools. ```typescript namespace github { interface get_pull_requestInput { /** Repository owner */ owner: string; /** Repository name */ repo: string; /** Pull request number */ pull_number: number; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.