rig-mcp-server 0.47.7

Serve Rig agents and tools over the Model Context Protocol (MCP): agents as tools with sessions, streamed progress and cancellation; typed agents with structured output; stdio and Streamable HTTP.
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
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
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
//! The MCP server: which Rig agents and tools it exposes, and how it runs them.

use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;

use futures::StreamExt;
use futures::future::BoxFuture;
use rig_agent::Agent;
use rig_agent::agent::MultiTurnStreamItem;
use rig_agent::completion::{PromptError, StructuredOutputError};
use rig_core::message::Message;
use rig_core::serve::adapters::ToolAdapter;
use rig_core::streaming::{Item, StreamEvent};
use rig_core::tool::{DynamicTool, Tool, ToolExecutionError, ToolOutput, tool_definition};
use rig_memory::AsyncStore;
use rig_memory::recent::{Recent, TokenBudget, view};
use rmcp::model::{
    CallToolRequestParams, CallToolResponse, CallToolResult, CompleteRequestMethod,
    CompleteRequestParams, CompleteResult, CompletionInfo, ContentBlock, GetPromptRequestParams,
    GetPromptResponse, GetPromptResult, Icon, Implementation, InitializeResult, JsonObject,
    ListPromptsResult, ListResourceTemplatesResult, ListResourcesResult, ListToolsResult,
    PaginatedRequestParams, ProgressNotificationParam, Prompt, PromptArgument, PromptMessage,
    PromptsCapability, ReadResourceRequestParams, ReadResourceResponse, ReadResourceResult,
    Reference, Resource, ResourceContents, ResourceTemplate, ResourcesCapability,
    ServerCapabilities, ServerConfig, ToolAnnotations,
};
use rmcp::service::RequestContext;
use rmcp::{ErrorData as McpError, RoleServer, ServerHandler};
use serde::Deserialize;
use serde_json::{Value, json};

use crate::catalog::{Piece, Render, StaticPrompt, StaticResource, StaticTemplate, TemplateVars};
use crate::completion::{BoxError, Completer, CompletionRequest, CompletionTarget};
use crate::content::{image_blocks, tool_result};
use crate::history::{
    DEFAULT_HISTORY_TOKENS, DEFAULT_MAX_CONTEXTS, HistoryStore, InMemory, Persistent,
    valid_context_id,
};
use crate::transport::DEFAULT_MAX_REQUEST_BYTES;

/// How many calls run at once by default; more are answered as busy.
pub const DEFAULT_MAX_CONCURRENT_CALLS: usize = 32;
/// How long one agent run may take by default before it is stopped.
pub const DEFAULT_MAX_RUN_DURATION: Duration = Duration::from_secs(600);

/// Longest tool name MCP clients and model providers accept.
const MAX_TOOL_NAME: usize = 64;

type RunTool =
    Arc<dyn Fn(Value) -> BoxFuture<'static, Result<ToolOutput, ToolExecutionError>> + Send + Sync>;
type TypedAnswer = Arc<
    dyn Fn(
            Agent,
            Message,
            Vec<Message>,
        ) -> BoxFuture<'static, Result<(Value, Vec<Message>), String>>
        + Send
        + Sync,
>;

/// Rig agents and tools served over the Model Context Protocol.
///
/// Each [`agent`](Self::agent) becomes a tool taking a `message` and an
/// optional `session_id`: a call runs the agent with that session's history
/// and answers with its text (streamed meanwhile as progress notifications
/// when the client asks for progress) and any image it made. Each
/// [`tool`](Self::tool) is exposed as itself, run without a model.
///
/// Serve it to a local client (Claude Code, Cursor, Zed...) over stdio with
/// [`serve_stdio`](Self::serve_stdio), or over Streamable HTTP with
/// [`into_router`](Self::into_router).
pub struct McpServer {
    name: String,
    version: String,
    instructions: Option<String>,
    title: Option<String>,
    icons: Vec<Icon>,
    tools: Vec<Entry>,
    resources: Vec<StaticResource>,
    resource_templates: Vec<StaticTemplate>,
    prompts: Vec<StaticPrompt>,
    history: Arc<dyn HistoryStore>,
    window: Arc<dyn Recent>,
    slots: Arc<tokio::sync::Semaphore>,
    max_run: Duration,
    pub(crate) bearer: Option<String>,
    pub(crate) allowed_hosts: Option<Vec<String>>,
    pub(crate) max_request_bytes: usize,
    pub(crate) ping: bool,
    completer: Option<Completer>,
}

struct Entry {
    tool: rmcp::model::Tool,
    kind: Kind,
}

enum Kind {
    Tool(RunTool),
    Agent(Box<Agent>, Option<TypedAnswer>),
}

impl McpServer {
    /// A server introducing itself to clients as `name`, with nothing to
    /// offer yet.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            version: env!("CARGO_PKG_VERSION").to_owned(),
            instructions: None,
            title: None,
            icons: Vec::new(),
            tools: Vec::new(),
            resources: Vec::new(),
            resource_templates: Vec::new(),
            prompts: Vec::new(),
            history: Arc::new(InMemory::new(DEFAULT_MAX_CONTEXTS)),
            window: Arc::new(TokenBudget::new(DEFAULT_HISTORY_TOKENS)),
            slots: Arc::new(tokio::sync::Semaphore::new(DEFAULT_MAX_CONCURRENT_CALLS)),
            max_run: DEFAULT_MAX_RUN_DURATION,
            bearer: None,
            allowed_hosts: None,
            max_request_bytes: DEFAULT_MAX_REQUEST_BYTES,
            ping: false,
            completer: None,
        }
    }

    /// Also serve `GET /ping` on the HTTP router, answering
    /// `{"status": "Healthy"}`, the health route AWS Bedrock AgentCore Runtime
    /// recommends for MCP servers. Off by default: a router that already has
    /// its own `/ping` would clash with it. The route takes no bearer token and
    /// no `Host` check; `/mcp` keeps both. HTTP only.
    #[must_use]
    pub fn ping_route(mut self) -> Self {
        self.ping = true;
        self
    }

    /// The version clients see. Defaults to this crate's version.
    #[must_use]
    pub fn version(mut self, version: impl Into<String>) -> Self {
        self.version = version.into();
        self
    }

    /// A human-readable title clients may show for the server. Optional: left
    /// out of `initialize` unless set.
    #[must_use]
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Add an icon clients may show for the server. Its `src` must be an
    /// `http://` or `https://` URL or a `data:` URI, or serving fails with
    /// [`BuildError::InvalidIcon`]. Optional: left out of `initialize` unless
    /// set. Icons keep the order they were added in.
    #[must_use]
    pub fn icon(mut self, icon: Icon) -> Self {
        self.icons.push(icon);
        self
    }

    /// Instructions clients may pass to their model about using this server.
    #[must_use]
    pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
        self.instructions = Some(instructions.into());
        self
    }

    /// Expose `agent` as a tool named after it (its name, made provider-safe),
    /// described by its description. It answers with text and any images,
    /// plus `{answer, session_id}` as structured content; passing that
    /// `session_id` back continues the conversation.
    ///
    /// Another tool with the same name makes serving fail with
    /// [`BuildError::DuplicateTool`].
    #[must_use]
    pub fn agent(self, agent: Agent) -> Self {
        let (name, description) = agent_identity(&agent);
        let output = json!({
            "type": "object",
            "properties": {
                "answer": {"type": "string"},
                "session_id": {"type": "string"}
            },
            "required": ["answer", "session_id"]
        });
        let tool = rmcp::model::Tool::new(name, description, Arc::new(agent_input()))
            .with_raw_output_schema(Arc::new(object(output)));
        self.add(Entry {
            tool,
            kind: Kind::Agent(Box::new(agent), None),
        })
    }

    /// Expose `agent` as a tool that answers with a `T`: each call runs as
    /// [`Agent::prompt_typed`] does (two retries when the JSON does not parse)
    /// and the `T` comes back as structured content matching the tool's
    /// output schema, the schema of `T`.
    ///
    /// Another tool with the agent's name makes serving fail with
    /// [`BuildError::DuplicateTool`].
    #[must_use]
    pub fn typed_agent<T>(self, agent: Agent) -> Self
    where
        T: schemars::JsonSchema
            + serde::de::DeserializeOwned
            + serde::Serialize
            + Send
            + Sync
            + 'static,
    {
        let (name, description) = agent_identity(&agent);
        let schema = serde_json::to_value(schemars::schema_for!(T)).unwrap_or_default();
        let tool = rmcp::model::Tool::new(name, description, Arc::new(agent_input()))
            .with_raw_output_schema(Arc::new(object(schema)));
        let typed: TypedAnswer = Arc::new(|agent, prompt, history| {
            Box::pin(async move {
                let response = agent
                    .prompt_typed::<T>(prompt)
                    .history(history)
                    .retries(2)
                    .await
                    .map_err(|error| {
                        let reason = match &error {
                            StructuredOutputError::Prompt(prompt) => status_message(prompt),
                            _ => "not a structured answer",
                        };
                        tracing::warn!(
                            kind = "run_failed",
                            reason = reason,
                            "typed agent call failed"
                        );
                        match &error {
                            StructuredOutputError::Prompt(prompt) => {
                                failure_message(prompt).into_owned()
                            }
                            _ => "The agent could not produce a structured answer.".to_owned(),
                        }
                    })?;
                let value =
                    serde_json::to_value(&response.output).map_err(|error| error.to_string())?;
                Ok((value, response.messages))
            })
        });
        self.add(Entry {
            tool,
            kind: Kind::Agent(Box::new(agent), Some(typed)),
        })
    }

    /// Expose a Rig tool as itself: same name, description, parameters and
    /// annotations; called directly, with no model involved.
    ///
    /// Another tool with the same name makes serving fail with
    /// [`BuildError::DuplicateTool`].
    #[must_use]
    pub fn tool<T: Tool + 'static>(self, tool: T) -> Self {
        self.tool_presented(tool, Presentation::default())
    }

    /// Expose a [`Tool`] as [`tool`](Self::tool) does, with a title and icons
    /// for clients to show; see [`Presentation`].
    ///
    /// Another tool with the same name makes serving fail with
    /// [`BuildError::DuplicateTool`].
    #[must_use]
    pub fn tool_presented<T: Tool + 'static>(self, tool: T, presentation: Presentation) -> Self {
        let definition = tool_definition(&tool);
        let adapter = Arc::new(ToolAdapter::new(tool));
        let run: RunTool = Arc::new(move |args| {
            let adapter = Arc::clone(&adapter);
            Box::pin(async move { adapter.run(args).await })
        });
        self.add_tool(definition, run, &presentation)
    }

    /// Expose a [`DynamicTool`] as itself; see [`tool`](Self::tool).
    ///
    /// Another tool with the same name makes serving fail with
    /// [`BuildError::DuplicateTool`].
    #[must_use]
    pub fn dynamic_tool(self, tool: DynamicTool) -> Self {
        self.dynamic_tool_presented(tool, Presentation::default())
    }

    /// Expose a [`DynamicTool`] with a title and icons; see
    /// [`tool_presented`](Self::tool_presented).
    ///
    /// Another tool with the same name makes serving fail with
    /// [`BuildError::DuplicateTool`].
    #[must_use]
    pub fn dynamic_tool_presented(self, tool: DynamicTool, presentation: Presentation) -> Self {
        let definition = tool.definition();
        let tool = Arc::new(tool);
        let run: RunTool = Arc::new(move |args| {
            let tool = Arc::clone(&tool);
            Box::pin(async move { tool.run(args).await })
        });
        self.add_tool(definition, run, &presentation)
    }

    /// Keep agent sessions in memory, at most `max` of them; the oldest one
    /// started is forgotten first. This is the default, with
    /// [`DEFAULT_MAX_CONTEXTS`](crate::DEFAULT_MAX_CONTEXTS).
    #[must_use]
    pub fn max_sessions(mut self, max: usize) -> Self {
        self.history = Arc::new(InMemory::new(max));
        self
    }

    /// Keep agent sessions in any [`rig_memory`] store (`DirStore` on disk,
    /// `rig-sqlite`, `rig-postgres`), so they survive restarts and several
    /// servers can share them.
    #[must_use]
    pub fn history_store<S>(mut self, store: S) -> Self
    where
        S: AsyncStore + Send + Sync + 'static,
    {
        self.history = Arc::new(Persistent(store));
        self
    }

    /// Which newest messages of a session each call sends the model.
    /// Defaults to [`DEFAULT_HISTORY_TOKENS`](crate::DEFAULT_HISTORY_TOKENS)
    /// tokens; a tool result is never sent without its call.
    #[must_use]
    pub fn history_window(mut self, window: impl Recent + 'static) -> Self {
        self.window = Arc::new(window);
        self
    }

    /// Run at most `max` calls at once (at least one); a call beyond that
    /// gets a "busy" error result before any model call.
    #[must_use]
    #[doc(alias = "max_concurrent_tasks")]
    pub fn max_concurrent_calls(mut self, max: usize) -> Self {
        self.slots = Arc::new(tokio::sync::Semaphore::new(max.max(1)));
        self
    }

    /// Stop an agent run that takes longer than `max`.
    #[must_use]
    pub fn max_run_duration(mut self, max: Duration) -> Self {
        self.max_run = max;
        self
    }

    /// Offer a text resource at `uri`, read with `resources/read`. `mime_type`
    /// tells the client what the text is, such as `text/markdown`.
    ///
    /// Another resource with the same URI makes serving fail with
    /// [`BuildError::DuplicateResource`]. Only fixed contents are offered here;
    /// for URIs with variables see [`resource_template`](Self::resource_template).
    /// No subscriptions and no list-changed notifications.
    #[must_use]
    pub fn resource(
        self,
        uri: impl Into<String>,
        name: impl Into<String>,
        mime_type: impl Into<String>,
        text: impl Into<String>,
    ) -> Self {
        self.resource_presented(uri, name, mime_type, text, Presentation::default())
    }

    /// Offer a binary resource at `uri`. The bytes travel base64-encoded in
    /// the `resources/read` result, labelled with `mime_type`.
    ///
    /// Another resource with the same URI makes serving fail with
    /// [`BuildError::DuplicateResource`].
    #[must_use]
    pub fn binary_resource(
        self,
        uri: impl Into<String>,
        name: impl Into<String>,
        mime_type: impl Into<String>,
        bytes: impl AsRef<[u8]>,
    ) -> Self {
        use base64::Engine;

        let uri = uri.into();
        let mime_type = mime_type.into();
        let resource = Resource::new(uri.clone(), name).with_mime_type(mime_type.clone());
        let contents = ResourceContents::BlobResourceContents {
            uri,
            mime_type: Some(mime_type),
            blob: base64::engine::general_purpose::STANDARD.encode(bytes.as_ref()),
            meta: None,
        };
        self.add_resource(StaticResource { resource, contents })
    }

    /// Offer a prompt named `name`. Its `arguments` are listed to the client;
    /// a call to `prompts/get` without a required one is refused with an
    /// invalid-params error. `render` turns the arguments the client passed
    /// (all strings, keyed by name) into the prompt's messages.
    ///
    /// Another prompt with the same name makes serving fail with
    /// [`BuildError::DuplicatePrompt`]. Prompts are fixed: no list-changed
    /// notifications. Their arguments complete through [`completer`](Self::completer).
    ///
    /// ```no_run
    /// use std::collections::HashMap;
    /// use rig_mcp_server::{McpServer, rmcp::model::{PromptArgument, PromptMessage, Role}};
    ///
    /// let server = McpServer::new("docs").prompt(
    ///     "explain",
    ///     "Explain a topic for a reader.",
    ///     vec![PromptArgument::new("topic").with_required(true)],
    ///     |args: &HashMap<String, String>| {
    ///         let topic = args.get("topic").map_or("", String::as_str);
    ///         vec![PromptMessage::new_text(Role::User, format!("Explain {topic} in plain words."))]
    ///     },
    /// );
    /// ```
    #[must_use]
    pub fn prompt<F>(
        self,
        name: impl Into<String>,
        description: impl Into<String>,
        arguments: Vec<PromptArgument>,
        render: F,
    ) -> Self
    where
        F: Fn(&HashMap<String, String>) -> Vec<PromptMessage> + Send + Sync + 'static,
    {
        self.prompt_presented(
            name,
            description,
            arguments,
            render,
            Presentation::default(),
        )
    }

    /// Expose a text resource as [`resource`](Self::resource) does, with a title
    /// and icons for clients to show; see [`Presentation`].
    ///
    /// Another resource with the same URI makes serving fail with
    /// [`BuildError::DuplicateResource`].
    #[must_use]
    pub fn resource_presented(
        self,
        uri: impl Into<String>,
        name: impl Into<String>,
        mime_type: impl Into<String>,
        text: impl Into<String>,
        presentation: Presentation,
    ) -> Self {
        let uri = uri.into();
        let mime_type = mime_type.into();
        let mut resource = Resource::new(uri.clone(), name).with_mime_type(mime_type.clone());
        presentation.apply_resource(&mut resource);
        let contents = ResourceContents::TextResourceContents {
            uri,
            mime_type: Some(mime_type),
            text: text.into(),
            meta: None,
        };
        self.add_resource(StaticResource { resource, contents })
    }

    fn add_resource(mut self, resource: StaticResource) -> Self {
        self.resources.push(resource);
        self
    }

    /// Offer a resource template, listed by `resources/templates/list`. Any URI
    /// that matches `uri_template` is read with `read`, which gets the variables
    /// the URI matched and returns the text. `description` and `mime_type` are
    /// listed to the client.
    ///
    /// `uri_template` is an RFC 6570 template with simple `{name}` variables only:
    /// each name is letters, digits or `_`, used once. A variable matches one path
    /// segment (no literal `/`) and its value is percent-decoded, so `%2F` reads
    /// as `/` inside the value. A URI whose value is not valid UTF-8 after decoding
    /// is not found. For example `memo://{id}`. When two templates match a URI, the
    /// one registered first is read. A malformed template, or a second one with the
    /// same text, makes serving fail with
    /// [`BuildError::InvalidResourceTemplate`] or
    /// [`BuildError::DuplicateResourceTemplate`]. A static resource with the same
    /// URI wins over a template.
    ///
    /// An error from `read` reaches the client as an internal JSON-RPC error with
    /// a fixed message; its text is logged by kind only and not sent.
    ///
    /// ```no_run
    /// use rig_mcp_server::{McpServer, TemplateVars};
    ///
    /// let server = McpServer::new("notes").resource_template(
    ///     "memo://{id}",
    ///     "memo",
    ///     "A memo, by its id.",
    ///     "text/plain",
    ///     |vars: TemplateVars| async move {
    ///         let id = vars.get("id").unwrap_or_default();
    ///         Ok::<_, std::io::Error>(format!("memo {id}"))
    ///     },
    /// );
    /// ```
    #[must_use]
    pub fn resource_template<F, Fut, E>(
        self,
        uri_template: impl Into<String>,
        name: impl Into<String>,
        description: impl Into<String>,
        mime_type: impl Into<String>,
        read: F,
    ) -> Self
    where
        F: Fn(TemplateVars) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<String, E>> + Send + 'static,
        E: std::error::Error + Send + Sync + 'static,
    {
        self.resource_template_presented(
            uri_template,
            name,
            description,
            mime_type,
            Presentation::default(),
            read,
        )
    }

    /// Offer a resource template as [`resource_template`](Self::resource_template)
    /// does, with a title and icons for clients to show; see [`Presentation`].
    ///
    /// Another template with the same text makes serving fail with
    /// [`BuildError::DuplicateResourceTemplate`].
    #[must_use]
    pub fn resource_template_presented<F, Fut, E>(
        mut self,
        uri_template: impl Into<String>,
        name: impl Into<String>,
        description: impl Into<String>,
        mime_type: impl Into<String>,
        presentation: Presentation,
        read: F,
    ) -> Self
    where
        F: Fn(TemplateVars) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<String, E>> + Send + 'static,
        E: std::error::Error + Send + Sync + 'static,
    {
        let mut template = ResourceTemplate::new(uri_template, name)
            .with_description(description)
            .with_mime_type(mime_type);
        presentation.apply_template(&mut template);
        let read = Arc::new(
            move |vars: TemplateVars| -> BoxFuture<'static, Result<String, BoxError>> {
                let answer = read(vars);
                Box::pin(async move {
                    answer
                        .await
                        .map_err(|error| -> BoxError { Box::new(error) })
                })
            },
        );
        self.resource_templates
            .push(StaticTemplate { template, read });
        self
    }

    /// Offer a prompt as [`prompt`](Self::prompt) does, with a title and icons
    /// for clients to show; see [`Presentation`].
    ///
    /// Another prompt with the same name makes serving fail with
    /// [`BuildError::DuplicatePrompt`].
    #[must_use]
    pub fn prompt_presented<F>(
        self,
        name: impl Into<String>,
        description: impl Into<String>,
        arguments: Vec<PromptArgument>,
        render: F,
        presentation: Presentation,
    ) -> Self
    where
        F: Fn(&HashMap<String, String>) -> Vec<PromptMessage> + Send + Sync + 'static,
    {
        let mut prompt = Prompt::new(name, Some(description), Some(arguments));
        presentation.apply_prompt(&mut prompt);
        let render: Render = Arc::new(render);
        self.add_prompt(StaticPrompt { prompt, render })
    }

    fn add_prompt(mut self, prompt: StaticPrompt) -> Self {
        self.prompts.push(prompt);
        self
    }

    /// Answer `completion/complete` with `complete`. It gets a
    /// [`CompletionRequest`] (the prompt or resource, the argument, the value
    /// typed so far, and the arguments already resolved) and returns the
    /// candidates. The server sends at most 100 and sets `hasMore` when it cuts
    /// the list. Filtering by the typed value is up to `complete`.
    ///
    /// A request for a prompt, argument, or resource the server does not offer is
    /// refused with invalid params (`-32602`) before `complete` runs. Setting a
    /// completer advertises the `completions` capability. Without one, the
    /// capability is absent and `completion/complete` is refused as an unknown
    /// method. An error from `complete` reaches the client as an internal
    /// JSON-RPC error with a fixed message; its text is logged by kind only and
    /// not sent.
    ///
    /// ```no_run
    /// use rig_mcp_server::{CompletionRequest, CompletionTarget, McpServer};
    ///
    /// let server = McpServer::new("docs").completer(|request: CompletionRequest| async move {
    ///     let topics = ["rust", "ruby", "python"];
    ///     let matches = match &request.target {
    ///         CompletionTarget::Prompt(name) if name == "explain" => topics
    ///             .iter()
    ///             .filter(|topic| topic.starts_with(request.value.as_str()))
    ///             .map(|topic| topic.to_string())
    ///             .collect(),
    ///         _ => Vec::new(),
    ///     };
    ///     Ok::<_, std::io::Error>(matches)
    /// });
    /// ```
    #[must_use]
    pub fn completer<F, Fut, E>(mut self, complete: F) -> Self
    where
        F: Fn(CompletionRequest) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Vec<String>, E>> + Send + 'static,
        E: std::error::Error + Send + Sync + 'static,
    {
        self.completer =
            Some(
                Arc::new(
                    move |request: CompletionRequest| -> BoxFuture<
                        'static,
                        Result<Vec<String>, crate::completion::BoxError>,
                    > {
                        let answer = complete(request);
                        Box::pin(async move {
                            answer
                                .await
                                .map_err(|error| -> crate::completion::BoxError { Box::new(error) })
                        })
                    },
                ),
            );
        self
    }

    fn add_tool(
        self,
        definition: rig_core::completion::ToolDefinition,
        run: RunTool,
        presentation: &Presentation,
    ) -> Self {
        let mut tool = rmcp::model::Tool::new(
            definition.name.to_string(),
            definition.description,
            Arc::new(object(definition.parameters)),
        );
        // Rig's annotations and MCP's have the same wire names (readOnlyHint, ...).
        if let Some(annotations) = serde_json::to_value(&definition.annotations)
            .ok()
            .filter(|value| value.as_object().is_some_and(|fields| !fields.is_empty()))
            .and_then(|value| serde_json::from_value::<ToolAnnotations>(value).ok())
        {
            tool = tool.with_annotations(annotations);
        }
        presentation.apply_tool(&mut tool);
        self.add(Entry {
            tool,
            kind: Kind::Tool(run),
        })
    }

    fn add(mut self, entry: Entry) -> Self {
        self.tools.push(entry);
        self
    }
}

/// The title and icons a client may show for a tool, resource or prompt.
///
/// Both are optional. An unset title or an empty icon list is left out of the
/// listing, as before. Icon sources are checked when the server is served, see
/// [`BuildError::InvalidIcon`].
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct Presentation {
    title: Option<String>,
    icons: Vec<Icon>,
}

impl Presentation {
    /// Nothing set: no title, no icons.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// A human-readable title, such as "Look up weather".
    #[must_use]
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Add an icon. Icons keep the order they were added in.
    #[must_use]
    pub fn icon(mut self, icon: Icon) -> Self {
        self.icons.push(icon);
        self
    }

    fn icon_list(&self) -> Option<Vec<Icon>> {
        (!self.icons.is_empty()).then(|| self.icons.clone())
    }

    fn apply_tool(&self, tool: &mut rmcp::model::Tool) {
        tool.title.clone_from(&self.title);
        tool.icons = self.icon_list();
    }

    fn apply_resource(&self, resource: &mut Resource) {
        resource.title.clone_from(&self.title);
        resource.icons = self.icon_list();
    }

    fn apply_template(&self, template: &mut ResourceTemplate) {
        template.title.clone_from(&self.title);
        template.icons = self.icon_list();
    }

    fn apply_prompt(&self, prompt: &mut Prompt) {
        prompt.title.clone_from(&self.title);
        prompt.icons = self.icon_list();
    }
}

/// Why an [`McpServer`] could not be served.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum BuildError {
    /// Two tools (agents, typed agents or plain tools) have the same name, so
    /// a client could not tell which one it calls.
    #[error("two tools are named `{0}`")]
    DuplicateTool(String),
    /// Two resources have the same URI, so a client could not tell which one
    /// it reads.
    #[error("two resources have the URI `{0}`")]
    DuplicateResource(String),
    /// Two prompts have the same name, so a client could not tell which one
    /// it gets.
    #[error("two prompts are named `{0}`")]
    DuplicatePrompt(String),
    /// An icon's `src` is neither an `http://` or `https://` URL nor a `data:`
    /// URI, so a client could not fetch it. Carries the `src` given.
    #[error("icon source `{0}` is not an http(s) URL or a data: URI")]
    InvalidIcon(String),
    /// A resource template is malformed: an unclosed or empty `{}`, a variable
    /// name that is not letters, digits or `_`, a stray `}`, or a variable used
    /// twice. Carries the template given.
    #[error(
        "resource template `{0}` is malformed: use `{{name}}` once per name, with letters, digits or `_`"
    )]
    InvalidResourceTemplate(String),
    /// Two resource templates have the same text, so a client could not tell
    /// which one it reads.
    #[error("two resource templates have the URI template `{0}`")]
    DuplicateResourceTemplate(String),
}

/// The server as an MCP handler, shared by every connection.
#[derive(Clone)]
pub(crate) struct Handler(Arc<Inner>);

struct Inner {
    server: McpServer,
    by_name: HashMap<String, usize>,
    /// The parsed pattern of each resource template, in the same order.
    templates: Vec<Vec<Piece>>,
}

impl Handler {
    /// The handler of `server`, refused when two of its tools share a name, two
    /// resources a URI, or two prompts a name.
    pub(crate) fn new(server: McpServer) -> Result<Self, BuildError> {
        let mut by_name = HashMap::with_capacity(server.tools.len());
        for (index, entry) in server.tools.iter().enumerate() {
            let name = entry.tool.name.to_string();
            if by_name.contains_key(&name) {
                return Err(BuildError::DuplicateTool(name));
            }
            by_name.insert(name, index);
        }
        let mut uris = HashSet::with_capacity(server.resources.len());
        for resource in &server.resources {
            let uri = &resource.resource.uri;
            if !uris.insert(uri.clone()) {
                return Err(BuildError::DuplicateResource(uri.clone()));
            }
        }
        let mut names = HashSet::with_capacity(server.prompts.len());
        for prompt in &server.prompts {
            let name = &prompt.prompt.name;
            if !names.insert(name.clone()) {
                return Err(BuildError::DuplicatePrompt(name.clone()));
            }
        }
        let mut templates = Vec::with_capacity(server.resource_templates.len());
        let mut texts = HashSet::with_capacity(server.resource_templates.len());
        for template in &server.resource_templates {
            let text = &template.template.uri_template;
            let pieces = crate::catalog::parse(text)
                .ok_or_else(|| BuildError::InvalidResourceTemplate(text.clone()))?;
            if !texts.insert(text.clone()) {
                return Err(BuildError::DuplicateResourceTemplate(text.clone()));
            }
            templates.push(pieces);
        }
        check_icons(server.icons.iter())?;
        for entry in &server.tools {
            check_icons(entry.tool.icons.iter().flatten())?;
        }
        for resource in &server.resources {
            check_icons(resource.resource.icons.iter().flatten())?;
        }
        for template in &server.resource_templates {
            check_icons(template.template.icons.iter().flatten())?;
        }
        for prompt in &server.prompts {
            check_icons(prompt.prompt.icons.iter().flatten())?;
        }
        Ok(Self(Arc::new(Inner {
            server,
            by_name,
            templates,
        })))
    }

    fn entry(&self, name: &str) -> Option<&Entry> {
        let index = *self.0.by_name.get(name)?;
        self.0.server.tools.get(index)
    }
}

/// Each icon's `src` must be an `http(s)` URL or a `data:` URI, as the spec
/// for icons (MCP 2025-11-25) allows.
fn check_icons<'a>(icons: impl IntoIterator<Item = &'a Icon>) -> Result<(), BuildError> {
    for icon in icons {
        let src = icon.src.to_ascii_lowercase();
        if !(src.starts_with("https://") || src.starts_with("http://") || src.starts_with("data:"))
        {
            return Err(BuildError::InvalidIcon(icon.src.clone()));
        }
    }
    Ok(())
}

impl ServerHandler for Handler {
    fn get_info(&self) -> ServerConfig {
        let server = &self.0.server;
        // Resources and prompts are advertised only when there are some, so a
        // server without them answers `initialize` as it always did.
        let mut capabilities = ServerCapabilities::builder().enable_tools().build();
        if !server.resources.is_empty() || !server.resource_templates.is_empty() {
            capabilities.resources = Some(ResourcesCapability::default());
        }
        if !server.prompts.is_empty() {
            capabilities.prompts = Some(PromptsCapability::default());
        }
        if server.completer.is_some() {
            capabilities.completions = Some(JsonObject::default());
        }
        let mut implementation = Implementation::new(server.name.clone(), server.version.clone());
        implementation.title.clone_from(&server.title);
        implementation.icons = (!server.icons.is_empty()).then(|| server.icons.clone());
        let mut info = InitializeResult::new(capabilities).with_server_info(implementation);
        if let Some(instructions) = &server.instructions {
            info = info.with_instructions(instructions.clone());
        }
        info
    }

    async fn list_resources(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListResourcesResult, McpError> {
        Ok(ListResourcesResult {
            resources: self
                .0
                .server
                .resources
                .iter()
                .map(|entry| entry.resource.clone())
                .collect(),
            ..Default::default()
        })
    }

    async fn list_resource_templates(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListResourceTemplatesResult, McpError> {
        Ok(ListResourceTemplatesResult {
            resource_templates: self
                .0
                .server
                .resource_templates
                .iter()
                .map(|entry| entry.template.clone())
                .collect(),
            ..Default::default()
        })
    }

    async fn read_resource(
        &self,
        request: ReadResourceRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<ReadResourceResponse, McpError> {
        // A static resource wins over a template with the same URI.
        if let Some(entry) = self
            .0
            .server
            .resources
            .iter()
            .find(|entry| entry.resource.uri == request.uri)
        {
            return Ok(ReadResourceResponse::Complete(ReadResourceResult::new(
                vec![entry.contents.clone()],
            )));
        }
        for (template, pieces) in self
            .0
            .server
            .resource_templates
            .iter()
            .zip(&self.0.templates)
        {
            let Some(vars) = crate::catalog::matches(pieces, &request.uri) else {
                continue;
            };
            let text = (template.read)(vars).await.map_err(|_| {
                tracing::warn!(kind = "resource_template", "resource template read failed");
                McpError::internal_error("resource read failed", None)
            })?;
            let contents = ResourceContents::TextResourceContents {
                uri: request.uri,
                mime_type: template.template.mime_type.clone(),
                text,
                meta: None,
            };
            return Ok(ReadResourceResponse::Complete(ReadResourceResult::new(
                vec![contents],
            )));
        }
        Err(McpError::resource_not_found(
            format!("no resource at `{}`", request.uri),
            None,
        ))
    }

    async fn list_prompts(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListPromptsResult, McpError> {
        Ok(ListPromptsResult {
            prompts: self
                .0
                .server
                .prompts
                .iter()
                .map(|entry| entry.prompt.clone())
                .collect(),
            ..Default::default()
        })
    }

    async fn get_prompt(
        &self,
        request: GetPromptRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<GetPromptResponse, McpError> {
        let entry = self
            .0
            .server
            .prompts
            .iter()
            .find(|entry| entry.prompt.name == request.name)
            .ok_or_else(|| {
                McpError::invalid_params(format!("no prompt named `{}`", request.name), None)
            })?;
        let mut arguments = HashMap::new();
        for (name, value) in request.arguments.unwrap_or_default() {
            let Value::String(text) = value else {
                return Err(McpError::invalid_params(
                    format!("argument `{name}` must be a string"),
                    None,
                ));
            };
            arguments.insert(name, text);
        }
        for declared in entry.prompt.arguments.iter().flatten() {
            if declared.required == Some(true) && !arguments.contains_key(&declared.name) {
                return Err(McpError::invalid_params(
                    format!("missing required argument `{}`", declared.name),
                    None,
                ));
            }
        }
        let messages = (entry.render)(&arguments);
        let mut result = GetPromptResult::new(messages);
        if let Some(description) = &entry.prompt.description {
            result = result.with_description(description.clone());
        }
        Ok(GetPromptResponse::Complete(result))
    }

    async fn complete(
        &self,
        request: CompleteRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<CompleteResult, McpError> {
        let server = &self.0.server;
        let Some(completer) = &server.completer else {
            return Err(McpError::method_not_found::<CompleteRequestMethod>());
        };
        let target = match request.r#ref {
            Reference::Prompt(prompt) => CompletionTarget::Prompt(prompt.name),
            Reference::Resource(resource) => CompletionTarget::Resource(resource.uri),
            _ => return Err(McpError::invalid_params("unsupported reference", None)),
        };
        match &target {
            CompletionTarget::Prompt(name) => {
                let entry = server
                    .prompts
                    .iter()
                    .find(|entry| entry.prompt.name == *name)
                    .ok_or_else(|| {
                        McpError::invalid_params(format!("no prompt named `{name}`"), None)
                    })?;
                let declared = entry
                    .prompt
                    .arguments
                    .iter()
                    .flatten()
                    .any(|argument| argument.name == request.argument.name);
                if !declared {
                    return Err(McpError::invalid_params(
                        format!(
                            "prompt `{name}` has no argument `{}`",
                            request.argument.name
                        ),
                        None,
                    ));
                }
            }
            CompletionTarget::Resource(uri) => {
                let served = server
                    .resources
                    .iter()
                    .any(|entry| entry.resource.uri == *uri);
                if !served {
                    // A template is completed by its own text, one variable at a time.
                    let index = server
                        .resource_templates
                        .iter()
                        .position(|entry| entry.template.uri_template == *uri);
                    let declared = index
                        .and_then(|index| self.0.templates.get(index))
                        .is_some_and(|pieces| {
                            pieces.iter().any(|piece| {
                                matches!(piece, Piece::Var(name) if *name == request.argument.name)
                            })
                        });
                    if !declared {
                        return Err(McpError::invalid_params(
                            format!("no resource at `{uri}`"),
                            None,
                        ));
                    }
                }
            }
        }
        let context = request
            .context
            .and_then(|context| context.arguments)
            .unwrap_or_default();
        let input = CompletionRequest::new(
            target,
            request.argument.name,
            request.argument.value,
            context,
        );
        let values = completer(input).await.map_err(|_| {
            tracing::warn!(kind = "completion", "completer failed");
            McpError::internal_error("completion failed", None)
        })?;
        let found = values.len();
        let truncated = found > CompletionInfo::MAX_VALUES;
        let values: Vec<String> = values
            .into_iter()
            .take(CompletionInfo::MAX_VALUES)
            .collect();
        let total = u32::try_from(found).unwrap_or(u32::MAX);
        let info = CompletionInfo::with_pagination(values, Some(total), truncated)
            .map_err(|_| McpError::internal_error("completion failed", None))?;
        Ok(CompleteResult::new(info))
    }

    async fn list_tools(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListToolsResult, McpError> {
        Ok(ListToolsResult {
            tools: self
                .0
                .server
                .tools
                .iter()
                .map(|entry| entry.tool.clone())
                .collect(),
            ..Default::default()
        })
    }

    fn get_tool(&self, name: &str) -> Option<rmcp::model::Tool> {
        self.entry(name).map(|entry| entry.tool.clone())
    }

    async fn call_tool(
        &self,
        request: CallToolRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<CallToolResponse, McpError> {
        let entry = self.entry(&request.name).ok_or_else(|| {
            McpError::invalid_params(format!("no tool named `{}`", request.name), None)
        })?;
        let args = Value::Object(request.arguments.unwrap_or_default());
        let Ok(_slot) = Arc::clone(&self.0.server.slots).try_acquire_owned() else {
            return Ok(CallToolResponse::Complete(error(
                "The server is busy; try again shortly.",
            )));
        };
        let result = match &entry.kind {
            // A tool's own failure is a result the model reads, not a protocol error.
            Kind::Tool(run) => {
                let run = run(args);
                #[cfg(feature = "otel")]
                let run = {
                    let span = tracing::info_span!("mcp.tool_call", mcp.tool = %request.name);
                    crate::otel::Incoming::of(&context).continue_in(&span, None);
                    tracing::Instrument::instrument(run, span)
                };
                match run.await {
                    Ok(output) => tool_result(output),
                    Err(failure) => error(&failure.to_string()),
                }
            }
            Kind::Agent(agent, typed) => {
                self.call_agent(agent, typed.as_ref(), args, &context)
                    .await?
            }
        };
        Ok(CallToolResponse::Complete(result))
    }
}

#[derive(Deserialize)]
struct AgentArgs {
    message: String,
    session_id: Option<String>,
}

impl Handler {
    async fn call_agent(
        &self,
        agent: &Agent,
        typed: Option<&TypedAnswer>,
        args: Value,
        context: &RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let server = &self.0.server;
        let AgentArgs {
            message,
            session_id,
        } = AgentArgs::deserialize(args)
            .map_err(|e| McpError::invalid_params(format!("invalid arguments: {e}"), None))?;
        let session = session_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
        if !valid_context_id(&session) {
            return Err(McpError::invalid_params(
                "session_id must be 1 to 128 ASCII letters, digits, `-` or `_`",
                None,
            ));
        }
        let span = tracing::info_span!("mcp.agent_call", mcp.session_id = %session);
        #[cfg(feature = "otel")]
        crate::otel::Incoming::of(context).continue_in(&span, Some(&session));
        let prior = match server.history.load(&session).await {
            Ok(messages) => view(&messages, server.window.as_ref())
                .iter()
                .map(|message| (**message).clone())
                .collect::<Vec<_>>(),
            Err(_) => {
                tracing::warn!(parent: &span, kind = "store_error", "could not load the session");
                return Ok(error("The session could not be loaded."));
            }
        };
        let deadline = tokio::time::Instant::now() + server.max_run;
        let prompt = Message::user(message);

        if let Some(typed) = typed {
            let run =
                tracing::Instrument::instrument(typed(agent.clone(), prompt, prior), span.clone());
            let outcome = tokio::select! {
                _ = context.ct.cancelled() => return Ok(error("Cancelled.")),
                outcome = tokio::time::timeout_at(deadline, run) => outcome,
            };
            return Ok(match outcome {
                Err(_) => error("The agent run took longer than allowed."),
                Ok(Err(message)) => error(&message),
                Ok(Ok((value, messages))) => {
                    self.save(&session, messages, &span).await;
                    let mut result = CallToolResult::success(vec![
                        ContentBlock::text(value.to_string()),
                        ContentBlock::text(format!("session_id: {session}")),
                    ]);
                    result.structured_content = Some(value);
                    result
                }
            });
        }

        let progress = context.meta.get_progress_token();
        let mut stream = span.in_scope(|| agent.prompt(prompt).history(prior).stream());
        let mut chunks = 0_u32;
        loop {
            let item = tokio::select! {
                _ = context.ct.cancelled() => return Ok(error("Cancelled.")),
                item = tokio::time::timeout_at(deadline, stream.next()) => match item {
                    Err(_) => return Ok(error("The agent run took longer than allowed.")),
                    Ok(None) => return Ok(error("The agent run ended without an answer.")),
                    Ok(Some(item)) => item,
                },
            };
            match item {
                Ok(MultiTurnStreamItem::StreamAssistantItem(Item::Event(StreamEvent::Text {
                    text,
                    ..
                }))) => {
                    chunks += 1;
                    if let Some(token) = &progress {
                        // Progress is best effort: a client that went away
                        // still gets its answer if it comes back.
                        let _ = context
                            .peer
                            .notify_progress(
                                ProgressNotificationParam::new(token.clone(), f64::from(chunks))
                                    .with_message(text),
                            )
                            .await;
                    }
                }
                Ok(MultiTurnStreamItem::FinalResponse(response)) => {
                    self.save(&session, response.messages.clone(), &span).await;
                    let answer = response.output();
                    let mut blocks = vec![ContentBlock::text(answer.clone())];
                    blocks.extend(image_blocks(&response.content));
                    let mut result = CallToolResult::success(blocks);
                    result.structured_content =
                        Some(json!({"answer": answer, "session_id": session}));
                    return Ok(result);
                }
                Ok(_) => {}
                Err(failure) => {
                    tracing::warn!(parent: &span, kind = "run_failed", reason = status_message(&failure), "agent call failed");
                    return Ok(error(&failure_message(&failure)));
                }
            }
        }
    }

    /// Add a finished run to its session. The answer stands if this fails;
    /// the next call then starts without this turn.
    async fn save(&self, session: &str, messages: Vec<Message>, span: &tracing::Span) {
        if self
            .0
            .server
            .history
            .append(session, messages)
            .await
            .is_err()
        {
            tracing::warn!(parent: span, kind = "store_error", "could not save the session");
        }
    }
}

/// What the calling model is told when a run fails: enough to decide whether to
/// retry, without the provider's own error text (which can name internals).
///
/// A failure arrives as the provider's error from an awaited run, or as its
/// report from a streamed one; both carry the status and whether to retry.
fn failure_message(failure: &PromptError) -> Cow<'static, str> {
    if let PromptError::MaxTurns { max_turns, .. } = failure {
        return Cow::Owned(if *max_turns <= 1 {
            "The agent reached its turn limit (1); agents with tools usually need AgentBuilder::default_max_turns(n) with n >= 2.".to_owned()
        } else {
            format!(
                "The agent reached its turn limit ({max_turns}); raise AgentBuilder::default_max_turns above {max_turns} if the task needs more steps."
            )
        });
    }
    Cow::Borrowed(status_message(failure))
}

fn status_message(failure: &PromptError) -> &'static str {
    let (status, retryable) = match failure {
        PromptError::Provider(provider) => (
            failure
                .provider_response_status()
                .map(|status| status.as_u16()),
            provider.is_retryable(),
        ),
        PromptError::Report(report) => (
            report.http_status.or(report
                .provider_response_status()
                .map(|status| status.as_u16())),
            report.retryable,
        ),
        _ => (None, false),
    };
    match status {
        Some(429) => "The model provider is rate limiting this server; try again in a moment.",
        Some(401 | 403) => "The model provider rejected this server's credentials.",
        Some(500..=599) => "The model provider is unavailable right now; try again shortly.",
        Some(_) => "The model provider rejected the request.",
        None if retryable => "The model provider could not be reached; try again shortly.",
        None => "The agent run failed.",
    }
}

fn error(text: &str) -> CallToolResult {
    CallToolResult::error(vec![ContentBlock::text(text)])
}

/// `value` as a JSON Schema object; an empty schema, or one that is not an
/// object, becomes the schema of an object with no properties.
fn object(value: Value) -> JsonObject {
    match value {
        Value::Object(map) if !map.is_empty() => map,
        _ => JsonObject::from_iter([
            ("type".to_owned(), json!("object")),
            ("properties".to_owned(), json!({})),
        ]),
    }
}

fn agent_input() -> JsonObject {
    object(json!({
        "type": "object",
        "properties": {
            "message": {
                "type": "string",
                "description": "What to ask or tell the agent, self-contained."
            },
            "session_id": {
                "type": "string",
                "description": "The session_id of an earlier answer, to continue that conversation."
            }
        },
        "required": ["message"],
        "additionalProperties": false
    }))
}

fn agent_identity(agent: &Agent) -> (String, String) {
    let name = tool_name(agent.name().unwrap_or("agent"));
    let description = format!(
        "{} Ask it in plain language; pass the session_id of an earlier answer to continue \
         the same conversation.",
        agent.description().unwrap_or("A Rig agent.")
    );
    (name, description)
}

/// A provider-safe tool name: ASCII letters, digits and `_`, at most 64
/// characters, never empty.
pub(crate) fn tool_name(name: &str) -> String {
    let mut safe: String = name
        .trim()
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() {
                c.to_ascii_lowercase()
            } else {
                '_'
            }
        })
        .collect();
    safe.truncate(MAX_TOOL_NAME);
    let safe = safe.trim_matches('_');
    if safe.is_empty() {
        "agent".to_owned()
    } else {
        safe.to_owned()
    }
}

#[cfg(test)]
mod tests;