mirror of
https://github.com/openai/codex.git
synced 2026-11-24 23:20:47 +00:00
Support encrypted context from MCP session-start hooks (#63474)
## Why MCP hook results were flattened to text, so `SessionStart` hooks could not pass encrypted context to the model as encrypted tool output. ## What changed Recognize text blocks marked with `codex/encryptedContent` in synchronous MCP `SessionStart` hooks. Send them to the model as standalone `function_call_output` items with the originating tool name and namespace. Keep ciphertext out of hook previews and plaintext spill files. Reject empty encrypted blocks and cap the serialized encrypted output at 40,000 bytes per hook run. ## Testing Add a scenario that checks that ciphertext above the plaintext spill threshold reaches the first model request unchanged, appears once after a cold resume, and stays out of hook previews and spill files. Cover discarding encrypted context when hook output fails JSON parsing under both failure policies. GitOrigin-RevId: cbc11c6f7055cc131212c6e9ddd37a882ed61d38
This commit is contained in:
@@ -1,5 +1,4 @@
|
||||
use super::ContextualUserFragment;
|
||||
use codex_hooks::HookContext;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ContentItemKind;
|
||||
use codex_protocol::models::ContentItemMetadata;
|
||||
@@ -7,12 +6,13 @@ use codex_protocol::models::input_text;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub(crate) struct HookAdditionalContext {
|
||||
context: HookContext,
|
||||
text: String,
|
||||
metadata: ContentItemMetadata,
|
||||
}
|
||||
|
||||
impl HookAdditionalContext {
|
||||
pub(crate) fn new(context: HookContext) -> Self {
|
||||
Self { context }
|
||||
pub(crate) fn new(text: String, metadata: ContentItemMetadata) -> Self {
|
||||
Self { text, metadata }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,10 +34,10 @@ impl ContextualUserFragment for HookAdditionalContext {
|
||||
}
|
||||
|
||||
fn body(&self) -> ContentItem {
|
||||
input_text(self.context.text.clone())
|
||||
input_text(self.text.clone())
|
||||
}
|
||||
|
||||
fn content_metadata(&self) -> ContentItemMetadata {
|
||||
self.context.metadata.clone()
|
||||
self.metadata.clone()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ use std::sync::OnceLock;
|
||||
use std::sync::Weak;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::bail;
|
||||
use codex_hooks::HookMcpCall;
|
||||
use codex_hooks::HookMcpExecutor;
|
||||
use codex_hooks::HookMcpOutput;
|
||||
@@ -110,24 +109,8 @@ impl HookMcpExecutor for CoreHookMcpExecutor {
|
||||
)
|
||||
.await
|
||||
.context("MCP hook timed out")??;
|
||||
let result = call_result.result;
|
||||
let text = result
|
||||
.content
|
||||
.iter()
|
||||
.filter_map(|content| {
|
||||
(content.get("type").and_then(Value::as_str) == Some("text"))
|
||||
.then(|| content.get("text").and_then(Value::as_str))
|
||||
.flatten()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
if result.is_error == Some(true) {
|
||||
bail!("MCP tool returned an error: {text}");
|
||||
}
|
||||
|
||||
Ok(HookMcpOutput {
|
||||
structured_content: result.structured_content,
|
||||
text,
|
||||
result: call_result.result,
|
||||
source_tool_namespace: call_result.source_tool_namespace,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -833,7 +833,7 @@ pub(crate) async fn drain_async_hook_results(
|
||||
.iter()
|
||||
.filter(|entry| entry.kind == HookOutputEntryKind::Context)
|
||||
.map(|entry| codex_hooks::HookContext {
|
||||
text: entry.text.clone(),
|
||||
payload: codex_hooks::HookContextPayload::Text(entry.text.clone()),
|
||||
metadata: codex_protocol::models::ContentItemMetadata::command_hook(),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -914,8 +914,34 @@ fn additional_context_messages(
|
||||
) -> Vec<ResponseItem> {
|
||||
additional_contexts
|
||||
.into_iter()
|
||||
.map(HookAdditionalContext::new)
|
||||
.map(ContextualUserFragment::into)
|
||||
.map(|context| match context.payload {
|
||||
codex_hooks::HookContextPayload::Text(text) => {
|
||||
ContextualUserFragment::into(HookAdditionalContext::new(text, context.metadata))
|
||||
}
|
||||
codex_hooks::HookContextPayload::EncryptedToolOutput {
|
||||
name,
|
||||
namespace,
|
||||
encrypted_content,
|
||||
} => ResponseItem::FunctionCallOutput {
|
||||
id: None,
|
||||
call_id: None,
|
||||
name: Some(name),
|
||||
namespace,
|
||||
output: codex_protocol::models::FunctionCallOutputPayload::from_content_items(
|
||||
vec![
|
||||
codex_protocol::models::FunctionCallOutputContentItem::EncryptedContent {
|
||||
encrypted_content,
|
||||
},
|
||||
],
|
||||
),
|
||||
internal_chat_message_metadata_passthrough: Some(
|
||||
codex_protocol::models::InternalChatMessageMetadataPassthrough {
|
||||
content_item_metadata: Some(vec![context.metadata]),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
},
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -161,6 +161,9 @@ mod restored_history_prewarm;
|
||||
#[path = "scenarios_retained_tool_outputs.rs"]
|
||||
mod retained_tool_outputs;
|
||||
|
||||
#[path = "scenarios_encrypted_hooks.rs"]
|
||||
mod encrypted_hooks;
|
||||
|
||||
#[path = "scenarios_exec_tools.rs"]
|
||||
mod exec_tools;
|
||||
#[path = "scenarios_incremental_tools.rs"]
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
//! Encrypted SessionStart context reaches sampling and survives a cold resume unchanged.
|
||||
|
||||
use super::super::rmcp_client::remote_aware_environment_id;
|
||||
use super::super::rmcp_client::remote_aware_stdio_server_bin;
|
||||
use super::*;
|
||||
use core_test_support::hooks::trust_discovered_hooks;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn encrypted_session_start_context_survives_resume() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
skip_if_wine_exec!(
|
||||
Ok(()),
|
||||
"requires a Windows test_stdio_server in the Wine-exec environment"
|
||||
);
|
||||
let server = start_mock_server().await;
|
||||
let mock = mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
sse(vec![
|
||||
ev_assistant_message("first", "Context loaded."),
|
||||
ev_completed("first-response"),
|
||||
]),
|
||||
sse(vec![
|
||||
ev_assistant_message("resumed", "Context is still available."),
|
||||
ev_completed("resumed-response"),
|
||||
]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
// Larger than the normal 2,500-token plaintext spill threshold.
|
||||
let ciphertext = "sealed-memory-".repeat(1_000);
|
||||
let fixture_ciphertext = ciphertext.clone();
|
||||
let command = remote_aware_stdio_server_bin()?;
|
||||
let configure = move |config: &mut Config| {
|
||||
configure_scenario_catalog(config);
|
||||
trust_discovered_hooks(config);
|
||||
let mut servers = config.mcp_servers.get().clone();
|
||||
servers.insert(
|
||||
"memory".to_string(),
|
||||
serde_json::from_value::<McpServerConfig>(json!({
|
||||
"command": command,
|
||||
"env": { "MCP_TEST_ENCRYPTED_OUTPUT": fixture_ciphertext },
|
||||
"environment_id": remote_aware_environment_id(),
|
||||
"cwd": config.cwd.as_path(),
|
||||
"enabled_tools": ["encrypted_output"],
|
||||
}))
|
||||
.expect("valid memory MCP fixture"),
|
||||
);
|
||||
config.mcp_servers.set(servers).expect("test MCP servers");
|
||||
};
|
||||
let test = test_codex()
|
||||
.with_model("gpt-6-astra")
|
||||
.with_pre_build_hook(|home| {
|
||||
fs::write(
|
||||
home.join("hooks.json"),
|
||||
json!({"hooks": {"SessionStart": [{
|
||||
"matcher": "startup",
|
||||
"hooks": [{
|
||||
"type": "mcp_tool", "server": "memory", "tool": "encrypted_output",
|
||||
}],
|
||||
}]}})
|
||||
.to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
})
|
||||
.with_config(configure.clone())
|
||||
.build_with_auto_env(&server)
|
||||
.await?;
|
||||
test.codex
|
||||
.start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text {
|
||||
text: "Load the context.".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}]))
|
||||
.await?;
|
||||
let mut hook_entries = Vec::new();
|
||||
loop {
|
||||
let event = test.codex.next_event().await?;
|
||||
match event.msg {
|
||||
EventMsg::HookCompleted(completed) => hook_entries.extend(completed.run.entries),
|
||||
EventMsg::TurnComplete(_) => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
hook_entries,
|
||||
vec![codex_protocol::protocol::HookOutputEntry {
|
||||
kind: codex_protocol::protocol::HookOutputEntryKind::Context,
|
||||
text: "Lookup completed".to_string(),
|
||||
}]
|
||||
);
|
||||
assert!(
|
||||
!std::env::temp_dir()
|
||||
.join("hook_outputs")
|
||||
.join(test.session_configured.thread_id.to_string())
|
||||
.exists()
|
||||
);
|
||||
|
||||
let resumed = test_codex()
|
||||
.with_model("gpt-6-astra")
|
||||
.with_config(configure)
|
||||
.restart_with_auto_env(&server, &test)
|
||||
.await?;
|
||||
resumed.submit_text_turn("Use the context again.").await?;
|
||||
let requests = mock.requests();
|
||||
assert_eq!(requests.len(), 2);
|
||||
for request in &requests {
|
||||
let items = request.input();
|
||||
let memory = items
|
||||
.iter()
|
||||
.position(|item| {
|
||||
item["type"] == "function_call_output" && item["name"] == "encrypted_output"
|
||||
})
|
||||
.expect("standalone encrypted MCP output");
|
||||
let user = items
|
||||
.iter()
|
||||
.position(|item| {
|
||||
item["role"] == "user" && item["content"][0]["text"] == "Load the context."
|
||||
})
|
||||
.expect("first user message");
|
||||
assert!(memory < user);
|
||||
assert_eq!(items[memory].get("call_id"), None);
|
||||
assert_eq!(items[memory]["namespace"], "mcp__memory");
|
||||
assert_eq!(
|
||||
items[memory]["output"],
|
||||
json!([{"type": "encrypted_content", "encrypted_content": ciphertext}]),
|
||||
);
|
||||
assert_eq!(
|
||||
items[memory]["internal_chat_message_metadata_passthrough"]["content_item_metadata"],
|
||||
json!([codex_protocol::models::ContentItemMetadata::tool(Some(
|
||||
"mcp__memory".to_string().into()
|
||||
))])
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_string(&items)?.matches(&ciphertext).count(),
|
||||
1
|
||||
);
|
||||
}
|
||||
insta::assert_snapshot!(
|
||||
"encrypted_session_start_context",
|
||||
context_snapshot::format_request_history_snapshot(
|
||||
"A synchronous MCP SessionStart hook returns a public status and marked memory. The status appears in the hook preview, and the named encrypted tool output reaches sampling before the user message and survives a cold resume.",
|
||||
&requests,
|
||||
&ContextSnapshotOptions::default().rewrite_known_segments(),
|
||||
)
|
||||
);
|
||||
resumed.codex.shutdown_and_wait().await?;
|
||||
Ok(())
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
---
|
||||
source: core/tests/suite/scenarios_encrypted_hooks.rs
|
||||
expression: "context_snapshot::format_request_history_snapshot(\"A synchronous MCP SessionStart hook returns a public status and marked memory. The status appears in the hook preview, and the named encrypted tool output reaches sampling before the user message and survives a cold resume.\",\n&requests, &ContextSnapshotOptions::default().rewrite_known_segments(),)"
|
||||
---
|
||||
Scenario: A synchronous MCP SessionStart hook returns a public status and marked memory. The status appears in the hook preview, and the named encrypted tool output reaches sampling before the user message and survives a cold resume.
|
||||
|
||||
## Window 1
|
||||
-- request 1 (turn) --
|
||||
00:additional_tools/developer (3; hash=a7c46a0959d54866):
|
||||
- namespace/functions; hash=81846de5bc4e7474
|
||||
- custom/exec
|
||||
- function/wait
|
||||
- function/request_user_input
|
||||
- function/request_user_input_async
|
||||
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
|
||||
- function/sleep
|
||||
- namespace/collaboration: Tools for spawning and managing sub-agents.; hash=a097b9364047b8bb
|
||||
- function/followup_task
|
||||
- function/interrupt_agent
|
||||
- function/list_agents
|
||||
- function/send_message
|
||||
- function/spawn_agent
|
||||
- function/wait_agent
|
||||
01:message/developer:
|
||||
<MODEL_INSTRUCTIONS>
|
||||
02:message/developer[2]:
|
||||
[01] <PERMISSIONS_INSTRUCTIONS>
|
||||
[02] <tools>
|
||||
Deferred tool namespaces:
|
||||
- mcp__memory: Use these tools to exercise the rmcp test server.
|
||||
</tools>
|
||||
03:message/developer:
|
||||
<MULTI_AGENT_ROLE>
|
||||
04:message/developer:
|
||||
<MULTI_AGENT_MODE>
|
||||
05:message/user:
|
||||
<ENVIRONMENT_CONTEXT>
|
||||
06:message/developer:
|
||||
Lookup completed
|
||||
07:function_call_output/mcp__memory.encrypted_output:<encrypted_content>
|
||||
08:message/user:
|
||||
Load the context.
|
||||
09:configuration_update:reasoning={"effort":"low"}
|
||||
-- request 2 (turn) --
|
||||
10:message/assistant:
|
||||
Context loaded.
|
||||
11:message/user:
|
||||
<ENVIRONMENT_CONTEXT>
|
||||
12:message/user:
|
||||
Use the context again.
|
||||
13:configuration_update:reasoning={"effort":"low"}
|
||||
@@ -1,17 +1,29 @@
|
||||
//! Model-visible hook context, attributed by the executor that produced it.
|
||||
//! Model-visible hook context. Plain text retains its source attribution, while
|
||||
//! encrypted MCP output retains the exact tool identity needed for tool-output admission.
|
||||
|
||||
use codex_protocol::models::ContentItemMetadata;
|
||||
|
||||
/// The model-visible payload produced by a hook.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum HookContextPayload {
|
||||
Text(String),
|
||||
EncryptedToolOutput {
|
||||
name: String,
|
||||
namespace: Option<String>,
|
||||
encrypted_content: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct HookContext {
|
||||
pub text: String,
|
||||
pub payload: HookContextPayload,
|
||||
pub metadata: ContentItemMetadata,
|
||||
}
|
||||
|
||||
impl HookContext {
|
||||
pub fn harness(text: String) -> Self {
|
||||
Self {
|
||||
text,
|
||||
payload: HookContextPayload::Text(text),
|
||||
metadata: ContentItemMetadata::harness(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -268,6 +268,7 @@ pub(crate) async fn run_command(
|
||||
Err(error) => (None, String::new(), String::new(), Some(error.to_string())),
|
||||
};
|
||||
return HandlerRunResult {
|
||||
encrypted_context: Vec::new(),
|
||||
structured_content: None,
|
||||
context_metadata: codex_protocol::models::ContentItemMetadata::command_hook(),
|
||||
started_at,
|
||||
@@ -433,6 +434,7 @@ fn finish_command_run(
|
||||
) -> HandlerRunResult {
|
||||
Span::current().record("hook.command_outcome", completion.outcome);
|
||||
HandlerRunResult {
|
||||
encrypted_context: Vec::new(),
|
||||
structured_content: None,
|
||||
context_metadata: codex_protocol::models::ContentItemMetadata::command_hook(),
|
||||
started_at,
|
||||
|
||||
@@ -38,8 +38,12 @@ impl HookMcpExecutor for McpResult {
|
||||
async move {
|
||||
match self.0 {
|
||||
Ok(text) => Ok(HookMcpOutput {
|
||||
text: text.to_string(),
|
||||
structured_content: None,
|
||||
result: codex_protocol::mcp::CallToolResult {
|
||||
content: vec![json!({"type": "text", "text": text})],
|
||||
structured_content: None,
|
||||
meta: None,
|
||||
is_error: None,
|
||||
},
|
||||
source_tool_namespace: None,
|
||||
}),
|
||||
Err(error) => anyhow::bail!(error),
|
||||
|
||||
@@ -6,6 +6,9 @@ use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use codex_protocol::mcp::is_node_repl_backed_server;
|
||||
use codex_protocol::models::ContentItemMetadata;
|
||||
use codex_protocol::models::FunctionCallOutputContentItem;
|
||||
use codex_protocol::protocol::HookEventName;
|
||||
use codex_protocol::protocol::HookExecutionMode;
|
||||
use regex::Regex;
|
||||
use serde_json::Map;
|
||||
use serde_json::Value;
|
||||
@@ -17,6 +20,9 @@ use super::HandlerSourcePath;
|
||||
use crate::mcp::HookMcpCall;
|
||||
use crate::mcp::HookMcpExecutor;
|
||||
|
||||
// The memory producer bounds the decrypted tokens. The runner can only bound the ciphertext.
|
||||
const MAX_ENCRYPTED_CONTEXT_BYTES: usize = 40_000;
|
||||
|
||||
/// Expands an MCP argument template against this hook event and invokes the configured tool.
|
||||
#[tracing::instrument(
|
||||
name = "codex.hooks.mcp_tool",
|
||||
@@ -73,7 +79,7 @@ pub(crate) async fn run_mcp_tool(
|
||||
.get_or_insert_with(Map::new)
|
||||
.extend(metadata.clone());
|
||||
}
|
||||
executor
|
||||
let output = executor
|
||||
.execute(HookMcpCall {
|
||||
skip_dormant_repl_cleanup: handler.builtin
|
||||
&& is_node_repl_backed_server(server)
|
||||
@@ -96,21 +102,78 @@ pub(crate) async fn run_mcp_tool(
|
||||
Duration::from_secs(handler.timeout_sec)
|
||||
},
|
||||
})
|
||||
.await
|
||||
.await?;
|
||||
let mut plaintext = Vec::new();
|
||||
let mut encrypted_context = Vec::new();
|
||||
let mut encrypted_bytes = 0;
|
||||
for block in &output.result.content {
|
||||
if block.get("type").and_then(Value::as_str) != Some("text") {
|
||||
continue;
|
||||
}
|
||||
let Some(text) = block.get("text").and_then(Value::as_str) else {
|
||||
continue;
|
||||
};
|
||||
if handler.event_name == HookEventName::SessionStart
|
||||
&& let Ok(part @ FunctionCallOutputContentItem::EncryptedContent { .. }) =
|
||||
FunctionCallOutputContentItem::from_mcp_content_block(block)
|
||||
{
|
||||
anyhow::ensure!(
|
||||
handler.execution_mode() == HookExecutionMode::Sync,
|
||||
"encrypted SessionStart context requires a synchronous MCP hook"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
!text.is_empty() && text.len() <= MAX_ENCRYPTED_CONTEXT_BYTES,
|
||||
"invalid encrypted SessionStart context size"
|
||||
);
|
||||
encrypted_bytes += serde_json::to_vec(&part)?.len();
|
||||
anyhow::ensure!(
|
||||
encrypted_bytes <= MAX_ENCRYPTED_CONTEXT_BYTES,
|
||||
"encrypted SessionStart context exceeds 40,000 bytes"
|
||||
);
|
||||
encrypted_context.push(crate::HookContextPayload::EncryptedToolOutput {
|
||||
name: tool.to_owned(),
|
||||
namespace: output.source_tool_namespace.clone(),
|
||||
encrypted_content: text.to_owned(),
|
||||
});
|
||||
} else {
|
||||
plaintext.push(text);
|
||||
}
|
||||
}
|
||||
let stdout = plaintext.join("\n");
|
||||
anyhow::ensure!(
|
||||
output.result.is_error != Some(true),
|
||||
"MCP tool returned an error: {stdout}"
|
||||
);
|
||||
Ok((
|
||||
stdout,
|
||||
encrypted_context,
|
||||
output.source_tool_namespace,
|
||||
output.result.structured_content,
|
||||
))
|
||||
}
|
||||
.await;
|
||||
|
||||
let (exit_code, stdout, error, source_tool_namespace, structured_content) = match result {
|
||||
Ok(output) => (
|
||||
Some(0),
|
||||
output.text,
|
||||
None,
|
||||
output.source_tool_namespace,
|
||||
output.structured_content,
|
||||
),
|
||||
Err(error) => (None, String::new(), Some(error.to_string()), None, None),
|
||||
};
|
||||
let (exit_code, stdout, encrypted_context, error, source_tool_namespace, structured_content) =
|
||||
match result {
|
||||
Ok((stdout, context, namespace, structured_content)) => (
|
||||
Some(0),
|
||||
stdout,
|
||||
context,
|
||||
None,
|
||||
namespace,
|
||||
structured_content,
|
||||
),
|
||||
Err(error) => (
|
||||
None,
|
||||
String::new(),
|
||||
Vec::new(),
|
||||
Some(error.to_string()),
|
||||
None,
|
||||
None,
|
||||
),
|
||||
};
|
||||
HandlerRunResult {
|
||||
encrypted_context,
|
||||
structured_content,
|
||||
context_metadata: ContentItemMetadata::tool(source_tool_namespace.map(Into::into)),
|
||||
started_at,
|
||||
|
||||
@@ -31,8 +31,12 @@ impl HookMcpExecutor for RecordingExecutor {
|
||||
async move {
|
||||
self.calls.lock().expect("lock calls").push(call);
|
||||
Ok(HookMcpOutput {
|
||||
structured_content: None,
|
||||
text: self.output.clone(),
|
||||
result: codex_protocol::mcp::CallToolResult {
|
||||
content: vec![serde_json::json!({"type":"text","text":self.output.clone()})],
|
||||
structured_content: None,
|
||||
meta: None,
|
||||
is_error: None,
|
||||
},
|
||||
source_tool_namespace: Some("security".into()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -164,6 +164,7 @@ pub(crate) enum ConfiguredHandlerKind {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct HandlerRunResult {
|
||||
pub encrypted_context: Vec<crate::HookContextPayload>,
|
||||
pub structured_content: Option<serde_json::Value>,
|
||||
pub context_metadata: codex_protocol::models::ContentItemMetadata,
|
||||
pub started_at: i64,
|
||||
|
||||
@@ -2376,8 +2376,12 @@ impl HookMcpExecutor for StaticMcpExecutor {
|
||||
.clone();
|
||||
self.calls.lock().expect("lock MCP calls").push(call);
|
||||
Ok(HookMcpOutput {
|
||||
text: output,
|
||||
structured_content: None,
|
||||
result: codex_protocol::mcp::CallToolResult {
|
||||
content: vec![serde_json::json!({"type":"text","text":output})],
|
||||
structured_content: None,
|
||||
meta: None,
|
||||
is_error: None,
|
||||
},
|
||||
source_tool_namespace: None,
|
||||
})
|
||||
}
|
||||
@@ -2924,8 +2928,12 @@ async fn executor_stop_hooks_do_not_delay_stop_completion() {
|
||||
self.started.notify_one();
|
||||
self.release.notified().await;
|
||||
Ok(HookMcpOutput {
|
||||
text: String::new(),
|
||||
structured_content: None,
|
||||
result: codex_protocol::mcp::CallToolResult {
|
||||
content: vec![serde_json::json!({"type":"text","text":String::new()})],
|
||||
structured_content: None,
|
||||
meta: None,
|
||||
is_error: None,
|
||||
},
|
||||
source_tool_namespace: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ pub(crate) fn append_additional_context(
|
||||
});
|
||||
additional_contexts_for_model.push(AdditionalContext {
|
||||
context: crate::HookContext {
|
||||
text: additional_context,
|
||||
payload: crate::HookContextPayload::Text(additional_context),
|
||||
metadata: metadata.clone(),
|
||||
},
|
||||
limit: handler.additional_context_limit,
|
||||
|
||||
@@ -550,6 +550,7 @@ mod tests {
|
||||
|
||||
fn run_result(exit_code: Option<i32>, stdout: &str, stderr: &str) -> HandlerRunResult {
|
||||
HandlerRunResult {
|
||||
encrypted_context: Vec::new(),
|
||||
structured_content: None,
|
||||
context_metadata: codex_protocol::models::ContentItemMetadata::harness(),
|
||||
started_at: 1_700_000_000,
|
||||
|
||||
@@ -119,6 +119,7 @@ fn handler() -> ConfiguredHandler {
|
||||
|
||||
fn run_result(exit_code: Option<i32>, stdout: &str, stderr: &str) -> HandlerRunResult {
|
||||
HandlerRunResult {
|
||||
encrypted_context: Vec::new(),
|
||||
structured_content: None,
|
||||
context_metadata: codex_protocol::models::ContentItemMetadata::harness(),
|
||||
started_at: 1,
|
||||
|
||||
@@ -637,6 +637,7 @@ mod tests {
|
||||
|
||||
fn run_result(exit_code: Option<i32>, stdout: &str, stderr: &str) -> HandlerRunResult {
|
||||
HandlerRunResult {
|
||||
encrypted_context: Vec::new(),
|
||||
structured_content: None,
|
||||
context_metadata: codex_protocol::models::ContentItemMetadata::harness(),
|
||||
started_at: 1_700_000_000,
|
||||
|
||||
@@ -840,6 +840,7 @@ mod tests {
|
||||
|
||||
fn run_result(exit_code: Option<i32>, stdout: &str, stderr: &str) -> HandlerRunResult {
|
||||
HandlerRunResult {
|
||||
encrypted_context: Vec::new(),
|
||||
structured_content: None,
|
||||
context_metadata: codex_protocol::models::ContentItemMetadata::harness(),
|
||||
started_at: 1,
|
||||
|
||||
@@ -43,6 +43,7 @@ fn session_end_ignores_successful_output() {
|
||||
let completed = parse_completed(
|
||||
&handler(/*matcher*/ None),
|
||||
HandlerRunResult {
|
||||
encrypted_context: Vec::new(),
|
||||
structured_content: None,
|
||||
context_metadata: codex_protocol::models::ContentItemMetadata::harness(),
|
||||
started_at: 1,
|
||||
|
||||
@@ -223,7 +223,7 @@ pub(crate) async fn run(
|
||||
/// `continue:false`; `SubagentStart` stays context-injection-only.
|
||||
fn parse_completed(
|
||||
handler: &ConfiguredHandler,
|
||||
run_result: HandlerRunResult,
|
||||
mut run_result: HandlerRunResult,
|
||||
turn_id: Option<String>,
|
||||
) -> dispatcher::ParsedHandler<SessionStartHandlerData> {
|
||||
let mut entries = Vec::new();
|
||||
@@ -330,6 +330,18 @@ fn parse_completed(
|
||||
},
|
||||
}
|
||||
|
||||
if status != HookRunStatus::Failed {
|
||||
additional_contexts_for_model.extend(run_result.encrypted_context.drain(..).map(
|
||||
|payload| AdditionalContext {
|
||||
context: crate::HookContext {
|
||||
payload,
|
||||
metadata: run_result.context_metadata.clone(),
|
||||
},
|
||||
limit: handler.additional_context_limit,
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(reason) = common::apply_failure_policy(handler, &mut status, &mut entries) {
|
||||
should_stop = true;
|
||||
stop_reason = Some(reason);
|
||||
@@ -363,6 +375,7 @@ fn serialization_failure_outcome(hook_events: Vec<HookCompletedEvent>) -> Sessio
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use codex_config::HookFailurePolicy;
|
||||
use codex_protocol::protocol::HookEventName;
|
||||
use codex_protocol::protocol::HookOutputEntry;
|
||||
use codex_protocol::protocol::HookOutputEntryKind;
|
||||
@@ -450,32 +463,49 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn invalid_json_like_stdout_fails_instead_of_becoming_model_context() {
|
||||
let parsed = parse_completed(
|
||||
&handler(),
|
||||
run_result(
|
||||
for (on_failure, expected_status, stop_reason) in [
|
||||
(HookFailurePolicy::Continue, HookRunStatus::Failed, None),
|
||||
(
|
||||
HookFailurePolicy::Block,
|
||||
HookRunStatus::Blocked,
|
||||
Some("SessionStart hook failed. This hook is configured to block continuation on failure.".to_string()),
|
||||
),
|
||||
] {
|
||||
let mut handler = handler();
|
||||
handler.on_failure = on_failure;
|
||||
let mut result = run_result(
|
||||
Some(0),
|
||||
r#"{"hookSpecificOutput":{"hookEventName":"SessionStart""#,
|
||||
"",
|
||||
),
|
||||
/*turn_id*/ None,
|
||||
);
|
||||
);
|
||||
result.encrypted_context.push(crate::HookContextPayload::EncryptedToolOutput {
|
||||
name: "encrypted_output".to_string(),
|
||||
namespace: Some("mcp__memory".to_string()),
|
||||
encrypted_content: "sealed-memory".to_string(),
|
||||
});
|
||||
let parsed = parse_completed(&handler, result, /*turn_id*/ None);
|
||||
|
||||
assert_eq!(
|
||||
parsed.data,
|
||||
SessionStartHandlerData {
|
||||
should_stop: false,
|
||||
stop_reason: None,
|
||||
additional_contexts_for_model: Vec::new(),
|
||||
}
|
||||
);
|
||||
assert_eq!(parsed.completed.run.status, HookRunStatus::Failed);
|
||||
assert_eq!(
|
||||
parsed.completed.run.entries,
|
||||
vec![HookOutputEntry {
|
||||
let mut entries = vec![HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Error,
|
||||
text: "hook returned invalid session start JSON output".to_string(),
|
||||
}]
|
||||
);
|
||||
}];
|
||||
if let Some(reason) = &stop_reason {
|
||||
entries.push(HookOutputEntry {
|
||||
kind: HookOutputEntryKind::Feedback,
|
||||
text: reason.clone(),
|
||||
});
|
||||
}
|
||||
assert_eq!(
|
||||
parsed.data,
|
||||
SessionStartHandlerData {
|
||||
should_stop: stop_reason.is_some(),
|
||||
stop_reason,
|
||||
additional_contexts_for_model: Vec::new(),
|
||||
}
|
||||
);
|
||||
assert_eq!(parsed.completed.run.status, expected_status);
|
||||
assert_eq!(parsed.completed.run.entries, entries);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -571,6 +601,7 @@ mod tests {
|
||||
|
||||
fn run_result(exit_code: Option<i32>, stdout: &str, stderr: &str) -> HandlerRunResult {
|
||||
HandlerRunResult {
|
||||
encrypted_context: Vec::new(),
|
||||
structured_content: None,
|
||||
context_metadata: codex_protocol::models::ContentItemMetadata::harness(),
|
||||
started_at: 1,
|
||||
|
||||
@@ -722,6 +722,7 @@ mod tests {
|
||||
|
||||
fn run_result(exit_code: Option<i32>, stdout: &str, stderr: &str) -> HandlerRunResult {
|
||||
HandlerRunResult {
|
||||
encrypted_context: Vec::new(),
|
||||
structured_content: None,
|
||||
context_metadata: codex_protocol::models::ContentItemMetadata::harness(),
|
||||
started_at: 1,
|
||||
|
||||
@@ -490,6 +490,7 @@ mod tests {
|
||||
|
||||
fn run_result(exit_code: Option<i32>, stdout: &str, stderr: &str) -> HandlerRunResult {
|
||||
HandlerRunResult {
|
||||
encrypted_context: Vec::new(),
|
||||
structured_content: None,
|
||||
context_metadata: codex_protocol::models::ContentItemMetadata::harness(),
|
||||
started_at: 1,
|
||||
|
||||
@@ -61,6 +61,7 @@ pub const HOOK_EVENT_NAMES_WITH_MATCHERS: [&str; 9] = [
|
||||
];
|
||||
|
||||
pub use context::HookContext;
|
||||
pub use context::HookContextPayload;
|
||||
pub use events::compact::PostCompactRequest;
|
||||
pub use events::compact::PreCompactOutcome;
|
||||
pub use events::compact::PreCompactRequest;
|
||||
|
||||
@@ -19,10 +19,9 @@ pub struct HookMcpCall {
|
||||
pub timeout: Duration,
|
||||
}
|
||||
|
||||
/// The MCP hook's text, structured result, and originating callable namespace.
|
||||
/// The original response returned by an MCP hook and the callable namespace that supplied it.
|
||||
pub struct HookMcpOutput {
|
||||
pub text: String,
|
||||
pub structured_content: Option<serde_json::Value>,
|
||||
pub result: codex_protocol::mcp::CallToolResult,
|
||||
pub source_tool_namespace: Option<String>,
|
||||
}
|
||||
|
||||
@@ -30,6 +29,6 @@ pub struct HookMcpOutput {
|
||||
///
|
||||
/// Implementations own server readiness, policy enforcement, timeout handling, and elicitation.
|
||||
pub trait HookMcpExecutor: Send + Sync {
|
||||
/// Returns text that is interpreted using ordinary command-hook output semantics.
|
||||
/// Preserves MCP content metadata so the hook runner can interpret the result.
|
||||
fn execute(&self, call: HookMcpCall) -> BoxFuture<'_, anyhow::Result<HookMcpOutput>>;
|
||||
}
|
||||
|
||||
@@ -97,7 +97,11 @@ impl HookOutputSpiller {
|
||||
) -> Vec<HookContext> {
|
||||
let mut spilled = Vec::with_capacity(contexts.len());
|
||||
for AdditionalContext { mut context, limit } in contexts {
|
||||
context.text = self.maybe_spill_text_with_limit(context.text, limit).await;
|
||||
if let crate::HookContextPayload::Text(text) = &mut context.payload {
|
||||
*text = self
|
||||
.maybe_spill_text_with_limit(std::mem::take(text), limit)
|
||||
.await;
|
||||
}
|
||||
spilled.push(context);
|
||||
}
|
||||
spilled
|
||||
|
||||
@@ -76,8 +76,11 @@ async fn additional_contexts_apply_limits_individually() -> Result<()> {
|
||||
let [limited_output, zero_limit_output, high_limit_output] = output.as_slice() else {
|
||||
panic!("expected one output for each additional context");
|
||||
};
|
||||
assert!(limited_output.text.contains("Full hook output saved to:"));
|
||||
assert_eq!(&zero_limit_output.text, &unlimited_text);
|
||||
assert_eq!(&high_limit_output.text, &unlimited_text);
|
||||
assert!(
|
||||
matches!(&limited_output.payload, crate::HookContextPayload::Text(text) if text.contains("Full hook output saved to:"))
|
||||
);
|
||||
let expected = crate::HookContext::harness(unlimited_text);
|
||||
assert_eq!(zero_limit_output, &expected);
|
||||
assert_eq!(high_limit_output, &expected);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -907,12 +907,14 @@ impl ServerHandler for TestToolServer {
|
||||
Ok(Self::structured_result(structured_content))
|
||||
}
|
||||
"encrypted_output" => {
|
||||
let ciphertext = std::env::var("MCP_TEST_ENCRYPTED_OUTPUT")
|
||||
.unwrap_or_else(|_| "gAAAA-test".to_string());
|
||||
let mut meta = MetaObject::new();
|
||||
meta.insert("codex/encryptedContent".to_string(), json!(true));
|
||||
let mut result = CallToolResult::success(vec![
|
||||
rmcp::model::ContentBlock::text("Lookup completed"),
|
||||
rmcp::model::ContentBlock::Text(
|
||||
rmcp::model::TextContent::new("gAAAA-test").with_meta(meta),
|
||||
rmcp::model::TextContent::new(ciphertext).with_meta(meta),
|
||||
),
|
||||
]);
|
||||
result.structured_content = Some(json!({"encrypted_output": "ignored"}));
|
||||
|
||||
Reference in New Issue
Block a user