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-1660-mcp-task-ttl.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
### Changed
- MCP tasks are forgotten once their lifetime has elapsed, so a long-running MCP session no longer accumulates them.
122 changes: 120 additions & 2 deletions crates/mcp-server/src/extension.rs
Original file line number Diff line number Diff line change
Expand Up @@ -467,14 +467,26 @@ pub struct ExtensionSet {
extensions: Vec<Arc<dyn McpExtension>>,
tools: Vec<(Tool, Arc<dyn McpExtension>)>,
/// Task id → creator and owning MCP session (issue #1633). Entries go
/// when their session closes.
/// when their session closes or their `ttlMs` has elapsed (issue #1660;
/// checked lazily on lookup and on registration, no timer).
tasks: Mutex<HashMap<String, TaskOwner>>,
}

struct TaskOwner {
ext: Arc<dyn McpExtension>,
session: McpSessionKey,
client_name: Option<String>,
/// Creation instant and the task's `ttlMs`; `None` ttl: kept until the
/// session closes.
created: tokio::time::Instant,
ttl: Option<Duration>,
}

impl TaskOwner {
fn expired(&self, now: tokio::time::Instant) -> bool {
self.ttl
.is_some_and(|ttl| now.saturating_duration_since(self.created) >= ttl)
}
}

impl ExtensionSet {
Expand Down Expand Up @@ -558,6 +570,8 @@ impl ExtensionSet {
Ok(Some(answer)) => {
let id = answer.task.task_id.clone();
let mut tasks = lock_tolerating_poison(&self.tasks);
let now = tokio::time::Instant::now();
tasks.retain(|_, owner| !owner.expired(now));
if tasks.contains_key(&id) {
tracing::warn!(
origin = "mcp",
Expand All @@ -571,6 +585,8 @@ impl ExtensionSet {
ext: ext.clone(),
session: ctx.session.clone(),
client_name: ctx.client_name.clone(),
created: now,
ttl: answer.task.ttl_ms.map(Duration::from_millis),
},
);
return Some(answer.task);
Expand All @@ -593,7 +609,12 @@ impl ExtensionSet {
caller: &McpCallContext,
task_id: &str,
) -> Option<(Arc<dyn McpExtension>, McpCallContext)> {
let tasks = lock_tolerating_poison(&self.tasks);
let mut tasks = lock_tolerating_poison(&self.tasks);
let now = tokio::time::Instant::now();
if tasks.get(task_id)?.expired(now) {
tasks.remove(task_id);
return None;
}
let owner = tasks.get(task_id)?;
if owner.session.client != caller.session.client {
return None;
Expand Down Expand Up @@ -639,6 +660,12 @@ impl ExtensionSet {
}
}

/// Number of remembered tasks (tests only).
#[cfg(test)]
fn task_count(&self) -> usize {
lock_tolerating_poison(&self.tasks).len()
}

/// Tells every extension that the MCP session of `ctx` closed.
pub async fn notify_session_closed(&self, ctx: &McpCallContext) {
lock_tolerating_poison(&self.tasks).retain(|_, owner| owner.session != ctx.session);
Expand Down Expand Up @@ -697,6 +724,97 @@ mod tests {
assert!(!lines.iter().any(|l| l.contains("secret-panic-payload")));
}

/// Answers every call with a task of the configured ttl and counts the
/// get/cancel hooks.
struct TtlExt {
ttl_ms: Option<u64>,
next: std::sync::atomic::AtomicUsize,
hook_calls: std::sync::atomic::AtomicUsize,
}

#[async_trait]
impl McpExtension for TtlExt {
async fn answer_as_task(
&self,
_ctx: McpCallContext,
_pending: PendingCommand,
) -> Option<TaskAnswer> {
let n = self.next.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let mut task = Task::new(format!("t{n}"), rmcp::model::TaskStatus::Working, "x", "x");
task.ttl_ms = self.ttl_ms;
Some(TaskAnswer::new(task))
}
async fn task_status(&self, _ctx: McpCallContext, task_id: &str) -> Option<DetailedTask> {
self.hook_calls
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Some(DetailedTask::new(
Task::new(task_id, rmcp::model::TaskStatus::Working, "x", "x"),
rmcp::model::TaskPayload::Working,
))
}
async fn cancel_task(&self, _ctx: McpCallContext, _task_id: &str) -> bool {
self.hook_calls
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
true
}
}

fn ttl_set(ttl_ms: Option<u64>) -> (ExtensionSet, Arc<TtlExt>, McpCallContext, PendingCommand) {
let ext = Arc::new(TtlExt {
ttl_ms,
next: Default::default(),
hook_calls: Default::default(),
});
let set = ExtensionSet::new(vec![ext.clone()]);
let ctx = McpCallContext::new(McpSessionKey::new(None, Some("c")), Some("c".into()))
.with_tasks_announced(true);
let (_tx, rx) = watch::channel(None);
(set, ext, ctx, PendingCommand::new(rx))
}

fn hook_calls(ext: &TtlExt) -> usize {
ext.hook_calls.load(std::sync::atomic::Ordering::SeqCst)
}

/// Issue #1660: before the ttl both reach the extension; after it both
/// give not-found without asking the extension.
#[tokio::test(start_paused = true)]
async fn test_task_expires_after_its_ttl_without_asking_the_extension() {
let (set, ext, ctx, pending) = ttl_set(Some(1_000));
let task = set.answer_as_task(&ctx, &pending).await.unwrap();
tokio::time::advance(Duration::from_millis(999)).await;
assert!(set.task_status(&ctx, &task.task_id).await.is_some());
assert!(set.cancel_task(&ctx, &task.task_id).await);
assert_eq!(hook_calls(&ext), 2);
tokio::time::advance(Duration::from_millis(1)).await;
assert!(set.task_status(&ctx, &task.task_id).await.is_none());
assert!(!set.cancel_task(&ctx, &task.task_id).await);
assert_eq!(hook_calls(&ext), 2);
assert_eq!(set.task_count(), 0);
}

/// Issue #1660: a task without ttl stays until the session closes.
#[tokio::test(start_paused = true)]
async fn test_task_without_ttl_is_kept() {
let (set, _ext, ctx, pending) = ttl_set(None);
let task = set.answer_as_task(&ctx, &pending).await.unwrap();
tokio::time::advance(Duration::from_secs(365 * 24 * 3600)).await;
assert!(set.task_status(&ctx, &task.task_id).await.is_some());
}

/// Issue #1660: registering a new task drops the expired entries.
#[tokio::test(start_paused = true)]
async fn test_registering_a_task_drops_expired_entries() {
let (set, _ext, ctx, pending) = ttl_set(Some(1_000));
set.answer_as_task(&ctx, &pending).await.unwrap();
set.answer_as_task(&ctx, &pending).await.unwrap();
assert_eq!(set.task_count(), 2);
tokio::time::advance(Duration::from_millis(1_000)).await;
assert_eq!(set.task_count(), 2, "no timer: nothing is swept by itself");
set.answer_as_task(&ctx, &pending).await.unwrap();
assert_eq!(set.task_count(), 1);
}

fn approved() -> (ApprovedCommand, watch::Sender<Option<PublishedOutcome>>) {
let (_signal, _rx, sink) = approval_channel();
let (tx, rx) = watch::channel(None);
Expand Down
62 changes: 58 additions & 4 deletions crates/mcp-server/tests/tasks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,14 +199,28 @@ async fn start_server_with(
SocketAddr,
Arc<Notify>,
Arc<Notify>,
) {
let (handle, addr, finish, gate, _set) = start_server_set(ext, confirm_timeout).await;
(handle, addr, finish, gate)
}

async fn start_server_set(
ext: Option<TaskExt>,
confirm_timeout: Duration,
) -> (
mcp_server::McpServerHandle,
SocketAddr,
Arc<Notify>,
Arc<Notify>,
Arc<ExtensionSet>,
) {
let finish = Arc::new(Notify::new());
let gate = Arc::new(Notify::new());
let set = ExtensionSet::new(
let set = Arc::new(ExtensionSet::new(
ext.into_iter()
.map(|e| Arc::new(e) as Arc<dyn McpExtension>)
.collect(),
);
));
let handle = mcp_server::serve_with_extensions(
McpServerConfig {
bind_addr: "127.0.0.1:0".parse().unwrap(),
Expand All @@ -217,12 +231,12 @@ async fn start_server_with(
gate: gate.clone(),
}),
SharedToken::new("t"),
Arc::new(set),
set.clone(),
)
.await
.unwrap();
let addr = handle.local_addr;
(handle, addr, finish, gate)
(handle, addr, finish, gate, set)
}

async fn connect(addr: SocketAddr, version: Option<ProtocolVersion>, tasks: bool) -> Client {
Expand Down Expand Up @@ -460,6 +474,46 @@ async fn test_task_id_of_another_client_session_is_not_found() {
handle.shutdown().await;
}

/// Issue #1660: once the MCP session has closed, the task is gone: not-found
/// (-32602 for 2026-07-28 peers) and the extension is not asked.
#[tokio::test]
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;
let client = connect(addr, Some(ProtocolVersion::V_2026_07_28), true).await;
let task = task_of(&client, "run").await;
client
.get_task(GetTaskParams::new(&task.task_id))
.await
.unwrap();
let before = state.lock().unwrap().status_ctx.len();
let key = {
let st = state.lock().unwrap();
st.answer_ctx.last().unwrap().clone()
};
set.notify_session_closed(&key).await;

let err = client
.get_task(GetTaskParams::new(&task.task_id))
.await
.unwrap_err();
assert!(err.to_string().contains("-32602"), "{err}");
let err = client
.cancel_task(CancelTaskParams::new(&task.task_id))
.await
.unwrap_err();
assert!(err.to_string().contains("-32602"), "{err}");
{
let st = state.lock().unwrap();
assert_eq!(st.status_ctx.len(), before);
assert!(st.cancelled.is_empty());
}
finish.notify_waiters();
client.cancel().await.ok();
handle.shutdown().await;
}

#[tokio::test]
async fn test_server_negotiates_2026_07_28_and_the_previous_revision() {
let (handle, addr, _finish) = start_server(None).await;
Expand Down
13 changes: 11 additions & 2 deletions docs/specs/0028-mcp-server-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,15 @@ Abschnitt 2). Ohne registrierte Erweiterung bleibt alles wie beschrieben:
hat (Revision 2026-07-28 hat keine Transport-Sitzung; maßgeblich ist der
Client-Name); eine unbekannte oder fremde ID und eine Aufgabe einer
geschlossenen MCP-Sitzung (Spec 0104) ergeben den Not-found-Fehler des
Protokolls, ohne dass die Erweiterung gefragt wird. Der Server nennt die
Protokolls, ohne dass die Erweiterung gefragt wird. Das gilt ebenso für
eine Aufgabe, deren Lebensdauer (`ttlMs`, gemessen ab dem Anlegen)
abgelaufen ist; eine Aufgabe ohne Lebensdauer bleibt bis zum Schließen der
Sitzung bekannt. Abgelaufene Aufgaben werden beim Nachschlagen und beim
Anlegen einer neuen Aufgabe vergessen, nicht über einen eigenen Zeitgeber.
Genehmigt der Nutzer das Kommando, ohne dass ein Zugriff darauf entsteht
(etwa weil es schon ohne Start fertig ist), ist die Entscheidung
„abgeschlossen“ und trägt das fertige Ergebnis (geschwärzt und gefenct wie
beim eingebauten Tool). Der Server nennt die
Aufgaben-Erweiterung nur, wenn eine Erweiterung registriert ist. Inhalt,
den eine Erweiterung in einem Aufgaben-Ergebnis liefert, muss wie bei
Tools geschwärzt und gefenct sein.
Expand Down Expand Up @@ -317,7 +325,8 @@ Abschnitt 2). Ohne registrierte Erweiterung bleibt alles wie beschrieben:
mit einer Aufgabe, bevor der Nutzer entschieden hat; `tasks/get` liefert
ihren Status, `tasks/cancel` erreicht sie. Ohne Ankündigung wird der Haken
nicht aufgerufen. Abgelehnt und vom Filter gesperrt lösen die Entscheidung
entsprechend auf. Die Aufgaben-ID eines anderen Clients ergibt Not-found.
entsprechend auf. Die Aufgaben-ID eines anderen Clients, einer geschlossenen Sitzung oder mit
abgelaufener Lebensdauer ergibt Not-found.

## 11. Grenzen

Expand Down
Loading