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 apply_patch::mutation_target_paths;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 defuddle::DefuddleTool;pub use optimized_registry::CachedToolMetadata as OptimizedToolMetadata;pub use optimized_registry::OptimizedToolRegistry;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::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 web_fetch::WebFetchTool;pub use web_search::WebSearchTool;pub use output_spooler::SpoolResult;pub use output_spooler::SpoolState;pub use output_spooler::SpooledOutputReference;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::MiddlewareToolResult;pub use async_middleware::ToolRequest as MiddlewareToolRequest;pub use cached_executor::CachedToolExecutor;pub use cached_executor::ExecutorStats;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::ChangeAttribution;pub use handlers::CommandSpec;pub use handlers::ConfiguredToolSpec;pub use handlers::ContentItem;pub use handlers::DiffTracker;pub use handlers::ExecCommandInput;pub use handlers::ExecCommandSource;pub use handlers::ExecEnv;pub use handlers::ExecToolCallOutput;pub use handlers::FileChange;pub use handlers::FileChangeKind;pub use handlers::McpToolResult;pub use handlers::ParsedCommand;pub use handlers::SandboxAttempt;pub use handlers::SandboxConfig;pub use handlers::SandboxManager;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::ToolEventCtx;pub use handlers::ToolEventFailureKind;pub use handlers::ToolEventStage;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::ToolCallRecord;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::EventType;pub use improvements_errors::ImprovementError;pub use improvements_errors::ImprovementEvent;pub use improvements_errors::ImprovementResult;pub use improvements_errors::ImprovementSeverity;pub use improvements_errors::ImprovementSeverity as ErrorSeverity;pub use improvements_errors::ObservabilityContext;pub use improvements_errors::ObservabilitySink;pub use improvements_registry_ext::ToolMetrics;pub use improvements_registry_ext::ToolRegistryImprovement;pub use lru_cache::CacheObserver;pub use lru_cache::CacheStats;pub use lru_cache::LruCache;pub use pattern_detection::DetectedPattern;pub use pattern_detection::PatternDetector;pub use tool_middleware::Middleware;pub use tool_middleware::MiddlewareChain;pub use workflow_optimizer::Optimization;pub use workflow_optimizer::OptimizationType;pub use workflow_optimizer::WorkflowOptimizer;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
- cached_
executor - Production ToolExecutor: Cache + Middleware + Patterns integrated.
- 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
- defuddle
- Defuddle-backed fetch:
https://defuddle.md/{link}-> clean markdown. - 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-indexer::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
- lru_
cache - LRU cache with TTL enforcement and observability hooks.
- mcp
- names
- native_
memory - optimized_
registry - Optimized tool registry with reduced lock contention and improved caching
- outline_
search - Bounded, read-only declaration discovery for
code_search. - output_
spooler - Tool Output Spooler for Dynamic Context Discovery
- path_
env - pattern_
detection - Pattern detection with sequence analysis and ML feature engineering.
- pattern_
engine - Advanced pattern detection with sequence analysis
- plugins
- pty
- PTY session management.
- read_
limits - Read limit configuration for file operations
- registry
- Tool registry and function declarations
- registry_
adapters - Workspace-aware adapters that bridge
vtcode-corewith thevtcode-commonstraits. - 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
- summarizers
- Tool result summarization strategies
- terminal_
app - time_
compat - Small compatibility helpers that avoid pulling in heavy dependencies
(e.g.
chrono) for trivial needs. - tool_
effectiveness - Tool effectiveness tracking and adaptive selection
- tool_
intent - Tool intent classification: mutating vs read-only, parallel-safe, and action extraction for unified tool surfaces.
- tool_
middleware - Composable async middleware for tool execution.
- 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
- untrusted_
data - Untrusted-data fence for tool output.
- validation
- validation_
cache - web_
fetch - WebFetch tool for fetching and analyzing web content using AI
- web_
search - WebSearch tool: query -> ranked web results (title, url, snippet).
- workflow_
optimizer - Workflow optimizer: Uses patterns and ML features to improve tool execution.
Structs§
- Enhanced
Tool Result - Enhanced tool result with metadata
- Exec
Policy Amendment - A proposed amendment to the execution policy.
- Freeform
Tool - Freeform
Tool Format - Reject
Config - Fine-grained rejection controls for approval prompts.
- Responses
ApiTool - Result
Metadata - Quality metadata for tool results
- Search
Tool Bundle Status
Enums§
- AskFor
Approval - Policy for when to ask for approval before executing commands.
- Exec
Approval Requirement - Requirement for approval before executing a command.
- Result
Completeness - Result completeness level
- Sandbox
Permissions - Fine-grained permissions for sandbox operations.
- Search
Tool Readiness
Traits§
- Result
Scorer - Trait for scoring tool results
Functions§
- code_
search_ scope_ contains_ mutated_ path - Return whether a mutated path lies within the file or directory scope of a
valid
code_searchrequest. - dominant_
workspace_ language - normalised_
code_ search_ identity - Normalised identity for result caching and replay.
- normalised_
code_ search_ loop_ identity - Normalised identity for detecting repeated search behaviour.
- normalised_
code_ search_ path - Lexically normalize a search path without erasing leading
..components. - parse_
tool_ input_ schema - search_
tool_ bundle_ status