procyon 0.1.2

Terminal development harness for Stellar and Soroban smart contracts, driven by a language model
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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
use std::sync::Arc;

use async_trait::async_trait;
use rmcp::model::{CallToolRequestParams, ClientCapabilities, ClientInfo, Implementation};
use rmcp::transport::StreamableHttpClientTransport;
use rmcp::ServiceExt;
use serde_json::Value;

use crate::config::McpServerConfig;
use crate::tools::Tool;

pub enum Transport {
    Http {
        url: String,
        token: Option<String>,
    },
    /// Authorization-code flow with PKCE against the server's own authorization server.
    HttpOAuth {
        url: String,
    },
    Stdio {
        command: String,
        args: Vec<String>,
    },
}

// Hand-written rather than derived: the HTTP variant carries a credential, and a derived Debug
// would print it anywhere this is formatted.
impl std::fmt::Debug for Transport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Transport::Http { url, token } => f
                .debug_struct("Http")
                .field("url", url)
                .field("token", &token.as_ref().map(|_| "<redacted>"))
                .finish(),
            Transport::HttpOAuth { url } => f.debug_struct("HttpOAuth").field("url", url).finish(),
            Transport::Stdio { command, args } => f
                .debug_struct("Stdio")
                .field("command", command)
                .field("args", args)
                .finish(),
        }
    }
}

impl McpServerConfig {
    // Resolved before connecting so a malformed entry names itself instead of failing as an
    // opaque transport error.
    pub fn transport(&self) -> Result<Transport, String> {
        if self.name.is_empty() {
            return Err("An mcp_servers entry is missing 'name'".to_string());
        }

        match (&self.url, &self.command) {
            (Some(_), Some(_)) => Err(format!(
                "'{}' sets both url and command; use one transport per entry",
                self.name
            )),
            (None, None) => Err(format!(
                "'{}' sets neither url nor command, so there is nothing to connect to",
                self.name
            )),
            (Some(url), None) if self.auth.as_deref() == Some("oauth") => {
                if self.token_env.is_some() {
                    return Err(format!(
                        "'{}' asks for oauth and also sets token_env; pick one",
                        self.name
                    ));
                }
                Ok(Transport::HttpOAuth { url: url.clone() })
            }
            (Some(url), None) => {
                if let Some(other) = self.auth.as_deref() {
                    return Err(format!(
                        "'{}' has auth = \"{}\", which is not a supported value; use \"oauth\" or \
                         omit it",
                        self.name, other
                    ));
                }
                let token = match &self.token_env {
                    Some(var) => match std::env::var(var) {
                        Ok(token) if !token.is_empty() => Some(token),
                        _ => {
                            return Err(format!(
                                "{} is not set, so no credential is available for '{}'",
                                var, self.name
                            ))
                        }
                    },
                    None => None,
                };
                Ok(Transport::Http {
                    url: url.clone(),
                    token,
                })
            }
            (None, Some(command)) => {
                if self.auth.is_some() {
                    return Err(format!(
                        "'{}' is a stdio server, so auth does not apply",
                        self.name
                    ));
                }
                if self.token_env.is_some() {
                    return Err(format!(
                        "'{}' is a stdio server, so token_env does not apply; pass secrets through \
                         the environment it inherits",
                        self.name
                    ));
                }
                Ok(Transport::Stdio {
                    command: command.clone(),
                    args: self.args.clone(),
                })
            }
        }
    }

    /// What to show the user for this server, without leaking the credential.
    pub fn endpoint_label(&self) -> String {
        match (&self.url, &self.command) {
            (Some(url), _) => url.clone(),
            (None, Some(command)) if self.args.is_empty() => command.clone(),
            (None, Some(command)) => format!("{} {}", command, self.args.join(" ")),
            (None, None) => "unconfigured".to_string(),
        }
    }
}

type Client = rmcp::service::RunningService<rmcp::service::RoleClient, ClientInfo>;

// Remote tools are namespaced because MCP servers commonly expose bare names such as `search` or
// `execute`, which would be meaningless to the model beside procyon's own tools.
fn qualified_name(server: &str, tool: &str) -> String {
    format!("{}__{}", server, tool)
}

// A server can die mid-conversation: an HTTP host goes away, a stdio child exits. The transport's
// own recovery only covers an expired HTTP session, so the connection is held behind a lock that
// every tool of that server shares and can replace.
pub struct McpConnection {
    config: McpServerConfig,
    client: tokio::sync::RwLock<Option<Arc<Client>>>,
    // Remembers the last failure so a burst of tool calls against a down server does not become a
    // burst of reconnect attempts.
    last_failure: tokio::sync::Mutex<Option<(std::time::Instant, String)>>,
}

const RECONNECT_COOLDOWN: std::time::Duration = std::time::Duration::from_secs(5);

impl McpConnection {
    fn new(config: McpServerConfig, client: Arc<Client>) -> Self {
        Self {
            config,
            client: tokio::sync::RwLock::new(Some(client)),
            last_failure: tokio::sync::Mutex::new(None),
        }
    }

    pub async fn client(&self) -> Result<Arc<Client>, String> {
        if let Some(client) = self.client.read().await.clone() {
            return Ok(client);
        }

        let mut slot = self.client.write().await;
        // Another caller may have reconnected while this one waited for the lock.
        if let Some(client) = slot.clone() {
            return Ok(client);
        }

        let mut failure = self.last_failure.lock().await;
        if let Some((at, reason)) = failure.as_ref() {
            if at.elapsed() < RECONNECT_COOLDOWN {
                return Err(format!(
                    "'{}' is disconnected: {}. Not retrying for another {}s.",
                    self.config.name,
                    reason,
                    (RECONNECT_COOLDOWN - at.elapsed()).as_secs() + 1
                ));
            }
        }

        match connect(&self.config).await {
            Ok(client) => {
                *slot = Some(client.clone());
                *failure = None;
                Ok(client)
            }
            Err(e) => {
                *failure = Some((std::time::Instant::now(), e.clone()));
                Err(e)
            }
        }
    }

    /// Drops the connection so the next call reconnects.
    pub async fn invalidate(&self) {
        *self.client.write().await = None;
    }
}

pub struct McpTool {
    name: String,
    remote_name: String,
    description: String,
    input_schema: Value,
    connection: Arc<McpConnection>,
    capability: crate::risk::Capability,
}

/// What a remote tool's own annotations say it does.
///
/// Only `readOnlyHint: true` is believed, and only far enough to skip a prompt on a lookup. Every
/// other answer — absent, false, or a hint this build cannot read — lands on the cautious default,
/// so a server that says nothing is asked about rather than trusted. The trust here is in the
/// server the operator configured, which is the same trust as installing it; it is not a claim the
/// model can make about a tool.
fn declared_capability(
    annotations: Option<&rmcp::model::ToolAnnotations>,
) -> crate::risk::Capability {
    match annotations.and_then(|a| a.read_only_hint) {
        Some(true) => crate::risk::Capability::ReadOnly,
        _ => crate::risk::Capability::default(),
    }
}

#[async_trait]
impl Tool for McpTool {
    fn name(&self) -> &str {
        &self.name
    }

    fn description(&self) -> &str {
        &self.description
    }

    fn input_schema(&self) -> Value {
        self.input_schema.clone()
    }

    fn capability(&self) -> crate::risk::Capability {
        self.capability
    }

    async fn execute(&self, input: Value) -> Result<String, String> {
        let arguments = match input {
            Value::Object(map) => Some(map),
            // A tool with no parameters may be called with null; the wire format wants an object.
            Value::Null => None,
            other => return Err(format!("Tool input must be a JSON object, got {}", other)),
        };

        let mut params = CallToolRequestParams::new(self.remote_name.clone());
        if let Some(arguments) = arguments {
            params = params.with_arguments(arguments);
        }

        let client = self.connection.client().await?;

        let result = match client.call_tool(params).await {
            Ok(result) => result,
            Err(e) => {
                // A healthy server reports tool failure in the payload via is_error, so an Err
                // here means the transport itself is in trouble: drop it and let the next call
                // reconnect.
                self.connection.invalidate().await;
                return Err(format!("{} failed: {}", self.name, e));
            }
        };

        let rendered = render_content(&result);

        // The server reports tool-level failure in the payload, not as a transport error.
        if result.is_error.unwrap_or(false) {
            return Err(if rendered.is_empty() {
                format!("{} reported an error with no detail", self.name)
            } else {
                rendered
            });
        }

        Ok(if rendered.is_empty() {
            format!("{} returned no content", self.name)
        } else {
            rendered
        })
    }
}

// Only text is surfaced: image and audio blocks cannot be shown in a terminal transcript, and
// silently dropping them would be worse than saying so.
fn render_content(result: &rmcp::model::CallToolResult) -> String {
    let mut parts: Vec<String> = Vec::new();
    let mut skipped = 0usize;

    for block in &result.content {
        match block.as_text() {
            Some(text) => parts.push(text.text.clone()),
            None => skipped += 1,
        }
    }

    if let Some(structured) = &result.structured_content {
        parts.push(
            serde_json::to_string_pretty(structured).unwrap_or_else(|_| structured.to_string()),
        );
    }

    if skipped > 0 {
        parts.push(format!("[{} non-text block(s) omitted]", skipped));
    }

    parts.join("\n")
}

fn client_info() -> ClientInfo {
    ClientInfo::new(
        ClientCapabilities::default(),
        Implementation::new("procyon", env!("CARGO_PKG_VERSION")),
    )
}

const STDERR_TAIL_LINES: usize = 10;
const STDERR_FLUSH_GRACE: std::time::Duration = std::time::Duration::from_millis(300);

// A stdio server writing diagnostics to an inherited stderr would scribble over the TUI, and
// piping it without reading would eventually fill the pipe and stall the child. So it is piped
// and drained into a bounded tail, which is the only explanation available when a server dies
// before it finishes the MCP handshake.
type StderrTail = (
    Arc<std::sync::Mutex<Vec<String>>>,
    tokio::task::JoinHandle<()>,
);

fn drain_stderr(stderr: tokio::process::ChildStderr) -> StderrTail {
    let tail = Arc::new(std::sync::Mutex::new(Vec::new()));
    let sink = tail.clone();

    let handle = tokio::spawn(async move {
        use tokio::io::{AsyncBufReadExt, BufReader};

        let mut lines = BufReader::new(stderr).lines();
        while let Ok(Some(line)) = lines.next_line().await {
            if let Ok(mut tail) = sink.lock() {
                if tail.len() == STDERR_TAIL_LINES {
                    tail.remove(0);
                }
                tail.push(line);
            }
        }
    });

    (tail, handle)
}

fn stderr_context(tail: &Arc<std::sync::Mutex<Vec<String>>>) -> String {
    match tail.lock() {
        Ok(tail) if !tail.is_empty() => format!("\nIts stderr said:\n  {}", tail.join("\n  ")),
        _ => String::new(),
    }
}

async fn connect_stdio(name: &str, command: &str, args: &[String]) -> Result<Arc<Client>, String> {
    let mut cmd = tokio::process::Command::new(command);
    cmd.args(args);

    let (process, stderr) = rmcp::transport::TokioChildProcess::builder(cmd)
        .stderr(std::process::Stdio::piped())
        .spawn()
        .map_err(|e| format!("Failed to launch '{}' ({}): {}", name, command, e))?;

    let drain = stderr.map(drain_stderr);

    match client_info().serve(process).await {
        Ok(client) => Ok(Arc::new(client)),
        Err(e) => {
            let context = match drain {
                Some((tail, handle)) => {
                    // A child that exits at once loses the race against its own stderr being
                    // read, so the drain gets a bounded moment to reach EOF before we quote it.
                    let _ = tokio::time::timeout(STDERR_FLUSH_GRACE, handle).await;
                    stderr_context(&tail)
                }
                None => String::new(),
            };
            Err(format!(
                "Failed to speak MCP with '{}' ({}): {}{}",
                name, command, e, context
            ))
        }
    }
}

async fn connect_http(name: &str, url: &str, token: Option<String>) -> Result<Arc<Client>, String> {
    let mut transport_config =
        rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig::with_uri(
            url.to_string(),
        )
        // Already the SDK default, but set here so the behaviour is visible and a change to that
        // default cannot silently remove it. On HTTP 404 the transport replays the handshake once
        // and retries the in-flight call, which is what keeps a long conversation working after
        // the server drops its session.
        .reinit_on_expired_session(true);
    if let Some(token) = token {
        transport_config = transport_config.auth_header(token);
    }

    let transport = StreamableHttpClientTransport::from_config(transport_config);

    client_info()
        .serve(transport)
        .await
        .map(Arc::new)
        .map_err(|e| format!("Failed to connect to '{}' at {}: {}", name, url, e))
}

const AUTHORIZE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(180);

fn credential_store(name: &str) -> Result<crate::oauth::FileCredentialStore, String> {
    Ok(crate::oauth::FileCredentialStore::new(
        crate::oauth::credentials_path(name)?,
    ))
}

fn build_oauth_transport(
    url: &str,
    manager: rmcp::transport::auth::AuthorizationManager,
) -> rmcp::transport::StreamableHttpClientTransport<
    rmcp::transport::auth::AuthClient<reqwest::Client>,
> {
    let auth_client = rmcp::transport::auth::AuthClient::new(reqwest::Client::default(), manager);
    let config =
        rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig::with_uri(
            url.to_string(),
        )
        // Left unset deliberately: the worker prefers a static token over OAuth, so setting it
        // here would shadow the access token the auth client provides.
        .reinit_on_expired_session(true);

    rmcp::transport::StreamableHttpClientTransport::with_client(auth_client, config)
}

/// Uses stored credentials only. Refresh happens inside the SDK, so a valid refresh token is
/// enough; a dead one surfaces as an error rather than hijacking the user's browser, which is
/// what makes this safe to call on reconnect mid-conversation.
async fn connect_oauth_stored(name: &str, url: &str) -> Result<Arc<Client>, String> {
    let mut manager = rmcp::transport::auth::AuthorizationManager::new(url)
        .await
        .map_err(|e| {
            format!(
                "Failed to reach the authorization server of '{}': {}",
                name, e
            )
        })?;
    manager.set_credential_store(credential_store(name)?);

    let restored = manager
        .initialize_from_store()
        .await
        .map_err(|e| format!("Failed to read stored credentials for '{}': {}", name, e))?;
    if !restored {
        return Err(format!(
            "'{}' is not authorized yet. Run `procyon --authorize {}`.",
            name, name
        ));
    }

    client_info()
        .serve(build_oauth_transport(url, manager))
        .await
        .map(Arc::new)
        .map_err(|e| format!("Failed to connect to '{}' at {}: {}", name, url, e))
}

/// The interactive authorization-code flow. Only ever run from an explicit user action, never
/// from a reconnect.
pub async fn authorize(config: &McpServerConfig) -> Result<(), String> {
    let Transport::HttpOAuth { url } = config.transport()? else {
        return Err(format!("'{}' is not configured for oauth", config.name));
    };

    // Bound before the browser opens, so a busy port is reported instead of sending the user to a
    // page that redirects nowhere.
    let listener = crate::oauth::bind_redirect_listener().await?;

    let mut manager = rmcp::transport::auth::AuthorizationManager::new(&url)
        .await
        .map_err(|e| format!("Failed to reach the authorization server: {}", e))?;
    manager.set_credential_store(credential_store(&config.name)?);

    let resolution = manager
        .resolve_metadata_from_challenge(None)
        .await
        .map_err(|e| format!("Failed to discover the authorization server: {}", e))?;
    manager.set_metadata(resolution.metadata);

    let request = rmcp::transport::auth::AuthorizationRequest::new(crate::oauth::redirect_uri())
        .with_client_name("procyon");

    let session = rmcp::transport::auth::AuthorizationSession::new(manager, request)
        .await
        .map_err(|(_manager, e)| format!("Failed to start authorization: {}", e))?;

    let auth_url = session.get_authorization_url().to_string();
    println!("Opening your browser to authorize '{}'.", config.name);
    println!("If it does not open, visit:\n\n  {}\n", auth_url);
    if !crate::oauth::open_browser(&auth_url).await {
        println!("(could not launch a browser automatically)");
    }
    println!(
        "Waiting for the redirect on {} ...",
        crate::oauth::redirect_uri()
    );
    // Stdout is block-buffered when it is not a terminal, and the next step blocks for minutes;
    // without this the user stares at nothing.
    let _ = std::io::Write::flush(&mut std::io::stdout());

    let callback = crate::oauth::wait_for_redirect(listener, AUTHORIZE_TIMEOUT).await?;

    // Handing over the whole redirect URL rather than code+state: the SDK also reads `iss` from
    // it and validates the issuer, which Raven requires. It validates `state` against its own
    // store too, so a mismatch surfaces here.
    session
        .handle_callback_url(&callback.url)
        .await
        .map_err(|e| format!("Failed to exchange the authorization code: {}", e))?;

    // Reported so the user knows what they got: the access token is short-lived and refreshed
    // silently, but the stored refresh token is what decides when the browser comes back.
    let stored = {
        use rmcp::transport::auth::CredentialStore;
        credential_store(&config.name)?.load().await.ok().flatten()
    };
    match stored.as_ref().and_then(crate::oauth::expires_at) {
        Some(at) => {
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);
            println!(
                "'{}' is authorized. The access token lasts {}s and refreshes automatically.",
                config.name,
                at.saturating_sub(now)
            );
        }
        None => println!("'{}' is authorized.", config.name),
    }
    println!(
        "Credentials stored in {}",
        crate::oauth::credentials_path(&config.name)?.display()
    );
    Ok(())
}

async fn connect(config: &McpServerConfig) -> Result<Arc<Client>, String> {
    match config.transport()? {
        Transport::Http { url, token } => connect_http(&config.name, &url, token).await,
        Transport::HttpOAuth { url } => connect_oauth_stored(&config.name, &url).await,
        Transport::Stdio { command, args } => connect_stdio(&config.name, &command, &args).await,
    }
}

/// Connects to every configured server and returns their tools, plus a human-readable line per
/// server for the chat and the system prompt. A server that fails to connect is reported and
/// skipped: a remote outage must not stop the harness from starting.
pub async fn load_servers(
    configs: &[McpServerConfig],
) -> (Vec<Box<dyn Tool>>, Vec<String>, Vec<String>) {
    let mut tools: Vec<Box<dyn Tool>> = Vec::new();
    let mut connected = Vec::new();
    let mut problems = Vec::new();

    for config in configs {
        let client = match connect(config).await {
            Ok(client) => client,
            Err(e) => {
                problems.push(e);
                continue;
            }
        };

        let listed = match client.list_tools(Default::default()).await {
            Ok(listed) => listed,
            Err(e) => {
                problems.push(format!("Could not list tools of '{}': {}", config.name, e));
                continue;
            }
        };

        let connection = Arc::new(McpConnection::new(config.clone(), client));

        let mut names = Vec::new();
        for tool in listed.tools {
            let name = qualified_name(&config.name, &tool.name);
            names.push(name.clone());
            tools.push(Box::new(McpTool {
                name,
                remote_name: tool.name.to_string(),
                description: tool.description.map(|d| d.to_string()).unwrap_or_else(|| {
                    format!("Tool '{}' on MCP server '{}'", tool.name, config.name)
                }),
                input_schema: Value::Object((*tool.input_schema).clone()),
                connection: connection.clone(),
                capability: declared_capability(tool.annotations.as_ref()),
            }));
        }

        let endpoint = config.endpoint_label();
        connected.push(if names.is_empty() {
            format!("{} ({}) — no tools exposed", config.name, endpoint)
        } else {
            format!("{} ({}): {}", config.name, endpoint, names.join(", "))
        });
    }

    (tools, connected, problems)
}

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

    fn result_with(text: &str) -> rmcp::model::CallToolResult {
        rmcp::model::CallToolResult::success(vec![rmcp::model::ContentBlock::text(text)])
    }

    #[test]
    fn tool_names_are_namespaced_by_server() {
        assert_eq!(qualified_name("raven", "search"), "raven__search");
    }

    #[test]
    fn text_content_is_rendered() {
        assert_eq!(render_content(&result_with("hello")), "hello");
    }

    #[test]
    fn multiple_text_blocks_are_joined() {
        let result = rmcp::model::CallToolResult::success(vec![
            rmcp::model::ContentBlock::text("one"),
            rmcp::model::ContentBlock::text("two"),
        ]);
        assert_eq!(render_content(&result), "one\ntwo");
    }

    #[test]
    fn an_empty_result_renders_empty() {
        let result = rmcp::model::CallToolResult::success(vec![]);
        assert!(render_content(&result).is_empty());
    }

    #[tokio::test]
    async fn a_missing_credential_is_reported_not_silently_ignored() {
        let config = McpServerConfig {
            name: "raven".to_string(),
            url: Some("https://example.invalid/mcp".to_string()),
            token_env: Some("PROCYON_TEST_TOKEN_THAT_IS_UNSET".to_string()),
            ..Default::default()
        };
        let err = connect(&config).await.unwrap_err();
        assert!(
            err.contains("PROCYON_TEST_TOKEN_THAT_IS_UNSET"),
            "got {}",
            err
        );
        assert!(err.contains("raven"), "got {}", err);
    }

    #[tokio::test]
    async fn an_unreachable_server_is_skipped_rather_than_fatal() {
        let configs = vec![McpServerConfig {
            name: "nowhere".to_string(),
            url: Some("http://127.0.0.1:1/mcp".to_string()),
            ..Default::default()
        }];
        let (tools, connected, problems) = load_servers(&configs).await;
        assert!(tools.is_empty());
        assert!(connected.is_empty());
        assert_eq!(problems.len(), 1, "got {:?}", problems);
        assert!(problems[0].contains("nowhere"));
    }

    // Real end-to-end check against a live server. Needs a credential:
    //   npm run mcp-key -- create procyon        (in the stellar-raven repo)
    //   PROCYON_MCP_TOKEN='<name>:<token>' cargo test raven_live -- --ignored --nocapture
    #[tokio::test]
    #[ignore]
    async fn raven_live_lists_and_calls_search() {
        // Skipped rather than failed when the credential is absent: a missing token is a missing
        // precondition, not a defect, and a red result here would look like one.
        if std::env::var("PROCYON_MCP_TOKEN")
            .map(|t| t.is_empty())
            .unwrap_or(true)
        {
            println!(
                "skipped: PROCYON_MCP_TOKEN is not set (the OAuth path is covered separately)"
            );
            return;
        }

        let url = std::env::var("PROCYON_MCP_URL")
            .unwrap_or_else(|_| "https://raven.stellar.org/mcp".to_string());

        let configs = vec![McpServerConfig {
            name: "raven".to_string(),
            url: Some(url),
            token_env: Some("PROCYON_MCP_TOKEN".to_string()),
            ..Default::default()
        }];

        let (tools, connected, problems) = load_servers(&configs).await;
        assert!(problems.is_empty(), "connection problems: {:?}", problems);
        assert!(!connected.is_empty());
        println!("connected: {:?}", connected);

        let names: Vec<&str> = tools.iter().map(|t| t.name()).collect();
        println!("tools: {:?}", names);
        assert!(
            names.contains(&"raven__search"),
            "expected a namespaced search tool, got {:?}",
            names
        );

        let search = tools
            .iter()
            .find(|t| t.name() == "raven__search")
            .expect("search tool");

        // The schema must be a JSON Schema object, or the Messages API rejects the tool.
        assert_eq!(search.input_schema()["type"], "object");

        let out = search
            .execute(json!({"query": "soroban storage ttl"}))
            .await
            .expect("search should succeed");
        println!("--- search result ---\n{}", out);
        assert!(!out.trim().is_empty());
    }

    // Pins the SDK default we rely on: if a future rmcp flips it, this fails instead of the
    // recovery quietly disappearing.
    #[test]
    fn session_recovery_is_enabled_by_default_in_the_sdk() {
        let config =
            rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig::with_uri(
                "https://example.invalid/mcp",
            );
        assert!(
            config.reinit_on_expired_session,
            "procyon relies on transparent re-initialization after HTTP 404"
        );
    }

    #[test]
    fn debug_never_prints_the_credential() {
        std::env::set_var("PROCYON_TEST_DEBUG_TOKEN", "super-secret-value");
        let config = McpServerConfig {
            name: "raven".to_string(),
            url: Some("https://x/mcp".to_string()),
            token_env: Some("PROCYON_TEST_DEBUG_TOKEN".to_string()),
            ..Default::default()
        };
        let rendered = format!("{:?}", config.transport().unwrap());
        std::env::remove_var("PROCYON_TEST_DEBUG_TOKEN");

        assert!(
            !rendered.contains("super-secret-value"),
            "leaked: {}",
            rendered
        );
        assert!(rendered.contains("redacted"), "got {}", rendered);
    }

    #[test]
    fn a_stdio_entry_resolves_to_the_stdio_transport() {
        let config = McpServerConfig {
            name: "fs".to_string(),
            command: Some("npx".to_string()),
            args: vec!["-y".to_string(), "server-filesystem".to_string()],
            ..Default::default()
        };
        match config.transport().unwrap() {
            Transport::Stdio { command, args } => {
                assert_eq!(command, "npx");
                assert_eq!(args, vec!["-y", "server-filesystem"]);
            }
            _ => panic!("expected stdio"),
        }
        assert_eq!(config.endpoint_label(), "npx -y server-filesystem");
    }

    #[test]
    fn declaring_both_transports_is_rejected() {
        let config = McpServerConfig {
            name: "both".to_string(),
            url: Some("https://x/mcp".to_string()),
            command: Some("npx".to_string()),
            ..Default::default()
        };
        let err = config.transport().unwrap_err();
        assert!(err.contains("one transport per entry"), "got {}", err);
    }

    #[test]
    fn declaring_neither_transport_is_rejected() {
        let config = McpServerConfig {
            name: "empty".to_string(),
            ..Default::default()
        };
        let err = config.transport().unwrap_err();
        assert!(err.contains("neither url nor command"), "got {}", err);
    }

    #[test]
    fn an_entry_without_a_name_is_rejected() {
        let config = McpServerConfig {
            command: Some("npx".to_string()),
            ..Default::default()
        };
        assert!(config.transport().unwrap_err().contains("missing 'name'"));
    }

    #[test]
    fn token_env_on_a_stdio_server_is_rejected_rather_than_ignored() {
        let config = McpServerConfig {
            name: "fs".to_string(),
            command: Some("npx".to_string()),
            token_env: Some("SOME_TOKEN".to_string()),
            ..Default::default()
        };
        let err = config.transport().unwrap_err();
        assert!(err.contains("token_env does not apply"), "got {}", err);
    }

    #[tokio::test]
    async fn a_command_that_does_not_exist_is_reported_with_its_name() {
        let configs = vec![McpServerConfig {
            name: "ghost".to_string(),
            command: Some("procyon-no-such-mcp-server".to_string()),
            ..Default::default()
        }];
        let (tools, connected, problems) = load_servers(&configs).await;
        assert!(tools.is_empty() && connected.is_empty());
        assert_eq!(problems.len(), 1, "got {:?}", problems);
        assert!(problems[0].contains("ghost"), "got {}", problems[0]);
    }

    #[tokio::test]
    async fn a_process_that_is_not_an_mcp_server_reports_its_stderr() {
        // `ls` on a missing path exits immediately with a message on stderr; the handshake fails
        // and the message is the only useful diagnostic.
        let configs = vec![McpServerConfig {
            name: "notmcp".to_string(),
            command: Some("ls".to_string()),
            args: vec!["/procyon-no-such-path".to_string()],
            ..Default::default()
        }];
        let (_, _, problems) = load_servers(&configs).await;
        assert_eq!(problems.len(), 1, "got {:?}", problems);
        assert!(
            problems[0].contains("stderr said"),
            "the child's own explanation must survive: {}",
            problems[0]
        );
    }

    #[tokio::test]
    async fn a_disconnected_server_reports_the_cause_and_backs_off() {
        let config = McpServerConfig {
            name: "nowhere".to_string(),
            url: Some("http://127.0.0.1:1/mcp".to_string()),
            ..Default::default()
        };

        // Built already-disconnected: no live client to hand out.
        let connection = McpConnection {
            config,
            client: tokio::sync::RwLock::new(None),
            last_failure: tokio::sync::Mutex::new(None),
        };

        let first = connection.client().await.unwrap_err();
        assert!(first.contains("nowhere"), "got {}", first);

        // The second attempt inside the cooldown must reuse the recorded cause instead of
        // dialing again.
        let second = connection.client().await.unwrap_err();
        assert!(
            second.contains("Not retrying"),
            "expected a backoff message, got {}",
            second
        );
        assert!(second.contains("nowhere"));
    }

    // Kills a live stdio server mid-session and checks the next call brings it back.
    // cargo test stdio_live_reconnect -- --ignored --nocapture
    #[tokio::test]
    #[ignore]
    async fn stdio_live_reconnects_after_the_server_dies() {
        let config = McpServerConfig {
            name: "fs".to_string(),
            command: Some("npx".to_string()),
            args: vec![
                "-y".to_string(),
                "@modelcontextprotocol/server-filesystem".to_string(),
                ".".to_string(),
            ],
            ..Default::default()
        };

        let client = connect(&config).await.expect("initial connect");
        let connection = Arc::new(McpConnection::new(config, client));

        let tool = McpTool {
            name: "fs__list_allowed_directories".to_string(),
            remote_name: "list_allowed_directories".to_string(),
            description: String::new(),
            input_schema: json!({"type": "object"}),
            connection: connection.clone(),
            capability: crate::risk::Capability::ReadOnly,
        };

        let before = tool.execute(json!({})).await.expect("first call");
        println!("before: {}", before.trim());

        // Simulates the child dying: the connection is gone and the next call must rebuild it.
        connection.invalidate().await;

        let after = tool.execute(json!({})).await.expect("call after reconnect");
        println!("after:  {}", after.trim());
        assert_eq!(
            before.trim(),
            after.trim(),
            "a reconnected server must answer the same"
        );
    }

    // Launches a real stdio MCP server over npx, so it needs Node and the network on first run.
    // cargo test stdio_live -- --ignored --nocapture
    #[tokio::test]
    #[ignore]
    async fn stdio_live_lists_filesystem_tools() {
        let configs = vec![McpServerConfig {
            name: "fs".to_string(),
            command: Some("npx".to_string()),
            args: vec![
                "-y".to_string(),
                "@modelcontextprotocol/server-filesystem".to_string(),
                ".".to_string(),
            ],
            ..Default::default()
        }];

        let (tools, connected, problems) = load_servers(&configs).await;
        assert!(problems.is_empty(), "problems: {:?}", problems);
        println!("connected: {:?}", connected);

        let names: Vec<&str> = tools.iter().map(|t| t.name()).collect();
        println!("tools: {:?}", names);
        assert!(!names.is_empty(), "a filesystem server exposes tools");
        assert!(
            names.iter().all(|n| n.starts_with("fs__")),
            "every tool must be namespaced: {:?}",
            names
        );
        // This server exposes read_file and write_file, which would shadow procyon's own tools
        // if they were not namespaced.
        assert!(names.contains(&"fs__read_file"), "got {:?}", names);

        let list = tools
            .iter()
            .find(|t| t.name() == "fs__list_allowed_directories")
            .expect("list_allowed_directories");
        let out = list.execute(json!({})).await.expect("call should succeed");
        println!("--- fs__list_allowed_directories ---\n{}", out);
        assert!(!out.trim().is_empty(), "a real call must return content");
    }

    // Connects to Raven using credentials already stored by `procyon --authorize raven`.
    // cargo test raven_oauth_live -- --ignored --nocapture
    #[tokio::test]
    #[ignore]
    async fn raven_oauth_live_connects_with_stored_credentials() {
        let configs = vec![McpServerConfig {
            name: "raven".to_string(),
            url: Some(
                std::env::var("PROCYON_MCP_URL")
                    .unwrap_or_else(|_| "https://raven.stellar.org/mcp".to_string()),
            ),
            auth: Some("oauth".to_string()),
            ..Default::default()
        }];

        let (tools, connected, problems) = load_servers(&configs).await;
        assert!(problems.is_empty(), "problems: {:?}", problems);
        println!("connected: {:?}", connected);

        let names: Vec<&str> = tools.iter().map(|t| t.name()).collect();
        println!("tools: {:?}", names);
        assert!(!names.is_empty(), "an authorized Raven exposes tools");
        assert!(
            names.iter().all(|n| n.starts_with("raven__")),
            "tools must be namespaced: {:?}",
            names
        );

        let search = tools
            .iter()
            .find(|t| t.name() == "raven__search")
            .expect("raven exposes search");
        assert_eq!(search.input_schema()["type"], "object");

        let out = search
            .execute(json!({"query": "soroban storage ttl"}))
            .await
            .expect("search should succeed over OAuth");
        println!("--- search ---\n{}", &out[..out.len().min(600)]);
        assert!(!out.trim().is_empty());
    }

    #[tokio::test]
    async fn oauth_and_token_env_together_are_rejected() {
        let config = McpServerConfig {
            name: "raven".to_string(),
            url: Some("https://x/mcp".to_string()),
            auth: Some("oauth".to_string()),
            token_env: Some("SOME_TOKEN".to_string()),
            ..Default::default()
        };
        let err = config.transport().unwrap_err();
        assert!(err.contains("pick one"), "got {}", err);
    }

    #[tokio::test]
    async fn an_unknown_auth_value_is_rejected() {
        let config = McpServerConfig {
            name: "x".to_string(),
            url: Some("https://x/mcp".to_string()),
            auth: Some("basic".to_string()),
            ..Default::default()
        };
        let err = config.transport().unwrap_err();
        assert!(err.contains("not a supported value"), "got {}", err);
    }

    #[tokio::test]
    async fn auth_on_a_stdio_server_is_rejected() {
        let config = McpServerConfig {
            name: "fs".to_string(),
            command: Some("npx".to_string()),
            auth: Some("oauth".to_string()),
            ..Default::default()
        };
        let err = config.transport().unwrap_err();
        assert!(err.contains("auth does not apply"), "got {}", err);
    }

    #[tokio::test]
    async fn no_configured_servers_is_not_an_error() {
        let (tools, connected, problems) = load_servers(&[]).await;
        assert!(tools.is_empty() && connected.is_empty() && problems.is_empty());
    }
}