Skip to main content

switchyard_translation/
codex_namespaces.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Codex tool namespace preservation across a Responses/Chat translation.
5//!
6//! Codex groups tools into non-standard ``namespace`` containers — MCP servers,
7//! usually behind an `mcp__` prefix, plus builtin groups such as
8//! `multi_agent_v1` — and dispatches on the pair of tool name and namespace. It
9//! therefore expects the namespace back on the call it receives:
10//! `{"type": "function_call", "name": "search", "namespace": "mcp__docs"}`.
11//!
12//! OpenAI-compatible upstreams accept only flat `function` tools, so the request
13//! codec flattens the containers and names each child `<namespace>__<tool>`.
14//! Two tools differing only by namespace therefore stay distinct upstream, and
15//! the conversation history uses the same spelling so the transcript never
16//! teaches the model a name the upstream was not offered.
17//!
18//! The qualified-name to namespace mapping rides in the request's
19//! [`ProviderExtensions`], so no provider-neutral type grows a Codex-specific
20//! field. No codec copies unknown extension keys into an outbound body, so the
21//! mapping reaches neither the upstream nor the client.
22//!
23//! No container is filtered by its name, because Codex resolves a call with no
24//! namespace against its default group: dropping a builtin group's namespace
25//! would look the call up in the wrong place.
26
27use std::collections::HashMap;
28
29use serde_json::{Map, Value};
30use switchyard_protocol::ProviderExtensions;
31
32pub use switchyard_protocol::codex_namespaces::{
33    NAMESPACE_SEPARATOR, TOOL_NAMESPACES_KEY, split_qualified_name, tool_namespaces,
34};
35
36/// Joins a namespace and a tool name into the name used on the wire.
37pub fn qualified_tool_name(namespace: &str, tool: &str) -> String {
38    format!("{namespace}{NAMESPACE_SEPARATOR}{tool}")
39}
40
41/// Records that `qualified` was produced by flattening a tool out of `namespace`.
42pub fn record_tool_namespace(
43    namespaces: &mut Map<String, Value>,
44    qualified: &str,
45    namespace: &str,
46    description: Option<&str>,
47) {
48    let value = description.map_or_else(
49        || Value::String(namespace.to_string()),
50        |description| {
51            serde_json::json!({
52                "namespace": namespace,
53                "description": description,
54            })
55        },
56    );
57    namespaces.insert(qualified.to_string(), value);
58}
59
60/// Stores a collected mapping on a request's extensions, when it has entries.
61pub fn attach_tool_namespaces(extensions: &mut ProviderExtensions, namespaces: Map<String, Value>) {
62    if !namespaces.is_empty() {
63        extensions
64            .fields
65            .insert(TOOL_NAMESPACES_KEY.to_string(), Value::Object(namespaces));
66    }
67}
68
69/// Returns a retained description for `namespace`.
70pub fn namespace_description<'a>(
71    namespaces: &'a Map<String, Value>,
72    namespace: &str,
73) -> Option<&'a str> {
74    namespaces.values().find_map(|value| {
75        let object = value.as_object()?;
76        (object.get("namespace").and_then(Value::as_str) == Some(namespace))
77            .then(|| object.get("description").and_then(Value::as_str))
78            .flatten()
79    })
80}
81
82/// Maps exact qualified tool names to their Codex tool names and namespaces.
83pub fn qualified_tool_origins(
84    extensions: &ProviderExtensions,
85) -> HashMap<String, (String, String)> {
86    let Some(namespaces) = tool_namespaces(extensions) else {
87        return HashMap::new();
88    };
89    namespaces
90        .keys()
91        .filter_map(|qualified| {
92            let (tool, namespace) = split_qualified_name(namespaces, qualified)?;
93            Some((qualified.clone(), (tool.to_string(), namespace.to_string())))
94        })
95        .collect()
96}
97
98/// Restore the Codex tool name and namespace on function calls and argument completions.
99///
100/// Walks the whole value, covering `function_call` items in buffered responses
101/// and streaming events, plus the top-level name in
102/// `response.function_call_arguments.done`. Preserves an existing `namespace`.
103pub fn restore_qualified_tool_names(body: &mut Value, origins: &HashMap<String, (String, String)>) {
104    if origins.is_empty() {
105        return;
106    }
107    match body {
108        Value::Array(values) => {
109            for value in values {
110                restore_qualified_tool_names(value, origins);
111            }
112        }
113        Value::Object(object) => {
114            if matches!(
115                object.get("type").and_then(Value::as_str),
116                Some("function_call" | "response.function_call_arguments.done")
117            ) && let Some(name) = object.get("name").and_then(Value::as_str)
118                && let Some((tool, namespace)) = origins.get(name)
119            {
120                object.insert("name".to_string(), Value::String(tool.clone()));
121                object
122                    .entry("namespace".to_string())
123                    .or_insert_with(|| Value::String(namespace.clone()));
124            }
125            for value in object.values_mut() {
126                restore_qualified_tool_names(value, origins);
127            }
128        }
129        _ => {}
130    }
131}
132
133/// Flattens Codex namespaces in an outbound Responses body for an OpenAI-compatible provider.
134///
135/// The Responses encoder rebuilds `namespace` containers and `namespace` fields on
136/// calls for the client, and a replayed preserved body still holds them as sent.
137/// Providers accept only flat function tools, so this pass runs on every body sent
138/// to a Responses upstream. It names each child `<namespace>__<tool>`, moves the
139/// `namespace` field of `function_call` items and a `tool_choice` into the name,
140/// and gives each function tool a string `description`.
141pub fn flatten_codex_namespaces_for_provider(body: &mut Value) {
142    let Value::Object(object) = body else {
143        return;
144    };
145    if let Some(Value::Array(items)) = object.get_mut("input") {
146        for item in items.iter_mut().filter_map(Value::as_object_mut) {
147            if item.get("type").and_then(Value::as_str) == Some("function_call") {
148                move_namespace_into_name(item);
149            }
150        }
151    }
152    if let Some(Value::Array(tools)) = object.get_mut("tools") {
153        let mut flat = Vec::with_capacity(tools.len());
154        for tool in std::mem::take(tools) {
155            push_flat_tool(&mut flat, tool);
156        }
157        *tools = flat;
158    }
159    if let Some(Value::Object(choice)) = object.get_mut("tool_choice")
160        && choice.get("type").and_then(Value::as_str) == Some("function")
161    {
162        move_namespace_into_name(choice);
163    }
164}
165
166fn push_flat_tool(out: &mut Vec<Value>, tool: Value) {
167    let Value::Object(mut object) = tool else {
168        out.push(tool);
169        return;
170    };
171    if object.get("type").and_then(Value::as_str) == Some("namespace") {
172        let namespace = object
173            .get("name")
174            .and_then(Value::as_str)
175            .unwrap_or_default()
176            .to_string();
177        let Some(Value::Array(children)) = object.remove("tools") else {
178            out.push(Value::Object(object));
179            return;
180        };
181        for child in children {
182            let Value::Object(mut child) = child else {
183                out.push(child);
184                continue;
185            };
186            if child.get("type").and_then(Value::as_str) == Some("function") {
187                qualify_name(&mut child, &namespace);
188                ensure_function_description(&mut child);
189            }
190            out.push(Value::Object(child));
191        }
192        return;
193    }
194    ensure_function_description(&mut object);
195    out.push(Value::Object(object));
196}
197
198fn move_namespace_into_name(object: &mut Map<String, Value>) {
199    if let Some(Value::String(namespace)) = object.remove("namespace") {
200        qualify_name(object, &namespace);
201    }
202}
203
204// Leaves a name that already carries the namespace prefix unchanged.
205fn qualify_name(object: &mut Map<String, Value>, namespace: &str) {
206    if namespace.is_empty() {
207        return;
208    }
209    let Some(name) = object.get("name").and_then(Value::as_str) else {
210        return;
211    };
212    if name
213        .strip_prefix(namespace)
214        .is_some_and(|rest| rest.starts_with(NAMESPACE_SEPARATOR))
215    {
216        return;
217    }
218    let qualified = qualified_tool_name(namespace, name);
219    object.insert("name".to_string(), Value::String(qualified));
220}
221
222fn ensure_function_description(object: &mut Map<String, Value>) {
223    if object.get("type").and_then(Value::as_str) == Some("function")
224        && !matches!(object.get("description"), Some(Value::String(_)))
225    {
226        object.insert("description".to_string(), Value::String(String::new()));
227    }
228}
229
230#[cfg(test)]
231mod tests {
232    use serde_json::{Map, json};
233    use switchyard_protocol::ProviderExtensions;
234
235    use super::{
236        attach_tool_namespaces, qualified_tool_name, qualified_tool_origins, record_tool_namespace,
237        restore_qualified_tool_names, split_qualified_name, tool_namespaces,
238    };
239
240    fn extensions(pairs: &[(&str, &str)]) -> ProviderExtensions {
241        let mut namespaces = Map::new();
242        for (namespace, tool) in pairs {
243            record_tool_namespace(
244                &mut namespaces,
245                &qualified_tool_name(namespace, tool),
246                namespace,
247                None,
248            );
249        }
250        let mut extensions = ProviderExtensions::default();
251        attach_tool_namespaces(&mut extensions, namespaces);
252        extensions
253    }
254
255    // A tool name may itself contain the separator, so the namespace is matched
256    // as a prefix rather than by splitting on the first `__`.
257    #[test]
258    fn splits_a_qualified_name_back_apart() {
259        let simple = extensions(&[("mcp__docs", "search")]);
260        let simple = tool_namespaces(&simple).expect("mapping present");
261        assert_eq!(
262            split_qualified_name(simple, "mcp__docs__search"),
263            Some(("search", "mcp__docs"))
264        );
265        assert_eq!(split_qualified_name(simple, "unknown_tool"), None);
266
267        let nested = extensions(&[("mcp__docs", "fetch__raw")]);
268        let nested = tool_namespaces(&nested).expect("mapping present");
269        assert_eq!(
270            split_qualified_name(nested, "mcp__docs__fetch__raw"),
271            Some(("fetch__raw", "mcp__docs"))
272        );
273    }
274
275    #[test]
276    fn leaves_unqualified_names_alone() {
277        let origins = qualified_tool_origins(&extensions(&[("mcp__docs", "search")]));
278        let mut response = json!([
279            {"output": [{"type": "function_call", "name": "search"}]},
280            {"type": "response.output_item.done", "item": {
281                "type": "function_call", "name": "docs__search"
282            }},
283            {"type": "response.function_call_arguments.done", "name": "docs__search"}
284        ]);
285        let before = response.clone();
286
287        restore_qualified_tool_names(&mut response, &origins);
288
289        assert_eq!(response, before);
290    }
291
292    // Codex namespaces builtin groups too, so nothing may key on `mcp__`.
293    #[test]
294    fn resolves_namespaces_that_are_not_mcp_servers() {
295        let origins = qualified_tool_origins(&extensions(&[("multi_agent_v1", "spawn_agent")]));
296        let mut response = json!({
297            "output": [{"type": "function_call", "name": "multi_agent_v1__spawn_agent"}]
298        });
299
300        restore_qualified_tool_names(&mut response, &origins);
301
302        assert_eq!(response["output"][0]["name"], "spawn_agent");
303        assert_eq!(response["output"][0]["namespace"], "multi_agent_v1");
304    }
305}