Skip to content

Switchyard lets LLM applications route traffic across models and providers while preserving native OpenAI and Anthropic API compatibility - enabling flexible model selection, benchmarking, and cost/performance optimization.

Rust

fix(stage): match tool semantics by bare MCP tool name (#831)

Graham King42784fdce3d9
diff --git a/crates/libsy/src/algorithms/util/tool_signals.rs b/crates/libsy/src/algorithms/util/tool_signals.rs
index 3cecf06a3..9c2ed8310 100644
--- a/crates/libsy/src/algorithms/util/tool_signals.rs
+++ b/crates/libsy/src/algorithms/util/tool_signals.rs
@@ -17,6 +17,7 @@ use std::path::Path;
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::Value;
+use switchyard_protocol::codex_namespaces::{split_qualified_name, tool_namespaces};
use switchyard_protocol::{ContentBlock, Request, Role, WireFormat};
use crate::{LibsyError, Result};
@@ -237,8 +238,9 @@ pub const DEFAULT_RECENT_WINDOW: usize = 3;
/// Exact tool-name semantics added to the stage router's built-in vocabulary.
///
-/// Matching is ASCII case-insensitive. These lists are additive: built-in tool
-/// names cannot be reclassified.
+/// Matching is ASCII case-insensitive. An MCP or Codex namespaced tool also
+/// matches by its bare tool name. These lists are additive: built-in tool names
+/// cannot be reclassified.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct ToolSemantics {
@@ -400,9 +402,11 @@ impl ToolSignals {
}
// `command` is the lowercased Bash command line; None for non-Bash tools.
+// `bare_name` is the tool's own name when `name` joins it to a namespace or MCP server.
#[derive(Debug, Clone)]
-struct ObservedToolCall {
+struct ObservedToolCall<'a> {
name: String,
+ bare_name: Option<&'a str>,
command: Option<String>,
}
@@ -706,6 +710,7 @@ fn extract_tool_signals_with_window_and_semantics(
) -> ToolSignals {
// Read the decoded conversation, including preserved built-in tool outputs.
let messages = &request.llm_request.messages;
+ let namespaces = tool_namespaces(&request.llm_request.extensions);
let mut tool_texts: Vec<(String, bool)> = Vec::new();
let mut tool_calls: Vec<ObservedToolCall> = Vec::new();
let mut compacted = false;
@@ -719,8 +724,14 @@ fn extract_tool_signals_with_window_and_semantics(
for block in &message.content {
match block {
ContentBlock::ToolCall(call) => {
+ // Responses namespaced tools arrive as `<namespace>__<tool>`.
+ let bare_name = namespaces
+ .and_then(|namespaces| split_qualified_name(namespaces, &call.name))
+ .map(|(tool, _)| tool)
+ .or_else(|| mcp_tool_name(&call.name));
tool_calls.push(ObservedToolCall {
name: call.name.clone(),
+ bare_name,
command: command_of(&call.arguments),
});
}
@@ -821,6 +832,14 @@ fn extract_tool_signals_with_window_and_semantics(
/// overflowed context. Matched case-insensitively; normal task text never contains it.
const COMPACTION_MARKER: &str = "session is being continued";
+/// The tool part of an `mcp__<server>__<tool>` name, the form Claude Code uses
+/// for MCP tools. The server name is assumed not to contain `__`; the tool name
+/// may.
+fn mcp_tool_name(name: &str) -> Option<&str> {
+ let (_server, tool) = name.strip_prefix("mcp__")?.split_once("__")?;
+ (!tool.is_empty()).then_some(tool)
+}
+
/// The shell command a tool call carries, when it has one. Harnesses name the
/// field `command`; anything else is a tool whose category comes from its name.
fn command_of(arguments: &Value) -> Option<String> {
@@ -908,7 +927,13 @@ fn build_signal(
let mut pure_bash_streak = 0u32;
let mut streak_open = true;
for (i, tc) in tool_calls.iter().enumerate().rev() {
- let cat = classify_tool_call_with_semantics(&tc.name, tc.command.as_deref(), semantics);
+ // The joined name wins, so configs that list it keep working.
+ let mut cat = classify_tool_call_with_semantics(&tc.name, tc.command.as_deref(), semantics);
+ if matches!(cat, ToolSemantic::Unknown)
+ && let Some(bare_name) = tc.bare_name
+ {
+ cat = classify_tool_call_with_semantics(bare_name, tc.command.as_deref(), semantics);
+ }
if streak_open {
if matches!(cat, ToolSemantic::Unknown) {
pure_bash_streak += 1;
@@ -1252,6 +1277,7 @@ mod tests {
use super::*;
use crate::algorithms::util::stage::score_signal;
use serde_json::json;
+ use switchyard_protocol::codex_namespaces::TOOL_NAMESPACES_KEY;
use switchyard_protocol::{
ContentBlock, LlmRequest, Message, Metadata, Role, ToolCall, ToolResult,
};
@@ -2248,6 +2274,30 @@ mod tests {
assert_eq!(signal.pure_bash_streak, 1);
}
+ #[test]
+ fn configured_tool_semantics_match_namespaced_and_mcp_tools() {
+ // The Responses decoder flattens namespaced tools and records the mapping.
+ let mut request = with_messages(vec![tc("mcp__billing__send_payment_request")]);
+ request.llm_request.extensions.fields.insert(
+ TOOL_NAMESPACES_KEY.to_string(),
+ json!({"mcp__billing__send_payment_request": "mcp__billing"}),
+ );
+
+ // Claude Code sends MCP tools flat, with no namespace mapping.
+ let claude_request = with_messages(vec![tc("mcp__billing__send_payment_request")]);
+
+ for request in [&request, &claude_request] {
+ for name in ["send_payment_request", "mcp__billing__send_payment_request"] {
+ let semantics = ToolSemantics {
+ mutate: vec![name.to_string()],
+ ..Default::default()
+ };
+ let signal = ToolSignals::from_request_with_semantics(request, None, &semantics);
+ assert_eq!(signal.write_count, 1, "{name}");
+ }
+ }
+ }
+
#[test]
fn configured_tool_semantics_only_fold_ascii_case() {
let semantics = ToolSemantics {
diff --git a/crates/protocol/src/codex_namespaces.rs b/crates/protocol/src/codex_namespaces.rs
new file mode 100644
index 000000000..e56064b87
--- /dev/null
+++ b/crates/protocol/src/codex_namespaces.rs
@@ -0,0 +1,50 @@
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+//! Reads the Codex tool namespaces that a Responses request decoder records.
+//!
+//! Codex groups tools into `namespace` containers. The Responses codec in
+//! `switchyard-translation` flattens each child to `<namespace>__<tool>` and
+//! stores the mapping in the request's [`ProviderExtensions`]. Code that does not
+//! depend on the translation crate uses these helpers to recover the tool name.
+
+use serde_json::{Map, Value};
+
+use crate::ProviderExtensions;
+
+/// Separator between a namespace and a tool name in a qualified wire name.
+pub const NAMESPACE_SEPARATOR: &str = "__";
+
+/// Request extension key holding the qualified-name to namespace mapping.
+///
+/// Prefixed so it cannot collide with a real provider field, and so a codec that
+/// allowlists provider fields never forwards it.
+pub const TOOL_NAMESPACES_KEY: &str = "switchyard_codex_tool_namespaces";
+
+/// Reads the mapping back off a request's extensions.
+pub fn tool_namespaces(extensions: &ProviderExtensions) -> Option<&Map<String, Value>> {
+ extensions
+ .fields
+ .get(TOOL_NAMESPACES_KEY)
+ .and_then(Value::as_object)
+}
+
+/// Splits a qualified wire name back into its tool name and namespace.
+///
+/// Returns `None` for a name the request never qualified, so an unrecognized
+/// call is left alone rather than attributed to the wrong namespace. The tool
+/// name may itself contain the separator, so the namespace is matched as a
+/// prefix rather than by splitting on it.
+pub fn split_qualified_name<'a>(
+ namespaces: &'a Map<String, Value>,
+ qualified: &'a str,
+) -> Option<(&'a str, &'a str)> {
+ let value = namespaces.get(qualified)?;
+ let namespace = value
+ .as_str()
+ .or_else(|| value.get("namespace").and_then(Value::as_str))?;
+ let tool = qualified
+ .strip_prefix(namespace)?
+ .strip_prefix(NAMESPACE_SEPARATOR)?;
+ Some((tool, namespace))
+}
diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs
index 663968ceb..0d76b4d17 100644
--- a/crates/protocol/src/lib.rs
+++ b/crates/protocol/src/lib.rs
@@ -6,6 +6,7 @@
pub mod category;
pub mod client;
+pub mod codex_namespaces;
pub mod envelope;
pub mod format;
pub mod llm;
diff --git a/crates/switchyard-translation/src/codecs/responses/buffered.rs b/crates/switchyard-translation/src/codecs/responses/buffered.rs
index eb76c59f4..724df4dba 100644
--- a/crates/switchyard-translation/src/codecs/responses/buffered.rs
+++ b/crates/switchyard-translation/src/codecs/responses/buffered.rs
@@ -1464,7 +1464,7 @@ fn encode_responses_special_input(
.and_then(|namespaces| {
crate::codex_namespaces::split_qualified_name(namespaces, &call.name)
})
- .map_or((call.name.clone(), None), |(name, namespace)| {
+ .map_or((call.name.as_str(), None), |(name, namespace)| {
(name, Some(namespace))
});
let mut item = json!({
@@ -1474,7 +1474,7 @@ fn encode_responses_special_input(
"arguments": json_string(&call.arguments),
});
if let Some(namespace) = namespace {
- item["namespace"] = Value::String(namespace);
+ item["namespace"] = Value::String(namespace.to_string());
}
Some(item)
}
@@ -1497,8 +1497,8 @@ fn encode_responses_special_input(
.and_then(|namespaces| {
crate::codex_namespaces::split_qualified_name(namespaces, name)
})
- .map_or_else(|| (*name).to_string(), |(name, _)| name);
- item["name"] = Value::String(name);
+ .map_or(*name, |(name, _)| name);
+ item["name"] = Value::String(name.to_string());
}
Some(item)
}
@@ -1698,13 +1698,13 @@ fn encode_responses_tools(
match split {
None => out.push(item),
Some((name, namespace)) => {
- item["name"] = Value::String(name);
+ item["name"] = Value::String(name.to_string());
match containers
.iter_mut()
.find(|(existing, _)| *existing == namespace)
{
Some((_, children)) => children.push(item),
- None => containers.push((namespace, vec![item])),
+ None => containers.push((namespace.to_string(), vec![item])),
}
}
}
diff --git a/crates/switchyard-translation/src/codex_namespaces.rs b/crates/switchyard-translation/src/codex_namespaces.rs
index ed5da2016..7c757513e 100644
--- a/crates/switchyard-translation/src/codex_namespaces.rs
+++ b/crates/switchyard-translation/src/codex_namespaces.rs
@@ -29,14 +29,9 @@ use std::collections::{HashMap, HashSet};
use serde_json::{Map, Value};
use switchyard_protocol::ProviderExtensions;
-/// Separator between a namespace and a tool name in a qualified wire name.
-pub const NAMESPACE_SEPARATOR: &str = "__";
-
-/// Request extension key holding the qualified-name to namespace mapping.
-///
-/// Prefixed so it cannot collide with a real provider field, and so a codec that
-/// allowlists provider fields never forwards it.
-pub const TOOL_NAMESPACES_KEY: &str = "switchyard_codex_tool_namespaces";
+pub use switchyard_protocol::codex_namespaces::{
+ NAMESPACE_SEPARATOR, TOOL_NAMESPACES_KEY, split_qualified_name, tool_namespaces,
+};
/// Joins a namespace and a tool name into the name used on the wire.
pub fn qualified_tool_name(namespace: &str, tool: &str) -> String {
@@ -71,34 +66,6 @@ pub fn attach_tool_namespaces(extensions: &mut ProviderExtensions, namespaces: M
}
}
-/// Reads the mapping back off a request's extensions.
-pub fn tool_namespaces(extensions: &ProviderExtensions) -> Option<&Map<String, Value>> {
- extensions
- .fields
- .get(TOOL_NAMESPACES_KEY)
- .and_then(Value::as_object)
-}
-
-/// Splits a qualified wire name back into its tool name and namespace.
-///
-/// Returns `None` for a name the request never qualified, so an unrecognized
-/// call is left alone rather than attributed to the wrong namespace. The tool
-/// name may itself contain the separator, so the namespace is matched as a
-/// prefix rather than by splitting on it.
-pub fn split_qualified_name(
- namespaces: &Map<String, Value>,
- qualified: &str,
-) -> Option<(String, String)> {
- let value = namespaces.get(qualified)?;
- let namespace = value
- .as_str()
- .or_else(|| value.get("namespace").and_then(Value::as_str))?;
- let tool = qualified
- .strip_prefix(namespace)?
- .strip_prefix(NAMESPACE_SEPARATOR)?;
- Some((tool.to_string(), namespace.to_string()))
-}
-
/// Returns a retained description for `namespace`.
pub fn namespace_description<'a>(
namespaces: &'a Map<String, Value>,
@@ -130,7 +97,7 @@ pub fn qualified_tool_origins(
.keys()
.filter_map(|qualified| {
let (tool, namespace) = split_qualified_name(namespaces, qualified)?;
- Some((qualified.clone(), tool, namespace))
+ Some((qualified.clone(), tool.to_string(), namespace.to_string()))
})
.collect();
@@ -233,7 +200,7 @@ mod tests {
let simple = tool_namespaces(&simple).expect("mapping present");
assert_eq!(
split_qualified_name(simple, "mcp__docs__search"),
- Some(("search".to_string(), "mcp__docs".to_string()))
+ Some(("search", "mcp__docs"))
);
assert_eq!(split_qualified_name(simple, "unknown_tool"), None);
@@ -241,7 +208,7 @@ mod tests {
let nested = tool_namespaces(&nested).expect("mapping present");
assert_eq!(
split_qualified_name(nested, "mcp__docs__fetch__raw"),
- Some(("fetch__raw".to_string(), "mcp__docs".to_string()))
+ Some(("fetch__raw", "mcp__docs"))
);
}
diff --git a/docs/routing_algorithms/stage_router_routing.md b/docs/routing_algorithms/stage_router_routing.md
index 84c815947..16cb53b7d 100644
--- a/docs/routing_algorithms/stage_router_routing.md
+++ b/docs/routing_algorithms/stage_router_routing.md
@@ -233,6 +233,13 @@ across categories, and unknown category keys are rejected when the route is
loaded. Argument-aware wrapper tools, inferred semantics, and learned routing
rules are outside this exact-name configuration.
+MCP tools match by their bare tool name or by their full name. Claude Code sends
+an MCP tool as `mcp__<server>__<tool>`, and Codex sends it with a separate
+`namespace`. For both, `send_payment_request` matches the `send_payment_request`
+tool on the `billing` MCP server, and so does
+`mcp__billing__send_payment_request`. A server name that contains `__` needs the
+full name.
+
### Optional: handoff notes
Add a `[routes.stage.handoff_notes]` section to append contextual guidance to a