Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog.d/issue-1659-mcp-task-hook-panics.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
### Fixed
- A crashing MCP extension can no longer break a task answer, `tasks/get` or `tasks/cancel`; the call carries on as if the extension had not answered.
87 changes: 80 additions & 7 deletions crates/mcp-server/src/extension.rs
Original file line number Diff line number Diff line change
Expand Up @@ -565,9 +565,9 @@ impl ExtensionSet {
pending: &PendingCommand,
) -> Option<Task> {
for ext in &self.extensions {
let hook = ext.answer_as_task(ctx.clone(), pending.clone());
let hook = contain_panic(ext.answer_as_task(ctx.clone(), pending.clone()));
match tokio::time::timeout(HOOK_TIMEOUT, hook).await {
Ok(Some(answer)) => {
Ok(Ok(Some(answer))) => {
let id = answer.task.task_id.clone();
let mut tasks = lock_tolerating_poison(&self.tasks);
let now = tokio::time::Instant::now();
Expand All @@ -591,7 +591,11 @@ impl ExtensionSet {
);
return Some(answer.task);
}
Ok(None) => {}
Ok(Ok(None)) => {}
// A panic counts like `None`; the next extension is asked.
Ok(Err(HookPanicked)) => {
tracing::warn!(origin = "mcp", "mcp extension panicked in answer_as_task")
}
Err(_) => tracing::warn!(
origin = "mcp",
"mcp extension did not answer answer_as_task in time"
Expand Down Expand Up @@ -631,8 +635,13 @@ impl ExtensionSet {
task_id: &str,
) -> Option<DetailedTask> {
let (ext, ctx) = self.task_owner(caller, task_id)?;
match tokio::time::timeout(HOOK_TIMEOUT, ext.task_status(ctx, task_id)).await {
Ok(status) => status,
match tokio::time::timeout(HOOK_TIMEOUT, contain_panic(ext.task_status(ctx, task_id))).await
{
Ok(Ok(status)) => status,
Ok(Err(HookPanicked)) => {
tracing::warn!(origin = "mcp", "mcp extension panicked in task_status");
None
}
Err(_) => {
tracing::warn!(
origin = "mcp",
Expand All @@ -648,8 +657,13 @@ impl ExtensionSet {
let Some((ext, ctx)) = self.task_owner(caller, task_id) else {
return false;
};
match tokio::time::timeout(HOOK_TIMEOUT, ext.cancel_task(ctx, task_id)).await {
Ok(found) => found,
match tokio::time::timeout(HOOK_TIMEOUT, contain_panic(ext.cancel_task(ctx, task_id))).await
{
Ok(Ok(found)) => found,
Ok(Err(HookPanicked)) => {
tracing::warn!(origin = "mcp", "mcp extension panicked in cancel_task");
false
}
Err(_) => {
tracing::warn!(
origin = "mcp",
Expand Down Expand Up @@ -815,6 +829,65 @@ mod tests {
assert_eq!(set.task_count(), 1);
}

/// Answers a task, then panics in `task_status` and `cancel_task`; a
/// second one panics in `answer_as_task`.
struct TaskPanicker {
panic_answer: bool,
}
#[async_trait]
impl McpExtension for TaskPanicker {
async fn answer_as_task(
&self,
_ctx: McpCallContext,
_pending: PendingCommand,
) -> Option<TaskAnswer> {
if self.panic_answer {
panic!("secret-panic-payload");
}
Some(TaskAnswer::new(Task::new(
"t0",
rmcp::model::TaskStatus::Working,
"x",
"x",
)))
}
async fn task_status(&self, _ctx: McpCallContext, _id: &str) -> Option<DetailedTask> {
panic!("secret-panic-payload");
}
async fn cancel_task(&self, _ctx: McpCallContext, _id: &str) -> bool {
panic!("secret-panic-payload");
}
}

/// Issue #1659: the three task hooks log a warning with origin `mcp`
/// when they panic, and never the panic payload.
#[tokio::test(flavor = "multi_thread")]
async fn test_task_hook_panics_log_a_warning_without_payload() {
let _guard = crate::test_support::start_recording();
let ctx = McpCallContext::new(McpSessionKey::new(None, Some("c")), Some("c".into()))
.with_tasks_announced(true);
let (_tx, rx) = watch::channel(None);
let pending = PendingCommand::new(rx);
let set = ExtensionSet::new(vec![Arc::new(TaskPanicker { panic_answer: true })]);
assert!(set.answer_as_task(&ctx, &pending).await.is_none());
let set = ExtensionSet::new(vec![Arc::new(TaskPanicker {
panic_answer: false,
})]);
let task = set.answer_as_task(&ctx, &pending).await.unwrap();
assert!(set.task_status(&ctx, &task.task_id).await.is_none());
assert!(!set.cancel_task(&ctx, &task.task_id).await);
let lines = crate::test_support::recorded_lines_at_info_or_above();
for hook in ["answer_as_task", "task_status", "cancel_task"] {
assert!(
lines.iter().any(|l| l.contains("\"level\":\"WARN\"")
&& l.contains("\"origin\":\"mcp\"")
&& l.contains(&format!("panicked in {hook}"))),
"{hook}: {lines:?}"
);
}
assert!(!lines.iter().any(|l| l.contains("secret-panic-payload")));
}

fn approved() -> (ApprovedCommand, watch::Sender<Option<PublishedOutcome>>) {
let (_signal, _rx, sink) = approval_channel();
let (tx, rx) = watch::channel(None);
Expand Down
118 changes: 111 additions & 7 deletions crates/mcp-server/tests/tasks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,10 @@ struct State {
struct TaskExt {
state: Arc<Mutex<State>>,
answer: bool,
/// Issue #1659: the hook panics (after recording the call).
panic_answer: bool,
panic_status: bool,
panic_cancel: bool,
}

#[async_trait]
Expand All @@ -126,6 +130,9 @@ impl McpExtension for TaskExt {
st.answered_calls += 1;
st.answer_ctx.push(ctx);
}
if self.panic_answer {
panic!("secret-panic-payload");
}
if !self.answer {
return None;
}
Expand Down Expand Up @@ -154,6 +161,9 @@ impl McpExtension for TaskExt {
}

async fn task_status(&self, ctx: McpCallContext, task_id: &str) -> Option<DetailedTask> {
if self.panic_status {
panic!("secret-panic-payload");
}
let mut st = self.state.lock().unwrap();
st.status_ctx.push(ctx);
let task = Task::new(
Expand All @@ -173,6 +183,9 @@ impl McpExtension for TaskExt {
}

async fn cancel_task(&self, _ctx: McpCallContext, task_id: &str) -> bool {
if self.panic_cancel {
panic!("secret-panic-payload");
}
self.state
.lock()
.unwrap()
Expand All @@ -187,25 +200,26 @@ type Client = rmcp::service::RunningService<rmcp::RoleClient, ClientConfig>;
async fn start_server(
ext: Option<TaskExt>,
) -> (mcp_server::McpServerHandle, SocketAddr, Arc<Notify>) {
let (handle, addr, finish, _gate) = start_server_with(ext, Duration::from_secs(30)).await;
let (handle, addr, finish, _gate) =
start_server_with(ext.into_iter().collect(), Duration::from_secs(30)).await;
(handle, addr, finish)
}

async fn start_server_with(
ext: Option<TaskExt>,
exts: Vec<TaskExt>,
confirm_timeout: Duration,
) -> (
mcp_server::McpServerHandle,
SocketAddr,
Arc<Notify>,
Arc<Notify>,
) {
let (handle, addr, finish, gate, _set) = start_server_set(ext, confirm_timeout).await;
let (handle, addr, finish, gate, _set) = start_server_set(exts, confirm_timeout).await;
(handle, addr, finish, gate)
}

async fn start_server_set(
ext: Option<TaskExt>,
exts: Vec<TaskExt>,
confirm_timeout: Duration,
) -> (
mcp_server::McpServerHandle,
Expand All @@ -217,7 +231,7 @@ async fn start_server_set(
let finish = Arc::new(Notify::new());
let gate = Arc::new(Notify::new());
let set = Arc::new(ExtensionSet::new(
ext.into_iter()
exts.into_iter()
.map(|e| Arc::new(e) as Arc<dyn McpExtension>)
.collect(),
));
Expand Down Expand Up @@ -301,6 +315,9 @@ fn ext(answer: bool) -> (TaskExt, Arc<Mutex<State>>) {
TaskExt {
state: state.clone(),
answer,
panic_answer: false,
panic_status: false,
panic_cancel: false,
},
state,
)
Expand Down Expand Up @@ -480,7 +497,7 @@ async fn test_task_id_of_another_client_session_is_not_found() {
async fn test_task_of_a_closed_session_is_not_found_and_the_extension_is_not_called() {
let (e, state) = ext(true);
let (handle, addr, finish, _gate, set) =
start_server_set(Some(e), Duration::from_secs(30)).await;
start_server_set(vec![e], Duration::from_secs(30)).await;
let client = connect(addr, Some(ProtocolVersion::V_2026_07_28), true).await;
let task = task_of(&client, "run").await;
client
Expand Down Expand Up @@ -533,7 +550,7 @@ async fn test_server_negotiates_2026_07_28_and_the_previous_revision() {
async fn test_task_is_answered_before_the_decision_and_no_timeout_applies() {
let (e, state) = ext(true);
// A very short confirmation timeout: the built-in wait would give up.
let (handle, addr, finish, gate) = start_server_with(Some(e), Duration::from_millis(100)).await;
let (handle, addr, finish, gate) = start_server_with(vec![e], Duration::from_millis(100)).await;
let client = connect(addr, Some(ProtocolVersion::V_2026_07_28), true).await;
// The backend does not approve until the gate is released, so the task
// must be returned before any decision exists.
Expand All @@ -555,3 +572,90 @@ async fn test_task_is_answered_before_the_decision_and_no_timeout_applies() {
client.cancel().await.ok();
handle.shutdown().await;
}

#[tokio::test]
async fn test_panicking_answer_as_task_still_waits_for_core_outcome() {
let (mut e, state) = ext(true);
e.panic_answer = true;
let (handle, addr, finish, gate) = start_server_with(vec![e], Duration::from_secs(30)).await;
let client = connect(addr, Some(ProtocolVersion::V_2026_07_28), true).await;
let call = tokio::spawn({
let peer = client.peer().clone();
async move { peer.call_tool(propose("gated")).await }
});
// The hook ran (and panicked); the call must still be waiting.
tokio::time::timeout(Duration::from_secs(20), async {
while state.lock().unwrap().answered_calls == 0 {
tokio::task::yield_now().await;
}
})
.await
.expect("hook was never entered");
assert!(!call.is_finished());
gate.notify_one();
finish.notify_one();
let result = tokio::time::timeout(Duration::from_secs(20), call)
.await
.expect("call hung")
.unwrap()
.unwrap();
assert_eq!(text(&result), "finished");
assert!(!text(&result).contains("secret-panic-payload"));
client.cancel().await.ok();
handle.shutdown().await;
}

#[tokio::test]
async fn test_second_extension_answers_after_first_panics_in_answer_as_task() {
let (mut first, _s1) = ext(true);
first.panic_answer = true;
let (second, s2) = ext(true);
let (handle, addr, _finish, _gate) =
start_server_with(vec![first, second], Duration::from_secs(30)).await;
let client = connect(addr, Some(ProtocolVersion::V_2026_07_28), true).await;
let task = task_of(&client, "run").await;
assert_eq!(s2.lock().unwrap().answered_calls, 1);
let got = client
.get_task(GetTaskParams::new(&task.task_id))
.await
.unwrap();
assert_eq!(got.task.status(), TaskStatus::Working);
client.cancel().await.ok();
handle.shutdown().await;
}

#[tokio::test]
async fn test_panicking_task_status_and_cancel_task_are_not_found_and_session_stays_usable() {
let (mut e, _state) = ext(true);
e.panic_status = true;
e.panic_cancel = true;
let (handle, addr, _finish) = start_server(Some(e)).await;
let client = connect(addr, Some(ProtocolVersion::V_2026_07_28), true).await;
let task = task_of(&client, "run").await;
for err in [
client
.get_task(GetTaskParams::new(&task.task_id))
.await
.unwrap_err(),
client
.cancel_task(CancelTaskParams::new(&task.task_id))
.await
.unwrap_err(),
] {
let rmcp::ServiceError::McpError(data) = &err else {
panic!("expected an MCP error, got {err:?}");
};
// `task_not_found()` is RESOURCE_NOT_FOUND; rmcp reports it as
// INVALID_PARAMS to peers negotiating 2026-07-28 (SEP-2164).
assert_eq!(data.code, rmcp::model::ErrorCode::INVALID_PARAMS);
assert_eq!(data.message, "task not found");
assert!(!format!("{err:?}").contains("secret-panic-payload"));
}
// The session is still usable: a built-in tool call on the same client works.
let second = tokio::time::timeout(Duration::from_secs(20), task_of(&client, "run"))
.await
.expect("built-in call hung");
assert!(!second.task_id.is_empty());
client.cancel().await.ok();
handle.shutdown().await;
}
6 changes: 5 additions & 1 deletion docs/specs/0028-mcp-server-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,11 @@ Abschnitt 2). Ohne registrierte Erweiterung bleibt alles wie beschrieben:
Erweiterung wird gefragt, sonst wartet der Kern auf das Ergebnis), beim
Schließen der Sitzung wird trotzdem jede weitere Erweiterung benachrichtigt
und das Schließen abgeschlossen, und ein abgestürzter Tool-Aufruf liefert
ein Fehlerergebnis; die Sitzung bleibt benutzbar. Die Erweiterung selbst
ein Fehlerergebnis; die Sitzung bleibt benutzbar. Dasselbe gilt für die
Aufgaben-Hooks: ein Absturz beim Beantworten als Aufgabe zählt wie „keine
Antwort“ (die nächste Erweiterung wird gefragt, sonst läuft der Aufruf wie
ohne Aufgabe weiter), ein Absturz bei `tasks/get` oder `tasks/cancel` wie
„nicht gefunden“. Die Erweiterung selbst
protokolliert nur, dass ein Hook abgestürzt ist (`origin: "mcp"`), nie den
Inhalt der Meldung; der allgemeine Panic-Hook der App (Spec 0094 §3)
protokolliert den Panic wie jeden anderen als „app panicked“.
Expand Down
Loading