Skip to main content

oi_kit_agent/
extension.rs

1pub mod registry;
2
3use std::collections::HashMap;
4
5use once_cell::sync::Lazy;
6use rmcp::service::ClientInitializeError;
7use rmcp::ServiceError as ClientError;
8use serde::Deserializer;
9use serde::{Deserialize, Serialize};
10use thiserror::Error;
11use tracing::warn;
12
13pub const DEFAULT_EXTENSION: &str = "developer";
14pub const DEFAULT_DISPLAY_NAME: &str = "Developer";
15pub const DEFAULT_EXTENSION_TIMEOUT: u64 = 300;
16
17pub trait ExtensionConfigResolver: Send + Sync {
18    fn get_secret(&self, key: &str) -> anyhow::Result<String>;
19}
20
21pub fn name_to_key(name: &str) -> String {
22    let mut result = String::with_capacity(name.len());
23    for c in name.chars() {
24        result.push(match c {
25            c if c.is_ascii_alphanumeric() || c == '_' || c == '-' => c,
26            c if c.is_whitespace() => continue,
27            _ => '_',
28        });
29    }
30    result.to_lowercase()
31}
32
33#[derive(Error, Debug)]
34#[error("process quit before initialization: stderr = {stderr}")]
35pub struct ProcessExit {
36    stderr: String,
37    #[source]
38    source: Box<ClientInitializeError>,
39}
40
41impl ProcessExit {
42    pub fn new<T>(stderr: T, source: Box<ClientInitializeError>) -> Self
43    where
44        T: Into<String>,
45    {
46        ProcessExit {
47            stderr: stderr.into(),
48            source,
49        }
50    }
51}
52
53#[derive(Error, Debug)]
54pub enum ExtensionError {
55    #[error("failed a client call to an MCP server: {0}")]
56    Client(#[from] ClientError),
57    #[error("invalid config: {0}")]
58    ConfigError(String),
59    #[error("error during extension setup: {0}")]
60    SetupError(String),
61    #[error("join error occurred during task execution: {0}")]
62    TaskJoinError(#[from] tokio::task::JoinError),
63    #[error("IO error: {0}")]
64    IoError(#[from] std::io::Error),
65    #[error("failed to initialize MCP client: {0}")]
66    InitializeError(#[from] Box<ClientInitializeError>),
67    #[error("{0}")]
68    ProcessExit(#[source] Box<ProcessExit>),
69    #[error("{0}")]
70    StartFailed(String),
71}
72
73impl From<ClientInitializeError> for ExtensionError {
74    fn from(error: ClientInitializeError) -> Self {
75        Self::InitializeError(Box::new(error))
76    }
77}
78
79impl From<ProcessExit> for ExtensionError {
80    fn from(error: ProcessExit) -> Self {
81        Self::ProcessExit(Box::new(error))
82    }
83}
84
85pub type ExtensionResult<T> = Result<T, ExtensionError>;
86
87#[derive(Debug, Clone, Serialize, Default, PartialEq)]
88pub struct Envs {
89    #[serde(default)]
90    #[serde(flatten)]
91    map: HashMap<String, String>,
92}
93
94impl<'de> Deserialize<'de> for Envs {
95    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
96    where
97        D: Deserializer<'de>,
98    {
99        let map = HashMap::<String, String>::deserialize(deserializer)?;
100        Ok(Self::new(map))
101    }
102}
103
104impl Envs {
105    const DISALLOWED_KEYS: [&'static str; 31] = [
106        // 🔧 Binary path manipulation
107        "PATH",       // Controls executable lookup paths — critical for command hijacking
108        "PATHEXT",    // Windows: Determines recognized executable extensions (e.g., .exe, .bat)
109        "SystemRoot", // Windows: Can affect system DLL resolution (e.g., `kernel32.dll`)
110        "windir",     // Windows: Alternative to SystemRoot (used in legacy apps)
111        // 🧬 Dynamic linker hijacking (Linux/macOS)
112        "LD_LIBRARY_PATH",  // Alters shared library resolution
113        "LD_PRELOAD",       // Forces preloading of shared libraries — common attack vector
114        "LD_AUDIT",         // Loads a monitoring library that can intercept execution
115        "LD_DEBUG",         // Enables verbose linker logging (information disclosure risk)
116        "LD_BIND_NOW",      // Forces immediate symbol resolution, affecting ASLR
117        "LD_ASSUME_KERNEL", // Tricks linker into thinking it's running on an older kernel
118        // 🍎 macOS dynamic linker variables
119        "DYLD_LIBRARY_PATH",     // Same as LD_LIBRARY_PATH but for macOS
120        "DYLD_INSERT_LIBRARIES", // macOS equivalent of LD_PRELOAD
121        "DYLD_FRAMEWORK_PATH",   // Overrides framework lookup paths
122        // 🐍 Python / Node / Ruby / Java / Golang hijacking
123        "PYTHONPATH",   // Overrides Python module resolution
124        "PYTHONHOME",   // Overrides Python root directory
125        "NODE_OPTIONS", // Injects options/scripts into every Node.js process
126        "RUBYOPT",      // Injects Ruby execution flags
127        "GEM_PATH",     // Alters where RubyGems looks for installed packages
128        "GEM_HOME",     // Changes RubyGems default install location
129        "CLASSPATH",    // Java: Controls where classes are loaded from — critical for RCE attacks
130        "GO111MODULE",  // Go: Forces use of module proxy or disables it
131        "GOROOT", // Go: Changes root installation directory (could lead to execution hijacking)
132        // 🖥️ Windows-specific process & DLL hijacking
133        "APPINIT_DLLS", // Forces Windows to load a DLL into every process
134        "SESSIONNAME",  // Affects Windows session configuration
135        "ComSpec",      // Determines default command interpreter (can replace `cmd.exe`)
136        "TEMP",
137        "TMP",          // Redirects temporary file storage (useful for injection attacks)
138        "LOCALAPPDATA", // Controls application data paths (can be abused for persistence)
139        "USERPROFILE",  // Windows user directory (can affect profile-based execution paths)
140        "HOMEDRIVE",
141        "HOMEPATH", // Changes where the user's home directory is located
142    ];
143
144    /// Constructs a new Envs, skipping disallowed env vars with a warning
145    pub fn new(map: HashMap<String, String>) -> Self {
146        let mut validated = HashMap::new();
147
148        for (key, value) in map {
149            if Self::is_disallowed(&key) {
150                warn!("Skipping disallowed env var: {}", key);
151                continue;
152            }
153            validated.insert(key, value);
154        }
155
156        Self { map: validated }
157    }
158
159    pub fn get_env(&self) -> HashMap<String, String> {
160        self.map.clone()
161    }
162
163    fn is_disallowed(key: &str) -> bool {
164        Self::DISALLOWED_KEYS
165            .iter()
166            .any(|disallowed| disallowed.eq_ignore_ascii_case(key))
167    }
168}
169
170#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
171#[serde(tag = "type")]
172pub enum ExtensionConfig {
173    #[serde(rename = "stdio")]
174    Stdio {
175        name: String,
176        #[serde(default)]
177        #[serde(deserialize_with = "deserialize_null_with_default")]
178        description: String,
179        cmd: String,
180        args: Vec<String>,
181        #[serde(default, alias = "env")]
182        envs: Envs,
183        #[serde(default)]
184        env_keys: Vec<String>,
185        timeout: Option<u64>,
186        #[serde(default)]
187        cwd: Option<String>,
188        #[serde(default)]
189        bundled: Option<bool>,
190        #[serde(default)]
191        #[serde(skip_serializing_if = "Vec::is_empty")]
192        available_tools: Vec<String>,
193    },
194    #[serde(rename = "streamable_http")]
195    StreamableHttp {
196        name: String,
197        #[serde(default)]
198        #[serde(deserialize_with = "deserialize_null_with_default")]
199        description: String,
200        uri: String,
201        #[serde(default)]
202        envs: Envs,
203        #[serde(default)]
204        env_keys: Vec<String>,
205        #[serde(default)]
206        headers: HashMap<String, String>,
207        // NOTE: set timeout to be optional for compatibility.
208        // However, new configurations should include this field.
209        timeout: Option<u64>,
210        /// Optional Unix domain socket path for HTTP-over-UDS transport.
211        /// When set, the HTTP connection is routed through this socket while
212        /// `uri` is used for the Host header and path.
213        /// Use `@name` for Linux abstract sockets.
214        #[serde(default)]
215        socket: Option<String>,
216        /// OAuth client ID pre-registered with the server's authorization
217        /// server. When set, it is used directly for the authorization flow
218        /// instead of Client ID Metadata Documents or Dynamic Client
219        /// Registration — required for authorization servers that support
220        /// neither. Supports `$VAR`/`${VAR}` substitution.
221        #[serde(default)]
222        #[serde(skip_serializing_if = "Option::is_none")]
223        client_id: Option<String>,
224        /// Name of the env/secret key holding the OAuth client secret paired
225        /// with `client_id`. The value is resolved from `envs`/`env_keys` or
226        /// the config secret store — never stored inline. Optional: public
227        /// clients using PKCE have no secret.
228        #[serde(default)]
229        #[serde(skip_serializing_if = "Option::is_none")]
230        client_secret_key: Option<String>,
231        /// OAuth scopes to request with `client_id`. When empty, scopes are
232        /// selected from server metadata, which may be broader than needed.
233        #[serde(default)]
234        #[serde(skip_serializing_if = "Vec::is_empty")]
235        scopes: Vec<String>,
236        #[serde(default)]
237        bundled: Option<bool>,
238        #[serde(default)]
239        #[serde(skip_serializing_if = "Vec::is_empty")]
240        available_tools: Vec<String>,
241    },
242}
243
244impl ExtensionConfig {
245    pub fn streamable_http<S: Into<String>, T: Into<u64>>(
246        name: S,
247        uri: S,
248        description: S,
249        timeout: T,
250    ) -> Self {
251        Self::StreamableHttp {
252            name: name.into(),
253            uri: uri.into(),
254            envs: Envs::default(),
255            env_keys: Vec::new(),
256            headers: HashMap::new(),
257            description: description.into(),
258            timeout: Some(timeout.into()),
259            socket: None,
260            client_id: None,
261            client_secret_key: None,
262            scopes: Vec::new(),
263            bundled: None,
264            available_tools: Vec::new(),
265        }
266    }
267
268    pub fn stdio<S: Into<String>, T: Into<u64>>(
269        name: S,
270        cmd: S,
271        description: S,
272        timeout: T,
273    ) -> Self {
274        Self::Stdio {
275            name: name.into(),
276            cmd: cmd.into(),
277            args: vec![],
278            envs: Envs::default(),
279            env_keys: Vec::new(),
280            description: description.into(),
281            timeout: Some(timeout.into()),
282            cwd: None,
283            bundled: None,
284            available_tools: Vec::new(),
285        }
286    }
287
288    pub fn with_args<I, S>(self, args: I) -> Self
289    where
290        I: IntoIterator<Item = S>,
291        S: Into<String>,
292    {
293        match self {
294            Self::Stdio {
295                name,
296                cmd,
297                envs,
298                env_keys,
299                timeout,
300                cwd,
301                description,
302                bundled,
303                available_tools,
304                ..
305            } => Self::Stdio {
306                name,
307                cmd,
308                envs,
309                env_keys,
310                args: args.into_iter().map(Into::into).collect(),
311                description,
312                timeout,
313                cwd,
314                bundled,
315                available_tools,
316            },
317            other => other,
318        }
319    }
320
321    pub fn key(&self) -> String {
322        name_to_key(&self.name())
323    }
324
325    pub fn name(&self) -> String {
326        match self {
327            Self::StreamableHttp { name, .. } => name,
328            Self::Stdio { name, .. } => name,
329        }
330        .to_string()
331    }
332
333    pub fn is_tool_available(&self, tool_name: &str) -> bool {
334        let available_tools = match self {
335            Self::StreamableHttp {
336                available_tools, ..
337            }
338            | Self::Stdio {
339                available_tools, ..
340            } => available_tools,
341        };
342
343        available_tools.is_empty() || available_tools.contains(&tool_name.to_string())
344    }
345
346    pub async fn resolve(self, config: &impl ExtensionConfigResolver) -> ExtensionResult<Self> {
347        match self {
348            Self::Stdio {
349                name,
350                description,
351                cmd,
352                args,
353                envs,
354                env_keys,
355                timeout,
356                cwd,
357                bundled,
358                available_tools,
359            } => {
360                let merged = merge_environments(&envs, env_keys.iter(), config).await?;
361                Ok(Self::Stdio {
362                    name,
363                    description,
364                    cmd,
365                    args,
366                    envs: Envs::new(merged.clone()),
367                    env_keys: vec![],
368                    timeout,
369                    cwd: cwd.map(|s| substitute_env_vars(&s, &merged)),
370                    bundled,
371                    available_tools,
372                })
373            }
374            Self::StreamableHttp {
375                name,
376                description,
377                uri,
378                envs,
379                env_keys,
380                headers,
381                timeout,
382                socket,
383                client_id,
384                client_secret_key,
385                scopes,
386                bundled,
387                available_tools,
388            } => {
389                // Resolve the OAuth client secret alongside env_keys so that
390                // rotating it changes the resolved config, which is what
391                // add_extension compares to decide whether to restart.
392                let merged =
393                    merge_environments(&envs, env_keys.iter().chain(&client_secret_key), config)
394                        .await?;
395                let headers = headers
396                    .into_iter()
397                    .map(|(k, v)| {
398                        let v = substitute_env_vars(&v, &merged);
399                        (k, v)
400                    })
401                    .collect();
402                let socket = socket.map(|s| substitute_env_vars(&s, &merged));
403                let client_id = client_id.map(|c| substitute_env_vars(&c, &merged));
404                Ok(Self::StreamableHttp {
405                    name,
406                    description,
407                    uri: substitute_env_vars(&uri, &merged),
408                    envs: Envs::new(merged),
409                    env_keys: vec![],
410                    headers,
411                    timeout,
412                    socket,
413                    client_id,
414                    client_secret_key,
415                    scopes,
416                    bundled,
417                    available_tools,
418                })
419            }
420        }
421    }
422}
423
424static RE_ENV: Lazy<regex::Regex> = Lazy::new(|| {
425    regex::Regex::new(r"\$\{\s*([^{}\s]+)\s*\}|\$([A-Za-z_][A-Za-z0-9_]*)").expect("valid regex")
426});
427
428async fn merge_environments(
429    envs: &Envs,
430    env_keys: impl Iterator<Item = &String>,
431    config: &impl ExtensionConfigResolver,
432) -> ExtensionResult<HashMap<String, String>> {
433    let mut all_envs = envs.get_env();
434    for key in env_keys {
435        // inline values shadow the secret store
436        if all_envs.contains_key(key) {
437            continue;
438        }
439        // Config::get_secret parses env values as JSON, so PORT=3000 would come
440        // back as a number. An env override is a string by definition; only
441        // the secret store gets the type check.
442        let value = match std::env::var(key.to_uppercase()) {
443            Ok(value) => value,
444            Err(_) => config.get_secret(key).map_err(|e| {
445                ExtensionError::ConfigError(format!(
446                    "Failed to fetch secret '{}' from config: {}",
447                    key, e
448                ))
449            })?,
450        };
451        all_envs.insert(key.clone(), value);
452    }
453    Ok(Envs::new(all_envs).get_env())
454}
455
456fn substitute_env_vars(value: &str, env_map: &HashMap<String, String>) -> String {
457    RE_ENV
458        .replace_all(value, |cap: &regex::Captures<'_>| {
459            let name = cap.get(1).or_else(|| cap.get(2)).unwrap();
460            env_map
461                .get(name.as_str())
462                .cloned()
463                .unwrap_or_else(|| cap[0].to_owned())
464        })
465        .into_owned()
466}
467
468impl std::fmt::Display for ExtensionConfig {
469    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
470        match self {
471            ExtensionConfig::StreamableHttp {
472                name, uri, socket, ..
473            } => {
474                if let Some(socket) = socket {
475                    write!(f, "StreamableHttp({}: {} via {})", name, uri, socket)
476                } else {
477                    write!(f, "StreamableHttp({}: {})", name, uri)
478                }
479            }
480            ExtensionConfig::Stdio {
481                name, cmd, args, ..
482            } => {
483                write!(f, "Stdio({}: {} {})", name, cmd, args.join(" "))
484            }
485        }
486    }
487}
488
489#[derive(Clone, Debug, Serialize)]
490pub struct ExtensionInfo {
491    pub name: String,
492    pub instructions: String,
493    pub has_resources: bool,
494}
495
496impl ExtensionInfo {
497    pub fn new(name: &str, instructions: &str, has_resources: bool) -> Self {
498        Self {
499            name: name.to_string(),
500            instructions: instructions.to_string(),
501            has_resources,
502        }
503    }
504}
505
506fn deserialize_null_with_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
507where
508    T: Default + Deserialize<'de>,
509    D: Deserializer<'de>,
510{
511    let opt = Option::deserialize(deserializer)?;
512    Ok(opt.unwrap_or_default())
513}
514
515pub fn check_unique_keys(extensions: &[ExtensionConfig]) -> anyhow::Result<()> {
516    let mut keys = std::collections::HashSet::new();
517    match extensions.iter().find(|config| !keys.insert(config.key())) {
518        Some(config) => Err(anyhow::anyhow!(
519            "extension '{}' appears twice in the selection",
520            config.name()
521        )),
522        None => Ok(()),
523    }
524}
525
526#[cfg(test)]
527mod tests {
528    use super::*;
529    use test_case::test_case;
530    #[test]
531    fn application_extension_kinds_are_not_transport_configs() {
532        for kind in ["builtin", "platform"] {
533            assert!(
534                serde_json::from_value::<ExtensionConfig>(serde_json::json!({
535                    "type": kind, "name": "developer"
536                }))
537                .is_err()
538            );
539        }
540    }
541    #[test_case("Bearer ${ AUTH_TOKEN }", "Bearer secret123"; "braces_with_spaces")]
542    #[test_case("Bearer ${AUTH_TOKEN}", "Bearer secret123"; "braces")]
543    #[test_case("${X-API-Key}", "hyphenated-key"; "hyphenated_name")]
544    #[test_case("${X.API.Key}", "dotted-key"; "dotted_name")]
545    #[test_case("${1APIKey}", "digit-prefixed-key"; "digit_prefixed_name")]
546    #[test_case("Bearer $AUTH_TOKEN", "Bearer secret123"; "bare")]
547    #[test_case("Key: $API_KEY, Token: ${AUTH_TOKEN}", "Key: key456, Token: secret123"; "multiple")]
548    #[test_case("Bearer ${UNKNOWN_VAR}", "Bearer ${UNKNOWN_VAR}"; "unknown_left_alone")]
549    #[test_case("${TOKEN}:$KEY:${KEY}", "abc$KEY:xyz:xyz"; "single_pass")]
550    #[test_case("${TOKEN}", "abc$KEY"; "substituted_value_not_expanded_again_braces")]
551    #[test_case("$TOKEN", "abc$KEY"; "substituted_value_not_expanded_again_bare")]
552    fn test_substitute_env_vars(input: &str, expected: &str) {
553        let env_map = HashMap::from(
554            [
555                ("AUTH_TOKEN", "secret123"),
556                ("API_KEY", "key456"),
557                ("X-API-Key", "hyphenated-key"),
558                ("X.API.Key", "dotted-key"),
559                ("1APIKey", "digit-prefixed-key"),
560                ("TOKEN", "abc$KEY"),
561                ("KEY", "xyz"),
562            ]
563            .map(|(k, v)| (k.to_string(), v.to_string())),
564        );
565        assert_eq!(substitute_env_vars(input, &env_map), expected);
566    }
567}