utcp-code-mode 0.0.1
UTCP client extension for Python code execution with tool access capabilities.
Requires Python: >=3.10

# UTCP Code Mode Client Extension

The UTCP Code Mode Client Extension provides a `CodeModeUtcpClient` that extends the base `UtcpClient` with Python code execution capabilities. This allows you to execute Python code that can directly call registered tools as functions.

## Features

- **Python Code Execution**: Execute Python code with access to registered UTCP tools
- **Automatic Type Generation**: Convert JSON schemas to Python TypedDict interfaces
- **Console Output Capture**: Capture print statements and console output
- **Tool Introspection**: Access tool interfaces and documentation at runtime
- **Safe Execution**: Subprocess isolation, timeout support, and comprehensive security
- **Namespace Organization**: Tools organized by manual namespace (e.g., `manual.tool`)
- **Security**: Restricted imports, safe builtins, and cooperative sandbox environment

## Installation

```bash
pip install utcp-code-mode
```

## Quick Start

```python
from utcp_code_mode import CodeModeUtcpClient
import asyncio

async def main():
    # Create a code mode client
    client = await CodeModeUtcpClient.create()
    
    # Register some tools (example with weather API)
    # ... register your tools here ...
    
    # Execute Python code with tool access
    result = await client.call_tool_chain('''
# Discover available tools
tools = await search_tools("weather")
print(f"Found {len(tools)} weather tools")

# Use a tool (assuming weather manual is registered)
weather_data = await weather.get_current_weather(city="London")
print(f"Weather in London: {weather_data}")

return weather_data
    ''')
    
    print("Execution result:", result["result"])
    print("Console logs:", result["logs"])

asyncio.run(main())
```

## Advanced Usage

### Tool Discovery and Introspection

```python
result = await client.call_tool_chain('''
# Access type interfaces
print("Available interfaces:")
print(__interfaces)

# Get specific tool interface
tool_interface = __get_tool_interface("weather.get_current_weather")
if tool_interface:
    print("Tool interface:")
    print(tool_interface)

# Search for tools
weather_tools = await search_tools("weather", limit=5)
for tool in weather_tools:
    print(f"- {tool.name}: {tool.description}")
''')
```

### Error Handling

```python
result = await client.call_tool_chain('''
try:
    # Tool call that might fail
    result = await weather.get_forecast(city="InvalidCity")
    print(f"Success: {result}")
except Exception as error:
    print(f"Error occurred: {error}")
    return {"error": str(error)}
    
return result
''')
```

### Working with Multiple Manuals

```python
result = await client.call_tool_chain('''
# Tools are organized by manual namespace
weather_data = await weather.get_current_weather(city="London")
news_data = await news.get_headlines(country="UK")

# Combine data from multiple sources
combined_result = {
    "weather": weather_data,
    "news": news_data,
    "location": "London"
}

print(f"Combined data: {combined_result}")
return combined_result
''')
```

## Code Execution Environment

The code execution environment includes:

- **Safe Python modules**: `json`, `asyncio`, `math`, `datetime`, `time`, `re`
- **Tool functions**: Registered tools accessible as async functions
- **Introspection utilities**: `__interfaces`, `__get_tool_interface()`
- **Console capture**: `print()` output is captured in logs

## Agent Prompt Template

The `CodeModeUtcpClient` includes a comprehensive agent prompt template at `CodeModeUtcpClient.AGENT_PROMPT_TEMPLATE` that provides guidance for AI agents on how to use the code execution capabilities effectively.

## Security Model

The CodeModeUtcpClient implements a **cooperative sandbox** designed for LLM-generated code execution:

### Security Features

- **Subprocess Isolation**: Code executes in separate processes for true timeout and memory isolation
- **Restricted Imports**: Only safe modules (json, math, asyncio, datetime, time, re, etc.) can be imported
- **Safe Builtins**: Limited set of built-in functions, dangerous ones like `exec`, `eval`, `open` are blocked
- **No System Access**: Modules like `os`, `sys`, `subprocess` are not available in execution context
- **Real Timeouts**: Processes can be forcibly terminated if they exceed time limits
- **Error Isolation**: Exceptions and errors are properly contained and reported

### Allowed Modules

- `json` - JSON parsing and serialization
- `math` - Mathematical functions
- `asyncio` - Async/await support (required for tool calls)
- `datetime` - Date and time utilities
- `time` - Time functions
- `re` - Regular expressions
- `typing` - Type hints (import only)
- `collections`, `itertools`, `functools`, `operator`, `uuid` - Standard utilities

### Blocked Features

- **System modules**: `os`, `sys`, `subprocess`, `shutil`
- **File I/O**: `open`, file operations
- **Network**: `socket`, `urllib`, `requests`
- **Code execution**: `exec`, `eval`, `compile`
- **Introspection**: Direct access to `__builtins__`, `globals()`, `locals()`

### Use Case

This security model is designed for:
- **Cooperative LLM-generated code** (not adversarial)
- **Tool-based workflows** where tools provide controlled external access  
- **Agent task execution** with defined interfaces
- **Educational and development environments**

**Not suitable for**: Production multi-tenant environments or untrusted user code.

## Configuration

### Timeout Settings

```python
# Set custom timeout (default: 30 seconds)
result = await client.call_tool_chain(code, timeout=60)
```

### Client Configuration

```python
# Create client with custom configuration
config = {
    "tool_repository": {"type": "in_memory"},
    "search_strategy": {"type": "tag_search"}
}

client = await CodeModeUtcpClient.create(
    root_dir="/path/to/project",
    config=config
)
```

## API Reference

### CodeModeUtcpClient

#### `create(root_dir=None, config=None) -> CodeModeUtcpClient`

Create a new CodeModeUtcpClient instance.

- `root_dir`: Root directory for resolving relative paths
- `config`: Client configuration (dict, str path, or UtcpClientConfig)

#### `call_tool_chain(code: str, timeout: int = 30) -> Dict[str, Any]`

Execute Python code with tool access.

- `code`: Python code to execute
- `timeout`: Timeout in seconds
- Returns: `{"result": execution_result, "logs": console_logs}`

#### `get_all_tools_python_interfaces() -> str`

Get Python type definitions for all registered tools.

#### `tool_to_python_interface(tool: Tool) -> str`

Convert a single tool to Python interface definition.

## Examples

See the `examples/` directory for more comprehensive examples of using the Code Mode Client Extension.

## Development

```bash
# Install in development mode
pip install -e .

# Run tests
pytest

# Run tests with coverage
pytest --cov=utcp_code_mode --cov-report=html
```

## License

This project is licensed under the Mozilla Public License 2.0 - see the LICENSE file for details.