Skip to main content

vtcode_core/skills/
cli_bridge.rs

1//! CLI Tool Bridge for External Tool Integration
2//!
3//! Bridges external CLI tools to VT Code's skill system, enabling integration
4//! of any command-line tool with proper documentation into the agent harness.
5//!
6//! ## Features
7//!
8//! - **Progressive Disclosure**: Load tool documentation only when needed
9//! - **JSON I/O**: Structured input/output via JSON when available
10//! - **Fallback Support**: Graceful degradation to text output
11//! - **Validation**: Schema-based validation for tool arguments
12//! - **Streaming**: Support for long-running operations
13//!
14//! ## Tool Discovery
15//!
16//! Tools are discovered by scanning for:
17//! - Executable files with accompanying README.md
18//! - tool.json metadata files
19//! - Standard installation paths (/usr/local/bin, ~/.local/bin, etc.)
20
21use crate::skills::types::{Skill, SkillManifest, SkillResource};
22use crate::tool_policy::ToolPolicy;
23use crate::tools::traits::Tool;
24use crate::utils::async_utils;
25use crate::utils::file_utils::{read_file_with_context_sync, read_json_file_sync};
26use anyhow::{Result, anyhow};
27use async_trait::async_trait;
28use serde::{Deserialize, Serialize};
29use serde_json::Value;
30use std::path::{Path, PathBuf};
31use std::process::Stdio;
32use std::time::Duration;
33use tokio::process::Command;
34use tracing::{debug, info, warn};
35
36/// Configuration for a CLI tool skill
37#[derive(Debug, Clone, Serialize, Deserialize)]
38pub struct CliToolConfig {
39    /// Tool name (must be unique)
40    pub name: String,
41
42    /// Brief description
43    pub description: String,
44
45    /// Path to the executable
46    pub executable_path: PathBuf,
47
48    /// Path to README/documentation
49    pub readme_path: Option<PathBuf>,
50
51    /// Path to JSON schema for arguments
52    pub schema_path: Option<PathBuf>,
53
54    /// Timeout for execution (seconds)
55    pub timeout_seconds: Option<u64>,
56
57    /// Whether tool supports JSON I/O
58    pub supports_json: bool,
59
60    /// Environment variables to set
61    pub environment: Option<hashbrown::HashMap<String, String>>,
62
63    /// Working directory for execution
64    pub working_dir: Option<PathBuf>,
65}
66
67/// Tool execution result
68#[derive(Debug, Clone, Serialize, Deserialize)]
69pub struct CliToolResult {
70    /// Exit code
71    pub exit_code: i32,
72
73    /// Standard output
74    pub stdout: String,
75
76    /// Standard error
77    pub stderr: String,
78
79    /// Parsed JSON output (if available)
80    pub json_output: Option<Value>,
81
82    /// Execution time in milliseconds
83    pub execution_time_ms: u64,
84}
85
86/// Bridge between CLI tools and VT Code skills
87#[derive(Debug, Clone)]
88pub struct CliToolBridge {
89    pub config: CliToolConfig,
90    instructions: String,
91    schema: Option<Value>,
92}
93
94impl CliToolBridge {
95    /// Create a new CLI tool bridge from configuration
96    pub fn new(config: CliToolConfig) -> Result<Self> {
97        let instructions = Self::load_readme(&config)?;
98        let schema = Self::load_schema(&config)?;
99
100        Ok(CliToolBridge { config, instructions, schema })
101    }
102
103    /// Create a bridge from a tool directory
104    pub fn from_directory(tool_dir: &Path) -> Result<Self> {
105        let config_path = tool_dir.join("tool.json");
106        let config: CliToolConfig = if config_path.exists() {
107            read_json_file_sync(&config_path)?
108        } else {
109            // Auto-discover tool configuration
110            Self::auto_discover_config(tool_dir)?
111        };
112
113        Self::new(config)
114    }
115
116    /// Auto-discover tool configuration from directory
117    fn auto_discover_config(tool_dir: &Path) -> Result<CliToolConfig> {
118        // Look for executable files
119        let executables = Self::find_executables(tool_dir)?;
120        if executables.is_empty() {
121            return Err(anyhow!("No executable files found in {}", tool_dir.display()));
122        }
123
124        // Look for README files
125        let readme_files = Self::find_readmes(tool_dir)?;
126
127        // Use first executable and README (if found)
128        let executable_path = executables[0].clone();
129        let readme_path = readme_files.first().cloned();
130
131        // Try to determine tool name from executable
132        let name = executable_path
133            .file_stem()
134            .and_then(|s| s.to_str())
135            .ok_or_else(|| anyhow!("Invalid executable filename"))?
136            .to_string();
137
138        Ok(CliToolConfig {
139            name: name.clone(),
140            description: format!("CLI tool: {name}"),
141            executable_path,
142            readme_path,
143            schema_path: None,
144            timeout_seconds: Some(30),
145            supports_json: false, // Will be tested during execution
146            environment: None,
147            working_dir: Some(tool_dir.to_path_buf()),
148        })
149    }
150
151    /// Find executable files in directory
152    fn find_executables(dir: &Path) -> Result<Vec<PathBuf>> {
153        let mut executables = vec![];
154
155        for entry in std::fs::read_dir(dir)? {
156            let entry = entry?;
157            let path = entry.path();
158
159            // Trust the dirent type: `path.is_file()` was a `stat` and the
160            // `entry.metadata()` below already fetches permissions.
161            if vtcode_commons::walk::entry_is_file(&entry) {
162                #[cfg(unix)]
163                {
164                    use std::os::unix::fs::PermissionsExt;
165                    let metadata = entry.metadata()?;
166                    let permissions = metadata.permissions();
167                    if permissions.mode() & 0o111 != 0 {
168                        executables.push(path);
169                    }
170                }
171
172                #[cfg(windows)]
173                {
174                    if let Some(ext) = path.extension() {
175                        if ext == "exe" || ext == "bat" || ext == "cmd" {
176                            executables.push(path);
177                        }
178                    }
179                }
180            }
181        }
182
183        Ok(executables)
184    }
185
186    /// Find README files in directory
187    fn find_readmes(dir: &Path) -> Result<Vec<PathBuf>> {
188        let mut readmes = vec![];
189
190        for entry in std::fs::read_dir(dir)? {
191            let entry = entry?;
192            let path = entry.path();
193            // Resolve the entry type once instead of stat-ing inside the filter.
194            let is_file = vtcode_commons::walk::entry_is_file(&entry);
195
196            if let Some(_name) = path
197                .file_name()
198                .and_then(|n| n.to_str())
199                .filter(|n| is_file && n.to_lowercase().starts_with("readme") && n.ends_with(".md"))
200            {
201                readmes.push(path);
202            }
203        }
204
205        Ok(readmes)
206    }
207
208    /// Load README/documentation content
209    fn load_readme(config: &CliToolConfig) -> Result<String> {
210        if let Some(readme_path) = config.readme_path.as_ref().filter(|p| p.exists()) {
211            return read_file_with_context_sync(readme_path, "README file");
212        }
213
214        // Generate basic instructions if no README
215        Ok(format!(
216            "# {}\n\nCLI tool: {}\n\nExecute with provided arguments.\n",
217            config.name,
218            config.executable_path.display()
219        ))
220    }
221
222    /// Load JSON schema for validation
223    fn load_schema(config: &CliToolConfig) -> Result<Option<Value>> {
224        if let Some(schema_path) = config.schema_path.as_ref().filter(|p| p.exists()) {
225            return Ok(Some(read_json_file_sync(schema_path)?));
226        }
227
228        Ok(None)
229    }
230
231    /// Execute the CLI tool with given arguments
232    pub async fn execute_internal(&self, args: Value) -> Result<CliToolResult> {
233        info!("Executing CLI tool: {} with args: {:?}", self.config.name, args);
234
235        let start_time = std::time::Instant::now();
236
237        // Validate arguments against schema if available
238        if let Some(schema) = &self.schema {
239            self.validate_args(&args, schema)?;
240        }
241
242        // Build command
243        let mut cmd = Command::new(&self.config.executable_path);
244
245        // Set working directory
246        if let Some(working_dir) = &self.config.working_dir {
247            cmd.current_dir(working_dir);
248        }
249
250        // Set environment variables
251        if let Some(env) = &self.config.environment {
252            for (key, value) in env {
253                cmd.env(key, value);
254            }
255        }
256
257        // Configure I/O
258        cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
259
260        // Add arguments based on configuration and input
261        self.configure_arguments(&mut cmd, &args)?;
262
263        // Execute with timeout
264        let timeout_duration = Duration::from_secs(self.config.timeout_seconds.unwrap_or(30));
265        let output_result = async_utils::with_timeout(cmd.output(), timeout_duration, "CLI tool execution").await??;
266
267        let execution_time_ms = start_time.elapsed().as_millis() as u64;
268
269        // Parse output
270        let stdout = String::from_utf8_lossy(&output_result.stdout).into_owned();
271        let stderr = String::from_utf8_lossy(&output_result.stderr).into_owned();
272
273        // Try to parse JSON output if supported
274        let json_output = if self.config.supports_json {
275            serde_json::from_str(&stdout).ok()
276        } else {
277            None
278        };
279
280        Ok(CliToolResult {
281            exit_code: output_result.status.code().unwrap_or(-1),
282            stdout,
283            stderr,
284            json_output,
285            execution_time_ms,
286        })
287    }
288
289    /// Configure command arguments based on input
290    fn configure_arguments(&self, cmd: &mut Command, args: &Value) -> Result<()> {
291        if args.is_null() || args == &Value::Null {
292            return Ok(());
293        }
294
295        // Handle different argument formats
296        match args {
297            Value::String(s) => {
298                // Single string argument
299                cmd.arg(s);
300            }
301            Value::Array(arr) => {
302                // Array of arguments
303                for arg in arr {
304                    if let Some(s) = arg.as_str() {
305                        cmd.arg(s);
306                    }
307                }
308            }
309            Value::Object(map) => {
310                // Named arguments - convert to command-line flags
311                for (key, value) in map {
312                    if let Some(s) = value.as_str() {
313                        cmd.arg(format!("--{key}"));
314                        cmd.arg(s);
315                    } else if value.as_bool().is_some_and(|flag| flag) {
316                        cmd.arg(format!("--{key}"));
317                    }
318                }
319            }
320            _ => {
321                // Fallback: serialize to JSON and pass as single argument
322                let json_str = serde_json::to_string(args)?;
323                cmd.arg(json_str);
324            }
325        }
326
327        Ok(())
328    }
329
330    /// Validate arguments against JSON schema
331    fn validate_args(&self, args: &Value, schema: &Value) -> Result<()> {
332        // Basic validation - in production, use jsonschema crate
333        debug!("Validating args against schema: {:?}", schema);
334
335        // For now, just check required fields
336        if let Some(required) = schema.get("required").and_then(|v| v.as_array()) {
337            for field in required {
338                if let Some(field_name) = field.as_str().filter(|f| args.get(*f).is_none()) {
339                    return Err(anyhow!("Missing required field: {field_name}"));
340                }
341            }
342        }
343
344        Ok(())
345    }
346
347    /// Test if tool supports JSON I/O
348    pub async fn test_json_support(&self) -> Result<bool> {
349        debug!("Testing JSON support for tool: {}", self.config.name);
350
351        // Try to execute with --help-json or similar flag
352        let mut cmd = Command::new(&self.config.executable_path);
353        cmd.arg("--help-json").stdout(Stdio::piped()).stderr(Stdio::piped());
354
355        let result = cmd.output().await;
356
357        match result {
358            Ok(output) => {
359                let stdout = String::from_utf8_lossy(&output.stdout);
360                // Check if output is valid JSON
361                Ok(serde_json::from_str::<Value>(&stdout).is_ok())
362            }
363            Err(_) => Ok(false),
364        }
365    }
366
367    /// Convert to VT Code Skill
368    pub fn to_skill(&self) -> Result<Skill> {
369        let manifest = SkillManifest {
370            name: self.config.name.clone(),
371            description: self.config.description.clone(),
372            version: Some("1.0.0".to_string()),
373            author: Some("VT Code CLI Bridge".to_string()),
374            variety: crate::skills::types::SkillVariety::SystemUtility,
375            ..Default::default()
376        };
377
378        let mut skill = Skill::new(
379            manifest,
380            self.config
381                .executable_path
382                .parent()
383                .unwrap_or_else(|| Path::new("."))
384                .to_path_buf(),
385            self.instructions.clone(),
386        )?;
387
388        // Add schema as resource if available
389        if let Some(schema) = &self.schema {
390            skill.add_resource(
391                "schema.json".to_string(),
392                SkillResource {
393                    path: "schema.json".to_string(),
394                    resource_type: crate::skills::types::ResourceType::Reference,
395                    content: Some(schema.to_string().into_bytes()),
396                },
397            );
398        }
399
400        Ok(skill)
401    }
402}
403
404#[async_trait]
405impl Tool for CliToolBridge {
406    fn name(&self) -> &str {
407        &self.config.name
408    }
409
410    fn description(&self) -> &str {
411        &self.config.description
412    }
413
414    fn parameter_schema(&self) -> Option<Value> {
415        self.schema.clone()
416    }
417
418    fn default_permission(&self) -> ToolPolicy {
419        ToolPolicy::Prompt
420    }
421
422    async fn execute(&self, args: Value) -> Result<Value> {
423        let result = self.execute_internal(args).await?;
424        Ok(serde_json::to_value(result)?)
425    }
426}
427
428/// Discover CLI tools in project-local locations.
429///
430/// Only project-scoped directories are scanned (`~/.local/bin`, `./tools`,
431/// `./vendor/tools`). System directories such as `/usr/bin` and
432/// `/usr/local/bin` are intentionally excluded: treating every system
433/// executable as a skill pollutes the catalog with hundreds of unrelated
434/// binaries (`kubectl`, `binhex`, versioned `python3.12`/`python3.15` pairs
435/// that collapse to the same `file_stem` name), slows startup, and exposes
436/// system binaries as model-invocable skills.
437pub fn discover_cli_tools() -> Result<Vec<CliToolConfig>> {
438    let mut tools = vec![];
439
440    // Project-local locations to search (no system directories).
441    let search_paths = vec![
442        PathBuf::from("~/.local/bin").expand_home()?,
443        PathBuf::from("./tools"),
444        PathBuf::from("./vendor/tools"),
445    ];
446
447    for path in search_paths {
448        if path.exists() && path.is_dir() {
449            match discover_tools_in_directory(&path) {
450                Ok(dir_tools) => tools.extend(dir_tools),
451                Err(e) => warn!("Failed to discover tools in {}: {}", path.display(), e),
452            }
453        }
454    }
455
456    debug!("Discovered {} CLI tools", tools.len());
457    Ok(tools)
458}
459
460/// Build a CLI tool config from an executable path.
461///
462/// This is the single shared predicate for "is this binary a skill": the
463/// path must be an executable file shipping with explicit per-tool metadata
464/// (`<stem>.md`, `<stem>.json`, or a sibling `tool.json`). Bare binaries
465/// without docs return `None` so system executables never pollute the skill
466/// catalog. Both directory scanners delegate here so the rule cannot drift.
467pub(crate) fn cli_tool_config_from_executable(dir: &Path, path: &Path) -> Option<CliToolConfig> {
468    if !path.is_file() {
469        return None;
470    }
471    #[cfg(unix)]
472    {
473        use std::os::unix::fs::PermissionsExt;
474        let Ok(metadata) = path.metadata() else {
475            return None;
476        };
477        if metadata.permissions().mode() & 0o111 == 0 {
478            return None;
479        }
480    }
481    #[cfg(windows)]
482    {
483        match path.extension().and_then(|ext| ext.to_str()) {
484            Some(ext) if matches!(ext.to_lowercase().as_str(), "exe" | "bat" | "cmd") => {}
485            _ => return None,
486        }
487    }
488
489    let stem = path.file_stem().and_then(|stem| stem.to_str())?;
490    let readme_path = dir.join(format!("{stem}.md"));
491    let schema_path = dir.join(format!("{stem}.json"));
492    let tool_json_path = dir.join("tool.json");
493    if !readme_path.exists() && !schema_path.exists() && !tool_json_path.exists() {
494        return None;
495    }
496
497    Some(CliToolConfig {
498        name: stem.to_string(),
499        description: format!("CLI tool: {}", path.display()),
500        executable_path: path.to_path_buf(),
501        readme_path: readme_path.exists().then(|| readme_path.clone()),
502        schema_path: if schema_path.exists() {
503            Some(schema_path)
504        } else if tool_json_path.exists() {
505            Some(tool_json_path)
506        } else {
507            None
508        },
509        timeout_seconds: Some(30),
510        supports_json: false,
511        environment: None,
512        working_dir: Some(dir.to_path_buf()),
513    })
514}
515
516/// Discover tools in a specific directory
517fn discover_tools_in_directory(dir: &Path) -> Result<Vec<CliToolConfig>> {
518    let mut tools = vec![];
519
520    for entry in std::fs::read_dir(dir)? {
521        let entry = entry?;
522        let path = entry.path();
523
524        if let Some(config) = cli_tool_config_from_executable(dir, &path) {
525            tools.push(config);
526        }
527    }
528
529    Ok(tools)
530}
531
532/// Extension trait for PathBuf to expand home directory
533trait PathExt {
534    fn expand_home(&self) -> Result<PathBuf>;
535}
536
537impl PathExt for PathBuf {
538    fn expand_home(&self) -> Result<PathBuf> {
539        if let Some(home) = std::env::var("HOME").ok().filter(|_| self.starts_with("~")) {
540            let stripped = self.trim_prefix("~");
541            return Ok(PathBuf::from(home).join(stripped));
542        }
543        Ok(self.clone())
544    }
545}
546
547#[cfg(test)]
548mod tests {
549    use super::*;
550    use tempfile::TempDir;
551
552    #[test]
553    fn test_cli_tool_config_creation() {
554        let config = CliToolConfig {
555            name: "test-tool".to_string(),
556            description: "Test tool".to_string(),
557            executable_path: PathBuf::from("/bin/echo"),
558            readme_path: None,
559            schema_path: None,
560            timeout_seconds: Some(10),
561            supports_json: false,
562            environment: None,
563            working_dir: None,
564        };
565
566        assert_eq!(config.name, "test-tool");
567        assert_eq!(config.timeout_seconds, Some(10));
568    }
569
570    #[tokio::test]
571    async fn test_simple_tool_execution() {
572        let config = CliToolConfig {
573            name: "echo".to_string(),
574            description: "Echo command".to_string(),
575            executable_path: PathBuf::from("/bin/echo"),
576            readme_path: None,
577            schema_path: None,
578            timeout_seconds: Some(5),
579            supports_json: false,
580            environment: None,
581            working_dir: None,
582        };
583
584        let bridge = CliToolBridge::new(config).unwrap();
585        let result = bridge.execute_internal(Value::String("hello world".to_string())).await.unwrap();
586
587        assert_eq!(result.exit_code, 0);
588        assert!(result.stdout.contains("hello world"));
589    }
590
591    #[cfg(unix)]
592    fn write_executable(dir: &Path, name: &str) -> PathBuf {
593        use std::os::unix::fs::PermissionsExt;
594        let path = dir.join(name);
595        std::fs::write(&path, "#!/bin/sh\necho hi\n").expect("write executable");
596        let mut perms = std::fs::metadata(&path).expect("metadata").permissions();
597        perms.set_mode(0o755);
598        std::fs::set_permissions(&path, perms).expect("chmod");
599        path
600    }
601
602    #[cfg(unix)]
603    #[test]
604    fn bare_executables_without_docs_are_not_skills() {
605        let temp = TempDir::new().expect("tempdir");
606        write_executable(temp.path(), "bare-tool");
607        // Versioned system-style binaries without docs must not collide either.
608        write_executable(temp.path(), "python3.12");
609        write_executable(temp.path(), "python3.15");
610
611        let tools = discover_tools_in_directory(temp.path()).expect("discover tools");
612        assert!(
613            tools.is_empty(),
614            "bare executables without <stem>.md/.json or tool.json must be skipped, got {:?}",
615            tools.iter().map(|t| &t.name).collect::<Vec<_>>()
616        );
617    }
618
619    #[cfg(unix)]
620    #[test]
621    fn documented_executables_are_discovered_as_skills() {
622        let temp = TempDir::new().expect("tempdir");
623        write_executable(temp.path(), "doc-tool");
624        std::fs::write(temp.path().join("doc-tool.md"), "# doc-tool\n").expect("write readme");
625        write_executable(temp.path(), "schema-tool");
626        std::fs::write(temp.path().join("schema-tool.json"), "{}").expect("write schema");
627
628        let tools = discover_tools_in_directory(temp.path()).expect("discover tools");
629        let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();
630        assert!(names.contains(&"doc-tool"), "expected doc-tool, got {names:?}");
631        assert!(names.contains(&"schema-tool"), "expected schema-tool, got {names:?}");
632        assert_eq!(tools.len(), 2, "only documented tools should load, got {names:?}");
633    }
634
635    #[cfg(unix)]
636    #[test]
637    fn non_executable_with_docs_is_skipped() {
638        let temp = TempDir::new().expect("tempdir");
639        let script = temp.path().join("not-executable");
640        std::fs::write(&script, "#!/bin/sh\necho hi\n").expect("write script");
641        #[cfg(unix)]
642        {
643            use std::os::unix::fs::PermissionsExt;
644            let mut perms = std::fs::metadata(&script).expect("metadata").permissions();
645            perms.set_mode(0o644);
646            std::fs::set_permissions(&script, perms).expect("chmod");
647        }
648        std::fs::write(temp.path().join("not-executable.md"), "# docs\n").expect("write readme");
649
650        let tools = discover_tools_in_directory(temp.path()).expect("discover tools");
651        assert!(
652            tools.is_empty(),
653            "non-executable files must be skipped even with docs, got {:?}",
654            tools.iter().map(|t| &t.name).collect::<Vec<_>>()
655        );
656    }
657
658    #[cfg(unix)]
659    #[test]
660    fn sibling_tool_json_counts_as_docs() {
661        let temp = TempDir::new().expect("tempdir");
662        write_executable(temp.path(), "json-tool");
663        std::fs::write(temp.path().join("tool.json"), "{}").expect("write tool.json");
664
665        let tools = discover_tools_in_directory(temp.path()).expect("discover tools");
666        assert_eq!(tools.len(), 1, "sibling tool.json should qualify the executable");
667        assert_eq!(tools[0].name, "json-tool");
668    }
669}