Skip to main content

Module tools

Module tools 

Source
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::SharedDiffTracker;
pub use handlers::SharedTurnDiffTracker;
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 handlers::new_shared_tracker;
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_file operations.
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§

FreeformTool
FreeformToolFormat
ResponsesApiTool
SearchToolBundleStatus

Enums§

SearchToolReadiness

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

Functions§

dominant_workspace_language
parse_tool_input_schema
search_tool_bundle_status

Type Aliases§

ToolJsonSchema