multicast 2.0.0

A declarative CLI framework for Rust with typed commands, agent discovery, HTTP, and MCP
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
//! The tasks extension (`io.modelcontextprotocol/tasks`) for ordinary commands.
//!
//! A `tools/call` returns a task instead of an inline result only when all of
//! these hold: the request uses protocol version 2026-07-28, its `_meta`
//! client capabilities list this extension, the command declares
//! [`crate::command::McpTaskSupport::Allowed`], and the server has an
//! [`McpTaskSpawner`]. Otherwise the call runs inline, unchanged.
//!
//! The command then runs detached. The client follows it with `tasks/get`,
//! answers its input requests with `tasks/update`, and stops it with
//! `tasks/cancel`. A tool error completes the task with `isError`; a
//! protocol fault fails it.
//!
//! Tasks live in server memory and are discarded [`TASK_TTL_MS`] after their
//! last update. A restart loses them, and a lost task is never re-executed.

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};

/// Extension identifier advertised in `server/discover` and expected in a
/// request's client capabilities.
pub const TASKS_EXTENSION: &str = "io.modelcontextprotocol/tasks";
/// How long a task is retained after its last update, in milliseconds.
pub const TASK_TTL_MS: u64 = 3_600_000;
/// Suggested interval between `tasks/get` polls, in milliseconds.
pub const TASK_POLL_INTERVAL_MS: u64 = 2_000;

const INVALID_PARAMS: i64 = -32602;

type SpawnFn = dyn Fn(BoxFuture<'static, ()>) -> bool + Send + Sync;

/// Starts a detached command run for a task and supplies the entropy that
/// makes task identifiers unguessable.
///
/// The spawn function returns `false` when it cannot start the run; the call
/// then runs inline as though tasks were unavailable.
#[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 {
    /// Builds a spawner from a spawn function and 32 bytes of host entropy.
    ///
    /// The entropy must come from a cryptographically secure source; task
    /// identifiers are the only proof of access within a session.
    pub fn new(
        entropy: [u8; 32],
        spawn: impl Fn(BoxFuture<'static, ()>) -> bool + Send + Sync + 'static,
    ) -> Self {
        Self {
            spawn: Arc::new(spawn),
            entropy,
            journal: None,
        }
    }

    /// Records every task in `journal` so it survives a server restart.
    ///
    /// When the server starts, a recorded task that was still working or
    /// waiting for input becomes `failed` with the code `TASK_INTERRUPTED`.
    /// Its command is never run again: whether its effects happened is
    /// unknown. Completed, failed, and cancelled tasks keep their outcome
    /// until their retention ends.
    #[must_use]
    pub fn with_journal(mut self, journal: impl McpTaskJournal + 'static) -> Self {
        self.journal = Some(Arc::new(journal));
        self
    }

    /// Spawns runs on the Tokio runtime that is current when the task starts,
    /// with entropy from the operating system's randomly seeded hashers.
    #[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,
        })
    }
}

/// One task as a [`McpTaskJournal`] stores it.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct McpTaskRecord {
    /// The task identifier.
    pub id: String,
    /// The trusted peer session that created the task, if any.
    pub owner: Option<String>,
    /// The wire status: `working`, `input_required`, `completed`,
    /// `failed`, or `cancelled`.
    pub status: String,
    /// Creation time in Unix milliseconds.
    pub created_ms: u64,
    /// Last update time in Unix milliseconds.
    pub updated_ms: u64,
    /// The result, error, or input requests the status carries.
    pub payload: Option<Value>,
}

/// Durable storage for tasks, written before each change is visible.
///
/// A write that fails when a task is created makes the call run inline
/// instead. A later write that fails leaves the previous record; after a
/// restart that task reports `TASK_INTERRUPTED` rather than running twice.
pub trait McpTaskJournal: Send + Sync {
    /// Returns every stored record.
    fn load(&self) -> Result<Vec<McpTaskRecord>, String>;
    /// Stores `record`, replacing any record with the same identifier.
    fn save(&self, record: &McpTaskRecord) -> Result<(), String>;
    /// Deletes the record for `id`; a missing record is not an error.
    fn remove(&self, id: &str) -> Result<(), String>;
}

/// A [`McpTaskJournal`] that keeps one JSON file per task in a directory.
///
/// Each save writes a temporary file and renames it over the record, so a
/// crash leaves either the old or the new record, never a partial one. One
/// server process should own the directory; [`Self::open_exclusive`]
/// enforces that.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone)]
pub struct McpTaskDirectoryJournal {
    directory: std::path::PathBuf,
    /// Held only so the claim is released when the last clone drops.
    _owner: Option<std::sync::Arc<DirectoryOwner>>,
}

/// The name of the file that records which process owns a journal directory.
#[cfg(not(target_arch = "wasm32"))]
const OWNER_FILE: &str = "owner.lock";

/// A claim on a journal directory, released when the last journal clone drops.
#[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) {
        // Remove the claim only while it is still ours.
        if std::fs::read_to_string(&self.path).is_ok_and(|pid| pid == self.pid) {
            let _ = std::fs::remove_file(&self.path);
        }
    }
}

/// Reports whether a process with this identifier is running.
#[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));
    // A probe that cannot run cannot prove the owner gone.
    probe.unwrap_or(true)
}

#[cfg(not(target_arch = "wasm32"))]
impl McpTaskDirectoryJournal {
    /// Uses `directory`, creating it when missing.
    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,
        })
    }

    /// Uses `directory` only when no other running process owns it.
    ///
    /// Returns `None` while another live process holds the directory, so two
    /// servers never fail each other's working tasks on startup. A claim left
    /// by a process that has exited is taken over. The claim is released when
    /// the last clone of the returned journal drops.
    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();
                    // An empty claim may be one another process is still writing.
                    if holder.is_empty() || process_running(&holder) {
                        return Ok(None);
                    }
                    // Move the stale claim aside, then confirm the moved claim
                    // is the stale one before claiming the directory afresh.
                    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 {
                        // Another process claimed it first; give its claim back.
                        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();
            // Temporary files are writes that never completed.
            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(()),
        }
    }
}

/// Everything needed to run, or re-run with input responses, a task's call.
#[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>,
    /// `None` for a task restored from a journal, which never runs again.
    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
    }
}

/// In-memory tasks for one server, partitioned by trusted peer session.
pub(crate) struct TaskStore {
    spawner: McpTaskSpawner,
    entries: Mutex<HashMap<String, TaskEntry>>,
    counter: AtomicU64,
}

impl TaskStore {
    /// Builds the store, restoring any journaled tasks. A task that was
    /// still running or waiting for input becomes `TASK_INTERRUPTED`.
    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()
    }

    /// Writes the entry's current state; failures keep the older record.
    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()
    }

    /// Records a working task and starts its run. Returns the
    /// `CreateTaskResult`, or `None` when the spawner could not start it.
    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");
        // The task is durable before its command can run or its id is sent.
        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))
    }

    /// Stores a run's outcome unless the task moved on while it ran.
    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);
    }

    /// Drops tasks whose retention ended, cancelling any still waiting.
    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" }))
    }

    /// Answers `tasks/get`.
    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"))
    }

    /// Answers `tasks/update`: resumes a task waiting for input with the
    /// client's responses. A task in any other state ignores the update.
    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" }))
    }

    /// Answers `tasks/cancel`: stops the run and marks the task cancelled.
    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" }))
    }
}

/// The error a restored task reports when a restart interrupted its run.
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 },
    })
}

/// Returns whether request client capabilities opt into the tasks extension.
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)
        })
}

/// Formats Unix milliseconds as an RFC 3339 UTC timestamp.
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;
    // Civil date from days since 1970-01-01 (proleptic Gregorian calendar).
    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()
        );
        // A second server while the first is alive keeps its tasks in memory.
        assert!(
            McpTaskDirectoryJournal::open_exclusive(&directory)
                .unwrap()
                .is_none()
        );
        // Clones share the claim; it is released with the last one.
        let clone = first.clone();
        drop(first);
        assert!(claim.exists());
        drop(clone);
        assert!(!claim.exists());

        // A claim from a live process other than this one is respected.
        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()
        );
        // Once that process has exited, its claim is stale and taken over.
        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);
    }
}