yapi-core 0.4.0

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
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
//! MCP tools as session tools, and the three resource tools. Port of
//! `extensions/mcp/tools.ts` and `resources.ts` in pi `v1.0.0`.
//!
//! Model-facing text over 20 KB keeps its start and end, with the full text
//! saved to a temp file the model can read. Binary resources other than
//! images are saved to temp files too. Results keep the server's whole
//! `CallToolResult`, without `_meta`, as structured content.

use std::path::PathBuf;
use std::sync::Arc;

use aws_lc_rs::digest::{SHA256, digest};
use base64::Engine as _;
use futures_util::future::BoxFuture;
use serde_json::{Map, Value, json};
use tokio_util::sync::CancellationToken;
use yapi_agent::{Tool, UpdateSink};
use yapi_types::event::ToolResult;
use yapi_types::message::{ContentBlock, ToolDeclaration, blocks_text};

use super::client::{RequestOptions, ResourceKind};
use super::connection::Connection;
use super::content::{block_to_llm, to_llm_content};
use crate::tools::truncate::{format_size, truncate_middle};

/// Provider tool names hold at most 64 characters of `[A-Za-z0-9_-]`.
const MAX_TOOL_NAME_LENGTH: usize = 64;
/// Model-facing text beyond this is cut in the middle.
pub const OUTPUT_MAX_BYTES: usize = 20 * 1024;
/// Reads the resources resource links name.
pub const READ_MCP_RESOURCE_TOOL: &str = "read_mcp_resource";
/// Lists resources.
pub const LIST_MCP_RESOURCES_TOOL: &str = "list_mcp_resources";
/// Lists resource templates.
pub const LIST_MCP_RESOURCE_TEMPLATES_TOOL: &str = "list_mcp_resource_templates";

/// `mcp__<server>__<tool>` with everything but `[A-Za-z0-9_]` as `_`. A
/// name too long, or taken by another tool, is cut and given a hash suffix.
pub fn tool_name(server: &str, tool: &str, is_taken: impl Fn(&str) -> bool) -> String {
    let name: String = format!("mcp__{server}__{tool}")
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect();
    if name.len() <= MAX_TOOL_NAME_LENGTH && !is_taken(&name) {
        return name;
    }
    let digest = digest(&SHA256, format!("{server}\0{tool}").as_bytes());
    let hash = crate::time::hex(&digest.as_ref()[..4]);
    format!(
        "{}_{hash}",
        &name[..name.len().min(MAX_TOOL_NAME_LENGTH - hash.len() - 1)]
    )
}

/// The `server/tool` label of the session tool `name` when an MCP server
/// provides it, which pi's MCP renderers show in place of the name.
pub fn server_tool_label(tools: &crate::extensions::Tools, name: &str) -> Option<String> {
    tools.with(|registry| {
        let tool = registry.get(name)?;
        let namespace = tool.namespace.as_ref()?;
        namespace
            .name
            .starts_with(&super::config::namespace(""))
            .then(|| tool.tool.label().to_owned())
    })
}

/// Saves `data` to a temp file only the user can read, and returns its path.
async fn save_temp(data: &[u8], extension: &str) -> Result<PathBuf, String> {
    let path = std::env::temp_dir().join(format!(
        "yapi-mcp-{}{extension}",
        crate::time::random_hex(8)
    ));
    let mut options = tokio::fs::OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(unix)]
    options.mode(0o600);
    let mut file = options
        .open(&path)
        .await
        .map_err(|error| error.to_string())?;
    tokio::io::AsyncWriteExt::write_all(&mut file, data)
        .await
        .map_err(|error| error.to_string())?;
    Ok(path)
}

/// Keeps model-facing text within [`OUTPUT_MAX_BYTES`]: longer text becomes
/// one block in Codex's format with the full text's path, before any
/// images.
pub async fn limit_content(content: Vec<ContentBlock>) -> (Vec<ContentBlock>, Option<PathBuf>) {
    let combined = blocks_text(&content, "\n");
    let truncation = truncate_middle(&combined, OUTPUT_MAX_BYTES);
    if !truncation.truncated {
        return (content, None);
    }
    let (where_, path) = match save_temp(combined.as_bytes(), ".txt").await {
        Ok(path) => (
            format!(
                "[Full output: {} (read it with offset/limit)]",
                path.display()
            ),
            Some(path),
        ),
        Err(error) => (format!("[Could not save the full output: {error}]"), None),
    };
    let tokens = truncation.total_bytes.div_ceil(4);
    let mut limited = vec![ContentBlock::text(format!(
        "Warning: truncated output (original token count: {tokens})\nTotal output lines: {}\n\n{}\n\n{where_}",
        truncation.total_lines, truncation.content
    ))];
    limited.extend(
        content
            .into_iter()
            .filter(|block| matches!(block, ContentBlock::Image(_))),
    );
    (limited, path)
}

/// The extension a saved binary resource gets: its URI's, else `.bin`.
fn extension_of(uri: &str) -> String {
    let path = reqwest::Url::parse(uri)
        .map(|url| url.path().to_owned())
        .unwrap_or_else(|_| uri.to_owned());
    let Some(dot) = path.rfind('.') else {
        return ".bin".into();
    };
    let suffix = &path[dot + 1..];
    if (1..=8).contains(&suffix.len()) && suffix.chars().all(|c| c.is_ascii_alphanumeric()) {
        format!(".{suffix}")
    } else {
        ".bin".into()
    }
}

/// Blobs of these types are shown as text.
fn is_text_mime(mime: Option<&str>) -> bool {
    let Some(mime) = mime else {
        return false;
    };
    let kind = mime
        .split(';')
        .next()
        .unwrap_or_default()
        .trim()
        .to_ascii_lowercase();
    kind.starts_with("text/")
        || kind == "application/json"
        || kind.ends_with("+json")
        || kind.ends_with("+xml")
}

fn field<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
    value.get(key).and_then(Value::as_str)
}

/// One block of `server`'s result for the model.
async fn block_content(server: &str, block: &Value, readable_resources: bool) -> ContentBlock {
    match field(block, "type") {
        Some("resource_link") => {
            let mut details = Vec::new();
            if let Some(mime) = field(block, "mimeType").filter(|mime| !mime.is_empty()) {
                details.push(mime.to_owned());
            }
            if let Some(size) = block.get("size").and_then(Value::as_f64) {
                details.push(format_size(size as usize));
            }
            let details = if details.is_empty() {
                String::new()
            } else {
                format!(" ({})", details.join(", "))
            };
            let description = field(block, "description")
                .filter(|text| !text.is_empty())
                .map(|text| format!(": {text}"))
                .unwrap_or_default();
            let read = if readable_resources {
                format!(". Read it with {READ_MCP_RESOURCE_TOOL} (server \"{server}\")")
            } else {
                String::new()
            };
            let title = field(block, "title")
                .or(field(block, "name"))
                .unwrap_or_default();
            ContentBlock::text(format!(
                "[Resource {} \"{title}\"{details}{description}{read}]",
                field(block, "uri").unwrap_or_default()
            ))
        }
        Some("resource")
            if block["resource"].get("blob").is_some()
                && !field(&block["resource"], "mimeType")
                    .is_some_and(|mime| mime.starts_with("image/")) =>
        {
            let resource = &block["resource"];
            let uri = field(resource, "uri").unwrap_or_default();
            let mime = field(resource, "mimeType");
            let data = node_base64(field(resource, "blob").unwrap_or_default());
            if is_text_mime(mime) {
                return ContentBlock::text(String::from_utf8_lossy(&data));
            }
            let kind = format!(
                "{}, {}",
                mime.unwrap_or("unknown type"),
                format_size(data.len())
            );
            match save_temp(&data, &extension_of(uri)).await {
                Ok(path) => ContentBlock::text(format!(
                    "[Binary resource {uri} ({kind}) saved to {}]",
                    path.display()
                )),
                Err(error) => ContentBlock::text(format!(
                    "[Binary resource {uri} ({kind}) could not be saved: {error}]"
                )),
            }
        }
        _ => block_to_llm(block),
    }
}

/// Node's `Buffer.from(text, "base64")`: characters outside the base64 and
/// base64url alphabets are skipped and decoding stops at the first `=`.
fn node_base64(text: &str) -> Vec<u8> {
    const LENIENT: base64::engine::GeneralPurpose = base64::engine::GeneralPurpose::new(
        &base64::alphabet::STANDARD,
        base64::engine::GeneralPurposeConfig::new()
            .with_decode_padding_mode(base64::engine::DecodePaddingMode::RequireNone)
            .with_decode_allow_trailing_bits(true),
    );
    let mut digits: Vec<u8> = text
        .bytes()
        .take_while(|&byte| byte != b'=')
        .filter_map(|byte| match byte {
            b'-' => Some(b'+'),
            b'_' => Some(b'/'),
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'+' | b'/' => Some(byte),
            _ => None,
        })
        .collect();
    // A lone final digit holds too few bits for a byte.
    if digits.len() % 4 == 1 {
        digits.pop();
    }
    LENIENT.decode(digits).unwrap_or_default()
}

/// `server`'s content blocks for the model, before the output limit.
pub async fn model_content(
    server: &str,
    blocks: &[Value],
    readable_resources: bool,
) -> Vec<ContentBlock> {
    let mut content = Vec::new();
    for block in blocks {
        content.push(block_content(server, block, readable_resources).await);
    }
    content
}

/// [`limit_content`] with the details pi records: the server, the tool and,
/// when the text was cut, the file with the full output.
async fn limit_with_details(
    content: Vec<ContentBlock>,
    server: &str,
    tool: &str,
) -> (Vec<ContentBlock>, Value) {
    let (content, path) = limit_content(content).await;
    let mut details = json!({"server": server, "tool": tool});
    if let Some(path) = path {
        details["fullOutputPath"] = json!(path.display().to_string());
    }
    (content, details)
}

/// pi's `convertMcpResult`: `isError` results become error results.
pub async fn convert_result(
    server: &str,
    tool: &str,
    result: Value,
    readable_resources: bool,
) -> ToolResult {
    let blocks = result
        .get("content")
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default();
    let mut converted = if blocks.is_empty() {
        to_llm_content(&result)
    } else {
        model_content(server, &blocks, readable_resources).await
    };
    let is_error = result.get("isError").and_then(Value::as_bool) == Some(true);
    if is_error && blocks_text(&converted, "\n").is_empty() {
        converted.push(ContentBlock::text(format!(
            "MCP tool {server}/{tool} returned an error"
        )));
    }
    let (content, details) = limit_with_details(converted, server, tool).await;
    let mut structured = result;
    if let Some(object) = structured.as_object_mut() {
        object.shift_remove("_meta");
    }
    ToolResult {
        content,
        details: Some(details),
        structured_content: Some(structured),
        is_error: is_error.then_some(true),
        ..ToolResult::default()
    }
}

/// Tool input schemas must be objects with `properties`, which some servers
/// omit.
fn parameters(schema: &Map<String, Value>) -> Value {
    let mut parameters = schema.clone();
    if !parameters.contains_key("type") {
        parameters.insert("type".into(), json!("object"));
    }
    if !parameters.contains_key("properties") {
        parameters.insert("properties".into(), json!({}));
    }
    Value::Object(parameters)
}

/// pi's `toToolAnnotations`: the boolean hints of `tool`'s annotations, or
/// `None` when it has none.
pub fn annotations(tool: &super::Tool) -> Option<Value> {
    const HINTS: [&str; 4] = [
        "readOnlyHint",
        "destructiveHint",
        "idempotentHint",
        "openWorldHint",
    ];
    let given = tool.annotations.as_ref()?;
    let hints: serde_json::Map<String, Value> = HINTS
        .iter()
        .filter_map(|hint| {
            Some((
                (*hint).to_owned(),
                given.get(*hint).filter(|value| value.is_boolean())?.clone(),
            ))
        })
        .collect();
    (!hints.is_empty()).then_some(Value::Object(hints))
}

/// An MCP server's tool.
pub struct McpTool {
    declaration: ToolDeclaration,
    output_schema: Value,
    label: String,
    server: String,
    tool: String,
    connection: Arc<Connection>,
}

impl McpTool {
    /// The tool `tool` of `connection`'s server, named `name`.
    pub fn new(connection: Arc<Connection>, tool: &super::Tool, name: String) -> McpTool {
        let server = connection.name().to_owned();
        let title = tool.title.clone().or_else(|| {
            tool.annotations
                .as_ref()
                .and_then(|annotations| annotations.get("title"))
                .and_then(Value::as_str)
                .map(str::to_owned)
        });
        let description = tool
            .description
            .as_deref()
            .map(str::trim)
            .filter(|text| !text.is_empty())
            .map(str::to_owned)
            .or(title)
            .unwrap_or_else(|| format!("MCP tool {} from server {server}", tool.name));
        McpTool {
            declaration: ToolDeclaration {
                name,
                description,
                parameters: parameters(&tool.input_schema),
                constrained_sampling: None,
            },
            output_schema: result_schema(tool.output_schema.as_ref()),
            label: format!("{server}/{}", tool.name),
            server,
            tool: tool.name.clone(),
            connection,
        }
    }
}

/// pi's `createMcpResultSchema`: the `CallToolResult` scripts receive, with
/// the tool's own output schema as `structuredContent`.
fn result_schema(structured: Option<&Map<String, Value>>) -> Value {
    let mut properties = Map::new();
    properties.insert(
        "content".into(),
        json!({"type": "array", "items": {"type": "object"}}),
    );
    if let Some(structured) = structured {
        properties.insert(
            "structuredContent".into(),
            Value::Object(structured.clone()),
        );
    }
    properties.insert("isError".into(), json!({"type": "boolean"}));
    properties.insert("_meta".into(), json!({"type": "object"}));
    json!({"type": "object", "properties": properties, "required": ["content"]})
}

impl Tool for McpTool {
    fn declaration(&self) -> &ToolDeclaration {
        &self.declaration
    }

    fn output_schema(&self) -> Option<&Value> {
        Some(&self.output_schema)
    }

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

    fn execute(
        &self,
        _call_id: String,
        args: Value,
        cancel: CancellationToken,
        updates: UpdateSink,
    ) -> BoxFuture<'_, Result<ToolResult, String>> {
        Box::pin(async move {
            let (server, tool) = (self.server.clone(), self.tool.clone());
            let options = RequestOptions {
                cancel: Some(cancel),
                timeout: Some(self.connection.timeout()),
                on_progress: Some(Arc::new(move |progress: &Value| {
                    let total = progress
                        .get("total")
                        .filter(|total| !total.is_null())
                        .map(|total| format!("/{total}"))
                        .unwrap_or_default();
                    let message = progress
                        .get("message")
                        .and_then(Value::as_str)
                        .map(str::to_owned)
                        .unwrap_or_else(|| format!("Progress {}{total}", progress["progress"]));
                    updates(ToolResult {
                        content: vec![ContentBlock::text(message)],
                        details: Some(json!({"server": server, "tool": tool})),
                        ..ToolResult::default()
                    });
                })),
            };
            let args = if args.is_null() { json!({}) } else { args };
            let result = self
                .connection
                .call_tool(&self.tool, args, options)
                .await
                .map_err(|error| error.to_string())?;
            Ok(convert_result(
                &self.server,
                &self.tool,
                result,
                self.connection.readable_resources(),
            )
            .await)
        })
    }
}

/// Which resource tool.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ResourceTool {
    List(ResourceKind),
    Read,
}

/// The servers resource tools reach, at call time.
pub type ResourceServers = Arc<dyn Fn() -> Vec<Arc<Connection>> + Send + Sync>;

/// One of `list_mcp_resources`, `list_mcp_resource_templates` and
/// `read_mcp_resource`, which take a `server` argument and reach every
/// connected server with resources.
pub struct McpResourceTool {
    declaration: ToolDeclaration,
    output_schema: Value,
    kind: ResourceTool,
    servers: ResourceServers,
}

/// MCP App user interfaces, which only hosts that render them can use.
pub fn is_app_resource(item: &Value) -> bool {
    let uri = field(item, "uri")
        .or_else(|| field(item, "uriTemplate"))
        .unwrap_or_default();
    let mime = field(item, "mimeType")
        .unwrap_or_default()
        .to_ascii_lowercase();
    let profile = mime.split(';').skip(1).any(|parameter| {
        parameter.split_once('=').is_some_and(|(key, value)| {
            key.trim() == "profile" && value.trim().trim_matches('"') == "mcp-app"
        })
    });
    uri.starts_with("ui://") || profile
}

/// A listed item without `_meta` and icons, tagged with its server.
fn listed(server: &str, item: &Value) -> Value {
    let mut out = Map::new();
    out.insert("server".into(), json!(server));
    if let Some(object) = item.as_object() {
        for (key, value) in object {
            if key != "_meta" && key != "icons" {
                out.insert(key.clone(), value.clone());
            }
        }
    }
    Value::Object(out)
}

fn string_argument(args: &Value, key: &str) -> Result<Option<String>, String> {
    match args.get(key) {
        None | Some(Value::Null) => Ok(None),
        Some(Value::String(value)) => {
            Ok(Some(value.trim().to_owned()).filter(|value| !value.is_empty()))
        }
        Some(_) => Err(format!("{key} must be a string")),
    }
}

/// The three resource tools over `servers`.
pub fn resource_tools(servers: ResourceServers) -> Vec<McpResourceTool> {
    let string = |description: &str| json!({"type": "string", "description": description});
    let list_parameters = json!({
        "type": "object",
        "properties": {
            "server": string("MCP server name. Omit to list every server with resources."),
            "cursor": string("Opaque cursor from a previous call with the same server; omit for the first page."),
        },
        "additionalProperties": false,
    });
    let read_parameters = json!({
        "type": "object",
        "properties": {
            "server": string("MCP server name exactly as configured. Must match the 'server' field returned by list_mcp_resources."),
            "uri": string("Resource URI to read. Must be one of the URIs returned by list_mcp_resources."),
        },
        "required": ["server", "uri"],
        "additionalProperties": false,
    });
    let declare = |name: &str, description: &str, parameters: Value| ToolDeclaration {
        name: name.into(),
        description: description.into(),
        parameters,
        constrained_sampling: None,
    };
    // pi's output schemas, which codemode describes scripts' results by.
    let optional_string = json!({"type": "string"});
    let listing_errors = json!({
        "type": "array",
        "description": "Servers that could not be listed",
        "items": {
            "type": "object",
            "properties": {"server": {"type": "string"}, "error": {"type": "string"}},
            "required": ["server", "error"],
        },
    });
    let list_output = json!({
        "type": "object",
        "properties": {
            "server": optional_string,
            "resources": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {
                        "server": {"type": "string"},
                        "uri": {"type": "string"},
                        "name": {"type": "string"},
                        "title": optional_string,
                        "description": optional_string,
                        "mimeType": optional_string,
                        "size": {"type": "number"},
                    },
                    "required": ["server", "uri", "name"],
                },
            },
            "nextCursor": optional_string,
            "errors": listing_errors,
        },
        "required": ["resources"],
    });
    let list_templates_output = json!({
        "type": "object",
        "properties": {
            "server": optional_string,
            "resourceTemplates": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {
                        "server": {"type": "string"},
                        "uriTemplate": {"type": "string", "description": "RFC 6570 URI template"},
                        "name": {"type": "string"},
                        "title": optional_string,
                        "description": optional_string,
                        "mimeType": optional_string,
                    },
                    "required": ["server", "uriTemplate", "name"],
                },
            },
            "nextCursor": optional_string,
            "errors": listing_errors,
        },
        "required": ["resourceTemplates"],
    });
    let read_output = json!({
        "type": "object",
        "properties": {
            "server": {"type": "string"},
            "uri": {"type": "string"},
            "contents": {
                "type": "array",
                "items": {
                    "anyOf": [
                        {
                            "type": "object",
                            "properties": {"uri": {"type": "string"}, "mimeType": optional_string, "text": {"type": "string"}},
                            "required": ["uri", "text"],
                        },
                        {
                            "type": "object",
                            "properties": {
                                "uri": {"type": "string"},
                                "mimeType": optional_string,
                                "blob": {"type": "string", "description": "base64"},
                            },
                            "required": ["uri", "blob"],
                        },
                    ],
                },
            },
        },
        "required": ["server", "uri", "contents"],
    });
    vec![
        McpResourceTool {
            declaration: declare(
                LIST_MCP_RESOURCES_TOOL,
                "Lists resources provided by MCP servers. Resources allow servers to share data that provides context to language models, such as files, database schemas, or application-specific information. Prefer resources over web search when possible.",
                list_parameters.clone(),
            ),
            output_schema: list_output,
            kind: ResourceTool::List(ResourceKind::Resources),
            servers: Arc::clone(&servers),
        },
        McpResourceTool {
            declaration: declare(
                LIST_MCP_RESOURCE_TEMPLATES_TOOL,
                "Lists resource templates provided by MCP servers. Parameterized resource templates allow servers to share data that takes parameters and provides context to language models, such as files, database schemas, or application-specific information. Prefer resource templates over web search when possible.",
                list_parameters,
            ),
            output_schema: list_templates_output,
            kind: ResourceTool::List(ResourceKind::Templates),
            servers: Arc::clone(&servers),
        },
        McpResourceTool {
            declaration: declare(
                READ_MCP_RESOURCE_TOOL,
                "Read a specific resource from an MCP server given the server name and resource URI.",
                read_parameters,
            ),
            output_schema: read_output,
            kind: ResourceTool::Read,
            servers,
        },
    ]
}

impl McpResourceTool {
    fn find(&self, name: &str) -> Result<Arc<Connection>, String> {
        let servers = (self.servers)();
        if let Some(server) = servers.iter().find(|server| server.name() == name) {
            return Ok(Arc::clone(server));
        }
        let available: Vec<&str> = servers.iter().map(|server| server.name()).collect();
        Err(if available.is_empty() {
            format!("MCP server \"{name}\" has no resources")
        } else {
            format!(
                "MCP server \"{name}\" has no resources. Servers with resources: {}",
                available.join(", ")
            )
        })
    }

    async fn list(
        &self,
        kind: ResourceKind,
        args: &Value,
        cancel: &CancellationToken,
    ) -> Result<Value, String> {
        let key = kind.key();
        let server_name = string_argument(args, "server")?;
        let cursor = string_argument(args, "cursor")?;
        let options = |server: &Connection| RequestOptions {
            cancel: Some(cancel.clone()),
            timeout: Some(server.timeout()),
            on_progress: None,
        };
        if let Some(name) = server_name {
            let server = self.find(&name)?;
            let (items, next) = server
                .resources_page(kind, cursor, options(&server))
                .await
                .map_err(|error| error.to_string())?;
            let items: Vec<Value> = items
                .iter()
                .filter(|item| !is_app_resource(item))
                .map(|item| listed(server.name(), item))
                .collect();
            let mut payload = json!({ "server": server.name(), key: items });
            if let Some(next) = next {
                payload["nextCursor"] = json!(next);
            }
            return Ok(payload);
        }
        if cursor.is_some() {
            return Err("cursor can only be used when a server is specified".into());
        }
        let mut servers = (self.servers)();
        servers.sort_by(|a, b| yapi_types::collate::locale_compare(a.name(), b.name()));
        let mut items = Vec::new();
        let mut errors = Vec::new();
        for server in &servers {
            match server.all_resources(kind, options(server)).await {
                Ok(found) => items.extend(
                    found
                        .iter()
                        .filter(|item| !is_app_resource(item))
                        .map(|item| listed(server.name(), item)),
                ),
                Err(error) => {
                    errors.push(json!({"server": server.name(), "error": error.to_string()}))
                }
            }
        }
        let mut payload = json!({ key: items });
        if !errors.is_empty() {
            payload["errors"] = json!(errors);
        }
        Ok(payload)
    }

    async fn read(&self, args: &Value, cancel: &CancellationToken) -> Result<ToolResult, String> {
        let name = string_argument(args, "server")?.ok_or("server must be provided")?;
        let uri = string_argument(args, "uri")?.ok_or("uri must be provided")?;
        let server = self.find(&name)?;
        let result = server
            .read_resource(
                &uri,
                RequestOptions {
                    cancel: Some(cancel.clone()),
                    timeout: Some(server.timeout()),
                    on_progress: None,
                },
            )
            .await
            .map_err(|error| error.to_string())?;
        let contents = result["contents"].as_array().cloned().unwrap_or_default();
        let mut blocks = Vec::new();
        for item in &contents {
            if contents.len() > 1 {
                blocks.push(json!({"type": "text", "text": format!("{}:", field(item, "uri").unwrap_or_default())}));
            }
            blocks.push(json!({"type": "resource", "resource": item}));
        }
        let converted = model_content(server.name(), &blocks, false).await;
        let converted = if converted.is_empty() {
            vec![ContentBlock::text(format!("Resource {uri} is empty."))]
        } else {
            converted
        };
        let (content, details) =
            limit_with_details(converted, server.name(), READ_MCP_RESOURCE_TOOL).await;
        let contents: Vec<Value> = contents
            .into_iter()
            .map(|mut item| {
                if let Some(object) = item.as_object_mut() {
                    object.shift_remove("_meta");
                }
                item
            })
            .collect();
        Ok(ToolResult {
            content,
            details: Some(details),
            structured_content: Some(
                json!({"server": server.name(), "uri": uri, "contents": contents}),
            ),
            ..ToolResult::default()
        })
    }
}

impl Tool for McpResourceTool {
    fn declaration(&self) -> &ToolDeclaration {
        &self.declaration
    }

    fn output_schema(&self) -> Option<&Value> {
        Some(&self.output_schema)
    }

    fn execute(
        &self,
        _call_id: String,
        args: Value,
        cancel: CancellationToken,
        _updates: UpdateSink,
    ) -> BoxFuture<'_, Result<ToolResult, String>> {
        Box::pin(async move {
            let kind = match self.kind {
                ResourceTool::Read => return self.read(&args, &cancel).await,
                ResourceTool::List(kind) => kind,
            };
            let payload = self.list(kind, &args, &cancel).await?;
            let json = yapi_types::json::stringify(&payload);
            let server = string_argument(&args, "server")?.unwrap_or_default();
            let (content, details) = limit_with_details(
                vec![ContentBlock::text(json)],
                &server,
                &self.declaration.name,
            )
            .await;
            Ok(ToolResult {
                content,
                details: Some(details),
                structured_content: Some(payload),
                ..ToolResult::default()
            })
        })
    }
}

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

    #[test]
    fn names_tools_like_pi() {
        assert_eq!(
            tool_name("docs", "search-pages", |_| false),
            "mcp__docs__search_pages"
        );
        let long = tool_name("server", &"x".repeat(80), |_| false);
        assert_eq!(long.len(), 64);
        assert!(long.starts_with("mcp__server__xxx"));
        let taken = tool_name("a", "b", |name| name == "mcp__a__b");
        assert_eq!(&taken[..10], "mcp__a__b_");
        assert_eq!(taken.len(), 18);
        assert_eq!(extension_of("file:///tmp/archive.tar.gz"), ".gz");
        assert_eq!(extension_of("blob:thing"), ".bin");
        assert!(is_app_resource(&json!({"uri": "ui://widget"})));
        assert!(is_app_resource(
            &json!({"uri": "a", "mimeType": "text/html;profile=mcp-app"})
        ));
    }

    #[tokio::test]
    async fn lenient_resource_blob() {
        let text = |blob: &str| {
            let block = json!({
                "type": "resource",
                "resource": {"uri": "file:///a.txt", "mimeType": "text/plain", "blob": blob},
            });
            async move { block_content("docs", &block, false).await }
        };
        // Unpadded, wrapped as Python's `base64.encodebytes` writes it, and
        // base64url, as Node's `Buffer.from` reads them.
        let wrapped = "aGVsbG8g".repeat(10) + "\n" + &"aGVsbG8g".repeat(2) + "\n";
        for (blob, expected) in [
            ("aGVsbG8", "hello".to_owned()),
            (&wrapped, "hello ".repeat(12)),
            ("_-8=QQ==", "\u{fffd}\u{fffd}".to_owned()),
        ] {
            assert_eq!(text(blob).await, ContentBlock::text(expected), "{blob:?}");
        }
    }
}