1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
use std::collections::HashMap;
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::codex::NamespaceMap;
use super::{CodexNamespaceHandler, GatewayExecutor, ToolError, ToolOutput};
use crate::types::io::OutputItem;
use crate::types::io::output::FunctionToolCall;
use crate::types::tools::{CodexNamespaceMember, ResponsesTool};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolType {
Function,
CodexNamespace,
Mcp,
/// Internal routing discriminant. Serializes as `"web_search"`.
/// Note: the corresponding `ResponsesTool` wire tag is `"web_search_preview"`.
/// `ToolType` is not used in wire-facing types so the names differ intentionally.
WebSearch,
FileSearch,
CodeInterpreter,
}
impl ToolType {
#[must_use]
pub const fn is_gateway_owned(self) -> bool {
!matches!(self, Self::Function | Self::CodexNamespace)
}
}
/// Per-request routing entry keyed by the tool name the model will call.
#[derive(Clone)]
pub struct ToolEntry {
pub tool_type: ToolType,
/// Full serialised tool param for the executor (used during dispatch).
pub config: Value,
/// For MCP tools: which server this tool belongs to.
pub server_label: Option<String>,
pub handler: Option<Arc<dyn GatewayExecutor>>,
}
impl std::fmt::Debug for ToolEntry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ToolEntry")
.field("tool_type", &self.tool_type)
.field("config", &self.config)
.field("server_label", &self.server_label)
.field("handler", &self.handler.is_some())
.finish()
}
}
pub struct GatewayDispatchResult {
pub tool_type: ToolType,
pub output: Result<ToolOutput, ToolError>,
}
/// Request-scoped registry built from `RequestPayload.tools`.
/// Maps the name the LLM sees → routing metadata.
#[derive(Debug, Default)]
pub struct ToolRegistry {
entries: HashMap<String, ToolEntry>,
/// Built once from the declared tools, so `restore_final_payload_output`
/// and `restore_stream_event_value` — the latter called once per SSE line
/// during streaming — don't rebuild it on every call.
namespace_map: Option<NamespaceMap>,
}
impl ToolRegistry {
/// Build a registry from the declared tools.
///
/// Duplicate tool names result in last-write-wins, logged at `warn` level.
///
/// # Errors
///
/// Returns [`ToolError::Config`] when Codex namespace member flattening
/// would collide with another declared tool name.
///
/// # Panics
///
/// Panics if serialization of a tool param struct fails, which cannot happen
/// for the types defined in this module (`#[derive(Serialize)]` on plain structs).
pub fn build(tools: &[ResponsesTool]) -> Result<Self, ToolError> {
Self::build_with_handlers(tools, |_| None)
}
/// Build a registry from declared tools and attach gateway handlers for dispatchable tool types.
///
/// # Errors
///
/// Returns [`ToolError::Config`] when Codex namespace member flattening
/// would collide with another declared tool name.
///
/// # Panics
///
/// Panics if serialization of a tool param struct fails, which cannot happen
/// for the types defined in this module (`#[derive(Serialize)]` on plain structs).
pub fn build_with_handlers(
tools: &[ResponsesTool],
mut handler_for: impl FnMut(ToolType) -> Option<Arc<dyn GatewayExecutor>>,
) -> Result<Self, ToolError> {
let mut entries = HashMap::with_capacity(tools.len());
// Namespace members must be keyed by the same flat, model-visible name
// the model will call, so resolve them first — the same pure pass used
// to build the upstream request.
let resolved_tools = CodexNamespaceHandler.resolve_namespace_members(tools)?;
for tool in &resolved_tools {
match tool {
ResponsesTool::Function(p) => {
// p.name is NonEmptyToolName — empty names are impossible here
// (serde rejects them at deserialization time).
if entries
.insert(
p.name.as_str().to_owned(),
ToolEntry {
tool_type: ToolType::Function,
config: serde_json::to_value(p).expect("serialization of known struct is infallible"),
server_label: None,
handler: None,
},
)
.is_some()
{
tracing::warn!(name = %p.name, "duplicate tool name — previous definition overwritten");
}
}
ResponsesTool::Mcp(p) => {
// MCP tool names are discovered at request-time via `tools/list`.
// Without discovery, we cannot know which tool names to register —
// keying by server_label would cause all MCP calls to miss on lookup
// since gateway_owned/client_owned look up by tool name, not server.
// MCP entries will be populated in PR C once HttpMcpHandler
// implements discover() and the executor calls it before build().
tracing::debug!(
server_label = %p.server_label,
"MCP server declared but skipped in registry — tool names unknown until discovery (PR C)"
);
}
ResponsesTool::WebSearch(p) => {
entries.insert(
"web_search".to_owned(),
ToolEntry {
tool_type: ToolType::WebSearch,
config: serde_json::to_value(p).expect("serialization of known struct is infallible"),
server_label: None,
handler: handler_for(ToolType::WebSearch),
},
);
}
ResponsesTool::FileSearch(p) => {
entries.insert(
"file_search".to_owned(),
ToolEntry {
tool_type: ToolType::FileSearch,
config: serde_json::to_value(p).expect("serialization of known struct is infallible"),
server_label: None,
handler: handler_for(ToolType::FileSearch),
},
);
}
ResponsesTool::CodeInterpreter(p) => {
entries.insert(
"code_interpreter".to_owned(),
ToolEntry {
tool_type: ToolType::CodeInterpreter,
config: serde_json::to_value(p).expect("serialization of known struct is infallible"),
server_label: None,
handler: handler_for(ToolType::CodeInterpreter),
},
);
}
ResponsesTool::Namespace(p) => {
// p's members already carry their flat, model-visible names
// (see the `resolve_namespace_members` call above).
let config = serde_json::to_value(p).expect("serialization of known struct is infallible");
for member in &p.tools {
let CodexNamespaceMember::Function(function) = member else {
continue;
};
let name = function.name.as_str().to_owned();
if entries
.insert(
name.clone(),
ToolEntry {
tool_type: ToolType::CodexNamespace,
config: config.clone(),
server_label: Some(p.name.clone()),
handler: None,
},
)
.is_some()
{
tracing::warn!(name = %name, namespace = %p.name, "duplicate tool name - previous definition overwritten");
}
}
}
ResponsesTool::Unknown => {
tracing::debug!("unknown tool declared but skipped in registry");
}
}
}
let namespace_map = CodexNamespaceHandler.build_namespace_map((!tools.is_empty()).then_some(tools))?;
Ok(Self { entries, namespace_map })
}
#[must_use]
pub fn lookup(&self, tool_name: &str) -> Option<&ToolEntry> {
self.entries.get(tool_name)
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
#[must_use]
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn restore_final_payload_output(&self, output: &mut [OutputItem]) {
CodexNamespaceHandler.restore_output_items(output, self.namespace_map.as_ref());
}
pub fn restore_stream_event_value(&self, value: &mut Value) -> bool {
CodexNamespaceHandler.restore_response_value(value, self.namespace_map.as_ref())
}
/// Returns the subset of `calls` whose names map to gateway-owned tools.
#[must_use]
pub fn gateway_owned<'a>(&self, calls: &'a [FunctionToolCall]) -> Vec<&'a FunctionToolCall> {
calls
.iter()
.filter(|c| {
self.entries
.get(&c.name)
.is_some_and(|e| e.tool_type.is_gateway_owned())
})
.collect()
}
#[must_use]
pub fn is_gateway_owned_name(&self, name: &str) -> bool {
self.entries
.get(name)
.is_some_and(|entry| entry.tool_type.is_gateway_owned())
}
/// Returns the subset of `calls` whose names map to client-owned tools
/// (`Function`, Codex namespace members, or unknown names).
#[must_use]
pub fn client_owned<'a>(&self, calls: &'a [FunctionToolCall]) -> Vec<&'a FunctionToolCall> {
calls
.iter()
.filter(|c| {
self.entries
.get(&c.name)
.is_none_or(|e| !e.tool_type.is_gateway_owned())
})
.collect()
}
pub async fn dispatch(&self, call: &FunctionToolCall) -> Option<GatewayDispatchResult> {
let entry = self.entries.get(&call.name)?;
let handler = entry.handler.clone()?;
let tool_type = entry.tool_type;
let config = entry.config.clone();
Some(GatewayDispatchResult {
tool_type,
output: handler
.execute(&call.call_id, &call.name, &call.arguments, &config)
.await,
})
}
}