harn-vm 0.10.116

Async bytecode virtual machine for the Harn programming language
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
//! One owner for the MCP tasks extension.
//!
//! Three Harn surfaces speak MCP: the orchestrator server (`harn serve
//! orchestrator`), the script-driven server (`mcp_tools(registry)`), and the
//! export server (`pub fn` entrypoints). All three advertise the same
//! `io.modelcontextprotocol/tasks` extension to clients, so all three owe
//! clients the same `tasks/get`, `tasks/update`, and `tasks/cancel` behavior.
//!
//! Before this module only the orchestrator implemented it. The script-driven
//! server advertised the capability and answered every one of the three methods
//! with `task not found` — a client that read the capability and polled was
//! told, truthfully-looking, that its task had vanished. Advertising a
//! capability a server cannot serve is worse than not advertising it: the
//! client has no way to tell the difference between "this server does not do
//! tasks" and "your task is gone".
//!
//! So the lifecycle lives here, once, and a server supplies only the part that
//! is actually its own: how to run the work. Everything a client can observe —
//! ids, ownership, status transitions, terminal-status rules, the JSON
//! projections, the wake-up on completion — is decided in this file, which is
//! what makes the three surfaces answer the same way by construction rather
//! than by three sets of matching tests.

use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};

use serde_json::{json, Value as JsonValue};
use tokio::sync::Notify;
use uuid::Uuid;

use crate::mcp_protocol;

/// How long a created task stays retrievable, in milliseconds.
///
/// Long enough that a client which drops its connection mid-run can reconnect
/// and still collect the result, short enough that an abandoned poll loop does
/// not pin memory for the life of the server.
pub const DEFAULT_TASK_TTL_MS: u64 = 10 * 60 * 1000;

/// Whether one tool may be invoked as a task, as `tools/list` reports it.
///
/// MCP lets a server declare this per tool rather than server-wide, which is
/// what makes an honest partial implementation possible: a server can serve the
/// extension for the tools it can actually run that way and say `forbidden` for
/// the rest, instead of advertising a blanket capability and failing whichever
/// calls it cannot honor.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum McpTaskSupport {
    /// The client must not ask for a task. This is the default: a tool has to
    /// opt in, so adding the extension cannot change how an existing tool
    /// behaves.
    #[default]
    Forbidden,
    /// The client may ask for a task; a plain call still works.
    Optional,
    /// The tool is only invocable as a task.
    Required,
}

impl McpTaskSupport {
    pub fn wire_name(self) -> &'static str {
        match self {
            Self::Forbidden => "forbidden",
            Self::Optional => "optional",
            Self::Required => "required",
        }
    }

    /// Parse a script-declared `execution: {taskSupport: "..."}` value.
    ///
    /// An unrecognized spelling reads as `Forbidden` rather than as the
    /// permissive value: a typo should cost the tool its task support, not
    /// silently grant a lifecycle the author did not ask for.
    pub fn from_wire(value: &str) -> Self {
        match value {
            "optional" => Self::Optional,
            "required" => Self::Required,
            _ => Self::Forbidden,
        }
    }

    pub fn allows_task(self) -> bool {
        matches!(self, Self::Optional | Self::Required)
    }
}

/// The observable state of one task, as `tasks/*` and the creating
/// `tools/call` project it.
#[derive(Clone, Debug)]
pub struct McpTaskState {
    pub task_id: String,
    /// Client identity that created the task. Reads and cancels from any other
    /// identity are answered as `task not found` rather than as a permission
    /// error, so one client cannot probe another's task ids.
    pub owner: String,
    pub status: mcp_protocol::McpTaskStatus,
    pub status_message: Option<String>,
    pub created_at: String,
    pub last_updated_at: String,
    pub ttl: Option<u64>,
    pub poll_interval: Option<u64>,
}

impl McpTaskState {
    pub fn to_json(&self) -> JsonValue {
        let mut value = json!({
            "taskId": self.task_id,
            "status": mcp_protocol::mcp_task_status_wire_name(self.status),
            "createdAt": self.created_at,
            "lastUpdatedAt": self.last_updated_at,
            "ttlMs": self.ttl,
        });
        if let Some(message) = &self.status_message {
            value["statusMessage"] = json!(message);
        }
        if let Some(poll_interval) = self.poll_interval {
            value["pollIntervalMs"] = json!(poll_interval);
        }
        value
    }
}

/// A task plus whatever it has produced, and the handle waiters park on.
#[derive(Clone, Debug)]
pub struct McpTaskRecord {
    pub task: McpTaskState,
    pub result: Option<JsonValue>,
    pub notify: Arc<Notify>,
}

impl McpTaskRecord {
    pub fn to_detailed_json(&self) -> JsonValue {
        let mut value = self.task.to_json();
        value["resultType"] = json!(mcp_protocol::RESULT_TYPE_COMPLETE);
        match self.task.status {
            mcp_protocol::McpTaskStatus::Completed => {
                value["result"] = self.result.clone().unwrap_or_else(|| json!({}));
            }
            mcp_protocol::McpTaskStatus::Failed => {
                value["error"] = json!({
                    "code": -32603,
                    "message": self.task.status_message.as_deref().unwrap_or("Task failed"),
                });
            }
            mcp_protocol::McpTaskStatus::Working
            | mcp_protocol::McpTaskStatus::InputRequired
            | mcp_protocol::McpTaskStatus::Cancelled => {}
            _ => unreachable!("Harn only creates MCP task statuses it handles"),
        }
        value
    }
}

/// Every task one MCP server is holding, and the whole lifecycle over them.
#[derive(Default)]
pub struct McpTaskStore {
    tasks: Mutex<BTreeMap<String, McpTaskRecord>>,
}

impl std::fmt::Debug for McpTaskStore {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let count = self.tasks.lock().map(|tasks| tasks.len()).unwrap_or(0);
        formatter
            .debug_struct("McpTaskStore")
            .field("tasks", &count)
            .finish()
    }
}

impl McpTaskStore {
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a new working task owned by `owner` and return its state.
    ///
    /// The caller then runs the work however that surface runs work, and
    /// reports back through [`McpTaskStore::complete`]. The store deliberately
    /// does not own execution: a script tool runs on the VM thread, an
    /// orchestrator tool can enter a child VM, and pretending one scheduler
    /// fits both is how the two implementations diverged in the first place.
    pub fn create(&self, owner: &str, ttl: Option<u64>) -> McpTaskState {
        let now = now_rfc3339();
        let task = McpTaskState {
            task_id: Uuid::now_v7().to_string(),
            owner: owner.to_string(),
            status: mcp_protocol::McpTaskStatus::Working,
            status_message: Some("The operation is now in progress.".to_string()),
            created_at: now.clone(),
            last_updated_at: now,
            ttl,
            poll_interval: Some(mcp_protocol::DEFAULT_TASK_POLL_INTERVAL_MS),
        };
        self.tasks.lock().expect("MCP tasks poisoned").insert(
            task.task_id.clone(),
            McpTaskRecord {
                task: task.clone(),
                result: None,
                notify: Arc::new(Notify::new()),
            },
        );
        task
    }

    /// Record a finished task and wake anything waiting on it.
    ///
    /// A cancelled task is left alone: the client has already been told the
    /// terminal status, and letting late work overwrite it would make cancel
    /// mean "maybe".
    pub fn complete(&self, task_id: &str, result: Result<JsonValue, String>) {
        let Some(wake) = ({
            let mut tasks = self.tasks.lock().expect("MCP tasks poisoned");
            let Some(record) = tasks.get_mut(task_id) else {
                return;
            };
            if record.task.status == mcp_protocol::McpTaskStatus::Cancelled {
                return;
            }
            let wake = record.notify.clone();
            record.task.last_updated_at = now_rfc3339();
            match result {
                Ok(value) => {
                    record.task.status = mcp_protocol::McpTaskStatus::Completed;
                    record.task.status_message =
                        Some("The task completed successfully.".to_string());
                    record.result = Some(tool_call_result_json(value, false));
                }
                Err(error) => {
                    record.task.status = mcp_protocol::McpTaskStatus::Failed;
                    record.task.status_message = Some(format!("Tool execution failed: {error}"));
                    record.result = Some(tool_call_result_json(json!(error), true));
                }
            }
            Some(wake)
        }) else {
            return;
        };
        wake.notify_waiters();
    }

    /// Record a finished task whose result is already an MCP `tools/call`
    /// result rather than a bare tool return value.
    ///
    /// A server that projects its own result -- the export adapter builds MCP
    /// content blocks before it knows whether the call was a task -- has
    /// nothing left for [`McpTaskStore::complete`] to wrap, and wrapping it
    /// again nests `content` inside `content`. Handing the projection over
    /// intact is also lossless: a multi-block or non-object result survives,
    /// where reconstructing a bare value from the blocks would not.
    pub fn complete_with_tool_result(&self, task_id: &str, result: JsonValue) {
        let failed = result
            .get("isError")
            .and_then(JsonValue::as_bool)
            .unwrap_or(false);
        let Some(wake) = ({
            let mut tasks = self.tasks.lock().expect("MCP tasks poisoned");
            let Some(record) = tasks.get_mut(task_id) else {
                return;
            };
            if record.task.status == mcp_protocol::McpTaskStatus::Cancelled {
                return;
            }
            record.task.last_updated_at = now_rfc3339();
            if failed {
                record.task.status = mcp_protocol::McpTaskStatus::Failed;
                record.task.status_message = Some(format!(
                    "Tool execution failed: {}",
                    result
                        .pointer("/content/0/text")
                        .and_then(JsonValue::as_str)
                        .unwrap_or("Tool execution failed")
                ));
            } else {
                record.task.status = mcp_protocol::McpTaskStatus::Completed;
                record.task.status_message = Some("The task completed successfully.".to_string());
            }
            record.result = Some(result);
            Some(record.notify.clone())
        }) else {
            return;
        };
        wake.notify_waiters();
    }

    /// A handle that fires when the named task reaches a terminal status.
    ///
    /// A caller that wants the result rather than a poll loop takes this
    /// *before* its first `tasks/get`, so a task that finishes between the read
    /// and the wait still wakes it.
    pub fn notifier(&self, task_id: &str) -> Option<Arc<Notify>> {
        self.tasks
            .lock()
            .expect("MCP tasks poisoned")
            .get(task_id)
            .map(|record| record.notify.clone())
    }

    /// The record `params.taskId` names, if `owner` is the one who created it.
    pub fn record_for_owner(
        &self,
        owner: &str,
        params: &JsonValue,
    ) -> Result<McpTaskRecord, String> {
        let task_id = params
            .get("taskId")
            .and_then(JsonValue::as_str)
            .ok_or_else(|| "Failed to retrieve task: missing taskId".to_string())?;
        let tasks = self.tasks.lock().expect("MCP tasks poisoned");
        let record = tasks
            .get(task_id)
            .ok_or_else(|| "Failed to retrieve task: task not found".to_string())?;
        if record.task.owner != owner {
            return Err("Failed to retrieve task: task not found".to_string());
        }
        Ok(record.clone())
    }

    pub fn handle_get(&self, id: JsonValue, owner: &str, params: &JsonValue) -> JsonValue {
        match self.record_for_owner(owner, params) {
            Ok(record) => crate::jsonrpc::response(id, record.to_detailed_json()),
            Err(error) => crate::jsonrpc::error_response(id, -32602, &error),
        }
    }

    /// `tasks/update` supplies responses to a task that asked for input.
    ///
    /// No Harn surface creates `input-required` tasks yet, so every update is
    /// answered as "nothing outstanding" — but the shape of the refusal still
    /// distinguishes a malformed call from a well-formed one against a task
    /// that simply is not waiting, which is what a client needs to know.
    pub fn handle_update(&self, id: JsonValue, owner: &str, params: &JsonValue) -> JsonValue {
        if let Err(error) = self.record_for_owner(owner, params) {
            return crate::jsonrpc::error_response(id, -32602, &error);
        }
        let supplied = params
            .get("inputResponses")
            .and_then(JsonValue::as_object)
            .is_some_and(|responses| !responses.is_empty());
        let message = if supplied {
            "Task has no outstanding input requests"
        } else {
            "tasks/update requires at least one input response"
        };
        crate::jsonrpc::error_response(id, -32602, message)
    }

    pub fn handle_cancel(&self, id: JsonValue, owner: &str, params: &JsonValue) -> JsonValue {
        let task_id = match params.get("taskId").and_then(JsonValue::as_str) {
            Some(task_id) if !task_id.is_empty() => task_id.to_string(),
            _ => {
                return crate::jsonrpc::error_response(
                    id,
                    -32602,
                    "Cannot cancel task: missing taskId",
                );
            }
        };
        let notify = {
            let mut tasks = self.tasks.lock().expect("MCP tasks poisoned");
            let Some(record) = tasks.get_mut(&task_id) else {
                return crate::jsonrpc::error_response(
                    id,
                    -32602,
                    "Cannot cancel task: task not found",
                );
            };
            if record.task.owner != owner {
                return crate::jsonrpc::error_response(
                    id,
                    -32602,
                    "Cannot cancel task: task not found",
                );
            }
            if record.task.status.is_terminal() {
                return crate::jsonrpc::error_response(
                    id,
                    -32602,
                    &format!(
                        "Cannot cancel task: already in terminal status '{}'",
                        mcp_protocol::mcp_task_status_wire_name(record.task.status)
                    ),
                );
            }
            record.task.status = mcp_protocol::McpTaskStatus::Cancelled;
            record.task.status_message = Some("The task was cancelled by request.".to_string());
            record.task.last_updated_at = now_rfc3339();
            record.result = Some(json!({
                "content": [{
                    "type": "text",
                    "text": "Task was cancelled by request.",
                }],
                "isError": true,
            }));
            record.notify.clone()
        };
        notify.notify_waiters();
        crate::jsonrpc::response(id, json!({}))
    }
}

/// The `tools/call` response that hands a client a task instead of a result.
pub fn task_created_response(id: JsonValue, task: &McpTaskState, note: &str) -> JsonValue {
    let mut result = task.to_json();
    result["resultType"] = json!("task");
    result["_meta"] = json!({
        "io.modelcontextprotocol/model-immediate-response": note,
    });
    crate::jsonrpc::response(id, result)
}

/// Project a tool's return value as an MCP `tools/call` result.
pub fn tool_call_result_json(value: JsonValue, is_error: bool) -> JsonValue {
    if is_error {
        return json!({
            "content": [{
                "type": "text",
                "text": value.as_str().unwrap_or("Tool execution failed"),
            }],
            "isError": true,
        });
    }
    json!({
        "content": [{
            "type": "text",
            "text": serde_json::to_string_pretty(&value).unwrap_or_else(|_| value.to_string()),
        }],
        "structuredContent": value,
        "isError": false,
    })
}

fn now_rfc3339() -> String {
    crate::clock::system_now_rfc3339()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn params(task_id: &str) -> JsonValue {
        json!({ "taskId": task_id })
    }

    #[test]
    fn a_created_task_is_readable_by_its_owner_and_invisible_to_everyone_else() {
        let store = McpTaskStore::new();
        let task = store.create("client-a", Some(DEFAULT_TASK_TTL_MS));

        let mine = store.handle_get(json!(1), "client-a", &params(&task.task_id));
        assert_eq!(mine["result"]["taskId"], json!(task.task_id));
        assert_eq!(mine["result"]["status"], json!("working"));

        // Not "forbidden": a distinguishable error would let one client
        // confirm another client's task ids by probing.
        let theirs = store.handle_get(json!(2), "client-b", &params(&task.task_id));
        assert_eq!(
            theirs["error"]["message"],
            json!("Failed to retrieve task: task not found")
        );
    }

    #[test]
    fn completing_a_task_publishes_its_result() {
        let store = McpTaskStore::new();
        let task = store.create("client-a", None);
        store.complete(&task.task_id, Ok(json!({ "answer": 42 })));

        let read = store.handle_get(json!(1), "client-a", &params(&task.task_id));
        assert_eq!(read["result"]["status"], json!("completed"));
        assert_eq!(
            read["result"]["result"]["structuredContent"],
            json!({ "answer": 42 })
        );
    }

    #[test]
    fn a_failed_task_reports_an_error_rather_than_an_empty_result() {
        let store = McpTaskStore::new();
        let task = store.create("client-a", None);
        store.complete(&task.task_id, Err("boom".to_string()));

        let read = store.handle_get(json!(1), "client-a", &params(&task.task_id));
        assert_eq!(read["result"]["status"], json!("failed"));
        assert_eq!(read["result"]["error"]["code"], json!(-32603));
        assert!(read["result"]["error"]["message"]
            .as_str()
            .expect("failed tasks carry a message")
            .contains("boom"));
    }

    #[test]
    fn cancel_is_terminal_and_late_work_cannot_overwrite_it() {
        let store = McpTaskStore::new();
        let task = store.create("client-a", None);

        let cancelled = store.handle_cancel(json!(1), "client-a", &params(&task.task_id));
        assert_eq!(cancelled["result"], json!({}));

        // The work was already in flight and finishes after the cancel. If it
        // won, `tasks/cancel` would mean "maybe", and a client that cancelled a
        // destructive operation would still see it succeed.
        store.complete(&task.task_id, Ok(json!({ "answer": 42 })));
        let read = store.handle_get(json!(2), "client-a", &params(&task.task_id));
        assert_eq!(read["result"]["status"], json!("cancelled"));

        let again = store.handle_cancel(json!(3), "client-a", &params(&task.task_id));
        assert!(again["error"]["message"]
            .as_str()
            .expect("a second cancel is refused with a message")
            .contains("already in terminal status 'cancelled'"));
    }

    #[test]
    fn an_unknown_task_id_is_not_found_rather_than_a_silent_success() {
        let store = McpTaskStore::new();
        for response in [
            store.handle_get(json!(1), "client-a", &params("missing")),
            store.handle_update(json!(2), "client-a", &params("missing")),
        ] {
            assert_eq!(
                response["error"]["message"],
                json!("Failed to retrieve task: task not found")
            );
        }
        assert_eq!(
            store.handle_cancel(json!(3), "client-a", &params("missing"))["error"]["message"],
            json!("Cannot cancel task: task not found")
        );
    }

    #[test]
    fn update_separates_a_malformed_call_from_a_task_that_is_not_waiting() {
        let store = McpTaskStore::new();
        let task = store.create("client-a", None);

        let empty = store.handle_update(json!(1), "client-a", &params(&task.task_id));
        assert_eq!(
            empty["error"]["message"],
            json!("tasks/update requires at least one input response")
        );

        let supplied = store.handle_update(
            json!(2),
            "client-a",
            &json!({ "taskId": task.task_id, "inputResponses": { "q": "a" } }),
        );
        assert_eq!(
            supplied["error"]["message"],
            json!("Task has no outstanding input requests")
        );
    }
}