rig-mcp-server 0.47.4

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
//! The MCP server: which Rig agents and tools it exposes, and how it runs them.

use std::borrow::Cow;
use std::collections::HashMap;
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, ContentBlock, GetPromptRequestParams,
    GetPromptResponse, GetPromptResult, Implementation, InitializeResult, JsonObject,
    ListPromptsResult, ListResourcesResult, ListToolsResult, PaginatedRequestParams,
    ProgressNotificationParam, Prompt, PromptArgument, PromptMessage, PromptsCapability,
    ReadResourceRequestParams, ReadResourceResponse, ReadResourceResult, Resource,
    ResourceContents, 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::{Render, StaticPrompt, StaticResource};
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>,
    tools: Vec<Entry>,
    resources: Vec<StaticResource>,
    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,
}

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,
            tools: Vec::new(),
            resources: 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,
        }
    }

    /// 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
    }

    /// 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 {
        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)
    }

    /// 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 {
        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)
    }

    /// 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: no
    /// subscriptions, no list-changed notifications, no resource templates.
    #[must_use]
    pub fn resource(
        self,
        uri: impl Into<String>,
        name: impl Into<String>,
        mime_type: impl Into<String>,
        text: impl Into<String>,
    ) -> Self {
        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::TextResourceContents {
            uri,
            mime_type: Some(mime_type),
            text: text.into(),
            meta: None,
        };
        self.add_resource(StaticResource { resource, contents })
    }

    /// 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 and no completion for their arguments.
    ///
    /// ```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,
    {
        let prompt = Prompt::new(name, Some(description), Some(arguments));
        let render: Render = Arc::new(render);
        self.add_prompt(StaticPrompt { prompt, render })
    }

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

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

    fn add_tool(self, definition: rig_core::completion::ToolDefinition, run: RunTool) -> 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);
        }
        self.add(Entry {
            tool,
            kind: Kind::Tool(run),
        })
    }

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

/// 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),
}

/// 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>,
}

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 = std::collections::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 = std::collections::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()));
            }
        }
        Ok(Self(Arc::new(Inner { server, by_name })))
    }

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

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() {
            capabilities.resources = Some(ResourcesCapability::default());
        }
        if !server.prompts.is_empty() {
            capabilities.prompts = Some(PromptsCapability::default());
        }
        let mut info = InitializeResult::new(capabilities).with_server_info(Implementation::new(
            server.name.clone(),
            server.version.clone(),
        ));
        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 read_resource(
        &self,
        request: ReadResourceRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<ReadResourceResponse, McpError> {
        let entry = self
            .0
            .server
            .resources
            .iter()
            .find(|entry| entry.resource.uri == request.uri)
            .ok_or_else(|| {
                McpError::resource_not_found(format!("no resource at `{}`", request.uri), None)
            })?;
        Ok(ReadResourceResponse::Complete(ReadResourceResult::new(
            vec![entry.contents.clone()],
        )))
    }

    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 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;