tandem-runtime 0.5.9

Runtime utilities for Tandem
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
#[cfg(test)]
mod tests {
    use super::*;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener;
    use uuid::Uuid;

    async fn spawn_fake_http_mcp_server() -> (String, tokio::task::JoinHandle<()>) {
        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind fake mcp server");
        let addr = listener.local_addr().expect("fake mcp addr");
        let handle = tokio::spawn(async move {
            loop {
                let Ok((mut socket, _)) = listener.accept().await else {
                    break;
                };
                tokio::spawn(async move {
                    let mut buf = vec![0_u8; 8192];
                    let Ok(n) = socket.read(&mut buf).await else {
                        return;
                    };
                    let request = String::from_utf8_lossy(&buf[..n]);
                    let body = if request.contains("\"initialize\"") {
                        json!({
                            "jsonrpc": "2.0",
                            "id": "initialize-1",
                            "result": {
                                "protocolVersion": MCP_PROTOCOL_VERSION,
                                "capabilities": {},
                                "serverInfo": {"name": "fake", "version": "test"}
                            }
                        })
                    } else if request.contains("\"tools/list\"") {
                        json!({
                            "jsonrpc": "2.0",
                            "id": "tools-list-1",
                            "result": {
                                "tools": [{
                                    "name": "get_me",
                                    "description": "Get authenticated user",
                                    "inputSchema": {"type": "object", "properties": {}}
                                }]
                            }
                        })
                    } else if request.contains("\"tools/call\"") {
                        json!({
                            "jsonrpc": "2.0",
                            "id": "call-1",
                            "result": {
                                "content": [{"type": "text", "text": "authenticated"}]
                            }
                        })
                    } else {
                        json!({
                            "jsonrpc": "2.0",
                            "id": "unknown",
                            "error": {"code": -32601, "message": "unknown method"}
                        })
                    };
                    let payload = body.to_string();
                    let response = format!(
                        "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nmcp-session-id: test-session\r\nconnection: close\r\n\r\n{}",
                        payload.len(),
                        payload
                    );
                    let _ = socket.write_all(response.as_bytes()).await;
                });
            }
        });
        (format!("http://{addr}/mcp"), handle)
    }

    async fn spawn_auth_required_http_mcp_server(
        expected_authorization: &'static str,
    ) -> (String, tokio::task::JoinHandle<()>) {
        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind fake auth mcp server");
        let addr = listener.local_addr().expect("fake auth mcp addr");
        let handle = tokio::spawn(async move {
            loop {
                let Ok((mut socket, _)) = listener.accept().await else {
                    break;
                };
                tokio::spawn(async move {
                    let mut buf = vec![0_u8; 8192];
                    let Ok(n) = socket.read(&mut buf).await else {
                        return;
                    };
                    let request = String::from_utf8_lossy(&buf[..n]);
                    let request_lower = request.to_ascii_lowercase();
                    let authorized = request_lower.contains(&format!(
                        "authorization: {}",
                        expected_authorization.to_ascii_lowercase()
                    ));
                    let body = if request.contains("\"initialize\"") {
                        json!({
                            "jsonrpc": "2.0",
                            "id": "initialize-1",
                            "result": {
                                "protocolVersion": MCP_PROTOCOL_VERSION,
                                "capabilities": {},
                                "serverInfo": {"name": "fake", "version": "test"}
                            }
                        })
                    } else if request.contains("\"tools/list\"") {
                        json!({
                            "jsonrpc": "2.0",
                            "id": "tools-list-1",
                            "result": {
                                "tools": [{
                                    "name": "get_me",
                                    "description": "Get authenticated user",
                                    "inputSchema": {"type": "object", "properties": {}}
                                }]
                            }
                        })
                    } else if request.contains("\"tools/call\"") && authorized {
                        json!({
                            "jsonrpc": "2.0",
                            "id": "call-1",
                            "result": {
                                "content": [{"type": "text", "text": "tenant-authenticated"}]
                            }
                        })
                    } else if request.contains("\"tools/call\"") {
                        json!({
                            "jsonrpc": "2.0",
                            "id": "call-1",
                            "error": {"code": -32001, "message": "unauthorized"}
                        })
                    } else {
                        json!({
                            "jsonrpc": "2.0",
                            "id": "unknown",
                            "error": {"code": -32601, "message": "unknown method"}
                        })
                    };
                    let payload = body.to_string();
                    let response = format!(
                        "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nmcp-session-id: test-session\r\nconnection: close\r\n\r\n{}",
                        payload.len(),
                        payload
                    );
                    let _ = socket.write_all(response.as_bytes()).await;
                });
            }
        });
        (format!("http://{addr}/mcp"), handle)
    }

    #[tokio::test]
    async fn add_connect_disconnect_non_stdio_server() {
        let file = std::env::temp_dir().join(format!("mcp-test-{}.json", Uuid::new_v4()));
        let registry = McpRegistry::new_with_state_file(file);
        registry
            .add("example".to_string(), "sse:https://example.com".to_string())
            .await;
        assert!(registry.connect("example").await);
        let listed = registry.list().await;
        assert!(listed.get("example").map(|s| s.connected).unwrap_or(false));
        assert!(registry.disconnect("example").await);
    }

    #[tokio::test]
    async fn call_tool_reconnects_enabled_remote_server_before_execution() {
        let (endpoint, server) = spawn_fake_http_mcp_server().await;
        let file = std::env::temp_dir().join(format!("mcp-test-{}.json", Uuid::new_v4()));
        let registry = McpRegistry::new_with_state_file(file);
        registry
            .add("githubcopilot".to_string(), endpoint.to_string())
            .await;

        assert!(registry.connect("githubcopilot").await);
        assert!(registry.disconnect("githubcopilot").await);
        assert!(
            !registry
                .list()
                .await
                .get("githubcopilot")
                .expect("server")
                .connected
        );

        let result = registry
            .call_tool("githubcopilot", "get_me", json!({}))
            .await
            .expect("call should reconnect and execute");

        assert!(result.output.contains("authenticated"));
        assert!(
            registry
                .list()
                .await
                .get("githubcopilot")
                .expect("server")
                .connected
        );
        server.abort();
    }

    #[tokio::test]
    async fn ensure_ready_rejects_unknown_server_with_typed_error() {
        let file = std::env::temp_dir().join(format!("mcp-test-{}.json", Uuid::new_v4()));
        let registry = McpRegistry::new_with_state_file(file);
        let err = registry
            .ensure_ready("nope", EnsureReadyPolicy::default())
            .await
            .expect_err("missing server should error");
        assert_eq!(err, McpReadyError::NotFound);
    }

    #[tokio::test]
    async fn ensure_ready_rejects_disabled_server_with_typed_error() {
        let file = std::env::temp_dir().join(format!("mcp-test-{}.json", Uuid::new_v4()));
        let registry = McpRegistry::new_with_state_file(file);
        registry
            .add("example".to_string(), "sse:https://example.com".to_string())
            .await;
        registry.set_enabled("example", false).await;
        let err = registry
            .ensure_ready("example", EnsureReadyPolicy::default())
            .await
            .expect_err("disabled server should error");
        assert_eq!(err, McpReadyError::Disabled);
    }

    #[tokio::test]
    async fn ensure_ready_returns_already_connected_server_without_reconnecting() {
        let (endpoint, server) = spawn_fake_http_mcp_server().await;
        let file = std::env::temp_dir().join(format!("mcp-test-{}.json", Uuid::new_v4()));
        let registry = McpRegistry::new_with_state_file(file);
        registry
            .add("githubcopilot".to_string(), endpoint.to_string())
            .await;
        assert!(registry.connect("githubcopilot").await);

        let ready = registry
            .ensure_ready("githubcopilot", EnsureReadyPolicy::default())
            .await
            .expect("connected server should be ready");
        assert!(ready.connected);
        server.abort();
    }

    #[tokio::test]
    async fn ensure_ready_reconnects_when_disconnected() {
        let (endpoint, server) = spawn_fake_http_mcp_server().await;
        let file = std::env::temp_dir().join(format!("mcp-test-{}.json", Uuid::new_v4()));
        let registry = McpRegistry::new_with_state_file(file);
        registry
            .add("githubcopilot".to_string(), endpoint.to_string())
            .await;
        assert!(registry.connect("githubcopilot").await);
        assert!(registry.disconnect("githubcopilot").await);

        let ready = registry
            .ensure_ready("githubcopilot", EnsureReadyPolicy::default())
            .await
            .expect("ensure_ready should reconnect");
        assert!(ready.connected);
        server.abort();
    }

    #[tokio::test]
    async fn ensure_ready_returns_permanently_failed_when_endpoint_unreachable() {
        let file = std::env::temp_dir().join(format!("mcp-test-{}.json", Uuid::new_v4()));
        let registry = McpRegistry::new_with_state_file(file);
        registry
            .add(
                "broken".to_string(),
                "https://127.0.0.1:1/unreachable".to_string(),
            )
            .await;

        let err = registry
            .ensure_ready("broken", EnsureReadyPolicy::default())
            .await
            .expect_err("unreachable endpoint should permanently fail");
        assert!(matches!(err, McpReadyError::PermanentlyFailed { .. }));
    }

    #[test]
    fn parse_remote_endpoint_supports_http_prefixes() {
        assert_eq!(
            parse_remote_endpoint("https://mcp.example.com/mcp"),
            Some("https://mcp.example.com/mcp".to_string())
        );
        assert_eq!(
            parse_remote_endpoint("http:https://mcp.example.com/mcp"),
            Some("https://mcp.example.com/mcp".to_string())
        );
    }

    #[test]
    fn normalize_schema_removes_non_string_enums_recursively() {
        let mut schema = json!({
            "type": "object",
            "properties": {
                "good": { "type": "string", "enum": ["a", "b"] },
                "good_nullable": { "type": ["string", "null"], "enum": ["asc", "desc"] },
                "bad_object": { "type": "object", "enum": ["asc", "desc"] },
                "bad_array": { "type": "array", "enum": ["asc", "desc"] },
                "bad_number": { "type": "number", "enum": [1, 2] },
                "bad_mixed": { "enum": ["ok", 1] },
                "nested": {
                    "type": "object",
                    "properties": {
                        "child": { "enum": [true, false] }
                    }
                }
            }
        });

        normalize_tool_input_schema(&mut schema);

        assert!(
            schema["properties"]["good"]["enum"].is_array(),
            "string enums should be preserved"
        );
        assert!(
            schema["properties"]["good_nullable"]["enum"].is_array(),
            "string|null enums should be preserved"
        );
        assert!(
            schema["properties"]["bad_object"]["enum"].is_null(),
            "object enums should be dropped"
        );
        assert!(
            schema["properties"]["bad_array"]["enum"].is_null(),
            "array enums should be dropped"
        );
        assert!(
            schema["properties"]["bad_number"]["enum"].is_null(),
            "non-string enums should be dropped"
        );
        assert!(
            schema["properties"]["bad_mixed"]["enum"].is_null(),
            "mixed enums should be dropped"
        );
        assert!(
            schema["properties"]["nested"]["properties"]["child"]["enum"].is_null(),
            "recursive non-string enums should be dropped"
        );
    }

    #[test]
    fn extract_auth_challenge_from_result_payload() {
        let payload = json!({
            "content": [
                {
                    "type": "text",
                    "llm_instructions": "Authorize Gmail access first.",
                    "authorization_url": "https://example.com/oauth/start"
                }
            ]
        });
        let challenge = extract_auth_challenge(&payload, "gmail_whoami")
            .expect("auth challenge should be detected");
        assert_eq!(challenge.tool_name, "gmail_whoami");
        assert_eq!(
            challenge.authorization_url,
            "https://example.com/oauth/start"
        );
        assert_eq!(challenge.status, "pending");
    }

    #[test]
    fn extract_auth_challenge_returns_none_without_url() {
        let payload = json!({
            "content": [
                {"type":"text","text":"No authorization needed"}
            ]
        });
        assert!(extract_auth_challenge(&payload, "gmail_whoami").is_none());
    }

    #[test]
    fn extract_auth_challenge_prefers_structured_content_message() {
        let payload = json!({
            "content": [
                {
                    "type": "text",
                    "text": "{\"authorization_url\":\"https://example.com/oauth\",\"message\":\"json blob\"}"
                }
            ],
            "structuredContent": {
                "authorization_url": "https://example.com/oauth",
                "message": "Authorize Reddit access first."
            }
        });
        let challenge = extract_auth_challenge(&payload, "reddit_getmyusername")
            .expect("auth challenge should be detected");
        assert_eq!(challenge.message, "Authorize Reddit access first.");
    }

    #[test]
    fn sanitize_auth_message_compacts_llm_instructions() {
        let raw = "Please show the following link to the end user formatted as markdown: https://example.com/auth\nInform the end user that this tool requires authorization.";
        let message = sanitize_auth_message(raw);
        assert!(!message.contains('\n'));
        assert!(message.len() <= 283);
    }

    #[test]
    fn normalize_mcp_tool_args_maps_clickup_aliases() {
        let server = McpServer {
            name: "arcade".to_string(),
            transport: "https://example.com/mcp".to_string(),
            auth_kind: String::new(),
            enabled: true,
            connected: true,
            pid: None,
            last_error: None,
            last_auth_challenge: None,
            mcp_session_id: None,
            headers: HashMap::new(),
            secret_headers: HashMap::new(),
            tool_cache: vec![McpToolCacheEntry {
                tool_name: "Clickup_CreateTask".to_string(),
                description: "Create task".to_string(),
                input_schema: json!({
                    "type":"object",
                    "properties":{
                        "list_id":{"type":"string"},
                        "task_title":{"type":"string"}
                    },
                    "required":["list_id","task_title"]
                }),
                fetched_at_ms: 0,
                schema_hash: "x".to_string(),
            }],
            tools_fetched_at_ms: None,
            pending_auth_by_tool: HashMap::new(),
            allowed_tools: None,
            purpose: String::new(),
            grounding_required: false,
            secret_header_values: HashMap::new(),
            oauth: None,
        };

        let normalized = normalize_mcp_tool_args(
            &server,
            "Clickup_CreateTask",
            json!({
                "listId": "123",
                "name": "Prep fish"
            }),
        );
        assert_eq!(
            normalized.get("list_id").and_then(|v| v.as_str()),
            Some("123")
        );
        assert_eq!(
            normalized.get("task_title").and_then(|v| v.as_str()),
            Some("Prep fish")
        );
    }

    #[test]
    fn normalize_arg_key_ignores_case_and_separators() {
        assert_eq!(normalize_arg_key("task_title"), "tasktitle");
        assert_eq!(normalize_arg_key("taskTitle"), "tasktitle");
        assert_eq!(normalize_arg_key("task-title"), "tasktitle");
    }

    #[test]
    fn pending_auth_blocks_retries_within_cooldown() {
        let mut server = McpServer {
            name: "arcade".to_string(),
            transport: "https://example.com/mcp".to_string(),
            auth_kind: String::new(),
            enabled: true,
            connected: true,
            pid: None,
            last_error: None,
            last_auth_challenge: None,
            mcp_session_id: None,
            headers: HashMap::new(),
            secret_headers: HashMap::new(),
            tool_cache: Vec::new(),
            tools_fetched_at_ms: None,
            pending_auth_by_tool: HashMap::new(),
            allowed_tools: None,
            purpose: String::new(),
            grounding_required: false,
            secret_header_values: HashMap::new(),
            oauth: None,
        };
        server.pending_auth_by_tool.insert(
            "clickup_whoami".to_string(),
            PendingMcpAuth {
                challenge_id: "abc".to_string(),
                authorization_url: "https://example.com/auth".to_string(),
                message: "Authorize ClickUp access.".to_string(),
                status: "pending".to_string(),
                first_seen_ms: 1_000,
                last_probe_ms: 2_000,
            },
        );
        let blocked =
            pending_auth_short_circuit(&server, "clickup_whoami", "Clickup_WhoAmI", 10_000, 15_000)
                .expect("should block");
        assert!(blocked.output.contains("Authorization pending"));
        assert!(blocked
            .mcp_auth
            .get("pending")
            .and_then(|v| v.as_bool())
            .unwrap_or(false));
    }

    #[test]
    fn pending_auth_allows_probe_after_cooldown() {
        let mut server = McpServer {
            name: "arcade".to_string(),
            transport: "https://example.com/mcp".to_string(),
            auth_kind: String::new(),
            enabled: true,
            connected: true,
            pid: None,
            last_error: None,
            last_auth_challenge: None,
            mcp_session_id: None,
            headers: HashMap::new(),
            secret_headers: HashMap::new(),
            tool_cache: Vec::new(),
            tools_fetched_at_ms: None,
            pending_auth_by_tool: HashMap::new(),
            allowed_tools: None,
            purpose: String::new(),
            grounding_required: false,
            secret_header_values: HashMap::new(),
            oauth: None,
        };
        server.pending_auth_by_tool.insert(
            "clickup_whoami".to_string(),
            PendingMcpAuth {
                challenge_id: "abc".to_string(),
                authorization_url: "https://example.com/auth".to_string(),
                message: "Authorize ClickUp access.".to_string(),
                status: "pending".to_string(),
                first_seen_ms: 1_000,
                last_probe_ms: 2_000,
            },
        );
        assert!(
            pending_auth_short_circuit(&server, "clickup_whoami", "Clickup_WhoAmI", 17_001, 15_000)
                .is_none(),
            "cooldown elapsed should allow re-probe"
        );
    }

    #[test]
    fn pending_auth_is_tool_scoped() {
        let mut server = McpServer {
            name: "arcade".to_string(),
            transport: "https://example.com/mcp".to_string(),
            auth_kind: String::new(),
            enabled: true,
            connected: true,
            pid: None,
            last_error: None,
            last_auth_challenge: None,
            mcp_session_id: None,
            headers: HashMap::new(),
            secret_headers: HashMap::new(),
            tool_cache: Vec::new(),
            tools_fetched_at_ms: None,
            pending_auth_by_tool: HashMap::new(),
            allowed_tools: None,
            purpose: String::new(),
            grounding_required: false,
            secret_header_values: HashMap::new(),
            oauth: None,
        };
        server.pending_auth_by_tool.insert(
            "gmail_sendemail".to_string(),
            PendingMcpAuth {
                challenge_id: "abc".to_string(),
                authorization_url: "https://example.com/auth".to_string(),
                message: "Authorize Gmail access.".to_string(),
                status: "pending".to_string(),
                first_seen_ms: 1_000,
                last_probe_ms: 2_000,
            },
        );
        assert!(pending_auth_short_circuit(
            &server,
            "gmail_sendemail",
            "Gmail_SendEmail",
            2_100,
            15_000
        )
        .is_some());
        assert!(pending_auth_short_circuit(
            &server,
            "clickup_whoami",
            "Clickup_WhoAmI",
            2_100,
            15_000
        )
        .is_none());
    }

    #[test]
    fn store_secret_ref_requires_matching_tenant_context() {
        let secret_id = "mcp_header::tenant::authorization".to_string();

        let current_tenant = TenantContext::explicit("tenant", "workspace", None);
        tandem_core::set_provider_auth_for_tenant(&current_tenant, &secret_id, "tenant-secret")
            .expect("store secret");
        let matching_ref = McpSecretRef::Store {
            secret_id: secret_id.clone(),
            tenant_context: current_tenant.clone(),
        };
        assert_eq!(
            resolve_secret_ref_value(&matching_ref, &current_tenant).as_deref(),
            Some("tenant-secret")
        );

        let mismatched_tenant = TenantContext::explicit("tenant", "other-workspace", None);
        assert!(
            resolve_secret_ref_value(&matching_ref, &mismatched_tenant).is_none(),
            "tenant mismatch should block secret lookup"
        );

        let _ = tandem_core::delete_provider_auth_for_tenant(&current_tenant, &secret_id);
    }

    #[test]
    fn env_secret_refs_are_local_only() {
        std::env::set_var("TANDEM_TEST_MCP_SECRET", "env-secret");
        let secret_ref = McpSecretRef::Env {
            env: "TANDEM_TEST_MCP_SECRET".to_string(),
        };

        assert_eq!(
            resolve_secret_ref_value(&secret_ref, &TenantContext::local_implicit()).as_deref(),
            Some("env-secret")
        );
        assert!(
            resolve_secret_ref_value(
                &secret_ref,
                &TenantContext::explicit("tenant", "workspace", None)
            )
            .is_none(),
            "explicit hosted tenants must not resolve process env-backed MCP secrets"
        );
        std::env::remove_var("TANDEM_TEST_MCP_SECRET");
    }

    #[test]
    fn explicit_tenant_mcp_secret_headers_are_not_cached_globally() {
        let current_tenant = TenantContext::explicit("tenant", "workspace", None);
        let (headers, secret_headers, secret_values) = split_headers_for_storage(
            "tenant-server",
            HashMap::from([(
                "Authorization".to_string(),
                "Bearer tenant-secret".to_string(),
            )]),
            HashMap::new(),
            &current_tenant,
        );

        assert!(headers.is_empty());
        assert!(secret_headers.contains_key("Authorization"));
        assert!(
            secret_values.is_empty(),
            "explicit hosted MCP secrets must not be cached in shared server rows"
        );

        let _ = tandem_core::delete_provider_auth_for_tenant(
            &current_tenant,
            "mcp_header::tenant-server::authorization",
        );
    }

    #[tokio::test]
    async fn call_tool_for_tenant_resolves_matching_tenant_store_secret() {
        let (endpoint, server) =
            spawn_auth_required_http_mcp_server("Bearer tenant-a-secret").await;
        let file = std::env::temp_dir().join(format!("mcp-test-{}.json", Uuid::new_v4()));
        let registry = McpRegistry::new_with_state_file(file);
        let tenant_a = TenantContext::explicit("tenant-a", "workspace-a", None);
        registry
            .add_or_update_with_secret_refs(
                "tenant-server".to_string(),
                endpoint,
                HashMap::from([(
                    "Authorization".to_string(),
                    "Bearer tenant-a-secret".to_string(),
                )]),
                HashMap::new(),
                &tenant_a,
                true,
            )
            .await;

        assert!(registry.connect("tenant-server").await);
        let result = registry
            .call_tool_for_tenant("tenant-server", "get_me", json!({}), &tenant_a)
            .await
            .expect("tenant A should execute with tenant A secret");
        assert!(result.output.contains("tenant-authenticated"));
        server.abort();
        let _ = tandem_core::delete_provider_auth_for_tenant(
            &tenant_a,
            "mcp_header::tenant-server::authorization",
        );
    }

    #[tokio::test]
    async fn call_tool_for_tenant_rejects_mismatched_tenant_store_secret() {
        let (endpoint, server) =
            spawn_auth_required_http_mcp_server("Bearer tenant-a-secret").await;
        let file = std::env::temp_dir().join(format!("mcp-test-{}.json", Uuid::new_v4()));
        let registry = McpRegistry::new_with_state_file(file);
        let tenant_a = TenantContext::explicit("tenant-a", "workspace-a", None);
        let tenant_b = TenantContext::explicit("tenant-b", "workspace-b", None);
        registry
            .add_or_update_with_secret_refs(
                "tenant-server".to_string(),
                endpoint,
                HashMap::from([(
                    "Authorization".to_string(),
                    "Bearer tenant-a-secret".to_string(),
                )]),
                HashMap::new(),
                &tenant_a,
                true,
            )
            .await;

        assert!(registry.connect("tenant-server").await);
        let err = registry
            .call_tool_for_tenant("tenant-server", "get_me", json!({}), &tenant_b)
            .await
            .expect_err("tenant B must not execute with tenant A secret");
        assert!(err.contains("unauthorized"));
        server.abort();
        let _ = tandem_core::delete_provider_auth_for_tenant(
            &tenant_a,
            "mcp_header::tenant-server::authorization",
        );
    }
}