yapi-core 0.4.1

Coding agent core: sessions, compaction, settings, resources, built-in tools, system prompt, packages, extension runner and MCP. An internal library of yapi, with no stable API.
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
//! One configured server's connection: lazy connects and reconnects, its
//! tools and resources, its credentials, and its state for `/mcp`. Port of
//! `extensions/mcp/runtime.ts` in pi `v1.0.0`.

use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use serde_json::Value;
use yapi_types::sync::lock;

use super::client::{ClientOptions, McpClient, RequestOptions, ResourceKind, Root, Tool};
use super::config::{ServerEntry, ServerTransport};
use super::http::{HttpAuth, HttpOptions, HttpTransport, ProviderToken};
use super::jsonrpc::{METHOD_NOT_FOUND, McpError};
use super::sign_in::{CredentialStore, McpAuth, SignInPrompt};
use super::stdio::{StdioOptions, StdioTransport};
use super::tools::is_app_resource;
use super::transport::Transport;

const DEFAULT_TIMEOUT_SECONDS: f64 = 60.0;
const STDERR_TAIL_CHARS: usize = 2_000;
/// Delays between attempts to reach an HTTP server after a transient error.
const CONNECT_RETRY_DELAYS: [Duration; 2] =
    [Duration::from_millis(250), Duration::from_millis(1_000)];

/// Where a connection stands.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum State {
    /// Connecting.
    Connecting,
    /// Connected.
    Connected,
    /// The connection dropped, and the next call reconnects.
    Disconnected,
    /// The server needs a sign-in.
    NeedsAuth,
    /// Connecting failed.
    Failed,
    /// Shut down.
    Closed,
}

impl State {
    /// pi's name for the state.
    pub fn as_str(self) -> &'static str {
        match self {
            State::Connecting => "connecting",
            State::Connected => "connected",
            State::Disconnected => "disconnected",
            State::NeedsAuth => "needs-auth",
            State::Failed => "failed",
            State::Closed => "closed",
        }
    }
}

/// What a connection knows of its server.
#[derive(Clone, Debug)]
pub struct Snapshot {
    /// Where it stands.
    pub state: State,
    /// Why it failed or dropped.
    pub error: Option<String>,
    /// The server's tools.
    pub tools: Vec<Tool>,
    /// Whether the server offers resources.
    pub has_resources: bool,
    /// Resources listed at the last connect, without MCP App resources.
    pub resources: Vec<Value>,
    /// Server instructions from `initialize`.
    pub instructions: Option<String>,
}

/// Called when the server's tools or resources change.
pub type ToolsListener = Arc<dyn Fn(&Arc<Connection>) + Send + Sync>;

/// A configured server, connected on demand.
pub struct Connection {
    entry: ServerEntry,
    cwd: PathBuf,
    agent_dir: PathBuf,
    snapshot: Mutex<Snapshot>,
    client: Mutex<Option<McpClient>>,
    opening: tokio::sync::Mutex<()>,
    closed: AtomicBool,
    on_tools: ToolsListener,
    readable_resources: Arc<dyn Fn(&str) -> bool + Send + Sync>,
    auth: Option<HttpAuth>,
    credentials: CredentialStore,
    /// The stored tokens when the server came to need a sign-in, to notice
    /// sign-ins of another process, such as `yapi mcp login`.
    tokens_at_sign_in: Mutex<Option<String>>,
}

/// pi's `resolveConfigValueOrThrow`: environment references and `!command`.
pub(super) async fn resolve_value(value: &str, description: &str) -> Result<String, McpError> {
    if let Some(resolved) = yapi_ai::credentials::resolve(value, None, false).await {
        return Ok(resolved);
    }
    if let Some(command) = value.strip_prefix('!') {
        return Err(McpError::Other(format!(
            "Failed to resolve {description} from shell command: {command}"
        )));
    }
    let missing: Vec<String> = yapi_ai::credentials::env_var_names(value)
        .into_iter()
        .filter(|name| std::env::var(name).map_or(true, |value| value.is_empty()))
        .collect();
    Err(McpError::Other(match missing.as_slice() {
        [name] => format!("Failed to resolve {description} from environment variable: {name}"),
        [] => format!("Failed to resolve {description}"),
        names => format!(
            "Failed to resolve {description} from environment variables: {}",
            names.join(", ")
        ),
    }))
}

impl Connection {
    /// A connection for `entry`, not yet connected, with OAuth credentials
    /// kept in `agent_dir`. Its callbacks:
    /// - `on_tools`: learns of tool and resource changes
    /// - `readable_resources`: tells whether the resource tools reach a server
    /// - `provider_token`: reads the token of servers with `auth.provider`
    pub fn new(
        entry: ServerEntry,
        cwd: PathBuf,
        agent_dir: PathBuf,
        on_tools: ToolsListener,
        readable_resources: Arc<dyn Fn(&str) -> bool + Send + Sync>,
        provider_token: Option<ProviderToken>,
    ) -> Arc<Connection> {
        let credentials = CredentialStore::new(&agent_dir);
        let auth = match &entry.config.transport {
            transport @ ServerTransport::Http {
                url,
                auth_provider,
                oauth,
                ..
            } => {
                if transport.uses_oauth() {
                    Some(HttpAuth::OAuth(Arc::new(McpAuth::new(
                        &entry.name,
                        url,
                        &credentials,
                        oauth.clone().unwrap_or_default(),
                    ))))
                } else {
                    // Read on every request, so the provider's refreshes apply. MCP stores no copy.
                    auth_provider.clone().map(|provider| HttpAuth::Provider {
                        provider,
                        token: provider_token,
                    })
                }
            }
            ServerTransport::Stdio { .. } => None,
        };
        Arc::new(Connection {
            entry,
            cwd,
            agent_dir,
            snapshot: Mutex::new(Snapshot {
                state: State::Connecting,
                error: None,
                tools: Vec::new(),
                has_resources: false,
                resources: Vec::new(),
                instructions: None,
            }),
            client: Mutex::new(None),
            opening: tokio::sync::Mutex::new(()),
            closed: AtomicBool::new(false),
            on_tools,
            readable_resources,
            auth,
            credentials,
            tokens_at_sign_in: Mutex::new(None),
        })
    }

    /// The server URL when the server signs in with OAuth.
    pub fn oauth_url(&self) -> Option<&str> {
        match &self.entry.config.transport {
            transport @ ServerTransport::Http { url, .. } if transport.uses_oauth() => Some(url),
            _ => None,
        }
    }

    fn oauth(&self) -> Option<&Arc<McpAuth>> {
        match &self.auth {
            Some(HttpAuth::OAuth(auth)) => Some(auth),
            _ => None,
        }
    }

    /// Signs in to an OAuth server. The caller reconnects afterwards.
    pub async fn sign_in(&self, prompt: &SignInPrompt) -> Result<(), yapi_ai::auth::AuthError> {
        match self.oauth() {
            Some(auth) => auth.sign_in(prompt).await,
            None => Err(yapi_ai::auth::AuthError::Failed(format!(
                "MCP server \"{}\" does not use OAuth.",
                self.entry.name
            ))),
        }
    }

    /// Removes the server's stored OAuth credentials. Returns whether any
    /// were stored.
    pub async fn remove_credentials(&self) -> Result<bool, McpError> {
        match self.oauth_url() {
            Some(url) => self.credentials.remove(&self.entry.name, url).await,
            None => Ok(false),
        }
    }

    /// Disconnects after the stored credentials were removed.
    pub async fn sign_out(&self) {
        let _opening = self.opening.lock().await;
        let client = lock(&self.client).take();
        if let Some(client) = client {
            client.close().await;
        }
        if !self.closed.load(Ordering::SeqCst) {
            self.mark_needs_auth().await;
        }
    }

    /// Whether the server needs a sign-in and its stored credentials changed
    /// since it came to, as when another process signed in.
    pub async fn signed_in_elsewhere(&self) -> bool {
        let Some(before) = lock(&self.tokens_at_sign_in).clone() else {
            return false;
        };
        self.snapshot().state == State::NeedsAuth && self.stored_tokens().await != before
    }

    async fn stored_tokens(&self) -> String {
        let tokens = match self.oauth_url() {
            Some(url) => self
                .credentials
                .tokens(&self.entry.name, url)
                .await
                .ok()
                .flatten(),
            None => None,
        };
        yapi_types::json::stringify(&tokens.unwrap_or(Value::Null))
    }

    /// OAuth servers that still reject requests after a refresh need the user
    /// to sign in again.
    fn needs_sign_in(&self, error: &McpError) -> bool {
        matches!(error, McpError::SignInRequired)
            || (self.auth.is_some() && matches!(error, McpError::AuthRequired { .. }))
    }

    fn sign_in_required_message(&self) -> String {
        let command = match &self.entry.config.transport {
            ServerTransport::Http {
                auth_provider: Some(provider),
                ..
            } => format!("/login {provider}"),
            _ => "/mcp".to_owned(),
        };
        format!(
            "MCP server \"{}\" requires sign-in. Run {command} to sign in.",
            self.entry.name
        )
    }

    async fn mark_needs_auth(&self) {
        self.set_state(State::NeedsAuth, None);
        if lock(&self.tokens_at_sign_in).is_none() {
            let tokens = self.stored_tokens().await;
            lock(&self.tokens_at_sign_in).get_or_insert(tokens);
        }
    }

    /// The server's name.
    pub fn name(&self) -> &str {
        &self.entry.name
    }

    /// The configured entry.
    pub fn entry(&self) -> &ServerEntry {
        &self.entry
    }

    /// The per-request timeout.
    pub fn timeout(&self) -> Duration {
        Duration::try_from_secs_f64(self.entry.config.timeout.unwrap_or(DEFAULT_TIMEOUT_SECONDS))
            .unwrap_or(Duration::MAX)
    }

    /// What it knows of its server.
    pub fn snapshot(&self) -> Snapshot {
        lock(&self.snapshot).clone()
    }

    /// Where it stands.
    pub fn state(&self) -> State {
        lock(&self.snapshot).state
    }

    /// Whether `read_mcp_resource` reaches this server.
    pub fn readable_resources(&self) -> bool {
        (self.readable_resources)(&self.entry.name)
    }

    fn connected_client(&self) -> Option<McpClient> {
        lock(&self.client)
            .as_ref()
            .filter(|client| client.is_connected())
            .cloned()
    }

    /// The connected client, connecting when needed.
    pub async fn client(self: &Arc<Self>) -> Result<McpClient, McpError> {
        if self.closed.load(Ordering::SeqCst) {
            return Err(McpError::Other(format!(
                "MCP server \"{}\" is shut down",
                self.entry.name
            )));
        }
        if let Some(client) = self.connected_client() {
            return Ok(client);
        }
        let _opening = self.opening.lock().await;
        if let Some(client) = self.connected_client() {
            return Ok(client);
        }
        self.open().await
    }

    async fn open(self: &Arc<Self>) -> Result<McpClient, McpError> {
        self.set_state(State::Connecting, None);
        let http = matches!(self.entry.config.transport, ServerTransport::Http { .. });
        let mut attempt = 0;
        loop {
            match self.connect_once().await {
                Ok(client) => return Ok(client),
                Err(failure) => {
                    let (error, stderr) = *failure;
                    if self.needs_sign_in(&error) && !self.closed.load(Ordering::SeqCst) {
                        self.mark_needs_auth().await;
                        return Err(McpError::Other(self.sign_in_required_message()));
                    }
                    let delay = http.then(|| CONNECT_RETRY_DELAYS.get(attempt)).flatten();
                    attempt += 1;
                    match delay {
                        Some(delay)
                            if error.is_transient() && !self.closed.load(Ordering::SeqCst) =>
                        {
                            tokio::time::sleep(*delay).await;
                        }
                        _ => return Err(self.connect_failed(&error, stderr)),
                    }
                }
            }
        }
    }

    async fn transport(&self) -> Result<Transport, McpError> {
        let name = &self.entry.name;
        match &self.entry.config.transport {
            ServerTransport::Http { url, headers, .. } => {
                let mut resolved = Vec::new();
                for (key, value) in headers {
                    let description = format!("MCP server \"{name}\" header \"{key}\"");
                    resolved.push((key.clone(), resolve_value(value, &description).await?));
                }
                Ok(Transport::Http(HttpTransport::new(HttpOptions {
                    url: url.clone(),
                    headers: resolved,
                    auth: self.auth.clone(),
                })))
            }
            ServerTransport::Stdio {
                command,
                args,
                env,
                cwd,
            } => {
                let mut resolved = Vec::new();
                for (key, value) in env {
                    let description = format!("MCP server \"{name}\" env \"{key}\"");
                    resolved.push((key.clone(), resolve_value(value, &description).await?));
                }
                Ok(Transport::Stdio(Box::new(StdioTransport::new(
                    StdioOptions {
                        command: crate::tools::path::expand_home(command),
                        args: args
                            .iter()
                            .map(|arg| crate::tools::path::expand_home(arg))
                            .collect(),
                        cwd: self.cwd.join(crate::tools::path::expand_home(
                            cwd.as_deref().unwrap_or("."),
                        )),
                        env: resolved,
                    },
                ))))
            }
        }
    }

    /// One attempt. On failure, the error and a stdio server's stderr.
    async fn connect_once(self: &Arc<Self>) -> Result<McpClient, Box<(McpError, Option<String>)>> {
        let transport = self
            .transport()
            .await
            .map_err(|error| Box::new((error, None)))?;
        let options = ClientOptions {
            name: "yapi".into(),
            version: env!("CARGO_PKG_VERSION").into(),
            request_timeout: self.timeout(),
            roots: vec![Root {
                uri: crate::tools::path::file_url(&self.cwd),
                name: self
                    .cwd
                    .file_name()
                    .map(|name| name.to_string_lossy().into_owned()),
            }],
        };
        let client = McpClient::connect_with_stderr(options, transport).await?;
        let log = super::log::Log::new(self.agent_dir.join("mcp.log"));
        let server = self.entry.name.clone();
        client.on_notification("notifications/message", move |params| {
            log.write(&server, params)
        });
        let weak = Arc::downgrade(self);
        let refreshing = client.clone();
        client.on_notification("notifications/tools/list_changed", move |_| {
            if let Some(connection) = weak.upgrade() {
                let client = refreshing.clone();
                tokio::spawn(async move { connection.refresh_tools(client).await });
            }
        });
        let weak = Arc::downgrade(self);
        let refreshing = client.clone();
        client.on_notification("notifications/resources/list_changed", move |_| {
            if let Some(connection) = weak.upgrade() {
                let client = refreshing.clone();
                tokio::spawn(async move { connection.refresh_resources(client).await });
            }
        });
        let weak = Arc::downgrade(self);
        let watched = client.clone();
        client.on_close(move || {
            if let Some(connection) = weak.upgrade() {
                connection.client_closed(&watched);
            }
        });
        let capabilities = client
            .server()
            .map(|server| server.capabilities)
            .unwrap_or_default();
        let has_resources = capabilities.contains_key("resources");
        let setup = async {
            let tools = if capabilities.contains_key("tools") {
                client.list_tools(RequestOptions::default()).await?
            } else {
                Vec::new()
            };
            let resources = if has_resources {
                fetch_resources(&client).await
            } else {
                Vec::new()
            };
            Ok::<_, McpError>((tools, resources))
        };
        let (tools, resources) = match setup.await {
            Ok(found) => found,
            Err(error) => {
                let stderr = client.stderr();
                client.close().await;
                return Err(Box::new((error, stderr)));
            }
        };
        if self.closed.load(Ordering::SeqCst) || !client.is_connected() {
            let stderr = client.stderr();
            client.close().await;
            let reason = if self.closed.load(Ordering::SeqCst) {
                "shut down while connecting"
            } else {
                "connection closed during setup"
            };
            return Err(Box::new((McpError::Other(reason.into()), stderr)));
        }
        let instructions = client
            .server()
            .and_then(|server| server.instructions)
            .map(|text| text.trim().to_owned())
            .filter(|text| !text.is_empty());
        *lock(&self.client) = Some(client.clone());
        {
            let mut snapshot = lock(&self.snapshot);
            snapshot.tools = tools;
            snapshot.has_resources = has_resources;
            snapshot.resources = resources;
            snapshot.instructions = instructions;
            snapshot.state = State::Connected;
            snapshot.error = None;
        }
        *lock(&self.tokens_at_sign_in) = None;
        (self.on_tools)(self);
        Ok(client)
    }

    fn connect_failed(&self, error: &McpError, stderr: Option<String>) -> McpError {
        let closed = self.closed.load(Ordering::SeqCst);
        let tail = stderr
            .map(|text| {
                let text = text.trim();
                let start = text
                    .char_indices()
                    .rev()
                    .nth(STDERR_TAIL_CHARS - 1)
                    .map_or(0, |(index, _)| index);
                text[start..].to_owned()
            })
            .filter(|text| !text.is_empty());
        let message = match tail {
            Some(tail) => format!("{error}\n{tail}"),
            None => error.to_string(),
        };
        self.set_state(
            if closed { State::Closed } else { State::Failed },
            Some(message.clone()),
        );
        McpError::Other(format!(
            "MCP server \"{}\" failed to connect: {message}",
            self.entry.name
        ))
    }

    fn set_state(&self, state: State, error: Option<String>) {
        let mut snapshot = lock(&self.snapshot);
        snapshot.state = state;
        snapshot.error = error;
        if state != State::NeedsAuth {
            *lock(&self.tokens_at_sign_in) = None;
        }
    }

    /// The transport dropped, and the next call reconnects.
    fn client_closed(&self, client: &McpClient) {
        let mut current = lock(&self.client);
        if !current.as_ref().is_some_and(|current| current.same(client))
            || self.closed.load(Ordering::SeqCst)
        {
            return;
        }
        *current = None;
        drop(current);
        let stderr = client
            .stderr()
            .map(|text| text.trim().to_owned())
            .filter(|text| !text.is_empty());
        let error = match stderr {
            Some(stderr) => format!("Connection closed\n{stderr}"),
            None => "Connection closed".to_owned(),
        };
        self.set_state(State::Disconnected, Some(error));
    }

    async fn refresh_tools(self: Arc<Self>, client: McpClient) {
        match client.list_tools(RequestOptions::default()).await {
            Ok(tools) => {
                if self.closed.load(Ordering::SeqCst) || !client.is_connected() {
                    return;
                }
                lock(&self.snapshot).tools = tools;
                (self.on_tools)(&self);
            }
            Err(error) => {
                lock(&self.snapshot).error = Some(format!("Failed to refresh tools: {error}"));
            }
        }
    }

    async fn refresh_resources(self: Arc<Self>, client: McpClient) {
        let resources = fetch_resources(&client).await;
        if self.closed.load(Ordering::SeqCst) || !client.is_connected() {
            return;
        }
        lock(&self.snapshot).resources = resources;
        (self.on_tools)(&self);
    }

    /// Runs a request, reconnecting when needed. Read-only requests are
    /// retried once after a transient HTTP error. Any request is retried once
    /// on a new session when the server forgot the old one.
    async fn with_client<T, F>(
        self: &Arc<Self>,
        read_only: bool,
        run: impl Fn(McpClient) -> F,
    ) -> Result<T, McpError>
    where
        F: std::future::Future<Output = Result<T, McpError>>,
    {
        let mut attempt = 1;
        loop {
            let client = self.client().await?;
            match run(client.clone()).await {
                Ok(value) => return Ok(value),
                Err(error)
                    if read_only
                        && attempt == 1
                        && error.status().is_some()
                        && error.is_transient() =>
                {
                    tokio::time::sleep(CONNECT_RETRY_DELAYS[0]).await;
                }
                // The server forgot the session, so it did not run the request.
                // The old client is detached, not closed: its other calls in
                // flight get the same answer and retry the same way.
                Err(McpError::SessionExpired) if attempt == 1 => {
                    let mut current = lock(&self.client);
                    if current
                        .as_ref()
                        .is_some_and(|current| current.same(&client))
                    {
                        *current = None;
                    }
                }
                Err(error) if self.needs_sign_in(&error) => {
                    {
                        let mut current = lock(&self.client);
                        if current
                            .as_ref()
                            .is_some_and(|current| current.same(&client))
                        {
                            *current = None;
                        }
                    }
                    client.close().await;
                    self.mark_needs_auth().await;
                    return Err(McpError::Other(self.sign_in_required_message()));
                }
                Err(error) => return Err(error),
            }
            attempt += 1;
        }
    }

    /// Calls one of the server's tools. Not retried, since it may have run.
    pub async fn call_tool(
        self: &Arc<Self>,
        name: &str,
        args: Value,
        options: RequestOptions,
    ) -> Result<Value, McpError> {
        self.with_client(false, |client| {
            let (args, options) = (args.clone(), options.clone());
            async move { client.call_tool(name, args, options).await }
        })
        .await
    }

    /// Reads a resource.
    pub async fn read_resource(
        self: &Arc<Self>,
        uri: &str,
        options: RequestOptions,
    ) -> Result<Value, McpError> {
        self.with_client(true, |client| {
            let options = options.clone();
            async move { client.read_resource(uri, options).await }
        })
        .await
    }

    /// One page of resources or resource templates, with no templates for
    /// servers without the method.
    pub async fn resources_page(
        self: &Arc<Self>,
        kind: ResourceKind,
        cursor: Option<String>,
        options: RequestOptions,
    ) -> Result<(Vec<Value>, Option<String>), McpError> {
        self.with_client(true, |client| {
            let (cursor, options) = (cursor.clone(), options.clone());
            async move {
                let page = client.list_resources_page(kind, cursor, options).await;
                without_templates(kind, page, (Vec::new(), None))
            }
        })
        .await
    }

    /// Every resource or resource template, with no templates for servers
    /// without the method.
    pub async fn all_resources(
        self: &Arc<Self>,
        kind: ResourceKind,
        options: RequestOptions,
    ) -> Result<Vec<Value>, McpError> {
        self.with_client(true, |client| {
            let options = options.clone();
            async move {
                without_templates(kind, client.list_resources(kind, options).await, Vec::new())
            }
        })
        .await
    }

    /// Connects again.
    pub async fn reconnect(self: &Arc<Self>) -> Result<(), McpError> {
        let _opening = self.opening.lock().await;
        let client = lock(&self.client).take();
        if let Some(client) = client {
            client.close().await;
        }
        self.open().await.map(|_| ())
    }

    /// Shuts the connection down for good. A refresh in flight is awaited:
    /// the server may already have rotated the refresh token.
    pub async fn close(&self) {
        self.closed.store(true, Ordering::SeqCst);
        self.set_state(State::Closed, None);
        let client = lock(&self.client).take();
        if let Some(client) = client {
            client.close().await;
        }
        if let Some(auth) = self.oauth() {
            auth.settled().await;
        }
    }
}

/// Servers that do not implement `resources/templates/list` have no templates.
fn without_templates<T>(
    kind: ResourceKind,
    result: Result<T, McpError>,
    empty: T,
) -> Result<T, McpError> {
    match result {
        Err(McpError::Rpc { code, .. })
            if kind == ResourceKind::Templates && code == METHOD_NOT_FOUND =>
        {
            Ok(empty)
        }
        other => other,
    }
}

/// Resources at connect time, for the counts in `/mcp`. Failures leave the
/// list empty, and the resource tools list on demand.
async fn fetch_resources(client: &McpClient) -> Vec<Value> {
    client
        .list_resources(ResourceKind::Resources, RequestOptions::default())
        .await
        .unwrap_or_default()
        .into_iter()
        .filter(|resource| !is_app_resource(resource))
        .collect()
}