use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use futures::future::BoxFuture;
use serde_json::{Map, Value, json};
use sha2::{Digest, Sha256};
use tokio_util::sync::CancellationToken;
use super::shared::{CallContext, ToolServer};
use crate::tool::{EnvironmentSource, ToolCallControl};
pub const TASKS_EXTENSION: &str = "io.modelcontextprotocol/tasks";
pub const TASK_TTL_MS: u64 = 3_600_000;
pub const TASK_POLL_INTERVAL_MS: u64 = 2_000;
const INVALID_PARAMS: i64 = -32602;
type SpawnFn = dyn Fn(BoxFuture<'static, ()>) -> bool + Send + Sync;
#[derive(Clone)]
pub struct McpTaskSpawner {
spawn: Arc<SpawnFn>,
entropy: [u8; 32],
journal: Option<Arc<dyn McpTaskJournal>>,
}
impl std::fmt::Debug for McpTaskSpawner {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("McpTaskSpawner")
}
}
impl McpTaskSpawner {
pub fn new(
entropy: [u8; 32],
spawn: impl Fn(BoxFuture<'static, ()>) -> bool + Send + Sync + 'static,
) -> Self {
Self {
spawn: Arc::new(spawn),
entropy,
journal: None,
}
}
#[must_use]
pub fn with_journal(mut self, journal: impl McpTaskJournal + 'static) -> Self {
self.journal = Some(Arc::new(journal));
self
}
#[cfg(not(target_arch = "wasm32"))]
pub fn tokio() -> Self {
use std::hash::{BuildHasher, Hasher};
let mut entropy = [0_u8; 32];
for chunk in entropy.chunks_mut(8) {
let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
hasher.write_u64(0);
chunk.copy_from_slice(&hasher.finish().to_le_bytes());
}
Self::new(entropy, |run| match tokio::runtime::Handle::try_current() {
Ok(handle) => {
handle.spawn(run);
true
}
Err(_) => false,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TaskStatus {
Working,
InputRequired,
Completed,
Failed,
Cancelled,
}
impl TaskStatus {
fn as_str(self) -> &'static str {
match self {
Self::Working => "working",
Self::InputRequired => "input_required",
Self::Completed => "completed",
Self::Failed => "failed",
Self::Cancelled => "cancelled",
}
}
fn terminal(self) -> bool {
matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
}
fn parse(status: &str) -> Option<Self> {
Some(match status {
"working" => Self::Working,
"input_required" => Self::InputRequired,
"completed" => Self::Completed,
"failed" => Self::Failed,
"cancelled" => Self::Cancelled,
_ => return None,
})
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct McpTaskRecord {
pub id: String,
pub owner: Option<String>,
pub status: String,
pub created_ms: u64,
pub updated_ms: u64,
pub payload: Option<Value>,
}
pub trait McpTaskJournal: Send + Sync {
fn load(&self) -> Result<Vec<McpTaskRecord>, String>;
fn save(&self, record: &McpTaskRecord) -> Result<(), String>;
fn remove(&self, id: &str) -> Result<(), String>;
}
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone)]
pub struct McpTaskDirectoryJournal {
directory: std::path::PathBuf,
_owner: Option<std::sync::Arc<DirectoryOwner>>,
}
#[cfg(not(target_arch = "wasm32"))]
const OWNER_FILE: &str = "owner.lock";
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug)]
struct DirectoryOwner {
path: std::path::PathBuf,
pid: String,
}
#[cfg(not(target_arch = "wasm32"))]
impl Drop for DirectoryOwner {
fn drop(&mut self) {
if std::fs::read_to_string(&self.path).is_ok_and(|pid| pid == self.pid) {
let _ = std::fs::remove_file(&self.path);
}
}
}
#[cfg(not(target_arch = "wasm32"))]
fn process_running(pid: &str) -> bool {
if pid.is_empty() || !pid.bytes().all(|byte| byte.is_ascii_digit()) {
return false;
}
#[cfg(unix)]
let probe = std::process::Command::new("kill")
.args(["-0", pid])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.map(|status| status.success());
#[cfg(not(unix))]
let probe = std::process::Command::new("tasklist")
.args(["/FI", &format!("PID eq {pid}"), "/NH"])
.output()
.map(|output| String::from_utf8_lossy(&output.stdout).contains(pid));
probe.unwrap_or(true)
}
#[cfg(not(target_arch = "wasm32"))]
impl McpTaskDirectoryJournal {
pub fn open(directory: impl Into<std::path::PathBuf>) -> std::io::Result<Self> {
let directory = directory.into();
std::fs::create_dir_all(&directory)?;
Ok(Self {
directory,
_owner: None,
})
}
pub fn open_exclusive(
directory: impl Into<std::path::PathBuf>,
) -> std::io::Result<Option<Self>> {
use std::io::Write;
let directory = directory.into();
std::fs::create_dir_all(&directory)?;
let path = directory.join(OWNER_FILE);
let pid = std::process::id().to_string();
for _ in 0..2 {
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
{
Ok(mut claim) => {
if let Err(error) = claim.write_all(pid.as_bytes()) {
let _ = std::fs::remove_file(&path);
return Err(error);
}
return Ok(Some(Self {
directory,
_owner: Some(std::sync::Arc::new(DirectoryOwner { path, pid })),
}));
}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
let holder = std::fs::read_to_string(&path).unwrap_or_default();
if holder.is_empty() || process_running(&holder) {
return Ok(None);
}
let aside = directory.join(format!("{OWNER_FILE}.{pid}"));
if std::fs::rename(&path, &aside).is_err() {
continue;
}
let moved = std::fs::read_to_string(&aside).unwrap_or_default();
if moved != holder {
let _ = std::fs::rename(&aside, &path);
return Ok(None);
}
let _ = std::fs::remove_file(&aside);
}
Err(error) => return Err(error),
}
}
Ok(None)
}
fn path(&self, id: &str, suffix: &str) -> Result<std::path::PathBuf, String> {
if id.is_empty() || !id.bytes().all(|byte| byte.is_ascii_alphanumeric()) {
return Err(format!("{id:?} is not a task identifier"));
}
Ok(self.directory.join(format!("{id}{suffix}")))
}
}
#[cfg(not(target_arch = "wasm32"))]
impl McpTaskJournal for McpTaskDirectoryJournal {
fn load(&self) -> Result<Vec<McpTaskRecord>, String> {
let entries = std::fs::read_dir(&self.directory).map_err(|error| error.to_string())?;
let mut records = Vec::new();
for entry in entries {
let path = entry.map_err(|error| error.to_string())?.path();
if path.extension().and_then(|extension| extension.to_str()) != Some("json") {
continue;
}
let bytes = std::fs::read(&path).map_err(|error| error.to_string())?;
let record: McpTaskRecord = serde_json::from_slice(&bytes)
.map_err(|error| format!("{}: {error}", path.display()))?;
records.push(record);
}
Ok(records)
}
fn save(&self, record: &McpTaskRecord) -> Result<(), String> {
let temporary = self.path(&record.id, ".json.tmp")?;
let target = self.path(&record.id, ".json")?;
let bytes = serde_json::to_vec(record).map_err(|error| error.to_string())?;
std::fs::write(&temporary, bytes).map_err(|error| error.to_string())?;
std::fs::rename(&temporary, &target).map_err(|error| error.to_string())
}
fn remove(&self, id: &str) -> Result<(), String> {
match std::fs::remove_file(self.path(id, ".json")?) {
Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.to_string()),
_ => Ok(()),
}
}
}
#[derive(Clone)]
pub(crate) struct TaskCall {
pub(crate) name: String,
pub(crate) arguments: Option<Map<String, Value>>,
pub(crate) protocol_version: String,
pub(crate) request: Option<crate::command::RequestContext>,
pub(crate) request_meta: Option<Value>,
pub(crate) client_capabilities: Option<Value>,
pub(crate) environment: EnvironmentSource,
}
struct TaskEntry {
owner: Option<String>,
status: TaskStatus,
created_ms: u64,
updated_ms: u64,
payload: Option<Value>,
request_state: Option<String>,
call: Option<TaskCall>,
cancellation: CancellationToken,
run: u64,
}
impl TaskEntry {
fn record(&self, id: &str) -> McpTaskRecord {
McpTaskRecord {
id: id.to_string(),
owner: self.owner.clone(),
status: self.status.as_str().to_string(),
created_ms: self.created_ms,
updated_ms: self.updated_ms,
payload: self.payload.clone(),
}
}
fn wire(&self, id: &str, result_type: &str) -> Value {
let mut value = json!({
"resultType": result_type,
"taskId": id,
"status": self.status.as_str(),
"createdAt": timestamp(self.created_ms),
"lastUpdatedAt": timestamp(self.updated_ms),
"ttlMs": TASK_TTL_MS,
"pollIntervalMs": TASK_POLL_INTERVAL_MS,
});
let key = match self.status {
TaskStatus::InputRequired => "inputRequests",
TaskStatus::Completed => "result",
TaskStatus::Failed => "error",
TaskStatus::Working | TaskStatus::Cancelled => return value,
};
if result_type == "complete"
&& let Some(payload) = &self.payload
{
value[key] = payload.clone();
}
value
}
}
pub(crate) struct TaskStore {
spawner: McpTaskSpawner,
entries: Mutex<HashMap<String, TaskEntry>>,
counter: AtomicU64,
}
impl TaskStore {
pub(crate) fn new(spawner: McpTaskSpawner) -> Result<Self, String> {
let mut entries = HashMap::new();
if let Some(journal) = &spawner.journal {
for record in journal.load()? {
let status = TaskStatus::parse(&record.status)
.ok_or_else(|| format!("task {} has status {}", record.id, record.status))?;
let mut entry = TaskEntry {
owner: record.owner,
status,
created_ms: record.created_ms,
updated_ms: record.updated_ms,
payload: record.payload,
request_state: None,
call: None,
cancellation: CancellationToken::new(),
run: 0,
};
if !status.terminal() {
entry.status = TaskStatus::Failed;
entry.payload = Some(interrupted());
entry.updated_ms = now_ms();
journal.save(&entry.record(&record.id))?;
}
entries.insert(record.id, entry);
}
}
Ok(Self {
spawner,
entries: Mutex::new(entries),
counter: AtomicU64::new(0),
})
}
fn journal(&self) -> Option<&dyn McpTaskJournal> {
self.spawner.journal.as_deref()
}
fn persist(&self, id: &str, entry: &TaskEntry) {
if let Some(journal) = self.journal() {
let _ = journal.save(&entry.record(id));
}
}
fn entries(&self) -> std::sync::MutexGuard<'_, HashMap<String, TaskEntry>> {
self.entries
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn next_id(&self) -> String {
let count = self.counter.fetch_add(1, Ordering::Relaxed);
let mut digest = Sha256::new();
digest.update(self.spawner.entropy);
digest.update(count.to_le_bytes());
digest.update(now_ms().to_le_bytes());
digest
.finalize()
.iter()
.map(|byte| format!("{byte:02x}"))
.collect()
}
pub(crate) fn create(
self: &Arc<Self>,
tools: &ToolServer,
owner: Option<String>,
call: TaskCall,
) -> Option<Value> {
let id = self.next_id();
let now = now_ms();
let entry = TaskEntry {
owner,
status: TaskStatus::Working,
created_ms: now,
updated_ms: now,
payload: None,
request_state: None,
call: Some(call),
cancellation: CancellationToken::new(),
run: 0,
};
let created = entry.wire(&id, "task");
if let Some(journal) = self.journal()
&& journal.save(&entry.record(&id)).is_err()
{
return None;
}
self.entries().insert(id.clone(), entry);
if self.start(tools, &id, None, None) {
Some(created)
} else {
self.entries().remove(&id);
if let Some(journal) = self.journal() {
let _ = journal.remove(&id);
}
None
}
}
fn start(
self: &Arc<Self>,
tools: &ToolServer,
id: &str,
input_responses: Option<Value>,
request_state: Option<String>,
) -> bool {
let Some((call, cancellation, run)) = self
.entries()
.get(id)
.and_then(|entry| Some((entry.call.clone()?, entry.cancellation.clone(), entry.run)))
else {
return false;
};
let store = Arc::clone(self);
let tools = tools.clone();
let id = id.to_string();
let run_future = async move {
let outcome = tools
.call_tool(
call.name,
call.arguments,
CallContext {
protocol_version: call.protocol_version,
request: call.request,
request_meta: call.request_meta,
client_capabilities: call.client_capabilities,
input_responses,
request_state,
peer: None,
control: ToolCallControl {
cancellation,
events: None,
},
environment: call.environment,
},
)
.await;
store.finish(&id, run, outcome);
};
(self.spawner.spawn)(Box::pin(run_future))
}
fn finish(&self, id: &str, run: u64, outcome: Result<Value, String>) {
let mut entries = self.entries();
let Some(entry) = entries.get_mut(id) else {
return;
};
if entry.run != run || entry.status != TaskStatus::Working {
return;
}
match outcome {
Ok(mut result) => {
if result.get("resultType") == Some(&json!("input_required")) {
entry.status = TaskStatus::InputRequired;
entry.request_state = result
.get("requestState")
.and_then(Value::as_str)
.map(ToString::to_string);
entry.payload = Some(result.get("inputRequests").cloned().unwrap_or(json!({})));
} else {
if let Some(object) = result.as_object_mut() {
object.remove("resultType");
}
entry.status = TaskStatus::Completed;
entry.payload = Some(result);
}
}
Err(message) => {
entry.status = TaskStatus::Failed;
entry.payload = Some(json!({ "code": INVALID_PARAMS, "message": message }));
}
}
entry.updated_ms = now_ms();
self.persist(id, entry);
}
fn purge(&self, entries: &mut HashMap<String, TaskEntry>) {
let now = now_ms();
entries.retain(|id, entry| {
let keep = entry.status == TaskStatus::Working
|| entry.updated_ms.saturating_add(TASK_TTL_MS) > now;
if !keep {
entry.cancellation.cancel();
if let Some(journal) = self.journal() {
let _ = journal.remove(id);
}
}
keep
});
}
fn owned<'a>(
&self,
entries: &'a mut HashMap<String, TaskEntry>,
id: &str,
owner: Option<&str>,
) -> Result<&'a mut TaskEntry, Value> {
self.purge(entries);
entries
.get_mut(id)
.filter(|entry| entry.owner.as_deref() == owner)
.ok_or_else(|| json!({ "code": INVALID_PARAMS, "message": "Unknown task" }))
}
pub(crate) fn get(&self, id: &str, owner: Option<&str>) -> Result<Value, Value> {
let mut entries = self.entries();
Ok(self.owned(&mut entries, id, owner)?.wire(id, "complete"))
}
pub(crate) fn update(
self: &Arc<Self>,
tools: &ToolServer,
id: &str,
owner: Option<&str>,
input_responses: Value,
) -> Result<Value, Value> {
let request_state = {
let mut entries = self.entries();
let entry = self.owned(&mut entries, id, owner)?;
if entry.status != TaskStatus::InputRequired {
return Ok(json!({ "resultType": "complete" }));
}
entry.status = TaskStatus::Working;
entry.payload = None;
entry.run += 1;
entry.updated_ms = now_ms();
self.persist(id, entry);
entry.request_state.take()
};
if !self.start(tools, id, Some(input_responses), request_state)
&& let Some(entry) = self.entries().get_mut(id)
{
entry.status = TaskStatus::Failed;
entry.payload = Some(json!({
"code": INVALID_PARAMS,
"message": "The server could not resume this task",
}));
entry.updated_ms = now_ms();
self.persist(id, entry);
}
Ok(json!({ "resultType": "complete" }))
}
pub(crate) fn cancel(&self, id: &str, owner: Option<&str>) -> Result<Value, Value> {
let mut entries = self.entries();
let entry = self.owned(&mut entries, id, owner)?;
if entry.status.terminal() {
return Err(json!({ "code": INVALID_PARAMS, "message": "Task is already terminal" }));
}
entry.cancellation.cancel();
entry.status = TaskStatus::Cancelled;
entry.payload = None;
entry.updated_ms = now_ms();
self.persist(id, entry);
Ok(json!({ "resultType": "complete" }))
}
}
fn interrupted() -> Value {
json!({
"code": -32603,
"message": "The server restarted before this task finished; it was not run again",
"data": { "code": "TASK_INTERRUPTED", "retryable": false },
})
}
pub(crate) fn opted_in(client_capabilities: Option<&Value>) -> bool {
client_capabilities
.and_then(|capabilities| capabilities.get("extensions"))
.and_then(|extensions| extensions.get(TASKS_EXTENSION))
.is_some()
}
fn now_ms() -> u64 {
web_time::SystemTime::now()
.duration_since(web_time::UNIX_EPOCH)
.map_or(0, |elapsed| {
u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)
})
}
fn timestamp(ms: u64) -> String {
let seconds = ms / 1000;
let days = i64::try_from(seconds / 86_400).unwrap_or(i64::MAX / 2);
let of_day = seconds % 86_400;
let shifted = days + 719_468;
let era = shifted.div_euclid(146_097);
let day_of_era = shifted.rem_euclid(146_097);
let year_of_era =
(day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let month_index = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * month_index + 2) / 5 + 1;
let month = if month_index < 10 {
month_index + 3
} else {
month_index - 9
};
let year = year_of_era + era * 400 + i64::from(month <= 2);
format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
of_day / 3600,
of_day / 60 % 60,
of_day % 60,
ms % 1000
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn timestamps_match_known_instants() {
assert_eq!(timestamp(0), "1970-01-01T00:00:00.000Z");
assert_eq!(timestamp(951_782_400_000), "2000-02-29T00:00:00.000Z");
assert_eq!(timestamp(1_785_196_800_123), "2026-07-28T00:00:00.123Z");
assert_eq!(timestamp(4_107_542_399_999), "2100-02-28T23:59:59.999Z");
}
#[test]
fn opt_in_requires_the_extension_key() {
assert!(opted_in(Some(
&json!({ "extensions": { (TASKS_EXTENSION): {} } })
)));
assert!(!opted_in(Some(&json!({ "extensions": {} }))));
assert!(!opted_in(None));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn directory_journal_round_trips_and_ignores_incomplete_writes() {
static SEQUENCE: AtomicU64 = AtomicU64::new(0);
let directory = std::env::temp_dir().join(format!(
"multicast-task-directory-{}-{}",
std::process::id(),
SEQUENCE.fetch_add(1, Ordering::SeqCst)
));
let _ = std::fs::remove_dir_all(&directory);
let journal = McpTaskDirectoryJournal::open(&directory).unwrap();
let record = McpTaskRecord {
id: "abc123".to_owned(),
owner: Some("alpha".to_owned()),
status: "completed".to_owned(),
created_ms: 1,
updated_ms: 2,
payload: Some(json!({ "content": [] })),
};
journal.save(&record).unwrap();
std::fs::write(directory.join("half.json.tmp"), b"{\"id\":").unwrap();
let loaded = journal.load().unwrap();
assert_eq!(loaded.len(), 1);
assert_eq!(loaded[0].id, "abc123");
assert_eq!(loaded[0].owner.as_deref(), Some("alpha"));
assert_eq!(loaded[0].payload, Some(json!({ "content": [] })));
for id in ["", "../escape", "a/b", "a.b"] {
let bad = McpTaskRecord {
id: id.to_owned(),
..record.clone()
};
assert!(journal.save(&bad).is_err(), "{id:?}");
assert!(journal.remove(id).is_err(), "{id:?}");
}
assert!(!directory.parent().unwrap().join("escape.json").exists());
journal.remove("abc123").unwrap();
journal.remove("abc123").unwrap();
assert!(journal.load().unwrap().is_empty());
let _ = std::fs::remove_dir_all(&directory);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn exclusive_directory_has_one_live_owner_and_recovers_a_dead_one() {
static SEQUENCE: AtomicU64 = AtomicU64::new(0);
let directory = std::env::temp_dir().join(format!(
"multicast-task-owner-{}-{}",
std::process::id(),
SEQUENCE.fetch_add(1, Ordering::SeqCst)
));
let _ = std::fs::remove_dir_all(&directory);
let claim = directory.join("owner.lock");
let first = McpTaskDirectoryJournal::open_exclusive(&directory)
.unwrap()
.expect("an unclaimed directory is claimed");
assert_eq!(
std::fs::read_to_string(&claim).unwrap(),
std::process::id().to_string()
);
assert!(
McpTaskDirectoryJournal::open_exclusive(&directory)
.unwrap()
.is_none()
);
let clone = first.clone();
drop(first);
assert!(claim.exists());
drop(clone);
assert!(!claim.exists());
let mut sleeper = std::process::Command::new("sleep")
.arg("30")
.spawn()
.unwrap();
std::fs::write(&claim, sleeper.id().to_string()).unwrap();
assert!(
McpTaskDirectoryJournal::open_exclusive(&directory)
.unwrap()
.is_none()
);
assert_eq!(
std::fs::read_to_string(&claim).unwrap(),
sleeper.id().to_string()
);
sleeper.kill().unwrap();
sleeper.wait().unwrap();
let taken = McpTaskDirectoryJournal::open_exclusive(&directory)
.unwrap()
.expect("a dead owner's claim is taken over");
assert_eq!(
std::fs::read_to_string(&claim).unwrap(),
std::process::id().to_string()
);
drop(taken);
let _ = std::fs::remove_dir_all(&directory);
}
}