JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 2204
  • Score
    100M100P100Q123446F
  • License MPL-2.0

Code execution mode for UTCP - enables executing TypeScript code chains with tool access

Package Exports

  • @utcp/code-mode

Readme

@utcp/code-mode

A powerful extension for UTCP that enables executing TypeScript code with direct access to all registered tools as native TypeScript functions.

Features

  • TypeScript Code Execution: Execute TypeScript code snippets with full access to registered tools
  • Tool Function Generation: Automatically converts UTCP tools into callable TypeScript functions
  • Type Safety: Generates proper TypeScript interfaces for all tool inputs and outputs
  • Secure Execution: Uses Node.js VM module for safe code execution with timeout support
  • Chain Tool Calls: Combine multiple tool calls in a single TypeScript code block

Installation

npm install @utcp/code-mode

Basic Usage

import { CodeModeUtcpClient } from '@utcp/code-mode';

const client = await CodeModeUtcpClient.create();

// Register some tools first (example)
await client.registerManual({
  name: 'math_tools',
  call_template_type: 'text',
  content: `
    name: add
    description: Adds two numbers
    inputs:
      type: object
      properties:
        a: { type: number }
        b: { type: number }
      required: [a, b]
    outputs:
      type: object
      properties:
        result: { type: number }
  `
});

// Now execute TypeScript code that uses the tools
const result = await client.callToolChain(`
  // Call the add tool
  const sum1 = await add({ a: 5, b: 3 });
  console.log('First sum:', sum1.result);
  
  // Chain multiple tool calls
  const sum2 = await add({ a: sum1.result, b: 10 });
  console.log('Second sum:', sum2.result);
  
  // Return final result
  return sum2.result;
`);

console.log('Final result:', result); // 18

Advanced Usage

Getting TypeScript Interfaces

You can generate TypeScript interfaces for all your tools to get better IDE support:

const interfaces = await client.getAllToolsTypeScriptInterfaces();
console.log(interfaces);

This will output something like:

// Auto-generated TypeScript interfaces for UTCP tools

interface math_tools_addInput {
  /** First number */
  a: number;
  /** Second number */
  b: number;
}

interface math_tools_addOutput {
  /** The sum result */
  result: number;
}

/**
 * Adds two numbers
 * Tags: math, arithmetic
 */
async function add(args: math_tools_addInput): Promise<math_tools_addOutput>;

Complex Tool Chains

Execute complex logic with multiple tools:

const result = await client.callToolChain(`
  // Get user data
  const user = await getUserData({ userId: "123" });
  
  // Process the data
  const processedData = await processUserData({
    userData: user,
    options: { normalize: true, validate: true }
  });
  
  // Generate report
  const report = await generateReport({
    data: processedData,
    format: "json",
    includeMetrics: true
  });
  
  // Send notification
  await sendNotification({
    recipient: user.email,
    subject: "Your report is ready",
    body: \`Report generated with \${report.metrics.totalItems} items\`
  });
  
  return {
    reportId: report.id,
    itemCount: report.metrics.totalItems,
    notificationSent: true
  };
`);

Error Handling

The code execution includes proper error handling:

try {
  const result = await client.callToolChain(`
    const result = await someToolThatMightFail({ input: "test" });
    return result;
  `);
} catch (error) {
  console.error('Code execution failed:', error.message);
}

Timeout Configuration

You can set custom timeouts for code execution:

const result = await client.callToolChain(`
  // Long running operation
  const result = await processLargeDataset({ data: largeArray });
  return result;
`, 60000); // 60 second timeout

API Reference

CodeModeUtcpClient

Extends UtcpClient with additional code execution capabilities.

Methods

callToolChain(code: string, timeout?: number): Promise<any>

Executes TypeScript code with access to all registered tools.

  • code: TypeScript code to execute
  • timeout: Optional timeout in milliseconds (default: 30000)
  • Returns: The result of the code execution
toolToTypeScriptInterface(tool: Tool): string

Converts a single tool to its TypeScript interface definition.

  • tool: The Tool object to convert
  • Returns: TypeScript interface as a string
getAllToolsTypeScriptInterfaces(): Promise<string>

Generates TypeScript interfaces for all registered tools.

  • Returns: Complete TypeScript interface definitions

Static Methods

CodeModeUtcpClient.create(root_dir?: string, config?: UtcpClientConfig): Promise<CodeModeUtcpClient>

Creates a new CodeModeUtcpClient instance.

  • root_dir: Root directory for relative path resolution
  • config: UTCP client configuration
  • Returns: New CodeModeUtcpClient instance

Security Considerations

  • Code execution happens in a secure Node.js VM context
  • No access to Node.js modules or filesystem by default
  • Timeout protection prevents infinite loops
  • Only registered tools are accessible in the execution context

Type Safety

The code mode client generates proper TypeScript interfaces for all tools, providing:

  • Compile-time type checking for tool parameters
  • IntelliSense support in IDEs
  • Automatic validation of tool inputs and outputs
  • Clear documentation through generated interfaces

Integration with IDEs

For the best development experience:

  1. Generate TypeScript interfaces for your tools
  2. Save them to a .d.ts file in your project
  3. Reference the file in your TypeScript configuration
  4. Enjoy full IntelliSense support for tool functions
// Generate and save interfaces
const interfaces = await client.getAllToolsTypeScriptInterfaces();
await fs.writeFile('tools.d.ts', interfaces);

License

MPL-2.0