harn-vm 0.8.92

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
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
866
867
868
869
870
871
872
873
874
875
use super::*;

pub(crate) fn vm_value_to_serde(val: &VmValue) -> serde_json::Value {
    match val {
        VmValue::String(s) => serde_json::Value::String(s.to_string()),
        VmValue::Int(n) => serde_json::json!(*n),
        VmValue::Float(n) => serde_json::json!(*n),
        VmValue::Bool(b) => serde_json::Value::Bool(*b),
        VmValue::Nil => serde_json::Value::Null,
        VmValue::List(items) => {
            serde_json::Value::Array(items.iter().map(vm_value_to_serde).collect())
        }
        VmValue::Dict(map) => {
            let obj: serde_json::Map<String, serde_json::Value> = map
                .iter()
                .map(|(k, v)| (k.clone(), vm_value_to_serde(v)))
                .collect();
            serde_json::Value::Object(obj)
        }
        _ => serde_json::Value::Null,
    }
}

pub(crate) async fn call_mcp_tool(
    client: &VmMcpClientHandle,
    tool_name: &str,
    arguments: serde_json::Value,
) -> Result<serde_json::Value, VmError> {
    let (content, _hint) = call_mcp_tool_with_hint(client, tool_name, arguments).await?;
    Ok(content)
}

/// Variant of [`call_mcp_tool`] that also returns the MCP cache hint
/// from the underlying envelope (when present). Used by
/// [`crate::mcp_host`] so the supervised host can populate its
/// per-(server, tool, args-hash) response cache from the same envelope
/// the unwrapping path consumes — no second network round-trip.
pub(crate) async fn call_mcp_tool_with_hint(
    client: &VmMcpClientHandle,
    tool_name: &str,
    arguments: serde_json::Value,
) -> Result<(serde_json::Value, Option<McpCacheHint>), VmError> {
    // Attach a unique progress token so the server can emit
    // `notifications/progress` updates that we route back into the
    // active session's `agent_inbox`. Tokens are scoped to the active
    // session id (when one is bound) and reaped on call completion via
    // the RAII `ProgressTokenGuard`.
    let progress_token = client_progress::issue_token(&client.name, tool_name);
    let _progress_guard = progress_token
        .as_ref()
        .map(|tok| client_progress::ProgressTokenGuard {
            token: tok.token.clone(),
        });
    let mut result = client
        .call(
            "tools/call",
            tool_call_params(tool_name, arguments.clone(), progress_token.as_ref(), None),
        )
        .await?;
    for _ in 0..MCP_INPUT_REQUIRED_MAX_ROUNDS {
        if result.get("resultType").and_then(|value| value.as_str())
            != Some(RESULT_TYPE_INPUT_REQUIRED)
        {
            break;
        }
        let Some(input_round) = resolve_input_required_result(&client.name, &result).await? else {
            break;
        };
        result = client
            .call(
                "tools/call",
                tool_call_params(
                    tool_name,
                    arguments.clone(),
                    progress_token.as_ref(),
                    Some(input_round),
                ),
            )
            .await?;
    }
    if result.get("resultType").and_then(|value| value.as_str()) == Some(RESULT_TYPE_INPUT_REQUIRED)
    {
        return Err(VmError::Runtime(format!(
            "MCP tool '{tool_name}' still required input after {MCP_INPUT_REQUIRED_MAX_ROUNDS} rounds"
        )));
    }

    if result.get("isError").and_then(|v| v.as_bool()) == Some(true) {
        let error_text = extract_content_text(&result);
        return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
            error_text,
        ))));
    }

    let cache_hint = McpCacheHint::from_result(&result);
    if let Some(structured) = result.get("structuredContent") {
        return Ok((structured.clone(), cache_hint));
    }
    let content = result
        .get("content")
        .and_then(|c| c.as_array())
        .cloned()
        .unwrap_or_default();

    let unwrapped =
        if content.len() == 1 && content[0].get("type").and_then(|t| t.as_str()) == Some("text") {
            if let Some(text) = content[0].get("text").and_then(|t| t.as_str()) {
                serde_json::Value::String(text.to_string())
            } else if content.is_empty() {
                serde_json::Value::Null
            } else {
                serde_json::Value::Array(content)
            }
        } else if content.is_empty() {
            serde_json::Value::Null
        } else {
            serde_json::Value::Array(content)
        };
    Ok((unwrapped, cache_hint))
}

pub(crate) fn tool_call_params(
    tool_name: &str,
    arguments: serde_json::Value,
    progress_token: Option<&client_progress::ProgressTokenContext>,
    input_round: Option<McpInputRound>,
) -> serde_json::Value {
    let mut params = serde_json::Map::from_iter([
        (
            "name".to_string(),
            serde_json::Value::String(tool_name.to_string()),
        ),
        ("arguments".to_string(), arguments),
    ]);
    if let Some(tok) = progress_token {
        params.insert(
            "_meta".to_string(),
            serde_json::json!({ "progressToken": tok.token }),
        );
    }
    if let Some(input_round) = input_round {
        params.insert("inputResponses".to_string(), input_round.input_responses);
        if let Some(request_state) = input_round.request_state {
            params.insert("requestState".to_string(), request_state);
        }
    }
    serde_json::Value::Object(params)
}

pub(crate) async fn resolve_input_required_result(
    server_name: &str,
    result: &serde_json::Value,
) -> Result<Option<McpInputRound>, VmError> {
    let Some(input_requests) = result
        .get("inputRequests")
        .and_then(|value| value.as_object())
    else {
        return Ok(None);
    };
    let mut responses = serde_json::Map::new();
    for (key, input_request) in input_requests {
        let Some(method) = input_request.get("method").and_then(|value| value.as_str()) else {
            return Err(VmError::Runtime(format!(
                "MCP input_required request {key:?} is missing method"
            )));
        };
        let request = serde_json::json!({
            "jsonrpc": "2.0",
            "id": format!("input-{key}"),
            "method": method,
            "params": input_request
                .get("params")
                .cloned()
                .unwrap_or_else(|| serde_json::json!({})),
        });
        let response = handle_inbound_client_request(server_name, &request)
            .await
            .ok_or_else(|| {
                VmError::Runtime(format!(
                    "MCP input_required request {key:?} used unsupported method {method:?}"
                ))
            })?;
        if let Some(result) = response.get("result") {
            responses.insert(key.clone(), result.clone());
        } else if let Some(error) = response.get("error") {
            return Err(jsonrpc_error_to_vm_error(error));
        } else {
            responses.insert(key.clone(), serde_json::Value::Null);
        }
    }
    Ok(Some(McpInputRound {
        input_responses: serde_json::Value::Object(responses),
        request_state: result.get("requestState").cloned(),
    }))
}

pub fn register_mcp_builtins(vm: &mut Vm) {
    vm.register_builtin("mcp_roots", mcp_roots_builtin);
    vm.register_builtin("harn.mcp.roots", mcp_roots_builtin);
    crate::mcp_file_upload::register_mcp_file_upload_builtins(vm);
    register_harn_mcp_namespace(vm);
    register_supervised_mcp_host_builtins(vm);

    vm.register_async_builtin("mcp_connect", |_ctx, args| async move {
        let command = args.first().map(|a| a.display()).unwrap_or_default();
        if command.is_empty() {
            return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
                "mcp_connect: command is required",
            ))));
        }

        let cmd_args: Vec<String> = match args.get(1) {
            Some(VmValue::List(list)) => list.iter().map(|v| v.display()).collect(),
            _ => Vec::new(),
        };

        let options = mcp_connect_options(args.get(2))?;
        let handle = mcp_connect_stdio_impl(
            &command,
            &cmd_args,
            &BTreeMap::new(),
            options.protocol_mode,
            options.protocol_version,
        )
        .await?;
        Ok(VmValue::mcp_client(handle))
    });

    // Lazy registry: ensure a registered server is booted and return its
    // live client handle. Used by skill activation (`requires_mcp`) and
    // by user code that wants to trigger a lazy connect explicitly.
    vm.register_async_builtin("mcp_ensure_active", |_ctx, args| async move {
        let name = match args.first() {
            Some(VmValue::String(s)) => s.to_string(),
            Some(other) => other.display(),
            None => String::new(),
        };
        if name.is_empty() {
            return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
                "mcp_ensure_active: server name is required",
            ))));
        }
        let handle = crate::mcp_registry::ensure_active(&name).await?;
        Ok(VmValue::mcp_client(handle))
    });

    // Decrement the binder refcount for a registered server. Called by
    // skill deactivation paths and by user code that manually bound via
    // `mcp_ensure_active`. No-op when the name isn't registered.
    vm.register_builtin("mcp_release", |args, _out| {
        let name = match args.first() {
            Some(VmValue::String(s)) => s.to_string(),
            Some(other) => other.display(),
            None => {
                return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
                    "mcp_release: server name is required",
                ))));
            }
        };
        crate::mcp_registry::release(&name);
        Ok(VmValue::Nil)
    });

    // Return the declared MCP servers and their current state as a list
    // of dicts. Purely diagnostic — useful for `harn` scripts that want
    // to show connection state in a status-line or dashboard.
    vm.register_builtin("mcp_registry_status", |_args, _out| {
        let mut out = Vec::new();
        for entry in crate::mcp_registry::snapshot_status() {
            let mut dict = BTreeMap::new();
            dict.insert(
                "name".to_string(),
                VmValue::String(std::sync::Arc::from(entry.name.as_str())),
            );
            dict.insert("lazy".to_string(), VmValue::Bool(entry.lazy));
            dict.insert("active".to_string(), VmValue::Bool(entry.active));
            dict.insert(
                "ref_count".to_string(),
                VmValue::Int(entry.ref_count as i64),
            );
            if let Some(card) = entry.card {
                dict.insert(
                    "card".to_string(),
                    VmValue::String(std::sync::Arc::from(card.as_str())),
                );
            }
            out.push(VmValue::Dict(std::sync::Arc::new(dict)));
        }
        Ok(VmValue::List(std::sync::Arc::new(out)))
    });

    // Fetch (or read from cache) the Server Card for a registered MCP
    // server, or from an explicit URL / local path.
    //
    // `mcp_server_card("notion")`           -> looks up `card = ...` in harn.toml
    // `mcp_server_card("https://.../card")` -> fetches that URL directly
    // `mcp_server_card("./card.json")`      -> reads that file directly
    vm.register_async_builtin("mcp_server_card", |_ctx, args| async move {
        let target = match args.first() {
            Some(VmValue::String(s)) => s.to_string(),
            Some(other) => other.display(),
            None => {
                return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
                    "mcp_server_card: server name, URL, or path is required",
                ))));
            }
        };

        // Source resolution: if the arg looks like a URL or path
        // (contains '/', '\\', or starts with a scheme), use it as-is.
        // Otherwise treat it as a registered server name and look up
        // its `card` field. This matches the user model: "I already
        // wrote down where the card lives in harn.toml — just use it."
        let source = if target.starts_with("http://")
            || target.starts_with("https://")
            || target.contains('/')
            || target.contains('\\')
            || target.ends_with(".json")
        {
            target.clone()
        } else {
            match crate::mcp_registry::get_registration(&target) {
                Some(reg) => match reg.card {
                    Some(card) => card,
                    None => {
                        return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
                            format!(
                            "mcp_server_card: server '{target}' has no 'card' field in harn.toml"
                        ),
                        ))));
                    }
                },
                None => {
                    return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
                        format!(
                        "mcp_server_card: no MCP server '{target}' registered (check harn.toml) \
                         — pass a URL or path directly instead"
                    ),
                    ))));
                }
            }
        };

        let card = crate::mcp_card::fetch_server_card(&source, None)
            .await
            .map_err(|e| {
                VmError::Thrown(VmValue::String(std::sync::Arc::from(format!(
                    "mcp_server_card: {e}"
                ))))
            })?;
        Ok(json_to_vm_value(&card))
    });

    vm.register_async_builtin("mcp_list_tools", |_ctx, args| async move {
        let client = match args.first() {
            Some(VmValue::McpClient(c)) => c.clone(),
            _ => {
                return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
                    "mcp_list_tools: argument must be an MCP client",
                ))));
            }
        };

        let result = client.call("tools/list", serde_json::json!({})).await?;
        client.record_cache_hint("tools/list", &result).await;
        let mut tools = result
            .get("tools")
            .and_then(|t| t.as_array())
            .cloned()
            .unwrap_or_default();
        if client.protocol_mode().await? == McpProtocolMode::Modern {
            tools = filter_tools_for_client(&tools);
            client.store_http_tool_headers(&tools).await;
        }

        // Tag every tool with its originating server name so
        // downstream indexers (tool_search BM25) can surface them
        // under queries like "github" or "mcp:github". Harmless to
        // non-indexing callers — just an extra dict key.
        let server_name = client.name.clone();
        for tool in tools.iter_mut() {
            if let Some(obj) = tool.as_object_mut() {
                obj.entry("_mcp_server")
                    .or_insert_with(|| serde_json::Value::String(server_name.clone()));
            }
        }

        let vm_tools: Vec<VmValue> = tools.iter().map(json_to_vm_value).collect();
        Ok(VmValue::List(std::sync::Arc::new(vm_tools)))
    });

    vm.register_async_builtin("mcp_call", |_ctx, args| async move {
        let client = match args.first() {
            Some(VmValue::McpClient(c)) => c.clone(),
            _ => {
                return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
                    "mcp_call: first argument must be an MCP client",
                ))));
            }
        };

        let tool_name = args.get(1).map(|a| a.display()).unwrap_or_default();
        if tool_name.is_empty() {
            return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
                "mcp_call: tool name is required",
            ))));
        }

        let arguments = match args.get(2) {
            Some(VmValue::Dict(d)) => {
                let obj: serde_json::Map<String, serde_json::Value> = d
                    .iter()
                    .map(|(k, v)| (k.clone(), vm_value_to_serde(v)))
                    .collect();
                serde_json::Value::Object(obj)
            }
            _ => serde_json::json!({}),
        };

        Ok(json_to_vm_value(
            &call_mcp_tool(&client, &tool_name, arguments).await?,
        ))
    });

    vm.register_async_builtin("mcp_server_info", |_ctx, args| async move {
        let client = match args.first() {
            Some(VmValue::McpClient(c)) => c.clone(),
            _ => {
                return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
                    "mcp_server_info: argument must be an MCP client",
                ))));
            }
        };

        let guard = client.inner.lock().await;
        if guard.is_none() {
            return Err(VmError::Runtime("MCP client is disconnected".into()));
        }
        drop(guard);

        let mut info = BTreeMap::new();
        info.insert(
            "name".to_string(),
            VmValue::String(std::sync::Arc::from(client.name.as_str())),
        );
        info.insert("connected".to_string(), VmValue::Bool(true));
        let initialize = client
            .initialize_result
            .lock()
            .await
            .clone()
            .unwrap_or(serde_json::Value::Null);
        if !initialize.is_null() {
            if let Some(instructions) = initialize
                .get("instructions")
                .or_else(|| {
                    initialize
                        .get("serverInfo")
                        .and_then(|value| value.get("instructions"))
                })
                .and_then(|value| value.as_str())
                .filter(|value| !value.is_empty())
            {
                info.insert(
                    "instructions".to_string(),
                    VmValue::String(std::sync::Arc::from(instructions)),
                );
            }
            info.insert("initialize".to_string(), json_to_vm_value(&initialize));
        }
        let cache_hints = client.cache_hints.lock().await;
        if !cache_hints.is_empty() {
            info.insert(
                "cache_hints".to_string(),
                json_to_vm_value(&cache_hints_to_json(cache_hints.iter())),
            );
        }
        Ok(VmValue::Dict(std::sync::Arc::new(info)))
    });

    vm.register_async_builtin("mcp_disconnect", |_ctx, args| async move {
        let client = match args.first() {
            Some(VmValue::McpClient(c)) => c.clone(),
            _ => {
                return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
                    "mcp_disconnect: argument must be an MCP client",
                ))));
            }
        };

        client.disconnect().await?;
        Ok(VmValue::Nil)
    });

    vm.register_async_builtin("mcp_list_resources", |_ctx, args| async move {
        let client = match args.first() {
            Some(VmValue::McpClient(c)) => c.clone(),
            _ => {
                return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
                    "mcp_list_resources: argument must be an MCP client",
                ))));
            }
        };

        let result = client.call("resources/list", serde_json::json!({})).await?;
        client.record_cache_hint("resources/list", &result).await;
        let resources = result
            .get("resources")
            .and_then(|r| r.as_array())
            .cloned()
            .unwrap_or_default();

        let vm_resources: Vec<VmValue> = resources.iter().map(json_to_vm_value).collect();
        Ok(VmValue::List(std::sync::Arc::new(vm_resources)))
    });

    vm.register_async_builtin("mcp_read_resource", |_ctx, args| async move {
        let client = match args.first() {
            Some(VmValue::McpClient(c)) => c.clone(),
            _ => {
                return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
                    "mcp_read_resource: first argument must be an MCP client",
                ))));
            }
        };

        let uri = args.get(1).map(|a| a.display()).unwrap_or_default();
        if uri.is_empty() {
            return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
                "mcp_read_resource: URI is required",
            ))));
        }

        let result = client
            .call("resources/read", serde_json::json!({ "uri": uri }))
            .await?;
        client.record_cache_hint("resources/read", &result).await;

        let contents = result
            .get("contents")
            .and_then(|c| c.as_array())
            .cloned()
            .unwrap_or_default();

        if contents.len() == 1 {
            if let Some(text) = contents[0].get("text").and_then(|t| t.as_str()) {
                return Ok(VmValue::String(std::sync::Arc::from(text)));
            }
        }

        if contents.is_empty() {
            Ok(VmValue::Nil)
        } else {
            Ok(VmValue::List(std::sync::Arc::new(
                contents.iter().map(json_to_vm_value).collect(),
            )))
        }
    });

    vm.register_async_builtin("mcp_list_resource_templates", |_ctx, args| async move {
        let client = match args.first() {
            Some(VmValue::McpClient(c)) => c.clone(),
            _ => {
                return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
                    "mcp_list_resource_templates: argument must be an MCP client",
                ))));
            }
        };

        let result = client
            .call("resources/templates/list", serde_json::json!({}))
            .await?;
        client
            .record_cache_hint("resources/templates/list", &result)
            .await;

        let templates = result
            .get("resourceTemplates")
            .and_then(|r| r.as_array())
            .cloned()
            .unwrap_or_default();

        let vm_templates: Vec<VmValue> = templates.iter().map(json_to_vm_value).collect();
        Ok(VmValue::List(std::sync::Arc::new(vm_templates)))
    });

    vm.register_async_builtin("mcp_list_prompts", |_ctx, args| async move {
        let client = match args.first() {
            Some(VmValue::McpClient(c)) => c.clone(),
            _ => {
                return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
                    "mcp_list_prompts: argument must be an MCP client",
                ))));
            }
        };

        let result = client.call("prompts/list", serde_json::json!({})).await?;
        client.record_cache_hint("prompts/list", &result).await;

        let prompts = result
            .get("prompts")
            .and_then(|p| p.as_array())
            .cloned()
            .unwrap_or_default();

        let vm_prompts: Vec<VmValue> = prompts.iter().map(json_to_vm_value).collect();
        Ok(VmValue::List(std::sync::Arc::new(vm_prompts)))
    });

    vm.register_async_builtin("mcp_get_prompt", |_ctx, args| async move {
        let client = match args.first() {
            Some(VmValue::McpClient(c)) => c.clone(),
            _ => {
                return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
                    "mcp_get_prompt: first argument must be an MCP client",
                ))));
            }
        };

        let name = args.get(1).map(|a| a.display()).unwrap_or_default();
        if name.is_empty() {
            return Err(VmError::Thrown(VmValue::String(std::sync::Arc::from(
                "mcp_get_prompt: prompt name is required",
            ))));
        }

        let arguments = match args.get(2) {
            Some(VmValue::Dict(d)) => {
                let obj: serde_json::Map<String, serde_json::Value> = d
                    .iter()
                    .map(|(k, v)| (k.clone(), vm_value_to_serde(v)))
                    .collect();
                serde_json::Value::Object(obj)
            }
            _ => serde_json::json!({}),
        };

        let result = client
            .call(
                "prompts/get",
                serde_json::json!({
                    "name": name,
                    "arguments": arguments,
                }),
            )
            .await?;

        Ok(json_to_vm_value(&result))
    });
}

pub(crate) fn mcp_roots_builtin(_args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    Ok(VmValue::List(std::sync::Arc::new(
        current_mcp_roots()
            .iter()
            .map(|root| json_to_vm_value(&root.script_json()))
            .collect(),
    )))
}

pub(crate) fn register_harn_mcp_namespace(vm: &mut Vm) {
    let mcp_namespace = VmValue::Dict(std::sync::Arc::new(BTreeMap::from([
        (
            "_namespace".to_string(),
            VmValue::String(std::sync::Arc::from("harn.mcp")),
        ),
        (
            "roots".to_string(),
            VmValue::BuiltinRef(std::sync::Arc::from("harn.mcp.roots")),
        ),
        (
            "configure".to_string(),
            VmValue::BuiltinRef(std::sync::Arc::from("harn.mcp.configure")),
        ),
        (
            "file_input".to_string(),
            VmValue::BuiltinRef(std::sync::Arc::from("harn.mcp.file_input")),
        ),
        (
            "upload_file".to_string(),
            VmValue::BuiltinRef(std::sync::Arc::from("harn.mcp.upload_file")),
        ),
        // Supervised host primitive (#2504, A.7). spawn/tools/call/stop
        // route to `crate::mcp_host` and add restart-budget, circuit
        // breaker, response cache, and allowlist enforcement on top of
        // the lazy-boot `mcp_registry` they share.
        (
            "spawn".to_string(),
            VmValue::BuiltinRef(std::sync::Arc::from("harn.mcp.spawn")),
        ),
        (
            "tools".to_string(),
            VmValue::BuiltinRef(std::sync::Arc::from("harn.mcp.tools")),
        ),
        (
            "call".to_string(),
            VmValue::BuiltinRef(std::sync::Arc::from("harn.mcp.call")),
        ),
        (
            "stop".to_string(),
            VmValue::BuiltinRef(std::sync::Arc::from("harn.mcp.stop")),
        ),
        (
            "discover".to_string(),
            VmValue::BuiltinRef(std::sync::Arc::from("harn.mcp.discover")),
        ),
        (
            "reload".to_string(),
            VmValue::BuiltinRef(std::sync::Arc::from("harn.mcp.reload")),
        ),
        (
            "status".to_string(),
            VmValue::BuiltinRef(std::sync::Arc::from("harn.mcp.status")),
        ),
    ])));
    vm.set_global(
        "harn",
        VmValue::Dict(std::sync::Arc::new(BTreeMap::from([
            (
                "_namespace".to_string(),
                VmValue::String(std::sync::Arc::from("harn")),
            ),
            (
                "mcp_roots".to_string(),
                VmValue::BuiltinRef(std::sync::Arc::from("harn.mcp.roots")),
            ),
            ("mcp".to_string(), mcp_namespace),
        ]))),
    );
}

/// Register the supervised MCP host builtins owned by [`crate::mcp_host`].
/// Each builtin is a thin adapter that converts VM values to/from JSON
/// and delegates to the host module. The host module owns supervision
/// state, the response cache, allowlist enforcement, and tracing spans.
pub(crate) fn register_supervised_mcp_host_builtins(vm: &mut Vm) {
    vm.register_async_builtin("harn.mcp.spawn", |_ctx, args| async move {
        let spec_value = args
            .first()
            .ok_or_else(|| VmError::Runtime("harn.mcp.spawn: spec dict is required".into()))?;
        let spec = vm_value_to_serde(spec_value);
        let options: crate::mcp_host::SpawnOptions = match args.get(1) {
            Some(VmValue::Dict(_)) => {
                let options_json = vm_value_to_serde(args.get(1).unwrap());
                serde_json::from_value(options_json).map_err(|e| {
                    VmError::Runtime(format!("harn.mcp.spawn: invalid options dict: {e}"))
                })?
            }
            _ => Default::default(),
        };
        let name = crate::mcp_host::spawn(spec, options).await?;
        Ok(VmValue::String(std::sync::Arc::from(name)))
    });

    vm.register_async_builtin("harn.mcp.tools", |_ctx, args| async move {
        let name = match args.first() {
            Some(VmValue::String(s)) => s.to_string(),
            Some(other) => other.display(),
            None => {
                return Err(VmError::Runtime(
                    "harn.mcp.tools: server name (string) is required".into(),
                ));
            }
        };
        let tools = crate::mcp_host::tools(&name).await?;
        Ok(VmValue::List(std::sync::Arc::new(
            tools.iter().map(json_to_vm_value).collect(),
        )))
    });

    vm.register_async_builtin("harn.mcp.call", |_ctx, args| async move {
        let name = match args.first() {
            Some(VmValue::String(s)) => s.to_string(),
            Some(other) => other.display(),
            None => {
                return Err(VmError::Runtime(
                    "harn.mcp.call: server name (string) is required".into(),
                ));
            }
        };
        let tool = match args.get(1) {
            Some(VmValue::String(s)) => s.to_string(),
            Some(other) => other.display(),
            None => {
                return Err(VmError::Runtime(
                    "harn.mcp.call: tool name (string) is required".into(),
                ));
            }
        };
        let tool_args = match args.get(2) {
            Some(VmValue::Dict(d)) => {
                let obj: serde_json::Map<String, serde_json::Value> = d
                    .iter()
                    .map(|(k, v)| (k.clone(), vm_value_to_serde(v)))
                    .collect();
                serde_json::Value::Object(obj)
            }
            Some(VmValue::Nil) | None => serde_json::json!({}),
            Some(other) => vm_value_to_serde(other),
        };
        let result = crate::mcp_host::call(&name, &tool, tool_args).await?;
        Ok(json_to_vm_value(&result))
    });

    vm.register_builtin("harn.mcp.stop", |args, _out| {
        let name = match args.first() {
            Some(VmValue::String(s)) => s.to_string(),
            Some(other) => other.display(),
            None => {
                return Err(VmError::Runtime(
                    "harn.mcp.stop: server name (string) is required".into(),
                ));
            }
        };
        crate::mcp_host::stop(&name)?;
        Ok(VmValue::Nil)
    });

    vm.register_builtin("harn.mcp.reload", |args, _out| {
        let name = match args.first() {
            Some(VmValue::String(s)) => s.to_string(),
            Some(other) => other.display(),
            None => {
                return Err(VmError::Runtime(
                    "harn.mcp.reload: server name (string) is required".into(),
                ));
            }
        };
        crate::mcp_host::reload(&name)?;
        Ok(VmValue::Nil)
    });

    vm.register_async_builtin("harn.mcp.discover", |_ctx, _args| async move {
        let entries = crate::mcp_host::discover().await?;
        Ok(VmValue::List(std::sync::Arc::new(
            entries.iter().map(json_to_vm_value).collect(),
        )))
    });

    vm.register_builtin("harn.mcp.status", |_args, _out| {
        let entries = crate::mcp_host::status();
        let list: Vec<VmValue> = entries
            .into_iter()
            .map(|s| {
                let mut dict = BTreeMap::new();
                dict.insert(
                    "name".to_string(),
                    VmValue::String(std::sync::Arc::from(s.name)),
                );
                dict.insert("active".to_string(), VmValue::Bool(s.active));
                dict.insert("lazy".to_string(), VmValue::Bool(s.lazy));
                dict.insert("ref_count".to_string(), VmValue::Int(s.ref_count as i64));
                dict.insert(
                    "restart_count".to_string(),
                    VmValue::Int(s.restart_count as i64),
                );
                dict.insert(
                    "consecutive_failures".to_string(),
                    VmValue::Int(s.consecutive_failures as i64),
                );
                dict.insert(
                    "circuit".to_string(),
                    VmValue::String(std::sync::Arc::from(s.circuit.as_str())),
                );
                dict.insert("ejected".to_string(), VmValue::Bool(s.ejected));
                dict.insert(
                    "cache_entries".to_string(),
                    VmValue::Int(s.cache_entries as i64),
                );
                VmValue::Dict(std::sync::Arc::new(dict))
            })
            .collect();
        Ok(VmValue::List(std::sync::Arc::new(list)))
    });
}