vtcode-core 0.103.1

Core library for VT Code - a Rust-based terminal coding agent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! MCP client management built on top of the Codex MCP building blocks.
//!
//! This module adapts the reference MCP client, server and type
//! definitions from <https://github.com/openai/codex> to integrate them
//! with VT Code's multi-provider configuration model. The original
//! implementation inside this project had grown organically and mixed a
//! large amount of bookkeeping logic with the lower level rmcp client
//! transport. The rewritten version keeps the VT Code specific surface
//! (allow lists, tool indexing, status reporting) but delegates the
//! actual protocol interaction to a lightweight `RmcpClient` adapter
//! that mirrors Codex' `mcp-client` crate. This dramatically reduces
//! the amount of bespoke glue we have to maintain while aligning the
//! behaviour with the upstream MCP implementations.

use crate::config::mcp::McpClientConfig;

pub mod cli;
mod client;
pub mod connection_pool;
pub mod enhanced_config;
pub mod errors;
mod provider;
mod rmcp_client;
pub mod rmcp_transport;
pub mod schema;
pub mod tool_discovery;
pub mod tool_discovery_cache;
pub mod traits;
pub mod types;
pub mod utils;

pub use client::McpClient;

pub use connection_pool::{
    ConnectionPoolStats, McpConnectionPool, McpPoolError, PooledMcpManager, PooledMcpStats,
};
pub use errors::{
    ErrorCode, McpResult, configuration_error, initialization_timeout, provider_not_found,
    provider_unavailable, schema_invalid, tool_invocation_failed, tool_not_found,
};
pub use provider::McpProvider;
pub(crate) use rmcp_client::RmcpClient;
pub use rmcp_transport::{
    HttpTransport, create_http_transport, create_stdio_transport,
    create_stdio_transport_with_stderr,
};
pub use schema::{validate_against_schema, validate_tool_input};
pub use tool_discovery::{DetailLevel, ToolDiscovery, ToolDiscoveryResult};
pub use traits::{McpElicitationHandler, McpToolExecutor};
pub use types::{
    FileParamSchemaEntry, FileUploadResult, McpClientStatus, McpElicitationRequest,
    McpElicitationResponse, McpPromptDetail, McpPromptInfo, McpResourceData, McpResourceInfo,
    McpToolInfo, OPENAI_FILE_PARAMS_META_KEY, OPENAI_FILE_PARAMS_VALUE, ProvidedFilePayload,
};
pub use utils::{
    LOCAL_TIMEZONE_ENV_VAR, TIMEZONE_ARGUMENT, TZ_ENV_VAR, build_headers, detect_local_timezone,
    ensure_timezone_argument, schema_requires_field,
};

use anyhow::{Result, anyhow};
use hashbrown::HashMap;
pub use rmcp::model::ElicitationAction;
use std::ffi::OsString;

/// MCP protocol version constants
pub const LATEST_PROTOCOL_VERSION: &str = "2024-11-05";
pub const SUPPORTED_PROTOCOL_VERSIONS: &[&str] = &[LATEST_PROTOCOL_VERSION];

/// Convert any serializable type to rmcp model type via JSON serialization
pub(crate) fn convert_to_rmcp<T, U>(value: T) -> Result<U>
where
    T: serde::Serialize,
    U: serde::de::DeserializeOwned,
{
    let json = serde_json::to_value(value)?;
    serde_json::from_value(json).map_err(|err| anyhow!(err))
}

fn create_env_for_mcp_server(
    extra_env: Option<HashMap<OsString, OsString>>,
) -> HashMap<OsString, OsString> {
    DEFAULT_ENV_VARS
        .iter()
        .filter_map(|var| std::env::var_os(var).map(|value| (OsString::from(*var), value)))
        .chain(extra_env.unwrap_or_default())
        .collect()
}

/// Validate MCP configuration settings
pub fn validate_mcp_config(config: &McpClientConfig) -> Result<()> {
    // Validate server configuration if enabled
    if config.server.enabled {
        // Validate port range
        if config.server.port == 0 {
            return Err(anyhow::anyhow!(
                "Invalid server port: {}",
                config.server.port
            ));
        }

        // Validate bind address
        if config.server.bind_address.is_empty() {
            return Err(anyhow::anyhow!("Server bind address cannot be empty"));
        }

        // Validate security settings if auth is enabled
        if config.security.auth_enabled && config.security.api_key_env.is_none() {
            return Err(anyhow::anyhow!(
                "API key environment variable must be set when auth is enabled"
            ));
        }
    }

    // Validate timeouts
    if let Some(startup_timeout) = config.startup_timeout_seconds
        && startup_timeout > 300
    {
        // Max 5 minutes
        return Err(anyhow::anyhow!("Startup timeout cannot exceed 300 seconds"));
    }

    if let Some(tool_timeout) = config.tool_timeout_seconds
        && tool_timeout > 3600
    {
        // Max 1 hour
        return Err(anyhow::anyhow!("Tool timeout cannot exceed 3600 seconds"));
    }

    // Validate provider configurations
    for provider in &config.providers {
        if provider.name.is_empty() {
            return Err(anyhow::anyhow!("MCP provider name cannot be empty"));
        }

        // Validate max_concurrent_requests
        if provider.max_concurrent_requests == 0 {
            return Err(anyhow::anyhow!(
                "Max concurrent requests must be greater than 0 for provider '{}'",
                provider.name
            ));
        }
    }

    Ok(())
}

#[cfg(unix)]
const DEFAULT_ENV_VARS: &[&str] = &[
    "HOME",
    "LOGNAME",
    "PATH",
    "SHELL",
    "USER",
    "__CF_USER_TEXT_ENCODING",
    "LANG",
    "LC_ALL",
    "TERM",
    "TMPDIR",
    "TZ",
];

#[cfg(windows)]
const DEFAULT_ENV_VARS: &[&str] = &[
    // Core path resolution
    "PATH",
    "PATHEXT",
    // Shell and system roots
    "COMSPEC",
    "SYSTEMROOT",
    "SYSTEMDRIVE",
    // User context and profiles
    "USERNAME",
    "USERDOMAIN",
    "USERPROFILE",
    "HOMEDRIVE",
    "HOMEPATH",
    // Program locations
    "PROGRAMFILES",
    "PROGRAMFILES(X86)",
    "PROGRAMW6432",
    "PROGRAMDATA",
    // App data and caches
    "LOCALAPPDATA",
    "APPDATA",
    // Temp locations
    "TEMP",
    "TMP",
    // Common shells/pwsh hints
    "POWERSHELL",
    "PWSH",
];

// Helper functions for file-based tool discovery

/// Sanitize a string for use in a filename
fn sanitize_filename(name: &str) -> String {
    name.chars()
        .map(|c| {
            if c.is_alphanumeric() || c == '_' || c == '-' {
                c
            } else {
                '_'
            }
        })
        .collect()
}

/// Format a tool description as Markdown
fn format_tool_markdown(tool: &McpToolInfo) -> String {
    let mut content = String::new();

    content.push_str(&format!("# {}\n\n", tool.name));
    content.push_str(&format!("**Provider**: {}\n\n", tool.provider));
    content.push_str("## Description\n\n");
    content.push_str(&tool.description);
    content.push_str("\n\n");

    content.push_str("## Input Schema\n\n");
    content.push_str("```json\n");
    content.push_str(
        &serde_json::to_string_pretty(&tool.input_schema)
            .unwrap_or_else(|_| tool.input_schema.to_string()),
    );
    content.push_str("\n```\n\n");

    // Extract required fields if present
    if let Some(obj) = tool.input_schema.as_object() {
        if let Some(required) = obj.get("required").and_then(|v| v.as_array())
            && !required.is_empty()
        {
            content.push_str("## Required Parameters\n\n");
            for req in required {
                if let Some(name) = req.as_str() {
                    content.push_str(&format!("- `{}`\n", name));
                }
            }
            content.push('\n');
        }

        // Extract properties descriptions
        if let Some(props) = obj.get("properties").and_then(|v| v.as_object())
            && !props.is_empty()
        {
            content.push_str("## Parameters\n\n");
            for (param_name, param_schema) in props {
                let param_type = param_schema
                    .get("type")
                    .and_then(|t| t.as_str())
                    .unwrap_or("any");
                let param_desc = param_schema
                    .get("description")
                    .and_then(|d| d.as_str())
                    .unwrap_or("");
                content.push_str(&format!("### `{}`\n\n", param_name));
                content.push_str(&format!("- **Type**: {}\n", param_type));
                if !param_desc.is_empty() {
                    content.push_str(&format!("- **Description**: {}\n", param_desc));
                }
                content.push('\n');
            }
        }
    }

    content.push_str("---\n");
    content.push_str("*Generated automatically for dynamic context discovery.*\n");

    content
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::mcp::{McpProviderConfig, McpStdioServerConfig, McpTransportConfig};
    use crate::mcp::rmcp_client::{
        build_elicitation_validator, directory_to_file_uri, validate_elicitation_payload,
    };
    use crate::mcp::utils::{clear_test_env_override, set_test_env_override};
    use hashbrown::HashMap;
    use serde_json::{Map, Value, json};
    use std::ffi::OsString;

    // Re-export rmcp types for tests
    use rmcp::model::{
        ClientCapabilities, Implementation, InitializeRequestParams, RootsCapabilities,
    };

    #[cfg(unix)]
    use serial_test::serial;

    #[cfg(unix)]
    use std::os::unix::ffi::OsStringExt;

    struct EnvGuard {
        key: &'static str,
    }

    impl EnvGuard {
        fn set(key: &'static str, value: &str) -> Self {
            set_test_env_override(key, Some(value));
            Self { key }
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            clear_test_env_override(self.key);
        }
    }

    #[test]
    fn schema_detection_handles_required_entries() {
        let schema = json!({
            "type": "object",
            "required": [TIMEZONE_ARGUMENT],
            "properties": {
                TIMEZONE_ARGUMENT: { "type": "string" }
            }
        });

        assert!(schema_requires_field(&schema, TIMEZONE_ARGUMENT));
        assert!(!schema_requires_field(&schema, "location"));
    }

    #[test]
    fn ensure_timezone_injects_from_override_env() {
        let _guard = EnvGuard::set(LOCAL_TIMEZONE_ENV_VAR, "Etc/UTC");
        let mut arguments = Map::new();

        ensure_timezone_argument(&mut arguments, true).unwrap();

        assert_eq!(
            arguments.get(TIMEZONE_ARGUMENT).and_then(Value::as_str),
            Some("Etc/UTC")
        );
    }

    #[test]
    fn ensure_timezone_does_not_override_existing_value() {
        let mut arguments = Map::new();
        arguments.insert(
            TIMEZONE_ARGUMENT.to_string(),
            Value::String("America/New_York".to_owned()),
        );

        ensure_timezone_argument(&mut arguments, true).unwrap();

        assert_eq!(
            arguments.get(TIMEZONE_ARGUMENT).and_then(Value::as_str),
            Some("America/New_York")
        );
    }

    #[test]
    fn create_env_merges_configured_values() {
        let mut extra_env = HashMap::new();
        extra_env.insert(OsString::from("A"), OsString::from("1"));
        extra_env.insert(OsString::from("B"), OsString::from("2"));

        let env = create_env_for_mcp_server(Some(extra_env));

        assert_eq!(env.get(&OsString::from("A")), Some(&OsString::from("1")));
        assert_eq!(env.get(&OsString::from("B")), Some(&OsString::from("2")));
    }

    #[test]
    #[cfg(unix)]
    #[serial]
    #[allow(unsafe_code)]
    fn create_env_preserves_non_utf8_path() {
        let original_path = std::env::var_os("PATH");
        let non_utf8_path = OsString::from_vec(b"/tmp/alpha:\xFFbeta".to_vec());

        // SAFETY: this test runs serially and restores PATH before returning.
        unsafe {
            std::env::set_var("PATH", &non_utf8_path);
        }

        let env = create_env_for_mcp_server(None);

        // SAFETY: These unsafe calls are used only in test code to restore original
        // environment state after testing. We are modifying process environment variables,
        // which requires unsafe in Rust's std::env API.
        match original_path {
            Some(value) => {
                // SAFETY: this test runs serially and restores the previous PATH value.
                unsafe {
                    std::env::set_var("PATH", value);
                }
            }
            None => {
                // SAFETY: this test runs serially and restores PATH to the original unset state.
                unsafe {
                    std::env::remove_var("PATH");
                }
            }
        }

        assert_eq!(env.get(&OsString::from("PATH")), Some(&non_utf8_path));
    }

    #[tokio::test]
    async fn convert_to_rmcp_round_trip() {
        let mut capabilities = ClientCapabilities::default();
        capabilities.roots = Some(RootsCapabilities {
            list_changed: Some(true),
        });
        let params =
            InitializeRequestParams::new(capabilities, Implementation::new("vtcode", "1.0"))
                .with_protocol_version(rmcp::model::ProtocolVersion::V_2024_11_05);

        let converted: InitializeRequestParams = convert_to_rmcp(params.clone()).unwrap();
        // Verify the conversion succeeded by checking the name
        assert_eq!(converted.client_info.name, "vtcode");
        assert_eq!(converted.client_info.version, "1.0");
    }

    #[test]
    fn validate_elicitation_payload_rejects_invalid_content() {
        let schema = json!({
            "type": "object",
            "properties": {
                "name": { "type": "string" }
            },
            "required": ["name"]
        });
        let validator =
            build_elicitation_validator("test", &schema).expect("schema should compile");

        let result = validate_elicitation_payload(
            "test",
            Some(&validator),
            &ElicitationAction::Accept,
            Some(&json!({ "name": 42 })),
        );

        assert!(result.is_err());
    }

    #[test]
    fn validate_elicitation_payload_accepts_valid_content() {
        let schema = json!({
            "type": "object",
            "properties": {
                "email": { "type": "string", "format": "email" }
            },
            "required": ["email"]
        });
        let validator =
            build_elicitation_validator("test", &schema).expect("schema should compile");

        let result = validate_elicitation_payload(
            "test",
            Some(&validator),
            &ElicitationAction::Accept,
            Some(&json!({ "email": "user@example.com" })),
        );

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn provider_max_concurrency_defaults_to_one() {
        let config = McpProviderConfig {
            name: "test".into(),
            transport: McpTransportConfig::Stdio(McpStdioServerConfig {
                command: "cat".into(),
                args: vec![],
                working_directory: None,
            }),
            env: HashMap::new(),
            enabled: true,
            max_concurrent_requests: 0,
            startup_timeout_ms: None,
        };

        let provider = McpProvider::connect(config, None).await.unwrap();
        assert_eq!(provider.semaphore.available_permits(), 1);
    }

    #[test]
    fn directory_to_file_uri_generates_file_scheme() {
        let temp_dir = std::env::temp_dir();
        let uri = directory_to_file_uri(temp_dir.as_path())
            .expect("should create file uri for temp directory");
        assert!(uri.starts_with("file://"));
    }
}