Split extension transports out of ExtensionManager (#12088)
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -29,15 +29,10 @@ fn truncate_with_ellipsis(s: &str, max_len: usize) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
// Plain String rather than `ExtensionError`: the only variant this function
|
||||
// ever constructs is `ConfigError(String)`, but clippy's `result_large_err`
|
||||
// sizes an error type by its largest variant, and `ExtensionError` carries a
|
||||
// `ClientError`/`ClientInitializeError` far past the 128-byte default
|
||||
// threshold. Callers wrap this back into `ExtensionError::ConfigError`.
|
||||
fn disambiguate_stdio_extension_names(
|
||||
extensions: &mut [(String, ExtensionConfig)],
|
||||
renameable: &HashSet<usize>,
|
||||
) -> Result<(), String> {
|
||||
) -> Result<(), ExtensionError> {
|
||||
let mut counts: HashMap<String, usize> = HashMap::new();
|
||||
// Only entries the caller marked fixed (explicitly named, or not a CLI
|
||||
// stdio extension at all) can make this an error — a fixed name colliding
|
||||
@@ -56,10 +51,10 @@ fn disambiguate_stdio_extension_names(
|
||||
!renameable.contains(index) && fixed_counts.get(&config.key()).copied().unwrap_or(0) > 1
|
||||
});
|
||||
if let Some((_, (_, config))) = duplicate_fixed_names {
|
||||
return Err(format!(
|
||||
return Err(ExtensionError::ConfigError(format!(
|
||||
"extension name '{}' is already in use",
|
||||
config.name()
|
||||
));
|
||||
)));
|
||||
}
|
||||
|
||||
let mut taken: HashSet<String> = counts.keys().cloned().collect();
|
||||
@@ -617,8 +612,7 @@ async fn collect_extension_configs(
|
||||
.into_iter()
|
||||
.map(|(label, config, _)| (label, config)),
|
||||
);
|
||||
disambiguate_stdio_extension_names(&mut all, &renameable)
|
||||
.map_err(ExtensionError::ConfigError)?;
|
||||
disambiguate_stdio_extension_names(&mut all, &renameable)?;
|
||||
|
||||
Ok(all.into_iter().map(|(_, config)| config).collect())
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ use crate::config;
|
||||
use crate::config::extensions::name_to_key;
|
||||
use crate::config::permission::PermissionLevel;
|
||||
use crate::config::Config;
|
||||
use once_cell::sync::Lazy;
|
||||
use rmcp::service::ClientInitializeError;
|
||||
use rmcp::ServiceError as ClientError;
|
||||
use serde::Deserializer;
|
||||
@@ -35,7 +36,6 @@ impl ProcessExit {
|
||||
}
|
||||
}
|
||||
|
||||
/// Errors from Extension operation
|
||||
#[derive(Error, Debug)]
|
||||
pub enum ExtensionError {
|
||||
#[error("failed a client call to an MCP server: {0}")]
|
||||
@@ -49,16 +49,27 @@ pub enum ExtensionError {
|
||||
#[error("IO error: {0}")]
|
||||
IoError(#[from] std::io::Error),
|
||||
#[error("failed to initialize MCP client: {0}")]
|
||||
InitializeError(#[from] ClientInitializeError),
|
||||
InitializeError(#[source] Box<ClientInitializeError>),
|
||||
#[error("{0}")]
|
||||
ProcessExit(#[from] ProcessExit),
|
||||
ProcessExit(#[source] Box<ProcessExit>),
|
||||
}
|
||||
|
||||
impl From<ClientInitializeError> for ExtensionError {
|
||||
fn from(error: ClientInitializeError) -> Self {
|
||||
Self::InitializeError(Box::new(error))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ProcessExit> for ExtensionError {
|
||||
fn from(error: ProcessExit) -> Self {
|
||||
Self::ProcessExit(Box::new(error))
|
||||
}
|
||||
}
|
||||
|
||||
pub type ExtensionResult<T> = Result<T, ExtensionError>;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Default, PartialEq)]
|
||||
pub struct Envs {
|
||||
/// A map of environment variables to set, e.g. API_KEY -> some_secret, HOST -> host
|
||||
#[serde(default)]
|
||||
#[serde(flatten)]
|
||||
map: HashMap<String, String>,
|
||||
@@ -75,7 +86,6 @@ impl<'de> Deserialize<'de> for Envs {
|
||||
}
|
||||
|
||||
impl Envs {
|
||||
/// List of sensitive env vars that should not be overridden
|
||||
const DISALLOWED_KEYS: [&'static str; 31] = [
|
||||
// 🔧 Binary path manipulation
|
||||
"PATH", // Controls executable lookup paths — critical for command hijacking
|
||||
@@ -130,24 +140,10 @@ impl Envs {
|
||||
Self { map: validated }
|
||||
}
|
||||
|
||||
/// Returns a copy of the validated env vars
|
||||
pub fn get_env(&self) -> HashMap<String, String> {
|
||||
self.map.clone()
|
||||
}
|
||||
|
||||
/// Returns an error if any disallowed env var is present
|
||||
pub fn validate(&self) -> Result<(), Box<ExtensionError>> {
|
||||
for key in self.map.keys() {
|
||||
if Self::is_disallowed(key) {
|
||||
return Err(Box::new(ExtensionError::ConfigError(format!(
|
||||
"environment variable {} not allowed to be overwritten",
|
||||
key
|
||||
))));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_disallowed(key: &str) -> bool {
|
||||
Self::DISALLOWED_KEYS
|
||||
.iter()
|
||||
@@ -155,14 +151,11 @@ impl Envs {
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents the different types of MCP extensions that can be added to the manager
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
|
||||
#[serde(tag = "type")]
|
||||
pub enum ExtensionConfig {
|
||||
/// Standard I/O client with command and arguments
|
||||
#[serde(rename = "stdio")]
|
||||
Stdio {
|
||||
/// The name used to identify this extension
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
#[serde(deserialize_with = "deserialize_null_with_default")]
|
||||
@@ -185,7 +178,6 @@ pub enum ExtensionConfig {
|
||||
/// Built-in extension that is part of the bundled goose MCP server
|
||||
#[serde(rename = "builtin")]
|
||||
Builtin {
|
||||
/// The name used to identify this extension
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
#[serde(deserialize_with = "deserialize_null_with_default")]
|
||||
@@ -201,7 +193,6 @@ pub enum ExtensionConfig {
|
||||
/// Platform extensions that have direct access to the agent etc and run in the agent process
|
||||
#[serde(rename = "platform")]
|
||||
Platform {
|
||||
/// The name used to identify this extension
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
#[serde(deserialize_with = "deserialize_null_with_default")]
|
||||
@@ -213,10 +204,8 @@ pub enum ExtensionConfig {
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
available_tools: Vec<String>,
|
||||
},
|
||||
/// Streamable HTTP client with a URI endpoint using MCP Streamable HTTP specification
|
||||
#[serde(rename = "streamable_http")]
|
||||
StreamableHttp {
|
||||
/// The name used to identify this extension
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
#[serde(deserialize_with = "deserialize_null_with_default")]
|
||||
@@ -369,7 +358,6 @@ impl ExtensionConfig {
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// Check if a tool should be available to the LLM
|
||||
pub fn is_tool_available(&self, tool_name: &str) -> bool {
|
||||
let available_tools = match self {
|
||||
Self::StreamableHttp {
|
||||
@@ -386,14 +374,10 @@ impl ExtensionConfig {
|
||||
} => available_tools,
|
||||
};
|
||||
|
||||
// If no tools are specified, all tools are available
|
||||
// If tools are specified, only those tools are available
|
||||
available_tools.is_empty() || available_tools.contains(&tool_name.to_string())
|
||||
}
|
||||
|
||||
pub async fn resolve(self, config: &Config) -> ExtensionResult<Self> {
|
||||
use crate::agents::extension_manager::{merge_environments, substitute_env_vars};
|
||||
|
||||
match self {
|
||||
Self::Stdio {
|
||||
name,
|
||||
@@ -407,7 +391,7 @@ impl ExtensionConfig {
|
||||
bundled,
|
||||
available_tools,
|
||||
} => {
|
||||
let merged = merge_environments(&envs, &env_keys, &name, config).await?;
|
||||
let merged = merge_environments(&envs, env_keys.iter(), config).await?;
|
||||
Ok(Self::Stdio {
|
||||
name,
|
||||
description,
|
||||
@@ -439,13 +423,9 @@ impl ExtensionConfig {
|
||||
// Resolve the OAuth client secret alongside env_keys so that
|
||||
// rotating it changes the resolved config, which is what
|
||||
// add_extension compares to decide whether to restart.
|
||||
let mut secret_keys = env_keys;
|
||||
if let Some(key) = &client_secret_key {
|
||||
if !secret_keys.contains(key) {
|
||||
secret_keys.push(key.clone());
|
||||
}
|
||||
}
|
||||
let merged = merge_environments(&envs, &secret_keys, &name, config).await?;
|
||||
let merged =
|
||||
merge_environments(&envs, env_keys.iter().chain(&client_secret_key), config)
|
||||
.await?;
|
||||
let headers = headers
|
||||
.into_iter()
|
||||
.map(|(k, v)| {
|
||||
@@ -476,6 +456,66 @@ impl ExtensionConfig {
|
||||
}
|
||||
}
|
||||
|
||||
static RE_ENV_BRACES: Lazy<regex::Regex> =
|
||||
Lazy::new(|| regex::Regex::new(r"\$\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}").expect("valid regex"));
|
||||
|
||||
static RE_ENV_SIMPLE: Lazy<regex::Regex> =
|
||||
Lazy::new(|| regex::Regex::new(r"\$([A-Za-z_][A-Za-z0-9_]*)").expect("valid regex"));
|
||||
|
||||
async fn merge_environments(
|
||||
envs: &Envs,
|
||||
env_keys: impl Iterator<Item = &String>,
|
||||
config: &Config,
|
||||
) -> ExtensionResult<HashMap<String, String>> {
|
||||
let mut all_envs = envs.get_env();
|
||||
for key in env_keys {
|
||||
// inline values shadow the secret store
|
||||
if all_envs.contains_key(key) {
|
||||
continue;
|
||||
}
|
||||
// Config::get_secret parses env values as JSON, so PORT=3000 would come
|
||||
// back as a number. An env override is a string by definition; only
|
||||
// the secret store gets the type check.
|
||||
let value = match std::env::var(key.to_uppercase()) {
|
||||
Ok(value) => value,
|
||||
Err(_) => config.get_secret::<String>(key).map_err(|e| {
|
||||
ExtensionError::ConfigError(format!(
|
||||
"Failed to fetch secret '{}' from config: {}",
|
||||
key, e
|
||||
))
|
||||
})?,
|
||||
};
|
||||
all_envs.insert(key.clone(), value);
|
||||
}
|
||||
Ok(Envs::new(all_envs).get_env())
|
||||
}
|
||||
|
||||
fn substitute_env_vars(value: &str, env_map: &HashMap<String, String>) -> String {
|
||||
let mut result = value.to_string();
|
||||
|
||||
for cap in RE_ENV_BRACES.captures_iter(value) {
|
||||
if let Some(var_name) = cap.get(1) {
|
||||
if let Some(env_value) = env_map.get(var_name.as_str()) {
|
||||
result = result.replace(&cap[0], env_value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Scan the original input for $VAR patterns (not the post-substitution result)
|
||||
// to avoid recursive expansion when a substituted value contains $OTHER_VAR.
|
||||
for cap in RE_ENV_SIMPLE.captures_iter(value) {
|
||||
if let Some(var_name) = cap.get(1) {
|
||||
if !value.contains(&format!("${{{}}}", var_name.as_str())) {
|
||||
if let Some(env_value) = env_map.get(var_name.as_str()) {
|
||||
result = result.replace(&cap[0], env_value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ExtensionConfig {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
@@ -499,7 +539,6 @@ impl std::fmt::Display for ExtensionConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Information about the extension used for building prompts
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct ExtensionInfo {
|
||||
pub name: String,
|
||||
@@ -526,7 +565,6 @@ where
|
||||
Ok(opt.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Information about the tool used for building prompts
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct ToolInfo {
|
||||
pub name: String,
|
||||
@@ -561,6 +599,7 @@ impl ToolInfo {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::agents::*;
|
||||
use crate::config;
|
||||
use test_case::test_case;
|
||||
@@ -1070,6 +1109,38 @@ timeout: 300",
|
||||
assert_eq!(config.resolve(&cfg).await.unwrap(), expected);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_resolve_takes_env_overrides_as_raw_strings() {
|
||||
let _guard = env_lock::lock_env([("PORT", Some("3000")), ("HEADLESS", Some("true"))]);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cfg = config::Config::new_with_file_secrets(
|
||||
dir.path().join("config.yaml"),
|
||||
dir.path().join("secrets.yaml"),
|
||||
)
|
||||
.unwrap();
|
||||
let config = ExtensionConfig::Stdio {
|
||||
name: "test".to_string(),
|
||||
description: String::new(),
|
||||
cmd: "cmd".to_string(),
|
||||
args: vec![],
|
||||
envs: Envs::default(),
|
||||
env_keys: vec!["PORT".to_string(), "HEADLESS".to_string()],
|
||||
timeout: None,
|
||||
cwd: None,
|
||||
bundled: None,
|
||||
available_tools: vec![],
|
||||
};
|
||||
|
||||
let resolved = config.resolve(&cfg).await.unwrap();
|
||||
|
||||
let ExtensionConfig::Stdio { envs, .. } = resolved else {
|
||||
panic!("expected stdio config");
|
||||
};
|
||||
let envs = envs.get_env();
|
||||
assert_eq!(envs["PORT"], "3000");
|
||||
assert_eq!(envs["HEADLESS"], "true");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_display_streamable_http_with_socket() {
|
||||
let config = ExtensionConfig::StreamableHttp {
|
||||
@@ -1115,4 +1186,24 @@ timeout: 300",
|
||||
"StreamableHttp(test: http://localhost:8080/mcp)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test_case("Bearer ${ AUTH_TOKEN }", "Bearer secret123"; "braces_with_spaces")]
|
||||
#[test_case("Bearer ${AUTH_TOKEN}", "Bearer secret123"; "braces")]
|
||||
#[test_case("Bearer $AUTH_TOKEN", "Bearer secret123"; "bare")]
|
||||
#[test_case("Key: $API_KEY, Token: ${AUTH_TOKEN}", "Key: key456, Token: secret123"; "multiple")]
|
||||
#[test_case("Bearer ${UNKNOWN_VAR}", "Bearer ${UNKNOWN_VAR}"; "unknown_left_alone")]
|
||||
#[test_case("${TOKEN}", "abc$KEY"; "substituted_value_not_expanded_again_braces")]
|
||||
#[test_case("$TOKEN", "abc$KEY"; "substituted_value_not_expanded_again_bare")]
|
||||
fn test_substitute_env_vars(input: &str, expected: &str) {
|
||||
let env_map = HashMap::from(
|
||||
[
|
||||
("AUTH_TOKEN", "secret123"),
|
||||
("API_KEY", "key456"),
|
||||
("TOKEN", "abc$KEY"),
|
||||
("KEY", "xyz"),
|
||||
]
|
||||
.map(|(k, v)| (k.to_string(), v.to_string())),
|
||||
);
|
||||
assert_eq!(substitute_env_vars(input, &env_map), expected);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,8 +13,8 @@ pub struct OsvChecker {
|
||||
|
||||
impl OsvChecker {
|
||||
/// Constructs a checker. Honors OSV_ENDPOINT env var if present.
|
||||
pub fn new() -> Result<Self, Box<ExtensionError>> {
|
||||
let client = http_client().map_err(Box::new)?;
|
||||
pub fn new() -> Result<Self, ExtensionError> {
|
||||
let client = http_client()?;
|
||||
let endpoint = std::env::var("OSV_ENDPOINT")
|
||||
.ok()
|
||||
.and_then(|s| Url::parse(&s).ok())
|
||||
@@ -23,8 +23,8 @@ impl OsvChecker {
|
||||
}
|
||||
|
||||
/// Constructs with a custom endpoint (handy for tests).
|
||||
pub fn with_endpoint(endpoint: Url) -> Result<Self, Box<ExtensionError>> {
|
||||
let client = http_client().map_err(Box::new)?;
|
||||
pub fn with_endpoint(endpoint: Url) -> Result<Self, ExtensionError> {
|
||||
let client = http_client()?;
|
||||
Ok(Self { client, endpoint })
|
||||
}
|
||||
|
||||
@@ -48,8 +48,7 @@ pub async fn deny_if_malicious_cmd_args(cmd: &str, args: &[String]) -> Result<()
|
||||
};
|
||||
|
||||
if let Some((name, version)) = parse_first_package_arg(ecosystem, args) {
|
||||
OsvChecker::new()
|
||||
.map_err(|e| *e)?
|
||||
OsvChecker::new()?
|
||||
.deny_if_malicious(&name, ecosystem, version.as_deref())
|
||||
.await?;
|
||||
} else {
|
||||
@@ -78,8 +77,7 @@ pub async fn deny_if_malicious(
|
||||
ecosystem: &str,
|
||||
version: Option<&str>,
|
||||
) -> Result<(), ExtensionError> {
|
||||
OsvChecker::new()
|
||||
.map_err(|e| *e)?
|
||||
OsvChecker::new()?
|
||||
.deny_if_malicious(name, ecosystem, version)
|
||||
.await
|
||||
}
|
||||
@@ -479,7 +477,6 @@ async fn deny_if_malicious_impl(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(clippy::result_large_err)]
|
||||
fn http_client() -> Result<reqwest::Client, ExtensionError> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::super::container::Container;
|
||||
use super::super::extension::{ExtensionError, ExtensionResult};
|
||||
use super::super::mcp_client::{ConnectContext, McpClient, McpClientTrait};
|
||||
use super::stdio;
|
||||
use crate::builtin_extension::get_builtin_extension;
|
||||
use crate::config::extensions::name_to_key;
|
||||
|
||||
pub(super) async fn connect(
|
||||
name: &str,
|
||||
container: Option<&Container>,
|
||||
mut ctx: ConnectContext,
|
||||
) -> ExtensionResult<Box<dyn McpClientTrait>> {
|
||||
let key = name_to_key(name);
|
||||
let extension_fn = get_builtin_extension(&key)
|
||||
.ok_or_else(|| ExtensionError::ConfigError(format!("Unknown extension: {}", name)))?;
|
||||
|
||||
if let Some(container) = container {
|
||||
ctx.docker_container = Some(container.id().to_string());
|
||||
tracing::info!(
|
||||
container = %container.id(),
|
||||
builtin = %name,
|
||||
"Starting builtin extension inside Docker container"
|
||||
);
|
||||
let command = stdio::docker_exec(
|
||||
container,
|
||||
HashMap::new(),
|
||||
"goose",
|
||||
&["mcp".to_string(), key],
|
||||
);
|
||||
return Ok(Box::new(stdio::spawn(command, ctx).await?));
|
||||
}
|
||||
|
||||
let (server_read, client_write) = tokio::io::duplex(65536);
|
||||
let (client_read, server_write) = tokio::io::duplex(65536);
|
||||
extension_fn(server_read, server_write);
|
||||
Ok(Box::new(
|
||||
McpClient::connect((client_read, client_write), ctx).await?,
|
||||
))
|
||||
}
|
||||
+62
-1790
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,101 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use rmcp::transport::ConfigureCommandExt;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::process::Command;
|
||||
|
||||
use super::super::container::Container;
|
||||
use super::super::extension::{ExtensionError, ExtensionResult, ProcessExit};
|
||||
use super::super::extension_malware_check;
|
||||
use super::super::mcp_client::{ConnectContext, McpClient};
|
||||
use crate::config::search_path::SearchPaths;
|
||||
use crate::subprocess::spawn_long_lived_mcp_subprocess;
|
||||
|
||||
pub(super) async fn connect(
|
||||
cmd: &str,
|
||||
args: &[String],
|
||||
envs: HashMap<String, String>,
|
||||
container: Option<&Container>,
|
||||
mut ctx: ConnectContext,
|
||||
) -> ExtensionResult<McpClient> {
|
||||
extension_malware_check::deny_if_malicious_cmd_args(cmd, args).await?;
|
||||
|
||||
let command = match container {
|
||||
Some(container) => {
|
||||
ctx.docker_container = Some(container.id().to_string());
|
||||
tracing::info!(
|
||||
container = %container.id(),
|
||||
cmd = %cmd,
|
||||
"Starting stdio extension inside Docker container"
|
||||
);
|
||||
docker_exec(container, envs, cmd, args)
|
||||
}
|
||||
None => Command::new(resolve_command(cmd)).configure(|command| {
|
||||
command.args(args).envs(envs);
|
||||
}),
|
||||
};
|
||||
spawn(command, ctx).await
|
||||
}
|
||||
|
||||
pub(super) fn docker_exec(
|
||||
container: &Container,
|
||||
envs: HashMap<String, String>,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
) -> Command {
|
||||
Command::new("docker").configure(|command| {
|
||||
command.arg("exec").arg("-i");
|
||||
for (key, value) in envs {
|
||||
command.arg("-e").arg(format!("{}={}", key, value));
|
||||
}
|
||||
command.arg(container.id()).arg(program).args(args);
|
||||
})
|
||||
}
|
||||
|
||||
fn resolve_command(cmd: &str) -> std::path::PathBuf {
|
||||
SearchPaths::builder()
|
||||
.with_npm()
|
||||
.resolve(cmd)
|
||||
.unwrap_or_else(|_| {
|
||||
// let the OS raise the error
|
||||
std::path::PathBuf::from(cmd)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn spawn(mut command: Command, ctx: ConnectContext) -> ExtensionResult<McpClient> {
|
||||
if let Ok(path) = SearchPaths::builder().path() {
|
||||
command.env("PATH", path);
|
||||
}
|
||||
|
||||
if ctx.working_dir.is_dir() {
|
||||
tracing::info!(
|
||||
"Setting MCP process working directory: {:?}",
|
||||
ctx.working_dir
|
||||
);
|
||||
command.current_dir(&ctx.working_dir);
|
||||
} else {
|
||||
tracing::warn!(
|
||||
"Working directory doesn't exist or isn't a directory: {:?}",
|
||||
ctx.working_dir
|
||||
);
|
||||
}
|
||||
|
||||
let (transport, mut stderr) = spawn_long_lived_mcp_subprocess(command).await?;
|
||||
let mut stderr = stderr.take().ok_or_else(|| {
|
||||
ExtensionError::SetupError("failed to attach child process stderr".to_owned())
|
||||
})?;
|
||||
|
||||
let stderr_task = tokio::spawn(async move {
|
||||
let mut all_stderr = Vec::new();
|
||||
stderr.read_to_end(&mut all_stderr).await?;
|
||||
Ok::<String, std::io::Error>(String::from_utf8_lossy(&all_stderr).into())
|
||||
});
|
||||
|
||||
match McpClient::connect(transport, ctx).await {
|
||||
Ok(client) => Ok(client),
|
||||
Err(error) => Err(match stderr_task.await? {
|
||||
Ok(stderr_content) => ProcessExit::new(stderr_content, error).into(),
|
||||
Err(e) => e.into(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -635,6 +635,18 @@ impl std::fmt::Debug for GooseMcpClientCapabilities {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ConnectContext {
|
||||
pub timeout: Duration,
|
||||
pub provider: SharedProvider,
|
||||
pub client_name: String,
|
||||
pub capabilities: GooseMcpClientCapabilities,
|
||||
pub working_dir: PathBuf,
|
||||
pub docker_container: Option<String>,
|
||||
pub action_required: Arc<ActionRequiredManager>,
|
||||
pub extension_manager: Weak<ExtensionManager>,
|
||||
}
|
||||
|
||||
/// The MCP client is the interface for MCP operations.
|
||||
pub struct McpClient {
|
||||
client: Mutex<Arc<RunningService<RoleClient, GooseClient>>>,
|
||||
@@ -645,51 +657,24 @@ pub struct McpClient {
|
||||
}
|
||||
|
||||
impl McpClient {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) async fn connect<T, E, A>(
|
||||
transport: T,
|
||||
timeout: std::time::Duration,
|
||||
provider: SharedProvider,
|
||||
client_name: String,
|
||||
capabilities: GooseMcpClientCapabilities,
|
||||
working_dir: PathBuf,
|
||||
action_required: Arc<ActionRequiredManager>,
|
||||
extension_manager: Weak<ExtensionManager>,
|
||||
ctx: ConnectContext,
|
||||
) -> Result<Self, ClientInitializeError>
|
||||
where
|
||||
T: IntoTransport<RoleClient, E, A>,
|
||||
E: std::error::Error + From<std::io::Error> + Send + Sync + 'static,
|
||||
{
|
||||
Self::connect_with_container(
|
||||
transport,
|
||||
let ConnectContext {
|
||||
timeout,
|
||||
provider,
|
||||
None,
|
||||
client_name,
|
||||
capabilities,
|
||||
working_dir,
|
||||
docker_container,
|
||||
action_required,
|
||||
extension_manager,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) async fn connect_with_container<T, E, A>(
|
||||
transport: T,
|
||||
timeout: std::time::Duration,
|
||||
provider: SharedProvider,
|
||||
docker_container: Option<String>,
|
||||
client_name: String,
|
||||
capabilities: GooseMcpClientCapabilities,
|
||||
working_dir: PathBuf,
|
||||
action_required: Arc<ActionRequiredManager>,
|
||||
extension_manager: Weak<ExtensionManager>,
|
||||
) -> Result<Self, ClientInitializeError>
|
||||
where
|
||||
T: IntoTransport<RoleClient, E, A>,
|
||||
E: std::error::Error + From<std::io::Error> + Send + Sync + 'static,
|
||||
{
|
||||
} = ctx;
|
||||
let notification_subscribers =
|
||||
Arc::new(Mutex::new(Vec::<mpsc::Sender<ServerNotification>>::new()));
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
use crate::agents::extension::ExtensionConfig;
|
||||
use crate::agents::extension::PlatformExtensionContext;
|
||||
use crate::agents::extension_manager::is_hidden_extension;
|
||||
use crate::agents::mcp_client::{Error, McpClientTrait};
|
||||
use crate::agents::tool_execution::ToolCallContext;
|
||||
use crate::config::get_extension_by_name;
|
||||
use crate::config::{get_all_extensions, get_extension_by_name};
|
||||
use crate::session::SessionType;
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
@@ -105,20 +107,20 @@ impl ExtensionManagerClient {
|
||||
async fn handle_search_available_extensions(
|
||||
&self,
|
||||
) -> Result<Vec<ContentBlock>, ExtensionManagerToolError> {
|
||||
if let Some(weak_ref) = &self.context.extension_manager {
|
||||
if let Some(extension_manager) = weak_ref.upgrade() {
|
||||
match extension_manager.search_available_extensions().await {
|
||||
Ok(content) => Ok(content),
|
||||
Err(e) => Err(ExtensionManagerToolError::OperationFailed {
|
||||
message: format!("Failed to search available extensions: {}", e.message),
|
||||
}),
|
||||
}
|
||||
} else {
|
||||
Err(ExtensionManagerToolError::ManagerUnavailable)
|
||||
let extension_manager = self
|
||||
.context
|
||||
.extension_manager
|
||||
.as_ref()
|
||||
.and_then(|weak| weak.upgrade())
|
||||
.ok_or(ExtensionManagerToolError::ManagerUnavailable)?;
|
||||
let enabled = extension_manager.list_extensions().await.map_err(|e| {
|
||||
ExtensionManagerToolError::OperationFailed {
|
||||
message: format!("Failed to search available extensions: {}", e),
|
||||
}
|
||||
} else {
|
||||
Err(ExtensionManagerToolError::ManagerUnavailable)
|
||||
}
|
||||
})?;
|
||||
Ok(vec![ContentBlock::text(search_available_extensions(
|
||||
&enabled,
|
||||
))])
|
||||
}
|
||||
|
||||
async fn handle_manage_extensions(
|
||||
@@ -505,6 +507,54 @@ impl McpClientTrait for ExtensionManagerClient {
|
||||
}
|
||||
}
|
||||
|
||||
fn search_available_extensions(enabled: &[String]) -> String {
|
||||
let disabled: Vec<String> = get_all_extensions()
|
||||
.into_iter()
|
||||
.filter(|extension| !extension.enabled && !is_hidden_extension(&extension.config.name()))
|
||||
.map(|extension| {
|
||||
let description = match &extension.config {
|
||||
ExtensionConfig::Builtin {
|
||||
description,
|
||||
display_name,
|
||||
..
|
||||
} if description.is_empty() => display_name
|
||||
.as_deref()
|
||||
.unwrap_or("Built-in extension")
|
||||
.to_string(),
|
||||
ExtensionConfig::Builtin { description, .. }
|
||||
| ExtensionConfig::Platform { description, .. }
|
||||
| ExtensionConfig::StreamableHttp { description, .. }
|
||||
| ExtensionConfig::Stdio { description, .. } => description.clone(),
|
||||
};
|
||||
format!("- {} - {}", extension.config.name(), description)
|
||||
})
|
||||
.collect();
|
||||
let enabled: Vec<String> = enabled
|
||||
.iter()
|
||||
.filter(|name| !is_hidden_extension(name))
|
||||
.map(|name| format!("- {}", name))
|
||||
.collect();
|
||||
|
||||
let mut output_parts = vec![];
|
||||
if disabled.is_empty() {
|
||||
output_parts.push("No extensions available to enable.\n".to_string());
|
||||
} else {
|
||||
output_parts.push(format!(
|
||||
"Extensions available to enable:\n{}\n",
|
||||
disabled.join("\n")
|
||||
));
|
||||
}
|
||||
if enabled.is_empty() {
|
||||
output_parts.push("No extensions that can be disabled.\n".to_string());
|
||||
} else {
|
||||
output_parts.push(format!(
|
||||
"\n\nExtensions available to disable:\n{}\n",
|
||||
enabled.join("\n")
|
||||
));
|
||||
}
|
||||
output_parts.join("\n")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
Reference in New Issue
Block a user