mirror of
https://github.com/openai/codex.git
synced 2026-11-19 22:30:42 +00:00
codex: add dynamic tool hook support
This commit is contained in:
@@ -95,7 +95,7 @@ pub(crate) async fn handle_mcp_tool_call(
|
||||
call_id: String,
|
||||
server: String,
|
||||
tool_name: String,
|
||||
hook_tool_name: String,
|
||||
hook_tool_name: HookToolName,
|
||||
arguments: String,
|
||||
) -> HandledMcpToolCall {
|
||||
// Parse the `arguments` as JSON. An empty string is OK, but invalid JSON
|
||||
@@ -198,7 +198,7 @@ pub(crate) async fn handle_mcp_tool_call(
|
||||
turn_context,
|
||||
&call_id,
|
||||
&invocation,
|
||||
&hook_tool_name,
|
||||
hook_tool_name.name(),
|
||||
metadata.as_ref(),
|
||||
approval_mode,
|
||||
)
|
||||
@@ -1009,13 +1009,13 @@ async fn maybe_request_mcp_tool_approval(
|
||||
sess,
|
||||
turn_context,
|
||||
call_id,
|
||||
PermissionRequestPayload {
|
||||
tool_name: HookToolName::new(hook_tool_name),
|
||||
tool_input: invocation
|
||||
PermissionRequestPayload::new(
|
||||
HookToolName::new(hook_tool_name),
|
||||
invocation
|
||||
.arguments
|
||||
.clone()
|
||||
.unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::new())),
|
||||
},
|
||||
),
|
||||
)
|
||||
.await
|
||||
{
|
||||
|
||||
@@ -3,8 +3,12 @@ use crate::session::session::Session;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use crate::tools::context::FunctionToolOutput;
|
||||
use crate::tools::context::ToolInvocation;
|
||||
use crate::tools::context::ToolOutput;
|
||||
use crate::tools::context::ToolPayload;
|
||||
use crate::tools::handlers::parse_arguments;
|
||||
use crate::tools::hook_names::HookToolName;
|
||||
use crate::tools::registry::PostToolUsePayload;
|
||||
use crate::tools::registry::PreToolUsePayload;
|
||||
use crate::tools::registry::ToolHandler;
|
||||
use crate::tools::registry::ToolKind;
|
||||
use codex_protocol::dynamic_tools::DynamicToolCallRequest;
|
||||
@@ -27,6 +31,27 @@ impl ToolHandler for DynamicToolHandler {
|
||||
ToolKind::Function
|
||||
}
|
||||
|
||||
fn pre_tool_use_payload(&self, invocation: &ToolInvocation) -> Option<PreToolUsePayload> {
|
||||
Some(PreToolUsePayload {
|
||||
tool_name: HookToolName::for_function_tool(&invocation.tool_name),
|
||||
tool_input: dynamic_tool_input(invocation).ok()?,
|
||||
})
|
||||
}
|
||||
|
||||
fn post_tool_use_payload(
|
||||
&self,
|
||||
invocation: &ToolInvocation,
|
||||
result: &Self::Output,
|
||||
) -> Option<PostToolUsePayload> {
|
||||
Some(PostToolUsePayload {
|
||||
tool_name: HookToolName::for_function_tool(&invocation.tool_name),
|
||||
tool_use_id: invocation.call_id.clone(),
|
||||
tool_input: dynamic_tool_input(invocation).ok()?,
|
||||
tool_response: result
|
||||
.post_tool_use_response(&invocation.call_id, &invocation.payload)?,
|
||||
})
|
||||
}
|
||||
|
||||
async fn is_mutating(&self, _invocation: &ToolInvocation) -> bool {
|
||||
true
|
||||
}
|
||||
@@ -67,7 +92,34 @@ impl ToolHandler for DynamicToolHandler {
|
||||
.into_iter()
|
||||
.map(FunctionCallOutputContentItem::from)
|
||||
.collect::<Vec<_>>();
|
||||
Ok(FunctionToolOutput::from_content(body, Some(success)))
|
||||
Ok(FunctionToolOutput {
|
||||
post_tool_use_response: Some(dynamic_tool_post_tool_use_response(&body)?),
|
||||
body,
|
||||
success: Some(success),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn dynamic_tool_input(invocation: &ToolInvocation) -> Result<Value, FunctionCallError> {
|
||||
let ToolPayload::Function { arguments } = &invocation.payload else {
|
||||
return Err(FunctionCallError::RespondToModel(
|
||||
"dynamic tool handler received unsupported payload".to_string(),
|
||||
));
|
||||
};
|
||||
|
||||
parse_arguments(arguments)
|
||||
}
|
||||
|
||||
fn dynamic_tool_post_tool_use_response(
|
||||
body: &[FunctionCallOutputContentItem],
|
||||
) -> Result<Value, FunctionCallError> {
|
||||
match body {
|
||||
[FunctionCallOutputContentItem::InputText { text }] => Ok(Value::String(text.clone())),
|
||||
_ => serde_json::to_value(body).map_err(|error| {
|
||||
FunctionCallError::RespondToModel(format!(
|
||||
"failed to serialize dynamic tool response for PostToolUse: {error}"
|
||||
))
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,3 +192,122 @@ async fn request_dynamic_tool(
|
||||
|
||||
response
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::DynamicToolHandler;
|
||||
use super::dynamic_tool_post_tool_use_response;
|
||||
use crate::session::tests::make_session_and_context;
|
||||
use crate::tools::context::FunctionToolOutput;
|
||||
use crate::tools::context::ToolCallSource;
|
||||
use crate::tools::context::ToolInvocation;
|
||||
use crate::tools::context::ToolPayload;
|
||||
use crate::tools::hook_names::HookToolName;
|
||||
use crate::tools::registry::PostToolUsePayload;
|
||||
use crate::tools::registry::PreToolUsePayload;
|
||||
use crate::tools::registry::ToolHandler;
|
||||
use crate::turn_diff_tracker::TurnDiffTracker;
|
||||
use codex_protocol::models::FunctionCallOutputContentItem;
|
||||
use codex_tools::ToolName;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
async fn dynamic_invocation(
|
||||
tool_name: ToolName,
|
||||
arguments: serde_json::Value,
|
||||
) -> ToolInvocation {
|
||||
let (session, turn) = make_session_and_context().await;
|
||||
ToolInvocation {
|
||||
session: session.into(),
|
||||
turn: turn.into(),
|
||||
cancellation_token: tokio_util::sync::CancellationToken::new(),
|
||||
tracker: Arc::new(Mutex::new(TurnDiffTracker::new())),
|
||||
call_id: "call-dynamic".to_string(),
|
||||
tool_name,
|
||||
source: ToolCallSource::Direct,
|
||||
payload: ToolPayload::Function {
|
||||
arguments: arguments.to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dynamic_pre_tool_use_payload_uses_plain_tool_name() {
|
||||
let invocation =
|
||||
dynamic_invocation(ToolName::plain("automation_update"), json!({"id": 1})).await;
|
||||
|
||||
assert_eq!(
|
||||
DynamicToolHandler.pre_tool_use_payload(&invocation),
|
||||
Some(PreToolUsePayload {
|
||||
tool_name: HookToolName::new("automation_update"),
|
||||
tool_input: json!({ "id": 1 }),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dynamic_post_tool_use_payload_uses_namespaced_hook_name() {
|
||||
let invocation = dynamic_invocation(
|
||||
ToolName::namespaced("codex_app", "automation_update"),
|
||||
json!({ "job": "sync" }),
|
||||
)
|
||||
.await;
|
||||
let output = FunctionToolOutput {
|
||||
body: vec![FunctionCallOutputContentItem::InputText {
|
||||
text: "ok".to_string(),
|
||||
}],
|
||||
success: Some(true),
|
||||
post_tool_use_response: Some(json!("ok")),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
DynamicToolHandler.post_tool_use_payload(&invocation, &output),
|
||||
Some(PostToolUsePayload {
|
||||
tool_name: HookToolName::new("dynamic__codex_app__automation_update"),
|
||||
tool_use_id: "call-dynamic".to_string(),
|
||||
tool_input: json!({ "job": "sync" }),
|
||||
tool_response: json!("ok"),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_post_tool_use_response_uses_text_for_single_text_item() {
|
||||
assert_eq!(
|
||||
dynamic_tool_post_tool_use_response(&[FunctionCallOutputContentItem::InputText {
|
||||
text: "done".to_string(),
|
||||
}]),
|
||||
Ok(json!("done"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_post_tool_use_response_uses_content_items_for_mixed_output() {
|
||||
let response = dynamic_tool_post_tool_use_response(&[
|
||||
FunctionCallOutputContentItem::InputText {
|
||||
text: "done".to_string(),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image_url: "https://example.com/image.png".to_string(),
|
||||
detail: None,
|
||||
},
|
||||
])
|
||||
.expect("serialize mixed dynamic tool output");
|
||||
|
||||
assert_eq!(
|
||||
response,
|
||||
json!([
|
||||
{
|
||||
"type": "input_text",
|
||||
"text": "done",
|
||||
},
|
||||
{
|
||||
"type": "input_image",
|
||||
"image_url": "https://example.com/image.png",
|
||||
}
|
||||
])
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ impl ToolHandler for McpHandler {
|
||||
};
|
||||
|
||||
Some(PreToolUsePayload {
|
||||
tool_name: HookToolName::new(invocation.tool_name.display()),
|
||||
tool_name: HookToolName::for_function_tool(&invocation.tool_name),
|
||||
tool_input: mcp_hook_tool_input(raw_arguments),
|
||||
})
|
||||
}
|
||||
@@ -46,7 +46,7 @@ impl ToolHandler for McpHandler {
|
||||
let tool_response =
|
||||
result.post_tool_use_response(&invocation.call_id, &invocation.payload)?;
|
||||
Some(PostToolUsePayload {
|
||||
tool_name: HookToolName::new(invocation.tool_name.display()),
|
||||
tool_name: HookToolName::for_function_tool(&invocation.tool_name),
|
||||
tool_use_id: invocation.call_id.clone(),
|
||||
tool_input: result.tool_input.clone(),
|
||||
tool_response,
|
||||
@@ -78,6 +78,7 @@ impl ToolHandler for McpHandler {
|
||||
|
||||
let (server, tool, raw_arguments) = payload;
|
||||
let arguments_str = raw_arguments;
|
||||
let hook_tool_name = HookToolName::for_function_tool(&model_tool_name);
|
||||
|
||||
let started = Instant::now();
|
||||
let result = handle_mcp_tool_call(
|
||||
@@ -86,7 +87,7 @@ impl ToolHandler for McpHandler {
|
||||
call_id.clone(),
|
||||
server,
|
||||
tool,
|
||||
model_tool_name.display(),
|
||||
hook_tool_name,
|
||||
arguments_str,
|
||||
)
|
||||
.await;
|
||||
@@ -147,7 +148,10 @@ mod tests {
|
||||
payload,
|
||||
}),
|
||||
Some(PreToolUsePayload {
|
||||
tool_name: HookToolName::new("mcp__memory__create_entities"),
|
||||
tool_name: HookToolName::for_function_tool(&codex_tools::ToolName::namespaced(
|
||||
"mcp__memory__",
|
||||
"create_entities",
|
||||
)),
|
||||
tool_input: json!({
|
||||
"entities": [{
|
||||
"name": "Ada",
|
||||
@@ -198,7 +202,10 @@ mod tests {
|
||||
assert_eq!(
|
||||
McpHandler.post_tool_use_payload(&invocation, &output),
|
||||
Some(PostToolUsePayload {
|
||||
tool_name: HookToolName::new("mcp__filesystem__read_file"),
|
||||
tool_name: HookToolName::for_function_tool(&codex_tools::ToolName::namespaced(
|
||||
"mcp__filesystem__",
|
||||
"read_file",
|
||||
)),
|
||||
tool_use_id: "call-mcp-post".to_string(),
|
||||
tool_input: json!({
|
||||
"path": {
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
//! concepts together prevents handlers from accidentally serializing a
|
||||
//! compatibility alias, such as `Write`, as the stable hook payload name.
|
||||
|
||||
use codex_tools::ToolName;
|
||||
|
||||
/// Identifies a tool in hook payloads and hook matcher selection.
|
||||
///
|
||||
/// `name` is the canonical value serialized into hook stdin. Matcher aliases are
|
||||
@@ -25,6 +27,21 @@ impl HookToolName {
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the canonical hook-facing identity for function-style tools that
|
||||
/// do not need Claude-compatibility aliases.
|
||||
///
|
||||
/// MCP tool names already use a stable fully qualified `mcp__...__tool`
|
||||
/// form, so we preserve them verbatim. Other namespaced tools use the
|
||||
/// `dynamic__namespace__tool` form so hooks can wildcard an entire dynamic
|
||||
/// namespace without colliding with plain tool names.
|
||||
pub(crate) fn for_function_tool(tool_name: &ToolName) -> Self {
|
||||
match tool_name.namespace.as_deref() {
|
||||
Some(namespace) if namespace.starts_with("mcp__") => Self::new(tool_name.display()),
|
||||
Some(namespace) => Self::new(format!("dynamic__{namespace}__{}", tool_name.name)),
|
||||
None => Self::new(tool_name.name.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the hook identity for file edits performed through `apply_patch`.
|
||||
///
|
||||
/// The serialized name remains `apply_patch` so logs and policies can key
|
||||
@@ -53,3 +70,40 @@ impl HookToolName {
|
||||
&self.matcher_aliases
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::HookToolName;
|
||||
use codex_tools::ToolName;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn for_function_tool_keeps_plain_tool_names() {
|
||||
assert_eq!(
|
||||
HookToolName::for_function_tool(&ToolName::plain("tool_search")),
|
||||
HookToolName::new("tool_search"),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn for_function_tool_keeps_mcp_names_stable() {
|
||||
assert_eq!(
|
||||
HookToolName::for_function_tool(&ToolName::namespaced(
|
||||
"mcp__memory__",
|
||||
"create_entities",
|
||||
)),
|
||||
HookToolName::new("mcp__memory__create_entities"),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn for_function_tool_prefixes_dynamic_namespaces() {
|
||||
assert_eq!(
|
||||
HookToolName::for_function_tool(&ToolName::namespaced(
|
||||
"codex_app",
|
||||
"automation_update",
|
||||
)),
|
||||
HookToolName::new("dynamic__codex_app__automation_update"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,10 +177,10 @@ impl Approvable<ApplyPatchRequest> for ApplyPatchRuntime {
|
||||
&self,
|
||||
req: &ApplyPatchRequest,
|
||||
) -> Option<PermissionRequestPayload> {
|
||||
Some(PermissionRequestPayload {
|
||||
tool_name: HookToolName::apply_patch(),
|
||||
tool_input: serde_json::json!({ "command": req.action.patch }),
|
||||
})
|
||||
Some(PermissionRequestPayload::new(
|
||||
HookToolName::apply_patch(),
|
||||
serde_json::json!({ "command": req.action.patch }),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -139,6 +139,13 @@ pub(crate) struct PermissionRequestPayload {
|
||||
}
|
||||
|
||||
impl PermissionRequestPayload {
|
||||
pub(crate) fn new(tool_name: HookToolName, tool_input: serde_json::Value) -> Self {
|
||||
Self {
|
||||
tool_name,
|
||||
tool_input,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn bash(command: String, description: Option<String>) -> Self {
|
||||
let mut tool_input = serde_json::Map::new();
|
||||
tool_input.insert("command".to_string(), serde_json::Value::String(command));
|
||||
@@ -149,10 +156,7 @@ impl PermissionRequestPayload {
|
||||
);
|
||||
}
|
||||
|
||||
Self {
|
||||
tool_name: HookToolName::bash(),
|
||||
tool_input: serde_json::Value::Object(tool_input),
|
||||
}
|
||||
Self::new(HookToolName::bash(), serde_json::Value::Object(tool_input))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user