Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(mcp): sanitize mangled MCP tool names for the provider pattern (#5921)

Eric Hayes20c56e9ecd5a
diff --git a/Cargo.lock b/Cargo.lock
index 5269c97fd3..48a3e41e73 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -9800,6 +9800,7 @@ dependencies = [
"model-error-response",
"oauth2",
"redis",
+ "regex",
"reqwest 0.13.4",
"rmcp",
"schemars 1.2.1",
@@ -11961,6 +11962,7 @@ dependencies = [
"macro_authorization",
"macro_user_id",
"model-error-response",
+ "regex",
"reqwest 0.13.4",
"rmcp",
"schemars 1.2.1",
diff --git a/crates/mcp_client/Cargo.toml b/crates/mcp_client/Cargo.toml
index 37717ad689..2561596b7a 100644
--- a/crates/mcp_client/Cargo.toml
+++ b/crates/mcp_client/Cargo.toml
@@ -38,4 +38,5 @@ utoipa.workspace = true
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
+regex.workspace = true
tokio.workspace = true
diff --git a/crates/mcp_client/src/domain/service/toolset.rs b/crates/mcp_client/src/domain/service/toolset.rs
index 487790d886..a279c25f62 100644
--- a/crates/mcp_client/src/domain/service/toolset.rs
+++ b/crates/mcp_client/src/domain/service/toolset.rs
@@ -12,20 +12,127 @@ use std::collections::BTreeMap;
use std::pin::Pin;
use std::sync::Arc;
+#[cfg(test)]
+mod test;
+
const MANGLED_PREFIX: &str = "mcp__";
const MANGLED_SEPARATOR: &str = "__";
+/// Model providers reject tool names that do not match
+/// `^[a-zA-Z0-9_-]{1,128}$`, and they validate the whole tool array: a single
+/// malformed name fails every request in the conversation, not just calls to
+/// that tool.
+const MAX_MANGLED_LEN: usize = 128;
+/// Substituted when the server segment sanitizes to nothing, so a mangled
+/// name can never contain an empty segment.
+const EMPTY_SERVER_SEGMENT: &str = "server";
+/// Substituted when the tool segment sanitizes to nothing.
+const EMPTY_TOOL_SEGMENT: &str = "tool";
+/// Floor for truncating the server segment, so a very long tool name cannot
+/// squeeze the server segment down to nothing. Must exceed both placeholders.
+const MIN_TRUNCATED_SEGMENT: usize = 8;
+
+/// The characters model providers accept in a tool name.
+fn is_allowed(c: char) -> bool {
+ c.is_ascii_alphanumeric() || c == '_' || c == '-'
+}
+
+/// Replaces every run of disallowed characters with a single `_` and trims
+/// leading and trailing underscores.
+///
+/// `collapse_underscores` additionally collapses runs of underscores into one.
+/// The server segment needs that: [`MangledName::parse`] splits on the first
+/// `__`, so a server segment containing `__` would make the split report the
+/// wrong server name.
+fn sanitize_segment(raw: &str, collapse_underscores: bool) -> String {
+ let mut out = String::with_capacity(raw.len());
+ let mut in_disallowed_run = false;
+ for c in raw.chars() {
+ let next = if is_allowed(c) {
+ in_disallowed_run = false;
+ c
+ } else if in_disallowed_run {
+ continue;
+ } else {
+ in_disallowed_run = true;
+ '_'
+ };
+ if collapse_underscores && next == '_' && out.ends_with('_') {
+ continue;
+ }
+ out.push(next);
+ }
+ out.trim_matches('_').to_owned()
+}
+
+/// Shortens an already sanitized (so ASCII) segment to at most `max` bytes,
+/// dropping any underscore left dangling at the cut and falling back to
+/// `placeholder` if nothing survives.
+fn fit_segment(segment: &mut String, max: usize, placeholder: &str) {
+ if segment.len() <= max {
+ return;
+ }
+ segment.truncate(max);
+ while segment.ends_with('_') {
+ segment.pop();
+ }
+ if segment.is_empty() {
+ segment.push_str(placeholder);
+ }
+}
+
+/// A mangled tool name plus whether sanitizing had to change it.
+struct Mangled {
+ /// The sanitized name, always matching `^[a-zA-Z0-9_-]{1,128}$`.
+ name: MangledName,
+ /// Set when the sanitized name differs from the raw `server__tool` join,
+ /// i.e. the raw names would have been rejected by the provider.
+ sanitized: bool,
+}
/// A mangled tool name in the format `mcp__<server>__<tool>`.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct MangledName(String);
-impl MangledName {
+impl Mangled {
+ /// Builds `mcp__<server>__<tool>`, sanitizing both segments so the result
+ /// always matches `^[a-zA-Z0-9_-]{1,128}$`.
+ ///
+ /// Server names are human-readable display names (`Google Sheets`), so
+ /// they routinely contain characters providers reject. Sanitizing here
+ /// rather than where the name is written also covers names already
+ /// persisted, and keeps every future source of the name covered.
+ ///
+ /// Truncation is safe for dispatch: the unmangled tool name is kept on
+ /// [`RegisteredTool`] and is what gets sent to the peer.
fn new(server_name: &str, tool_name: &str) -> Self {
- Self(format!(
- "{MANGLED_PREFIX}{server_name}{MANGLED_SEPARATOR}{tool_name}"
- ))
+ let mut server = sanitize_segment(server_name, true);
+ let mut tool = sanitize_segment(tool_name, false);
+
+ if server.is_empty() {
+ server = EMPTY_SERVER_SEGMENT.to_owned();
+ }
+ if tool.is_empty() {
+ tool = EMPTY_TOOL_SEGMENT.to_owned();
+ }
+
+ let budget = MAX_MANGLED_LEN - MANGLED_PREFIX.len() - MANGLED_SEPARATOR.len();
+ if server.len() + tool.len() > budget {
+ let server_max = budget.saturating_sub(tool.len()).max(MIN_TRUNCATED_SEGMENT);
+ fit_segment(&mut server, server_max, EMPTY_SERVER_SEGMENT);
+ }
+ if server.len() + tool.len() > budget {
+ fit_segment(&mut tool, budget - server.len(), EMPTY_TOOL_SEGMENT);
+ }
+
+ let sanitized = server != server_name || tool != tool_name;
+ Self {
+ name: MangledName(format!("{MANGLED_PREFIX}{server}{MANGLED_SEPARATOR}{tool}")),
+ sanitized,
+ }
}
+}
+impl MangledName {
fn parse(s: &str) -> Option<(&str, &str)> {
s.strip_prefix(MANGLED_PREFIX)?
.split_once(MANGLED_SEPARATOR)
@@ -102,7 +209,12 @@ impl McpToolSet {
}
};
- Some((record.server_name.clone(), client, server_tools))
+ Some((
+ record.server_name.clone(),
+ record.url.clone(),
+ client,
+ server_tools,
+ ))
}
});
@@ -110,12 +222,33 @@ impl McpToolSet {
let mut tools = BTreeMap::new();
let mut connections = Vec::new();
- for (server_name, client, server_tools) in results.into_iter().flatten() {
+ for (server_name, url, client, server_tools) in results.into_iter().flatten() {
for tool in server_tools {
- let mangled = MangledName::new(&server_name, &tool.name);
+ let Mangled {
+ name: mangled,
+ sanitized,
+ } = Mangled::new(&server_name, &tool.name);
+
+ if sanitized {
+ tracing::warn!(
+ user_id = ?user_id,
+ server = %server_name,
+ url = %url,
+ tool = %tool.name,
+ %mangled,
+ "sanitized tool name to satisfy the provider tool-name pattern"
+ );
+ }
if tools.contains_key(&mangled) {
- tracing::warn!(%mangled, "skipping duplicate tool");
+ tracing::warn!(
+ user_id = ?user_id,
+ server = %server_name,
+ url = %url,
+ tool = %tool.name,
+ %mangled,
+ "skipping duplicate tool"
+ );
continue;
}
diff --git a/crates/mcp_client/src/domain/service/toolset/test.rs b/crates/mcp_client/src/domain/service/toolset/test.rs
new file mode 100644
index 0000000000..4cc6346c54
--- /dev/null
+++ b/crates/mcp_client/src/domain/service/toolset/test.rs
@@ -0,0 +1,183 @@
+use super::*;
+use regex::Regex;
+
+/// The pattern model providers enforce on every tool name they are sent. One
+/// name that fails it rejects the whole request, so every mangled name we
+/// produce is checked against it.
+const PROVIDER_TOOL_NAME_PATTERN: &str = r"^[a-zA-Z0-9_-]{1,128}$";
+
+fn assert_provider_valid(name: &MangledName) {
+ let pattern = Regex::new(PROVIDER_TOOL_NAME_PATTERN).expect("pattern compiles");
+ assert!(
+ pattern.is_match(name.as_str()),
+ "`{name}` does not match {PROVIDER_TOOL_NAME_PATTERN}"
+ );
+}
+
+/// Mangle, assert the result is something a provider will accept, and return
+/// the name plus whether sanitizing changed it.
+fn mangle(server_name: &str, tool_name: &str) -> (MangledName, bool) {
+ let Mangled { name, sanitized } = Mangled::new(server_name, tool_name);
+ assert_provider_valid(&name);
+ (name, sanitized)
+}
+
+#[test]
+fn clean_names_are_left_byte_identical() {
+ for (server, tool) in [
+ ("Linear", "create_issue"),
+ ("Notion", "search"),
+ ("Slack", "post_message"),
+ ("github-mcp", "list-pull-requests"),
+ ] {
+ let (name, sanitized) = mangle(server, tool);
+ assert_eq!(name.as_str(), format!("mcp__{server}__{tool}"));
+ assert!(!sanitized, "`{server}`/`{tool}` should not need sanitizing");
+ assert_eq!(MangledName::parse(name.as_str()), Some((server, tool)));
+ }
+}
+
+#[test]
+fn spaces_in_the_server_name_become_underscores() {
+ let (name, sanitized) = mangle("Google Sheets", "list_worksheets");
+
+ assert_eq!(name.as_str(), "mcp__Google_Sheets__list_worksheets");
+ assert!(sanitized);
+ assert_eq!(
+ MangledName::parse(name.as_str()),
+ Some(("Google_Sheets", "list_worksheets"))
+ );
+}
+
+#[test]
+fn punctuation_and_non_ascii_are_replaced() {
+ for (server, tool, expected_server, expected_tool) in [
+ ("Notion.so", "search", "Notion_so", "search"),
+ ("Zoom & Teams", "join(call)", "Zoom_Teams", "join_call"),
+ (
+ "Google Drive/Docs",
+ "list.files",
+ "Google_Drive_Docs",
+ "list_files",
+ ),
+ ("Café Münster", "naïve_tool", "Caf_M_nster", "na_ve_tool"),
+ ("Bücher 🇩🇪", "lesen!", "B_cher", "lesen"),
+ ] {
+ let (name, sanitized) = mangle(server, tool);
+
+ assert!(sanitized, "`{server}`/`{tool}` should have been sanitized");
+ assert_eq!(
+ MangledName::parse(name.as_str()),
+ Some((expected_server, expected_tool)),
+ "unexpected mangling of `{server}`/`{tool}`: {name}"
+ );
+ }
+}
+
+#[test]
+fn the_server_segment_never_contains_a_double_underscore() {
+ // Each of these would produce `__` inside the server segment under a naive
+ // one-for-one character replacement, which would make `parse` split in the
+ // wrong place and report the wrong server.
+ for (server, expected_server) in [
+ ("A B", "A_B"),
+ ("A. B", "A_B"),
+ ("A_ B", "A_B"),
+ ("A__B", "A_B"),
+ ("A.-B", "A_-B"),
+ ("(A) (B)", "A_B"),
+ ] {
+ let (name, _) = mangle(server, "do_thing");
+
+ let (parsed_server, parsed_tool) =
+ MangledName::parse(name.as_str()).expect("mangled name parses");
+ assert_eq!(parsed_server, expected_server, "for server `{server}`");
+ assert_eq!(parsed_tool, "do_thing", "for server `{server}`");
+ assert!(!parsed_server.contains("__"));
+ }
+}
+
+#[test]
+fn the_tool_segment_keeps_its_own_double_underscores() {
+ // Only the server segment has to avoid `__`; `parse` splits on the first
+ // one, so the tool segment can keep the name the server reported.
+ let (name, sanitized) = mangle("Linear", "list__issues");
+
+ assert!(!sanitized);
+ assert_eq!(
+ MangledName::parse(name.as_str()),
+ Some(("Linear", "list__issues"))
+ );
+}
+
+#[test]
+fn a_long_server_name_is_truncated() {
+ let server = "Very Long Connector Name ".repeat(20);
+ let (name, sanitized) = mangle(&server, "list_worksheets");
+
+ assert!(sanitized);
+ assert!(name.as_str().len() <= 128);
+ let (parsed_server, parsed_tool) =
+ MangledName::parse(name.as_str()).expect("mangled name parses");
+ assert!(parsed_server.starts_with("Very_Long_Connector_Name"));
+ assert!(!parsed_server.ends_with('_'));
+ assert_eq!(parsed_tool, "list_worksheets");
+}
+
+#[test]
+fn a_long_tool_name_truncates_both_segments() {
+ let tool = "a".repeat(200);
+ let (name, sanitized) = mangle("Some Connector", &tool);
+
+ assert!(sanitized);
+ assert_eq!(name.as_str().len(), 128);
+ let (parsed_server, parsed_tool) =
+ MangledName::parse(name.as_str()).expect("mangled name parses");
+ assert_eq!(parsed_server, "Some_Con");
+ assert_eq!(parsed_tool, "a".repeat(113));
+}
+
+#[test]
+fn truncation_never_leaves_a_dangling_underscore() {
+ // `abcdefg_hij` cut to the 8-byte server floor lands exactly on `_`.
+ let (name, _) = mangle("abcdefg hij", &"b".repeat(200));
+
+ assert_eq!(name.as_str().len(), 5 + 7 + 2 + 114);
+ assert_eq!(
+ MangledName::parse(name.as_str()),
+ Some(("abcdefg", "b".repeat(114).as_str()))
+ );
+}
+
+#[test]
+fn a_server_name_that_sanitizes_to_nothing_gets_a_placeholder() {
+ for server in ["", "!!!", " ", "日本語", "__"] {
+ let (name, sanitized) = mangle(server, "do_thing");
+
+ assert!(sanitized, "`{server}` should have been sanitized");
+ assert_eq!(name.as_str(), "mcp__server__do_thing");
+ assert_eq!(
+ MangledName::parse(name.as_str()),
+ Some(("server", "do_thing"))
+ );
+ }
+}
+
+#[test]
+fn a_tool_name_that_sanitizes_to_nothing_gets_a_placeholder() {
+ let (name, sanitized) = mangle("Linear", "###");
+
+ assert!(sanitized);
+ assert_eq!(name.as_str(), "mcp__Linear__tool");
+ assert_eq!(MangledName::parse(name.as_str()), Some(("Linear", "tool")));
+}
+
+#[test]
+fn sanitizing_can_collide_which_the_duplicate_check_skips() {
+ // Two distinct server names can sanitize to the same segment; registration
+ // relies on the equality of the mangled key to skip the second one.
+ let (first, _) = mangle("Google Sheets", "list_worksheets");
+ let (second, _) = mangle("Google/Sheets", "list_worksheets");
+
+ assert_eq!(first, second);
+}
diff --git a/crates/pipedream_mcp/Cargo.toml b/crates/pipedream_mcp/Cargo.toml
index b02921c696..529c7f2955 100644
--- a/crates/pipedream_mcp/Cargo.toml
+++ b/crates/pipedream_mcp/Cargo.toml
@@ -26,4 +26,5 @@ utoipa.workspace = true
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
+regex.workspace = true
tokio.workspace = true
diff --git a/crates/pipedream_mcp/src/domain/service/toolset.rs b/crates/pipedream_mcp/src/domain/service/toolset.rs
index 0e4533ff8a..a7c9031241 100644
--- a/crates/pipedream_mcp/src/domain/service/toolset.rs
+++ b/crates/pipedream_mcp/src/domain/service/toolset.rs
@@ -13,20 +13,127 @@ use std::collections::BTreeMap;
use std::pin::Pin;
use std::sync::Arc;
+#[cfg(test)]
+mod test;
+
const MANGLED_PREFIX: &str = "mcp__";
const MANGLED_SEPARATOR: &str = "__";
+/// Model providers reject tool names that do not match
+/// `^[a-zA-Z0-9_-]{1,128}$`, and they validate the whole tool array: a single
+/// malformed name fails every request in the conversation, not just calls to
+/// that tool.
+const MAX_MANGLED_LEN: usize = 128;
+/// Substituted when the server segment sanitizes to nothing, so a mangled
+/// name can never contain an empty segment.
+const EMPTY_SERVER_SEGMENT: &str = "server";
+/// Substituted when the tool segment sanitizes to nothing.
+const EMPTY_TOOL_SEGMENT: &str = "tool";
+/// Floor for truncating the server segment, so a very long tool name cannot
+/// squeeze the server segment down to nothing. Must exceed both placeholders.
+const MIN_TRUNCATED_SEGMENT: usize = 8;
+
+/// The characters model providers accept in a tool name.
+fn is_allowed(c: char) -> bool {
+ c.is_ascii_alphanumeric() || c == '_' || c == '-'
+}
+
+/// Replaces every run of disallowed characters with a single `_` and trims
+/// leading and trailing underscores.
+///
+/// `collapse_underscores` additionally collapses runs of underscores into one.
+/// The server segment needs that: [`MangledName::parse`] splits on the first
+/// `__`, so a server segment containing `__` would make the split report the
+/// wrong server name.
+fn sanitize_segment(raw: &str, collapse_underscores: bool) -> String {
+ let mut out = String::with_capacity(raw.len());
+ let mut in_disallowed_run = false;
+ for c in raw.chars() {
+ let next = if is_allowed(c) {
+ in_disallowed_run = false;
+ c
+ } else if in_disallowed_run {
+ continue;
+ } else {
+ in_disallowed_run = true;
+ '_'
+ };
+ if collapse_underscores && next == '_' && out.ends_with('_') {
+ continue;
+ }
+ out.push(next);
+ }
+ out.trim_matches('_').to_owned()
+}
+
+/// Shortens an already sanitized (so ASCII) segment to at most `max` bytes,
+/// dropping any underscore left dangling at the cut and falling back to
+/// `placeholder` if nothing survives.
+fn fit_segment(segment: &mut String, max: usize, placeholder: &str) {
+ if segment.len() <= max {
+ return;
+ }
+ segment.truncate(max);
+ while segment.ends_with('_') {
+ segment.pop();
+ }
+ if segment.is_empty() {
+ segment.push_str(placeholder);
+ }
+}
+
+/// A mangled tool name plus whether sanitizing had to change it.
+struct Mangled {
+ /// The sanitized name, always matching `^[a-zA-Z0-9_-]{1,128}$`.
+ name: MangledName,
+ /// Set when the sanitized name differs from the raw `server__tool` join,
+ /// i.e. the raw names would have been rejected by the provider.
+ sanitized: bool,
+}
/// A mangled tool name in the format `mcp__<server>__<tool>`.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct MangledName(String);
-impl MangledName {
+impl Mangled {
+ /// Builds `mcp__<server>__<tool>`, sanitizing both segments so the result
+ /// always matches `^[a-zA-Z0-9_-]{1,128}$`.
+ ///
+ /// Server names are human-readable display names (`Google Sheets`), so
+ /// they routinely contain characters providers reject. Sanitizing here
+ /// rather than where the name is written also covers names already
+ /// persisted, and keeps every future source of the name covered.
+ ///
+ /// Truncation is safe for dispatch: the unmangled tool name is kept on
+ /// [`RegisteredTool`] and is what gets sent to the peer.
fn new(server_name: &str, tool_name: &str) -> Self {
- Self(format!(
- "{MANGLED_PREFIX}{server_name}{MANGLED_SEPARATOR}{tool_name}"
- ))
+ let mut server = sanitize_segment(server_name, true);
+ let mut tool = sanitize_segment(tool_name, false);
+
+ if server.is_empty() {
+ server = EMPTY_SERVER_SEGMENT.to_owned();
+ }
+ if tool.is_empty() {
+ tool = EMPTY_TOOL_SEGMENT.to_owned();
+ }
+
+ let budget = MAX_MANGLED_LEN - MANGLED_PREFIX.len() - MANGLED_SEPARATOR.len();
+ if server.len() + tool.len() > budget {
+ let server_max = budget.saturating_sub(tool.len()).max(MIN_TRUNCATED_SEGMENT);
+ fit_segment(&mut server, server_max, EMPTY_SERVER_SEGMENT);
+ }
+ if server.len() + tool.len() > budget {
+ fit_segment(&mut tool, budget - server.len(), EMPTY_TOOL_SEGMENT);
+ }
+
+ let sanitized = server != server_name || tool != tool_name;
+ Self {
+ name: MangledName(format!("{MANGLED_PREFIX}{server}{MANGLED_SEPARATOR}{tool}")),
+ sanitized,
+ }
}
+}
+impl MangledName {
fn parse(s: &str) -> Option<(&str, &str)> {
s.strip_prefix(MANGLED_PREFIX)?
.split_once(MANGLED_SEPARATOR)
@@ -107,7 +214,12 @@ impl PipedreamToolSet {
}
};
- Some((record.server_name.clone(), client, server_tools))
+ Some((
+ record.server_name.clone(),
+ record.app_slug.clone(),
+ client,
+ server_tools,
+ ))
}
});
@@ -115,12 +227,33 @@ impl PipedreamToolSet {
let mut tools = BTreeMap::new();
let mut connections = Vec::new();
- for (server_name, client, server_tools) in results.into_iter().flatten() {
+ for (server_name, app_slug, client, server_tools) in results.into_iter().flatten() {
for tool in server_tools {
- let mangled = MangledName::new(&server_name, &tool.name);
+ let Mangled {
+ name: mangled,
+ sanitized,
+ } = Mangled::new(&server_name, &tool.name);
+
+ if sanitized {
+ tracing::warn!(
+ user_id = ?user_id,
+ server = %server_name,
+ app = %app_slug,
+ tool = %tool.name,
+ %mangled,
+ "sanitized tool name to satisfy the provider tool-name pattern"
+ );
+ }
if tools.contains_key(&mangled) {
- tracing::warn!(%mangled, "skipping duplicate tool");
+ tracing::warn!(
+ user_id = ?user_id,
+ server = %server_name,
+ app = %app_slug,
+ tool = %tool.name,
+ %mangled,
+ "skipping duplicate tool"
+ );
continue;
}
diff --git a/crates/pipedream_mcp/src/domain/service/toolset/test.rs b/crates/pipedream_mcp/src/domain/service/toolset/test.rs
new file mode 100644
index 0000000000..4cc6346c54
--- /dev/null
+++ b/crates/pipedream_mcp/src/domain/service/toolset/test.rs
@@ -0,0 +1,183 @@
+use super::*;
+use regex::Regex;
+
+/// The pattern model providers enforce on every tool name they are sent. One
+/// name that fails it rejects the whole request, so every mangled name we
+/// produce is checked against it.
+const PROVIDER_TOOL_NAME_PATTERN: &str = r"^[a-zA-Z0-9_-]{1,128}$";
+
+fn assert_provider_valid(name: &MangledName) {
+ let pattern = Regex::new(PROVIDER_TOOL_NAME_PATTERN).expect("pattern compiles");
+ assert!(
+ pattern.is_match(name.as_str()),
+ "`{name}` does not match {PROVIDER_TOOL_NAME_PATTERN}"
+ );
+}
+
+/// Mangle, assert the result is something a provider will accept, and return
+/// the name plus whether sanitizing changed it.
+fn mangle(server_name: &str, tool_name: &str) -> (MangledName, bool) {
+ let Mangled { name, sanitized } = Mangled::new(server_name, tool_name);
+ assert_provider_valid(&name);
+ (name, sanitized)
+}
+
+#[test]
+fn clean_names_are_left_byte_identical() {
+ for (server, tool) in [
+ ("Linear", "create_issue"),
+ ("Notion", "search"),
+ ("Slack", "post_message"),
+ ("github-mcp", "list-pull-requests"),
+ ] {
+ let (name, sanitized) = mangle(server, tool);
+ assert_eq!(name.as_str(), format!("mcp__{server}__{tool}"));
+ assert!(!sanitized, "`{server}`/`{tool}` should not need sanitizing");
+ assert_eq!(MangledName::parse(name.as_str()), Some((server, tool)));
+ }
+}
+
+#[test]
+fn spaces_in_the_server_name_become_underscores() {
+ let (name, sanitized) = mangle("Google Sheets", "list_worksheets");
+
+ assert_eq!(name.as_str(), "mcp__Google_Sheets__list_worksheets");
+ assert!(sanitized);
+ assert_eq!(
+ MangledName::parse(name.as_str()),
+ Some(("Google_Sheets", "list_worksheets"))
+ );
+}
+
+#[test]
+fn punctuation_and_non_ascii_are_replaced() {
+ for (server, tool, expected_server, expected_tool) in [
+ ("Notion.so", "search", "Notion_so", "search"),
+ ("Zoom & Teams", "join(call)", "Zoom_Teams", "join_call"),
+ (
+ "Google Drive/Docs",
+ "list.files",
+ "Google_Drive_Docs",
+ "list_files",
+ ),
+ ("Café Münster", "naïve_tool", "Caf_M_nster", "na_ve_tool"),
+ ("Bücher 🇩🇪", "lesen!", "B_cher", "lesen"),
+ ] {
+ let (name, sanitized) = mangle(server, tool);
+
+ assert!(sanitized, "`{server}`/`{tool}` should have been sanitized");
+ assert_eq!(
+ MangledName::parse(name.as_str()),
+ Some((expected_server, expected_tool)),
+ "unexpected mangling of `{server}`/`{tool}`: {name}"
+ );
+ }
+}
+
+#[test]
+fn the_server_segment_never_contains_a_double_underscore() {
+ // Each of these would produce `__` inside the server segment under a naive
+ // one-for-one character replacement, which would make `parse` split in the
+ // wrong place and report the wrong server.
+ for (server, expected_server) in [
+ ("A B", "A_B"),
+ ("A. B", "A_B"),
+ ("A_ B", "A_B"),
+ ("A__B", "A_B"),
+ ("A.-B", "A_-B"),
+ ("(A) (B)", "A_B"),
+ ] {
+ let (name, _) = mangle(server, "do_thing");
+
+ let (parsed_server, parsed_tool) =
+ MangledName::parse(name.as_str()).expect("mangled name parses");
+ assert_eq!(parsed_server, expected_server, "for server `{server}`");
+ assert_eq!(parsed_tool, "do_thing", "for server `{server}`");
+ assert!(!parsed_server.contains("__"));
+ }
+}
+
+#[test]
+fn the_tool_segment_keeps_its_own_double_underscores() {
+ // Only the server segment has to avoid `__`; `parse` splits on the first
+ // one, so the tool segment can keep the name the server reported.
+ let (name, sanitized) = mangle("Linear", "list__issues");
+
+ assert!(!sanitized);
+ assert_eq!(
+ MangledName::parse(name.as_str()),
+ Some(("Linear", "list__issues"))
+ );
+}
+
+#[test]
+fn a_long_server_name_is_truncated() {
+ let server = "Very Long Connector Name ".repeat(20);
+ let (name, sanitized) = mangle(&server, "list_worksheets");
+
+ assert!(sanitized);
+ assert!(name.as_str().len() <= 128);
+ let (parsed_server, parsed_tool) =
+ MangledName::parse(name.as_str()).expect("mangled name parses");
+ assert!(parsed_server.starts_with("Very_Long_Connector_Name"));
+ assert!(!parsed_server.ends_with('_'));
+ assert_eq!(parsed_tool, "list_worksheets");
+}
+
+#[test]
+fn a_long_tool_name_truncates_both_segments() {
+ let tool = "a".repeat(200);
+ let (name, sanitized) = mangle("Some Connector", &tool);
+
+ assert!(sanitized);
+ assert_eq!(name.as_str().len(), 128);
+ let (parsed_server, parsed_tool) =
+ MangledName::parse(name.as_str()).expect("mangled name parses");
+ assert_eq!(parsed_server, "Some_Con");
+ assert_eq!(parsed_tool, "a".repeat(113));
+}
+
+#[test]
+fn truncation_never_leaves_a_dangling_underscore() {
+ // `abcdefg_hij` cut to the 8-byte server floor lands exactly on `_`.
+ let (name, _) = mangle("abcdefg hij", &"b".repeat(200));
+
+ assert_eq!(name.as_str().len(), 5 + 7 + 2 + 114);
+ assert_eq!(
+ MangledName::parse(name.as_str()),
+ Some(("abcdefg", "b".repeat(114).as_str()))
+ );
+}
+
+#[test]
+fn a_server_name_that_sanitizes_to_nothing_gets_a_placeholder() {
+ for server in ["", "!!!", " ", "日本語", "__"] {
+ let (name, sanitized) = mangle(server, "do_thing");
+
+ assert!(sanitized, "`{server}` should have been sanitized");
+ assert_eq!(name.as_str(), "mcp__server__do_thing");
+ assert_eq!(
+ MangledName::parse(name.as_str()),
+ Some(("server", "do_thing"))
+ );
+ }
+}
+
+#[test]
+fn a_tool_name_that_sanitizes_to_nothing_gets_a_placeholder() {
+ let (name, sanitized) = mangle("Linear", "###");
+
+ assert!(sanitized);
+ assert_eq!(name.as_str(), "mcp__Linear__tool");
+ assert_eq!(MangledName::parse(name.as_str()), Some(("Linear", "tool")));
+}
+
+#[test]
+fn sanitizing_can_collide_which_the_duplicate_check_skips() {
+ // Two distinct server names can sanitize to the same segment; registration
+ // relies on the equality of the mangled key to skip the second one.
+ let (first, _) = mangle("Google Sheets", "list_worksheets");
+ let (second, _) = mangle("Google/Sheets", "list_worksheets");
+
+ assert_eq!(first, second);
+}