Support direct Guardian review of recorded MCP calls (#59735)

## What changed

Extend `guardian_review` to assess recorded MCP tool calls using the current tool catalog, bindings, and approval policy without executing the call or remembering an approval. Return no assessment when policy or a remembered approval skips review, and reject tools blocked by app configuration.

## Testing

Add a scenario test that compares direct and live MCP review inputs, verifies that neither dispatches the tool, and checks that the current app approval policy can skip review.

GitOrigin-RevId: 05746dd0804a0f96d7946468701d5222171ff64f
This commit is contained in:
swastik-oai
2026-11-05 20:55:46 +00:00
committed by copyberry
parent c8a1109fa7
commit 3934ae926a
15 changed files with 588 additions and 111 deletions
+2 -2
View File
@@ -986,7 +986,7 @@ impl CodexThread {
Ok(())
}
/// Review the final injected exec, patch, or permission request without executing it.
/// Review the final injected tool call without executing it.
pub async fn guardian_review(
&self,
cancellation: &CancellationToken,
@@ -997,7 +997,7 @@ impl CodexThread {
let history = self.session.clone_history().await;
let tool_call = history.raw_items().next_back().cloned().ok_or_else(|| {
CodexErr::InvalidRequest(
"expected a final plaintext exec_command, apply_patch, or request_permissions call"
"expected a final plaintext exec_command, apply_patch, request_permissions, or MCP call"
.into(),
)
})?;
+108 -76
View File
@@ -1,4 +1,4 @@
//! Prepares a supplied exec, patch, or permission request for review against captured history.
//! Prepares a recorded tool call for review against captured history and current policy.
//! Preparation never executes the tool or grants permissions.
use std::sync::Arc;
@@ -20,6 +20,7 @@ use super::from_approval_action;
use super::review::ReviewInput;
use crate::context_manager::ContextManager;
use crate::guardian_review::GuardianReviewResult;
use crate::mcp_tool_call;
use crate::session::session::Session;
use crate::tools::context::ToolInvocation;
use crate::tools::context::ToolPayload;
@@ -42,7 +43,7 @@ pub(crate) async fn review_tool_call(
tool_call: &ResponseItem,
cancellation: &CancellationToken,
) -> Result<GuardianReviewResult> {
match tool_call {
let is_supported_builtin = match tool_call {
ResponseItem::FunctionCall {
call_id,
name,
@@ -50,11 +51,13 @@ pub(crate) async fn review_tool_call(
status,
encrypted_function_args,
..
} if matches!(name.as_str(), "exec_command" | "request_permissions")
&& encrypted_function_args.as_ref().is_none_or(Vec::is_empty)
&& ToolName::new(namespace.clone(), name).is_default_namespace()
} if encrypted_function_args.as_ref().is_none_or(Vec::is_empty)
&& !call_id.trim().is_empty()
&& matches!(status.as_deref(), None | Some("completed")) => {}
&& matches!(status.as_deref(), None | Some("completed")) =>
{
matches!(name.as_str(), "exec_command" | "request_permissions")
&& ToolName::new(namespace.clone(), name).is_default_namespace()
}
ResponseItem::CustomToolCall {
call_id,
name,
@@ -64,10 +67,13 @@ pub(crate) async fn review_tool_call(
} if name == "apply_patch"
&& ToolName::new(namespace.clone(), name).is_default_namespace()
&& !call_id.trim().is_empty()
&& matches!(status.as_deref(), None | Some("completed")) => {}
&& matches!(status.as_deref(), None | Some("completed")) =>
{
true
}
_ => {
return Err(CodexErr::InvalidRequest(
"expected a completed plaintext exec_command, apply_patch, or request_permissions call with a nonempty call ID".into(),
"expected a completed plaintext exec_command, apply_patch, request_permissions, or MCP call with a nonempty call ID".into(),
));
}
};
@@ -95,7 +101,8 @@ pub(crate) async fn review_tool_call(
.map_err(tool_error)?
.ok_or_else(|| {
CodexErr::InvalidRequest(
"expected an exec_command, apply_patch, or request_permissions call".into(),
"expected an exec_command, apply_patch, request_permissions, or MCP call"
.into(),
)
})?;
let tool = step
@@ -105,6 +112,12 @@ pub(crate) async fn review_tool_call(
.ok_or_else(|| {
CodexErr::InvalidRequest("the requested tool is unavailable on this thread".into())
})?;
let advertised_mcp_tool = tool.runtime.mcp_tool_info();
if !is_supported_builtin && advertised_mcp_tool.is_none() {
return Err(CodexErr::InvalidRequest(
"unsupported tool for direct review".into(),
));
}
let source = parsed_call.direct_source();
let mut invocation = ToolInvocation {
session: Arc::clone(session),
@@ -131,78 +144,97 @@ pub(crate) async fn review_tool_call(
PreToolUseError::Cancelled(_) => CodexErr::TurnAborted,
})?;
let step = &invocation.step_context;
let (requirement, action) = match (invocation.tool_name.name.as_str(), &invocation.payload)
{
("exec_command", ToolPayload::Function { arguments }) => {
let args: ToolEnvironmentArgs = parse_arguments(arguments).map_err(tool_error)?;
let environment =
resolve_tool_environment(&step.environments, args.environment_id.as_deref())
.map_err(tool_error)?;
let parsed = ParsedExecCommand::parse(arguments, session, step, environment)
.map_err(tool_error)?;
let lifetime = if step.turn.config.features.enabled(Feature::UnifiedExec) {
ExecCommandLifetime::Interactive
} else {
ExecCommandLifetime::OneShot
};
let prepared = parsed.prepare(lifetime).map_err(tool_error)?;
let fs = prepared.turn_environment.environment().get_filesystem();
if let Some(patch) = prepare_intercepted_patch(
&prepared.resolved.command,
&prepared.cwd,
fs.as_ref(),
&prepared.turn_environment,
step,
)
let (requirement, action) = if let Some(tool_info) = advertised_mcp_tool {
let prepared = mcp_tool_call::recorded::prepare_approval_action(&invocation, tool_info)
.await
.map_err(tool_error)?
{
let action = patch.approval_action(&invocation.call_id);
(Some(patch.exec_approval_requirement), action)
} else {
let requirement = prepared.approval_requirement(session, step).await;
let action = prepared.approval_action(&invocation.call_id, &requirement);
(Some(requirement), action)
}
}
("apply_patch", ToolPayload::Custom { input }) => {
let environment = selected_executor(&invocation.environments, &step.environments)
.map_err(tool_error)?;
let Some(action) = prepared else {
return Ok(GuardianReviewResult {
call_id: invocation.call_id,
assessment: None,
});
};
(None, action)
} else {
match (invocation.tool_name.name.as_str(), &invocation.payload) {
("exec_command", ToolPayload::Function { arguments }) => {
let args: ToolEnvironmentArgs =
parse_arguments(arguments).map_err(tool_error)?;
let environment = resolve_tool_environment(
&step.environments,
args.environment_id.as_deref(),
)
.map_err(tool_error)?;
let prepared = prepare_patch_request(input, environment, step)
let parsed = ParsedExecCommand::parse(arguments, session, step, environment)
.map_err(tool_error)?;
let lifetime = if step.turn.config.features.enabled(Feature::UnifiedExec) {
ExecCommandLifetime::Interactive
} else {
ExecCommandLifetime::OneShot
};
let prepared = parsed.prepare(lifetime).map_err(tool_error)?;
let fs = prepared.turn_environment.environment().get_filesystem();
if let Some(patch) = prepare_intercepted_patch(
&prepared.resolved.command,
&prepared.cwd,
fs.as_ref(),
&prepared.turn_environment,
step,
)
.await
.map_err(tool_error)?;
let action = prepared.approval_action(&invocation.call_id);
(Some(prepared.exec_approval_requirement), action)
}
("request_permissions", ToolPayload::Function { arguments }) => {
let environment = selected_executor(&invocation.environments, &step.environments)
.map_err(tool_error)?;
let prepared =
PreparedPermissionRequest::parse(arguments, environment).map_err(tool_error)?;
match step.settings.approval_policy() {
AskForApproval::Never => {
return Ok(GuardianReviewResult {
call_id: invocation.call_id,
assessment: None,
});
.map_err(tool_error)?
{
let action = patch.approval_action(&invocation.call_id);
(Some(patch.exec_approval_requirement), action)
} else {
let requirement = prepared.approval_requirement(session, step).await;
let action = prepared.approval_action(&invocation.call_id, &requirement);
(Some(requirement), action)
}
AskForApproval::Granular(policy) if !policy.allows_request_permissions() => {
return Ok(GuardianReviewResult {
call_id: invocation.call_id,
assessment: None,
});
}
AskForApproval::OnRequest
| AskForApproval::UnlessTrusted
| AskForApproval::Granular(_) => {}
}
let action = prepared.approval_action(&invocation.call_id, &step.turn.sub_id);
(None, action)
}
_ => {
return Err(CodexErr::Fatal(
"unsupported tool or payload for direct review".into(),
));
("apply_patch", ToolPayload::Custom { input }) => {
let environment =
selected_executor(&invocation.environments, &step.environments)
.map_err(tool_error)?;
let prepared = prepare_patch_request(input, environment, step)
.await
.map_err(tool_error)?;
let action = prepared.approval_action(&invocation.call_id);
(Some(prepared.exec_approval_requirement), action)
}
("request_permissions", ToolPayload::Function { arguments }) => {
let environment =
selected_executor(&invocation.environments, &step.environments)
.map_err(tool_error)?;
let prepared = PreparedPermissionRequest::parse(arguments, environment)
.map_err(tool_error)?;
match step.settings.approval_policy() {
AskForApproval::Never => {
return Ok(GuardianReviewResult {
call_id: invocation.call_id,
assessment: None,
});
}
AskForApproval::Granular(policy)
if !policy.allows_request_permissions() =>
{
return Ok(GuardianReviewResult {
call_id: invocation.call_id,
assessment: None,
});
}
AskForApproval::OnRequest
| AskForApproval::UnlessTrusted
| AskForApproval::Granular(_) => {}
}
let action = prepared.approval_action(&invocation.call_id, &step.turn.sub_id);
(None, action)
}
_ => {
return Err(CodexErr::Fatal(
"unsupported tool or payload for direct review".into(),
));
}
}
};
let approval = match &requirement {
+1 -1
View File
@@ -11,6 +11,6 @@ pub use crate::mcp_tool_call::conversation_history::conversation_history_tools;
#[derive(Debug, PartialEq, Eq)]
pub struct GuardianReviewResult {
pub call_id: String,
/// Absent when exec policy skips approval.
/// Absent when current policy or a remembered approval skips review.
pub assessment: Option<codex_guardian_reviewer::GuardianAssessment>,
}
+2
View File
@@ -1,3 +1,5 @@
pub(crate) mod recorded;
use std::collections::HashMap;
use std::time::Duration;
use std::time::Instant;
@@ -0,0 +1,70 @@
//! Prepares MCP approval actions using current bindings without dispatching or remembering approval.
use codex_mcp::ToolInfo;
use codex_protocol::protocol::McpInvocation;
use codex_tools::FunctionCallError;
use super::McpToolApprovalRequirement;
use super::mcp_tool_approval_policy;
use super::mcp_tool_metadata;
use super::parse_mcp_tool_arguments;
use super::prepare_mcp_tool_approval;
use crate::tools::context::ToolInvocation;
use crate::tools::context::ToolPayload;
use crate::tools::handlers::McpHandler;
use crate::tools::sandboxing::ApprovalAction;
pub(crate) async fn prepare_approval_action(
invocation: &ToolInvocation,
advertised_tool: &ToolInfo,
) -> Result<Option<ApprovalAction>, FunctionCallError> {
let ToolPayload::Function { arguments } = &invocation.payload else {
return Err(FunctionCallError::RespondToModel(
"mcp handler received unsupported payload".into(),
));
};
let arguments = parse_mcp_tool_arguments(arguments)
.map_err(|error| FunctionCallError::RespondToModel(error.to_string()))?;
let call = invocation
.session
.prepare_mcp_call(advertised_tool)
.await
.ok_or_else(|| {
FunctionCallError::RespondToModel(
"the requested MCP tool is unavailable on this thread".into(),
)
})?;
let mcp_invocation = McpInvocation {
server: advertised_tool.server_name.clone(),
tool: advertised_tool.tool.name.to_string(),
arguments,
};
let metadata = mcp_tool_metadata(
call.tool_info(),
call.plugin_id(),
mcp_invocation.arguments.as_ref(),
)
.map_err(|error| FunctionCallError::RespondToModel(error.to_string()))?;
let policy = mcp_tool_approval_policy(&call, &metadata).ok_or_else(|| {
FunctionCallError::RespondToModel("MCP tool call blocked by app configuration".into())
})?;
match prepare_mcp_tool_approval(
&invocation.session,
&invocation.step_context,
&invocation.call_id,
&mcp_invocation,
&McpHandler::hook_tool_name_for(advertised_tool),
&metadata,
call.config(),
call.permission_source(),
call.server_environment_id(),
policy,
)
.await
{
McpToolApprovalRequirement::NotRequired | McpToolApprovalRequirement::Remembered => {
Ok(None)
}
McpToolApprovalRequirement::Required { action, .. } => Ok(Some(*action)),
}
}
+8 -3
View File
@@ -137,7 +137,12 @@ impl McpHandler {
}
fn hook_tool_name(&self) -> HookToolName {
HookToolName::new(ensure_mcp_prefix(&join_tool_name(&self.tool_name())))
Self::hook_tool_name_for(self.tool_info())
}
pub(crate) fn hook_tool_name_for(tool_info: &ToolInfo) -> HookToolName {
let name = tool_info.canonical_tool_name();
HookToolName::new(ensure_mcp_prefix(&join_tool_name(&name)))
}
}
@@ -356,8 +361,8 @@ impl CoreToolRuntime for McpHandler {
true
}
fn mcp_server_name(&self) -> Option<&str> {
Some(&self.definition.tool_info.server_name)
fn mcp_tool_info(&self) -> Option<&ToolInfo> {
Some(self.tool_info())
}
fn on_tool_result_accepted(&self, invocation: &ToolInvocation, result: &dyn ToolOutput) {
+6 -1
View File
@@ -111,9 +111,14 @@ pub(crate) trait CoreToolRuntime: ToolExecutor<ToolInvocation> {
None
}
/// Returns the MCP tool advertised by this runtime.
fn mcp_tool_info(&self) -> Option<&codex_mcp::ToolInfo> {
None
}
/// Returns the owning server only for MCP-backed tool runtimes.
fn mcp_server_name(&self) -> Option<&str> {
None
self.mcp_tool_info().map(|tool| tool.server_name.as_str())
}
fn matches_kind(&self, payload: &ToolPayload) -> bool {