Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(mcp): scrub configured secrets from MCP tool results and errors

oxoxDevf5540f5b129a
diff --git a/crates/openhuman-core/src/tools/impl/network/mcp.rs b/crates/openhuman-core/src/tools/impl/network/mcp.rs
index b043d63fdb..f49875c41c 100644
--- a/crates/openhuman-core/src/tools/impl/network/mcp.rs
+++ b/crates/openhuman-core/src/tools/impl/network/mcp.rs
@@ -1,9 +1,10 @@
use crate::mcp::config_servers::{McpDefinitionAuth, McpRegistrySource, McpServerRegistry};
use crate::security::{SecurityPolicy, ToolOperation};
use async_trait::async_trait;
+use base64::Engine as _;
use serde_json::{json, Value};
use std::sync::Arc;
-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult};
+use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolContent, ToolResult};
pub struct McpListServersTool {
registry: Arc<McpServerRegistry>,
@@ -147,9 +148,14 @@ impl Tool for McpListToolsTool {
async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
let server = required_string_arg(&args, "server")?;
+ let scrubber = SecretScrubber::for_server(&self.registry, &server);
let tools = match self.registry.list_tools(&server).await {
Ok(tools) => tools,
- Err(err) => return Ok(ToolResult::error(format!("mcp_list_tools failed: {err}"))),
+ Err(err) => {
+ return Ok(ToolResult::error(
+ scrubber.scrub(&format!("mcp_list_tools failed: {err}")),
+ ))
+ }
};
let payload = tools
@@ -181,10 +187,10 @@ impl Tool for McpListToolsTool {
}
}
- Ok(ToolResult::success_with_markdown(
+ Ok(scrubber.scrub_result(ToolResult::success_with_markdown(
json!({ "server": server, "tools": payload }),
markdown,
- ))
+ )))
}
}
@@ -258,15 +264,20 @@ impl Tool for McpCallTool {
return Ok(ToolResult::error("`arguments` must be an object"));
}
+ let scrubber = SecretScrubber::for_server(&self.registry, &server);
let mut result = match self.registry.call_tool(&server, &tool, arguments).await {
Ok(result) => result.rendered,
- Err(err) => return Ok(ToolResult::error(format!("mcp_call_tool failed: {err}"))),
+ Err(err) => {
+ return Ok(ToolResult::error(
+ scrubber.scrub(&format!("mcp_call_tool failed: {err}")),
+ ))
+ }
};
if options.prefer_markdown && result.markdown_formatted.is_none() {
result.markdown_formatted = Some(result.output());
}
- Ok(crate::skills::types::tool_result_from_mcp(result))
+ Ok(scrubber.scrub_result(crate::skills::types::tool_result_from_mcp(result)))
}
async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
@@ -275,6 +286,136 @@ impl Tool for McpCallTool {
}
}
+const REDACTED: &str = "[redacted]";
+
+struct SecretScrubber {
+ secrets: Vec<String>,
+}
+
+impl SecretScrubber {
+ fn for_server(registry: &McpServerRegistry, server: &str) -> Self {
+ let Some(definition) = registry.get(server) else {
+ return Self {
+ secrets: Vec::new(),
+ };
+ };
+ Self::new(&definition.auth, &definition.endpoint)
+ }
+
+ fn new(auth: &McpDefinitionAuth, endpoint: &str) -> Self {
+ let mut raw: Vec<String> = Vec::new();
+ match auth {
+ McpDefinitionAuth::BearerToken { token } => raw.push(token.clone()),
+ McpDefinitionAuth::Basic { username, password } => {
+ raw.push(password.clone());
+ raw.push(
+ base64::engine::general_purpose::STANDARD
+ .encode(format!("{username}:{password}")),
+ );
+ }
+ McpDefinitionAuth::Header { value, .. } => raw.push(value.clone()),
+ McpDefinitionAuth::Headers { headers } => {
+ raw.extend(headers.iter().map(|header| header.value.clone()));
+ }
+ McpDefinitionAuth::QueryParam { value, .. } => raw.push(value.clone()),
+ _ => {}
+ }
+ if let Some(query) = endpoint_query(endpoint) {
+ raw.push(query.to_string());
+ if let Ok(url) = url::Url::parse(endpoint) {
+ raw.extend(url.query_pairs().map(|(_, value)| value.into_owned()));
+ }
+ }
+
+ let mut secrets: Vec<String> = Vec::new();
+ for value in raw {
+ let value = value.trim();
+ if value.is_empty() {
+ continue;
+ }
+ let encoded = urlencoding::encode(value).into_owned();
+ if encoded != value {
+ secrets.push(encoded);
+ }
+ secrets.push(value.to_string());
+ }
+ secrets.sort_by(|a, b| b.len().cmp(&a.len()).then_with(|| a.cmp(b)));
+ secrets.dedup();
+ Self { secrets }
+ }
+
+ fn scrub(&self, text: &str) -> String {
+ let mut out = text.to_string();
+ for secret in &self.secrets {
+ if out.contains(secret.as_str()) {
+ out = out.replace(secret.as_str(), REDACTED);
+ }
+ }
+ out
+ }
+
+ fn scrub_value(&self, value: &mut Value) {
+ match value {
+ Value::String(text) => *text = self.scrub(text),
+ Value::Array(items) => items.iter_mut().for_each(|item| self.scrub_value(item)),
+ Value::Object(map) => {
+ let entries = std::mem::take(map);
+ for (key, mut item) in entries {
+ self.scrub_value(&mut item);
+ map.insert(self.scrub(&key), item);
+ }
+ }
+ _ => {}
+ }
+ }
+
+ fn scrub_result(&self, mut result: ToolResult) -> ToolResult {
+ if self.secrets.is_empty() {
+ return result;
+ }
+ let mut redactions = 0usize;
+ for block in &mut result.content {
+ match block {
+ ToolContent::Text { text } => {
+ let scrubbed = self.scrub(text);
+ if scrubbed != *text {
+ redactions += 1;
+ *text = scrubbed;
+ }
+ }
+ ToolContent::Json { data } => {
+ let before = data.clone();
+ self.scrub_value(data);
+ if *data != before {
+ redactions += 1;
+ }
+ }
+ _ => {}
+ }
+ }
+ if let Some(markdown) = result.markdown_formatted.as_mut() {
+ let scrubbed = self.scrub(markdown);
+ if scrubbed != *markdown {
+ redactions += 1;
+ *markdown = scrubbed;
+ }
+ }
+ if redactions > 0 {
+ tracing::debug!(
+ redactions,
+ "[mcp] redacted configured secrets from tool output"
+ );
+ }
+ result
+ }
+}
+
+fn endpoint_query(endpoint: &str) -> Option<&str> {
+ let (_, rest) = endpoint.split_once('?')?;
+ let query = rest.split('#').next().unwrap_or_default();
+ (!query.is_empty()).then_some(query)
+}
+
fn auth_kind(auth: &McpDefinitionAuth) -> &'static str {
match auth {
McpDefinitionAuth::None => "none",