use std::collections::{HashMap, HashSet};
use serde_json::{Map, Value};
use switchyard_protocol::ProviderExtensions;
pub const NAMESPACE_SEPARATOR: &str = "__";
pub const TOOL_NAMESPACES_KEY: &str = "switchyard_codex_tool_namespaces";
pub fn qualified_tool_name(namespace: &str, tool: &str) -> String {
format!("{namespace}{NAMESPACE_SEPARATOR}{tool}")
}
pub fn record_tool_namespace(
namespaces: &mut Map<String, Value>,
qualified: &str,
namespace: &str,
description: Option<&str>,
) {
let value = description.map_or_else(
|| Value::String(namespace.to_string()),
|description| {
serde_json::json!({
"namespace": namespace,
"description": description,
})
},
);
namespaces.insert(qualified.to_string(), value);
}
pub fn attach_tool_namespaces(extensions: &mut ProviderExtensions, namespaces: Map<String, Value>) {
if !namespaces.is_empty() {
extensions
.fields
.insert(TOOL_NAMESPACES_KEY.to_string(), Value::Object(namespaces));
}
}
pub fn tool_namespaces(extensions: &ProviderExtensions) -> Option<&Map<String, Value>> {
extensions
.fields
.get(TOOL_NAMESPACES_KEY)
.and_then(Value::as_object)
}
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()))
}
pub fn namespace_description<'a>(
namespaces: &'a Map<String, Value>,
namespace: &str,
) -> Option<&'a str> {
namespaces.values().find_map(|value| {
let object = value.as_object()?;
(object.get("namespace").and_then(Value::as_str) == Some(namespace))
.then(|| object.get("description").and_then(Value::as_str))
.flatten()
})
}
pub fn qualified_tool_origins(
extensions: &ProviderExtensions,
) -> HashMap<String, (String, String)> {
let Some(namespaces) = tool_namespaces(extensions) else {
return HashMap::new();
};
let split: Vec<(String, String, String)> = namespaces
.keys()
.filter_map(|qualified| {
let (tool, namespace) = split_qualified_name(namespaces, qualified)?;
Some((qualified.clone(), tool, namespace))
})
.collect();
let mut bare_claims: HashMap<&str, usize> = HashMap::new();
for (_, tool, _) in &split {
*bare_claims.entry(tool.as_str()).or_default() += 1;
}
let qualified_names: HashSet<&str> = split
.iter()
.map(|(qualified, _, _)| qualified.as_str())
.collect();
let mut origins = HashMap::new();
for (qualified, tool, namespace) in &split {
let origin = (tool.clone(), namespace.clone());
if let Some(stripped) = namespace.strip_prefix("mcp__") {
let spelling = qualified_tool_name(stripped, tool);
if !qualified_names.contains(spelling.as_str()) {
origins.entry(spelling).or_insert_with(|| origin.clone());
}
}
if bare_claims.get(tool.as_str()) == Some(&1) && !qualified_names.contains(tool.as_str()) {
origins
.entry(tool.clone())
.or_insert_with(|| origin.clone());
}
origins.insert(qualified.clone(), origin);
}
origins
}
pub fn restore_qualified_tool_names(body: &mut Value, origins: &HashMap<String, (String, String)>) {
if origins.is_empty() {
return;
}
match body {
Value::Array(values) => {
for value in values {
restore_qualified_tool_names(value, origins);
}
}
Value::Object(object) => {
if matches!(
object.get("type").and_then(Value::as_str),
Some("function_call" | "response.function_call_arguments.done")
) && let Some(name) = object.get("name").and_then(Value::as_str)
&& let Some((tool, namespace)) = origins.get(name)
{
object.insert("name".to_string(), Value::String(tool.clone()));
object
.entry("namespace".to_string())
.or_insert_with(|| Value::String(namespace.clone()));
}
for value in object.values_mut() {
restore_qualified_tool_names(value, origins);
}
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use serde_json::{Map, json};
use switchyard_protocol::ProviderExtensions;
use super::{
attach_tool_namespaces, qualified_tool_name, qualified_tool_origins, record_tool_namespace,
restore_qualified_tool_names, split_qualified_name, tool_namespaces,
};
fn extensions(pairs: &[(&str, &str)]) -> ProviderExtensions {
let mut namespaces = Map::new();
for (namespace, tool) in pairs {
record_tool_namespace(
&mut namespaces,
&qualified_tool_name(namespace, tool),
namespace,
None,
);
}
let mut extensions = ProviderExtensions::default();
attach_tool_namespaces(&mut extensions, namespaces);
extensions
}
#[test]
fn splits_a_qualified_name_back_apart() {
let simple = extensions(&[("mcp__docs", "search")]);
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()))
);
assert_eq!(split_qualified_name(simple, "unknown_tool"), None);
let nested = extensions(&[("mcp__docs", "fetch__raw")]);
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()))
);
}
#[test]
fn leaves_an_ambiguous_bare_name_alone() {
let origins =
qualified_tool_origins(&extensions(&[("mcp__a", "search"), ("mcp__b", "search")]));
let mut response = json!({"output": [{"type": "function_call", "name": "search"}]});
let before = response.clone();
restore_qualified_tool_names(&mut response, &origins);
assert_eq!(response, before);
}
#[test]
fn resolves_namespaces_that_are_not_mcp_servers() {
let origins = qualified_tool_origins(&extensions(&[("multi_agent_v1", "spawn_agent")]));
let mut response = json!({
"output": [{"type": "function_call", "name": "multi_agent_v1__spawn_agent"}]
});
restore_qualified_tool_names(&mut response, &origins);
assert_eq!(response["output"][0]["name"], "spawn_agent");
assert_eq!(response["output"][0]["namespace"], "multi_agent_v1");
}
}