Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
PCTX Code Mode
A TypeScript code execution engine that enables AI agents to dynamically call tools through generated code. Code Mode converts tool schemas (like MCP tools) into TypeScript interfaces, executes LLM-generated code in a sandboxed Deno runtime, and bridges function calls back to your Rust callbacks.
Quick Start
use ;
use CallbackConfig;
use json;
use Arc;
async
Core Concepts
1. CodeMode
The [CodeMode] struct is the main execution engine. It provides:
Builder methods (chainable):
with_server()/with_servers()- Add MCP serverswith_callback()/with_callbacks()- Add callback tools
Registration methods (mutable):
add_server()/add_servers()- Add MCP serversadd_callback()/add_callbacks()- Add callback toolsadd_tool_set()- Add a pre-built ToolSet directly
Accessor methods:
tool_sets()- Get registered ToolSetsservers()- Get registered server configurationscallbacks()- Get registered callback configurations
Execution methods:
list_functions()- List all available functions with minimal interfacesget_function_details()- Get full typed interfaces for specific functionsexecute()- Execute TypeScript code in the sandbox
use CodeMode;
use ;
use json;
let mut code_mode = default;
// Add callback tools
code_mode.add_callback?;
// List available functions
let list = code_mode.list_functions;
for func in list.functions
// Get detailed type information
let details = code_mode.get_function_details;
println!;
2. Tools and ToolSets
[Tool]s represent individual functions callable from TypeScript.
They are organized into [ToolSet]s (namespaces). Tools can be:
- MCP tools: Loaded from MCP servers via
add_server() - Callback tools: Defined via
CallbackConfigandadd_callback()
3. Callbacks
[CallbackFn] are Rust async functions that execute when TypeScript code calls callback tools.
Register them in a [CallbackRegistry] and pass it to execute().
use ;
use Arc;
let registry = default;
let callback: CallbackFn = new;
// Register with namespace.function format
registry.add?;
4. Code Execution
Execute LLM-generated TypeScript code that calls your registered tools.
let code = r#"
async function run() {
// Call your registered tools
const user = await DataApi.fetchData({ id: 123 });
const greeting = await Greeter.greet({ name: user.name });
// Chain multiple calls
const result = await DataApi.saveData({
id: user.id,
message: greeting.message
});
// Return the final result
return result;
}
"#;
let output = code_mode.execute.await?;
match output.success
API Reference
CodeMode
The main execution engine.
default()
let code_mode = default;
Builder Methods
Chainable methods for fluent construction:
use CodeMode;
use CallbackConfig;
use ServerConfig;
// Build with callbacks
let code_mode = default
.with_callback?
.with_callbacks?;
// Build with MCP servers (async)
let code_mode = default
.with_server.await?
.with_servers.await?;
add_callback(config: &CallbackConfig) -> Result<()>
Adds a callback-based tool to the code mode.
use CallbackConfig;
use json;
code_mode.add_callback?;
add_server(server: &ServerConfig) -> Result<()>
Connects to an MCP server and registers its tools.
use ServerConfig;
code_mode.add_server.await?;
// Or add multiple servers with a timeout (in seconds)
code_mode.add_servers.await?;
list_functions() -> ListFunctionsOutput
Lists all available functions with their TypeScript interface declarations.
let list = code_mode.list_functions;
println!;
for func in list.functions
get_function_details(input: GetFunctionDetailsInput) -> GetFunctionDetailsOutput
Gets detailed TypeScript type definitions for specific functions.
use ;
let details = code_mode.get_function_details;
println!;
execute(code: &str, callbacks: Option<CallbackRegistry>) -> Result<ExecuteOutput>
Executes TypeScript code in a sandboxed Deno runtime.
let output = code_mode.execute.await?;
if output.success else
Accessor Methods
// Get registered tool sets
let tool_sets: & = code_mode.tool_sets;
// Get registered server configurations
let servers: & = code_mode.servers;
// Get registered callback configurations
let callbacks: & = code_mode.callbacks;
CallbackRegistry
Thread-safe registry for managing callback functions.
default() -> CallbackRegistry
let registry = default;
add(id: &str, callback: CallbackFn) -> Result<()>
Registers a callback with a specific ID (format: Namespace.functionName).
registry.add?;
has(id: &str) -> bool
Checks if a callback is registered.
if registry.has
Types
CallbackConfig
Configuration for defining callback-based tools:
use CallbackConfig;
use json;
let config = CallbackConfig ;
Tool and ToolSet
Tools represent individual functions callable from TypeScript. They are organized into ToolSets (namespaces). These are typically created internally when you call add_callback() or add_server().
// Access registered tool sets
for tool_set in code_mode.tool_sets
ExecuteOutput
CallbackFn
Type alias for callback functions:
pub type CallbackFn = ;
Advanced Usage
Adding MCP Servers
Connect to MCP (Model Context Protocol) servers to automatically register their tools:
use ServerConfig;
// Create server configuration
let server_config = new_stdio;
// Or for HTTP-based servers
let server_config = new_http;
// Add to CodeMode (connects and registers tools)
code_mode.add_server.await?;
// Add multiple servers in parallel with timeout
code_mode.add_servers.await?;
Dynamic Tool Registration
Register tools at runtime based on configuration:
use CallbackConfig;
for config in tool_configs
Async Tool Execution
Callbacks support full async operations:
registry.add?;
Error Handling
let output = code_mode.execute.await?;
if !output.success
TypeScript Code Requirements
LLM-generated code must follow this pattern:
async function run() {
// Your code that calls registered tools
const result = await Namespace.toolName({ param: value });
// MUST return a value
return result;
}
The code execution engine:
- Wraps your code with namespace implementations
- Automatically calls
run()and captures its return value - Provides the return value in
ExecuteOutput.output
Architecture
- Tool Definition: Tools are defined with JSON Schemas for inputs/outputs
- Code Generation: TypeScript interface definitions are generated from schemas
- Code Execution: User code is wrapped with namespace implementations and executed in Deno
- Callback Routing: Function calls in TypeScript are routed to Rust callbacks or MCP servers
- Result Marshaling: JSON values are passed between TypeScript and Rust
Sandbox Security
Code is executed in a Deno runtime with:
- Network access restricted to allowed hosts (from registered MCP servers)
- No file system access
- No subprocess spawning
- Isolated V8 context per execution
// Add servers
code_mode.add_server.await?;
Examples
Multi-Tool Workflow
let code = r#"
async function run() {
// Fetch user data
const user = await UserApi.getUser({ id: 123 });
// Process the data
const processed = await DataProcessor.transform({
input: user.data,
format: "normalized"
});
// Save results
const saved = await Storage.save({
key: `user_${user.id}`,
value: processed
});
return {
userId: user.id,
saved: saved.success,
location: saved.url
};
}
"#;
let output = code_mode.execute.await?;
Error Recovery
let code = r#"
async function run() {
try {
return await RiskyApi.operation({ id: 1 });
} catch (error) {
console.error("Operation failed:", error);
// Fall back to safe default
return await SafeApi.getDefault();
}
}
"#;
let output = code_mode.execute.await?;
// Check console output
if !output.stdout.is_empty
Parallel Execution
let code = r#"
async function run() {
// Execute multiple operations in parallel
const [users, posts, comments] = await Promise.all([
UserApi.listUsers(),
PostApi.listPosts(),
CommentApi.listComments()
]);
return { users, posts, comments };
}
"#;
Related Crates
pctx_config: Server configuration types (ServerConfig)pctx_codegen: TypeScript code generation from JSON schemaspctx_executor: Deno runtime execution enginepctx_code_execution_runtime: Runtime environment and callback system
License
MIT