Expand description
§Tool System Architecture
This module provides a modular, composable architecture for VT Code agent tools, implementing a registry-based system for tool discovery, execution, and management.
§Architecture Overview
The tool system is designed around several key principles:
- Modularity: Each tool is a focused, reusable component
- Registry Pattern: Centralized tool registration and discovery
- Policy-Based Execution: Configurable execution policies and safety checks
- Type Safety: Strong typing for tool parameters and results
- Async Support: Full async/await support for all tool operations
§Core Components
§Tool Registry
use vtcode_core::tools::{ToolRegistry, ToolRegistration};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let workspace = std::env::current_dir()?;
let mut registry = ToolRegistry::new(workspace);
// Register a custom tool
let tool = ToolRegistration {
name: "my_tool".to_string(),
description: "A custom tool".to_string(),
parameters: serde_json::json!({"type": "object"}),
handler: |args| async move {
Ok(serde_json::json!({"result": "success"}))
},
};
registry.register_tool(tool).await?;
Ok(())
}§Tool Categories
§File Operations
- File Operations: Read, write, create, delete files
- Search Tools: grep_file with ripgrep for fast regex-based pattern matching, glob patterns, type filtering
- Cache Management: File caching and performance optimization
§Terminal Integration
- Bash Tools: Shell command execution
- PTY Support: Full terminal emulation
- Command Policies: Safety and execution controls
§Code Analysis
§Tool Execution
use vtcode_core::tools::ToolRegistry;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut registry = ToolRegistry::new(std::env::current_dir()?);
// Execute a tool
let args = serde_json::json!({"path": "."});
let result = registry.execute_tool("list_files", args).await?;
println!("Result: {}", result);
Ok(())
}§Safety & Policies
The tool system includes comprehensive safety features:
- Path Validation: All file operations check workspace boundaries
- Command Policies: Configurable allow/deny lists for terminal commands
- Execution Limits: Timeout and resource usage controls
- Audit Logging: Complete trail of tool executions
§Custom Tool Development
use vtcode_core::tools::traits::Tool;
use serde_json::Value;
struct MyCustomTool;
#[async_trait::async_trait]
impl Tool for MyCustomTool {
async fn execute(&self, args: Value) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
// Tool implementation
Ok(serde_json::json!({"status": "completed"}))
}
fn name(&self) -> &str {
"my_custom_tool"
}
fn description(&self) -> &str {
"A custom tool for specific tasks"
}
fn parameters(&self) -> Value {
serde_json::json!({
"type": "object",
"properties": {
"input": {"type": "string"}
}
})
}
}Modular tool system for VT Code
This module provides a composable architecture for agent tools, breaking down the monolithic implementation into focused, reusable components.
Re-exports§
pub use resilience::rate_limiter;pub use resilience::adaptive_rate_limiter;pub use resilience::circuit_breaker;pub use ast_grep_installer::AstGrepInstallOutcome;pub use ast_grep_installer::AstGrepStatus;pub use autonomous_executor::AutonomousExecutor;pub use autonomous_executor::AutonomousPolicy;pub use cache::FileCache;pub use command_cache::PermissionCache;pub use command_resolver::CommandResolver;pub use editing::Patch;pub use editing::PatchError;pub use editing::PatchHunk;pub use editing::PatchLine;pub use editing::PatchOperation;pub use exec_session_id::ExecSessionId;pub use execution_context::ToolExecutionContext;pub use execution_context::ToolExecutionRecord;pub use execution_context::ToolPattern;pub use execution_tracker::ExecutionRecord;pub use execution_tracker::ExecutionStats;pub use execution_tracker::ExecutionStatus;pub use execution_tracker::ExecutionTracker;pub use file_search_rpc::FileMatchRpc;pub use file_search_rpc::FileSearchRpcHandler;pub use file_search_rpc::ListFilesRequest;pub use file_search_rpc::ListFilesResponse;pub use file_search_rpc::RpcError;pub use file_search_rpc::RpcRequest;pub use file_search_rpc::RpcResponse;pub use file_search_rpc::SearchFilesRequest;pub use file_search_rpc::SearchFilesResponse;pub use grep_file::GrepSearchManager;pub use invocation::InvocationBuilder;pub use invocation::ToolInvocation as UnifiedToolInvocation;pub use invocation::ToolInvocationId;pub use optimized_registry::OptimizedToolRegistry;pub use optimized_registry::ToolMetadata as OptimizedToolMetadata;pub use plugins::PluginHandle;pub use plugins::PluginId;pub use plugins::PluginInstaller;pub use plugins::PluginManifest;pub use plugins::PluginRuntime;pub use pty::PtyCommandRequest;pub use pty::PtyCommandResult;pub use pty::PtyManager;pub use registry::ApprovalPattern;pub use registry::ApprovalRecorder;pub use registry::CgpRuntimeMode;pub use registry::JustificationExtractor;pub use registry::JustificationManager;pub use registry::RiskLevel;pub use registry::ToolJustification;pub use registry::ToolRegistration;pub use registry::ToolRegistry;pub use registry::ToolRiskContext;pub use registry::ToolRiskScorer;pub use registry::ToolSource;pub use registry::WorkspaceTrust;pub use registry::native_cgp_tool_factory;pub use registry::wrap_registered_native_tool;pub use request_response::ToolCallRequest;pub use request_response::ToolCallResponse;pub use result::TokenCounts;pub use result::ToolMetadata;pub use result::ToolMetadataBuilder;pub use result::ToolResult as SplitToolResult;pub use result_cache::ToolCacheKey;pub use result_cache::ToolResultCache;pub use result_metadata::EnhancedToolResult;pub use result_metadata::ResultCompleteness;pub use result_metadata::ResultMetadata;pub use result_metadata::ResultScorer;pub use result_metadata::ScorerRegistry;pub use ripgrep_installer::RipgrepStatus;pub use safety_gateway::SafetyCheckResult;pub use safety_gateway::SafetyContext;pub use safety_gateway::SafetyDecision;pub use safety_gateway::SafetyError;pub use safety_gateway::SafetyGateway;pub use safety_gateway::SafetyGatewayConfig;pub use safety_gateway::SafetyStats;pub use safety_gateway::SafetyTrustLevel;pub use search_metrics::SearchMetric;pub use search_metrics::SearchMetrics;pub use search_metrics::SearchMetricsStats;pub use shell_snapshot::FileFingerprint;pub use shell_snapshot::ShellKind;pub use shell_snapshot::ShellSnapshot;pub use shell_snapshot::ShellSnapshotManager;pub use shell_snapshot::SnapshotStats;pub use shell_snapshot::apply_snapshot_env;pub use shell_snapshot::global_snapshot_manager;pub use tool_effectiveness::AdaptiveToolSelector;pub use tool_effectiveness::ToolEffectiveness;pub use tool_effectiveness::ToolEffectivenessTracker;pub use tool_effectiveness::ToolFailureMode;pub use tool_effectiveness::ToolSelectionContext;pub use tool_effectiveness::ToolSelector;pub use traits::Tool;pub use traits::ToolExecutor;pub use unified_error::DebugContext as UnifiedToolDebugContext;pub use unified_error::ErrorSeverity as UnifiedErrorSeverity;pub use unified_error::UnifiedErrorKind;pub use unified_error::UnifiedToolError;pub use unified_error::classify_error as classify_unified_error;pub use web_fetch::WebFetchTool;pub use output_spooler::SpoolResult;pub use output_spooler::SpoolerConfig;pub use output_spooler::ToolOutputSpooler;pub use async_middleware::AsyncCachingMiddleware;pub use async_middleware::AsyncLoggingMiddleware;pub use async_middleware::AsyncMiddleware;pub use async_middleware::AsyncMiddlewareChain;pub use async_middleware::AsyncRetryMiddleware;pub use async_middleware::ToolRequest as MiddlewareToolRequest;pub use async_middleware::ToolResult;pub use handlers::ApplyPatchHandler;pub use handlers::ApplyPatchRequest;pub use handlers::ApplyPatchRuntime;pub use handlers::ApplyPatchToolArgs;pub use handlers::Approvable;pub use handlers::ApprovalPolicy;pub use handlers::AskForApproval;pub use handlers::ChangeAttribution;pub use handlers::CommandSpec;pub use handlers::ConfiguredToolSpec;pub use handlers::ContentItem;pub use handlers::DiffTracker;pub use handlers::ExecApprovalRequirement;pub use handlers::ExecCommandInput;pub use handlers::ExecCommandSource;pub use handlers::ExecEnv;pub use handlers::ExecPolicyAmendment;pub use handlers::ExecToolCallOutput;pub use handlers::FileChange;pub use handlers::FileChangeKind;pub use handlers::McpToolResult;pub use handlers::ParsedCommand;pub use handlers::RejectConfig;pub use handlers::SandboxAttempt;pub use handlers::SandboxManager;pub use handlers::SandboxMode;pub use handlers::SandboxPermissions;pub use handlers::SandboxPolicy;pub use handlers::SandboxTransformError;pub use handlers::Sandboxable;pub use handlers::SandboxablePreference;pub use handlers::ShellEnvironmentPolicy;pub use handlers::ShellToolCallParams;pub use handlers::ToolCallError;pub use handlers::ToolCtx;pub use handlers::ToolEmitter;pub use handlers::ToolError;pub use handlers::ToolEvent;pub use handlers::ToolEventBegin;pub use handlers::ToolEventCtx;pub use handlers::ToolEventFailure;pub use handlers::ToolEventFailureKind;pub use handlers::ToolEventStage;pub use handlers::ToolEventSuccess;pub use handlers::ToolHandler;pub use handlers::ToolInvocation;pub use handlers::ToolKind;pub use handlers::ToolOrchestrator;pub use handlers::ToolOutput;pub use handlers::ToolPayload;pub use handlers::ToolRuntime;pub use handlers::ToolSession;pub use handlers::ToolSpec;pub use handlers::TurnContext;pub use handlers::TurnDiffTracker;pub use handlers::create_apply_patch_freeform_tool;pub use handlers::create_apply_patch_json_tool;pub use handlers::default_exec_approval_requirement;pub use handlers::intercept_apply_patch;pub use handlers::intercept_apply_patch;pub use improvement_algorithms::MLScoreComponents;pub use improvement_algorithms::PatternState;pub use improvement_algorithms::TimeDecayedScore;pub use improvement_algorithms::detect_pattern;pub use improvement_algorithms::jaro_winkler_similarity;pub use improvements_config::CacheConfig;pub use improvements_config::ContextConfig;pub use improvements_config::FallbackConfig;pub use improvements_config::ImprovementsConfig;pub use improvements_config::PatternConfig;pub use improvements_config::SimilarityConfig;pub use improvements_config::TimeDecayConfig;pub use improvements_errors::ErrorKind;pub use improvements_errors::ErrorSeverity;pub use improvements_errors::EventType;pub use improvements_errors::ImprovementError;pub use improvements_errors::ImprovementEvent;pub use improvements_errors::ImprovementResult;pub use improvements_errors::ObservabilityContext;pub use improvements_errors::ObservabilitySink;pub use improvements_registry_ext::ToolMetrics;pub use improvements_registry_ext::ToolRegistryImprovement;pub use types::*;
Modules§
- apply_
patch - Patch tool facade that exposes Codex-compatible patch parsing and application.
- ast_
grep_ binary - ast_
grep_ installer - async_
middleware - Async middleware for LLM-compatible tool execution
- autonomous_
executor - Autonomous tool execution with safety checks
- builder
- Unified builder for tool responses
- cache
- Caching system for tool results
- command
- Command execution tool
- command_
args - Shared helpers for command-style tool arguments.
- command_
cache - command_
policy - command_
resolver - Command resolution system Maps command names to their actual filesystem paths Used by policy evaluator to validate and log command locations
- constants
- Shared constants for tool operations to eliminate duplication
- continuation
- edited_
file_ monitor - editing
- error_
helpers - Shared error helpers to reduce repetitive .with_context() patterns
- error_
messages - exec_
session - exec_
session_ id - execution_
context - Tool execution context tracking
- execution_
tracker - Tool execution tracking with optimized storage
- file_
ops - File operation tools with composable functionality.
- file_
search_ bridge - Bridge module integrating vtcode-file-search with grep_file.rs
- file_
search_ rpc - RPC endpoint for file search operations
- file_
tracker - generation_
helpers - Generation Helpers
- grep_
cache - Caching layer for grep file search results to avoid redundant searches
- grep_
file - Helper that owns the debounce/cancellation logic for
grep_fileoperations. - handlers
- Tool handlers module (Codex-compatible compatibility layer)
- health
- improvement_
algorithms - Production-grade algorithms for tool improvements.
- improvements_
config - Configuration management for tool improvements system
- improvements_
errors - Error types and observability for core improvements
- improvements_
registry_ ext - Real integration with ToolRegistry
- invocation
- Unified tool invocation tracking
- mcp
- names
- native_
memory - optimized_
registry - Optimized tool registry with reduced lock contention and improved caching
- output_
spooler - Tool Output Spooler for Dynamic Context Discovery
- path_
env - pattern_
engine - Advanced pattern detection with sequence analysis
- plugins
- pty
- PTY session management.
- registry
- Tool registry and function declarations
- request_
response - request_
user_ input - resilience
- Resilience primitives for tool execution.
- result
- Split tool results: Dual-channel output for LLM and UI
- result_
cache - Tool result caching for read-only operations
- result_
metadata - Tool result metadata and quality scoring
- ripgrep_
binary - ripgrep_
installer - Ripgrep availability detection and explicit installation management.
- safety_
gateway - Unified Safety Gateway
- search_
metrics - shell
- High-level shell command runner and workspace utilities
- shell_
snapshot - Shell environment snapshot for avoiding repeated login script execution.
- skills
- structural_
search - summarizers
- Tool result summarization strategies
- terminal_
app - tool_
effectiveness - Tool effectiveness tracking and adaptive selection
- tool_
intent - traits
- Core traits for the composable tool system
- types
- Common types used across the tool system
- unified_
error - Unified tool error envelope for consistent error handling across execution paths
- validation
- validation_
cache - web_
fetch - WebFetch tool for fetching and analyzing web content using AI
Structs§
Enums§
Constants§
- CREATE_
APPLY_ PATCH_ FREEFORM_ TOOL_ ID - Internal helper IDs for apply_patch and tracker constructors.
- CREATE_
APPLY_ PATCH_ JSON_ TOOL_ ID - INTERCEPT_
APPLY_ PATCH_ ID - NEW_
SHARED_ TRACKER_ ID