Skip to main content

oi_kit_agent/mcp/
host.rs

1use std::ffi::OsString;
2use std::path::PathBuf;
3use std::sync::Arc;
4
5use rmcp::model::{CallToolResult, JsonObject};
6use rmcp::transport::auth::CredentialStore;
7use rmcp::transport::AuthorizationManager;
8
9use crate::extension::ExtensionConfig as TransportConfig;
10use crate::extension::{
11    name_to_key, ExtensionConfigResolver, ExtensionError, ExtensionResult,
12    DEFAULT_EXTENSION_TIMEOUT,
13};
14use crate::mcp::client::{ConnectContext, McpClientTrait};
15use crate::mcp::container::Container;
16
17/// A config the runtime can select, compare and start.
18pub trait ExtensionSpec: Clone + PartialEq + std::fmt::Debug + Send + Sync + 'static {
19    fn name(&self) -> String;
20
21    fn key(&self) -> String {
22        name_to_key(&self.name())
23    }
24
25    fn is_tool_available(&self, tool: &str) -> bool;
26
27    /// Configs the runtime connects itself. Any other config is connected by
28    /// [`ExtensionHost::connect`].
29    fn transport(&self) -> Option<&TransportConfig>;
30}
31
32impl ExtensionSpec for TransportConfig {
33    fn name(&self) -> String {
34        TransportConfig::name(self)
35    }
36
37    fn is_tool_available(&self, tool: &str) -> bool {
38        TransportConfig::is_tool_available(self, tool)
39    }
40
41    fn transport(&self) -> Option<&TransportConfig> {
42        Some(self)
43    }
44}
45
46pub type TraceContextInjector = fn(&mut JsonObject);
47
48/// Application services the runtime needs. Every method has a default, so a host
49/// that only runs stdio and HTTP extensions can implement it with no methods.
50#[async_trait::async_trait]
51pub trait ExtensionHost<C: ExtensionSpec>: Send + Sync {
52    fn get_secret(&self, key: &str) -> anyhow::Result<String> {
53        anyhow::bail!("secret '{key}' is not available")
54    }
55
56    /// Changes whenever secrets or environment may have changed. On the next
57    /// resolution, runtime-connected extensions are checked against their
58    /// re-resolved config; host-connected extensions get new connections.
59    /// Existing leases keep their connections.
60    fn config_generation(&self) -> u64 {
61        0
62    }
63
64    fn default_timeout(&self) -> u64 {
65        DEFAULT_EXTENSION_TIMEOUT
66    }
67
68    /// Where extensions run when their set has no working directory.
69    fn default_working_dir(&self) -> PathBuf {
70        std::env::current_dir().unwrap_or_default()
71    }
72
73    fn resolve_command(&self, cmd: &str) -> PathBuf {
74        PathBuf::from(cmd)
75    }
76
77    /// `PATH` for stdio extensions; `None` inherits the process environment.
78    fn search_path(&self) -> Option<OsString> {
79        None
80    }
81
82    /// OAuth for streamable HTTP extensions; `None` connects without it.
83    fn auth(&self) -> Option<Arc<dyn ExtensionAuth>> {
84        None
85    }
86
87    fn trace_context(&self) -> Option<TraceContextInjector> {
88        None
89    }
90
91    async fn connect(
92        &self,
93        config: &C,
94        _container: Option<&Container>,
95        _ctx: ConnectContext,
96    ) -> ExtensionResult<Box<dyn McpClientTrait>> {
97        Err(ExtensionError::ConfigError(format!(
98            "no connector for extension {}",
99            config.name()
100        )))
101    }
102
103    /// Remove result metadata that only the host may attach.
104    fn sanitize_result(&self, _result: &mut CallToolResult) {}
105}
106
107#[async_trait::async_trait]
108pub trait ExtensionAuth: Send + Sync {
109    fn credential_store(&self, name: &str) -> Box<dyn CredentialStore>;
110
111    async fn authorize(
112        &self,
113        uri: &str,
114        name: &str,
115        static_client: Option<&StaticOAuthClientConfig>,
116        challenge: Option<String>,
117    ) -> anyhow::Result<AuthorizationManager>;
118}
119
120/// OAuth client credentials registered with the authorization server out of
121/// band, for servers whose authorization server supports neither Dynamic
122/// Client Registration nor Client ID Metadata Documents.
123#[derive(Clone, Debug, PartialEq)]
124pub struct StaticOAuthClientConfig {
125    pub client_id: String,
126    /// Secret paired with the client ID. Optional: public clients using PKCE
127    /// have no secret.
128    pub client_secret: Option<String>,
129    /// Scopes to request. When empty, scopes are selected from server
130    /// metadata, which may be broader than the extension needs.
131    pub scopes: Vec<String>,
132}
133
134pub(super) struct Secrets<'a, C: ExtensionSpec>(pub(super) &'a dyn ExtensionHost<C>);
135
136impl<C: ExtensionSpec> ExtensionConfigResolver for Secrets<'_, C> {
137    fn get_secret(&self, key: &str) -> anyhow::Result<String> {
138        self.0.get_secret(key)
139    }
140}