This document describes the Python implementation of the Code-Mode library for UTCP.
The Python implementation provides equivalent functionality to the TypeScript version, allowing Python code execution with access to UTCP tools. It follows the same design patterns and API structure for consistency across languages.
-
CodeModeClient (
src/code_mode/code_mode_client.py)- Main client class for managing tools and executing code
- Async/await support for tool execution
- Isolated code execution using Python's
exec() - Console output capture
- Timeout protection
-
Tool class
- Represents UTCP tool definitions
- Contains metadata, input/output schemas, and call templates
- Python code is wrapped in an async function for execution
- Supports
awaitfor tool calls - Return values are properly captured
- stdout/stderr are captured as logs
- Tools organized by namespace (e.g.,
manual.tool) - Dynamic tool registration
- Interface generation for IDE support
- Isolated execution context with limited globals
- No file system access by default
- Configurable timeouts to prevent runaway code
- Tools only accessible through registered manual
const client = await CodeModeUtcpClient.create();
await client.registerManual({...});
const { result, logs } = await client.callToolChain(`...`);client = CodeModeClient.create()
await client.register_manual({...})
response = await client.call_tool_chain("...")
result = response['result']
logs = response['logs']- User code is wrapped in an async function:
async def __code_mode_exec():
# user code here
return result-
The function is executed in a controlled context with:
- Tool functions as async callables
- Standard Python built-ins
- Interface introspection functions
- Custom print function for log capture
-
Return value and logs are collected and returned
Tools are organized by namespace:
# Tool named "github.get_pull_request" is accessed as:
result = await github.get_pull_request(owner='...', repo='...', pull_number=123)Python interface definitions are generated for each tool:
class github:
async def get_pull_request(self, **kwargs) -> dict:
"""
Get a pull request from GitHub
Args:
owner (str): Repository owner
repo (str): Repository name
pull_number (int): Pull request number
Returns:
dict: Pull request data
Tags: github, pr
"""
passThe test suite (tests/test_code_mode_client.py) includes 18 comprehensive tests:
- Client creation and initialization
- Tool registration
- Interface generation
- Simple code execution
- Code with return values
- Single tool calls
- Multiple chained tool calls
- Complex data structures
- Array processing
- Error handling
- Timeout handling
- Syntax error handling
- Python built-ins access
- Interface introspection
- Console output capture
- Complex multi-step workflows
- Agent prompt template
All tests pass successfully.
See examples/basic_usage.py for a simple calculator example.
See examples/chained_operations.py for a complex workflow with multiple tool calls.
-
Execution Environment
- TypeScript uses Node.js VM for sandboxing
- Python uses
exec()with controlled globals
-
Type System
- TypeScript has native TypeScript interface generation
- Python uses docstring-based interface documentation
-
Async Handling
- Both use async/await but with language-specific syntax
- Python requires explicit
asyncio.run()for top-level execution
-
Error Handling
- Similar patterns but language-specific exception types
Potential improvements for the Python implementation:
-
Real UTCP SDK Integration
- Currently uses mock tools for testing
- Production implementation would connect to actual UTCP servers
-
Enhanced Security
- RestrictedPython for more secure code execution
- Resource limits (memory, CPU)
-
Performance Optimization
- Code compilation caching
- Tool call batching
-
Type Hints
- Full type hint support throughout
- mypy validation
-
Additional Protocols
- HTTP tool support
- File-based tool support
- CLI tool support
cd python
pip install -e .Or with development dependencies:
pip install -e ".[dev]"cd python
pytest tests/ -vMPL-2.0 (same as main project)