Skip to main content

rig_mcp_server/
server.rs

1//! The MCP server: which Rig agents and tools it exposes, and how it runs them.
2
3use std::borrow::Cow;
4use std::collections::{HashMap, HashSet};
5use std::future::Future;
6use std::sync::Arc;
7use std::time::Duration;
8
9use futures::StreamExt;
10use futures::future::BoxFuture;
11use rig_agent::Agent;
12use rig_agent::agent::MultiTurnStreamItem;
13use rig_agent::completion::{PromptError, StructuredOutputError};
14use rig_core::message::Message;
15use rig_core::serve::adapters::ToolAdapter;
16use rig_core::streaming::{Item, StreamEvent};
17use rig_core::tool::{DynamicTool, Tool, ToolExecutionError, ToolOutput, tool_definition};
18use rig_memory::AsyncStore;
19use rig_memory::recent::{Recent, TokenBudget, view};
20use rmcp::model::{
21    CacheScope, CallToolRequestParams, CallToolResponse, CallToolResult, CompleteRequestMethod,
22    CompleteRequestParams, CompleteResult, CompletionInfo, ContentBlock, GetPromptRequestParams,
23    GetPromptResponse, GetPromptResult, Icon, Implementation, InitializeResult, JsonObject,
24    ListPromptsResult, ListResourceTemplatesResult, ListResourcesResult, ListToolsResult,
25    PaginatedRequestParams, ProgressNotificationParam, Prompt, PromptArgument, PromptMessage,
26    PromptsCapability, ReadResourceRequestParams, ReadResourceResponse, ReadResourceResult,
27    Reference, Resource, ResourceContents, ResourceTemplate, ResourcesCapability,
28    ServerCapabilities, ServerConfig, ToolAnnotations,
29};
30use rmcp::service::RequestContext;
31use rmcp::{ErrorData as McpError, RoleServer, ServerHandler};
32use serde::Deserialize;
33use serde_json::{Value, json};
34
35use crate::catalog::{Piece, Render, StaticPrompt, StaticResource, StaticTemplate, TemplateVars};
36use crate::completion::{BoxError, Completer, CompletionRequest, CompletionTarget};
37use crate::content::{image_blocks, tool_result};
38use crate::history::{
39    DEFAULT_HISTORY_TOKENS, DEFAULT_MAX_CONTEXTS, HistoryStore, InMemory, Persistent,
40    valid_context_id,
41};
42use crate::transport::DEFAULT_MAX_REQUEST_BYTES;
43
44/// How many calls run at once by default; more are answered as busy.
45pub const DEFAULT_MAX_CONCURRENT_CALLS: usize = 32;
46/// How long one agent run may take by default before it is stopped.
47pub const DEFAULT_MAX_RUN_DURATION: Duration = Duration::from_secs(600);
48/// How long clients may cache the fixed catalog (tools, prompts, resources and
49/// static resource reads) by default; see [`McpServer::list_ttl`].
50const DEFAULT_LIST_TTL: Duration = Duration::from_secs(60);
51
52/// Longest tool name MCP clients and model providers accept.
53const MAX_TOOL_NAME: usize = 64;
54
55type RunTool =
56    Arc<dyn Fn(Value) -> BoxFuture<'static, Result<ToolOutput, ToolExecutionError>> + Send + Sync>;
57type TypedAnswer = Arc<
58    dyn Fn(
59            Agent,
60            Message,
61            Vec<Message>,
62        ) -> BoxFuture<'static, Result<(Value, Vec<Message>), String>>
63        + Send
64        + Sync,
65>;
66
67/// Rig agents and tools served over the Model Context Protocol.
68///
69/// Each [`agent`](Self::agent) becomes a tool taking a `message` and an
70/// optional `session_id`: a call runs the agent with that session's history
71/// and answers with its text (streamed meanwhile as progress notifications
72/// when the client asks for progress) and any image it made. Each
73/// [`tool`](Self::tool) is exposed as itself, run without a model.
74///
75/// Serve it to a local client (Claude Code, Cursor, Zed...) over stdio with
76/// [`serve_stdio`](Self::serve_stdio), or over Streamable HTTP with
77/// [`into_router`](Self::into_router).
78pub struct McpServer {
79    name: String,
80    version: String,
81    instructions: Option<String>,
82    title: Option<String>,
83    icons: Vec<Icon>,
84    tools: Vec<Entry>,
85    resources: Vec<StaticResource>,
86    resource_templates: Vec<StaticTemplate>,
87    prompts: Vec<StaticPrompt>,
88    history: Arc<dyn HistoryStore>,
89    window: Arc<dyn Recent>,
90    slots: Arc<tokio::sync::Semaphore>,
91    max_run: Duration,
92    list_ttl: Duration,
93    pub(crate) bearer: Option<String>,
94    pub(crate) allowed_hosts: Option<Vec<String>>,
95    pub(crate) max_request_bytes: usize,
96    pub(crate) ping: bool,
97    completer: Option<Completer>,
98}
99
100struct Entry {
101    tool: rmcp::model::Tool,
102    kind: Kind,
103}
104
105enum Kind {
106    Tool(RunTool),
107    Agent(Box<Agent>, Option<TypedAnswer>),
108}
109
110impl McpServer {
111    /// A server introducing itself to clients as `name`, with nothing to
112    /// offer yet.
113    pub fn new(name: impl Into<String>) -> Self {
114        Self {
115            name: name.into(),
116            version: env!("CARGO_PKG_VERSION").to_owned(),
117            instructions: None,
118            title: None,
119            icons: Vec::new(),
120            tools: Vec::new(),
121            resources: Vec::new(),
122            resource_templates: Vec::new(),
123            prompts: Vec::new(),
124            history: Arc::new(InMemory::new(DEFAULT_MAX_CONTEXTS)),
125            window: Arc::new(TokenBudget::new(DEFAULT_HISTORY_TOKENS)),
126            slots: Arc::new(tokio::sync::Semaphore::new(DEFAULT_MAX_CONCURRENT_CALLS)),
127            max_run: DEFAULT_MAX_RUN_DURATION,
128            list_ttl: DEFAULT_LIST_TTL,
129            bearer: None,
130            allowed_hosts: None,
131            max_request_bytes: DEFAULT_MAX_REQUEST_BYTES,
132            ping: false,
133            completer: None,
134        }
135    }
136
137    /// Also serve `GET /ping` on the HTTP router, answering
138    /// `{"status": "Healthy"}`, the health route AWS Bedrock AgentCore Runtime
139    /// recommends for MCP servers. Off by default: a router that already has
140    /// its own `/ping` would clash with it. The route takes no bearer token and
141    /// no `Host` check; `/mcp` keeps both. HTTP only.
142    #[must_use]
143    pub fn ping_route(mut self) -> Self {
144        self.ping = true;
145        self
146    }
147
148    /// The version clients see. Defaults to this crate's version.
149    #[must_use]
150    pub fn version(mut self, version: impl Into<String>) -> Self {
151        self.version = version.into();
152        self
153    }
154
155    /// A human-readable title clients may show for the server. Optional: left
156    /// out of `initialize` unless set.
157    #[must_use]
158    pub fn title(mut self, title: impl Into<String>) -> Self {
159        self.title = Some(title.into());
160        self
161    }
162
163    /// Add an icon clients may show for the server. Its `src` must be an
164    /// `http://` or `https://` URL or a `data:` URI, or serving fails with
165    /// [`BuildError::InvalidIcon`]. Optional: left out of `initialize` unless
166    /// set. Icons keep the order they were added in.
167    #[must_use]
168    pub fn icon(mut self, icon: Icon) -> Self {
169        self.icons.push(icon);
170        self
171    }
172
173    /// Instructions clients may pass to their model about using this server.
174    #[must_use]
175    pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
176        self.instructions = Some(instructions.into());
177        self
178    }
179
180    /// Expose `agent` as a tool named after it (its name, made provider-safe),
181    /// described by its description. It answers with text and any images,
182    /// plus `{answer, session_id}` as structured content; passing that
183    /// `session_id` back continues the conversation.
184    ///
185    /// Another tool with the same name makes serving fail with
186    /// [`BuildError::DuplicateTool`].
187    #[must_use]
188    pub fn agent(self, agent: Agent) -> Self {
189        let (name, description) = agent_identity(&agent);
190        let output = json!({
191            "type": "object",
192            "properties": {
193                "answer": {"type": "string"},
194                "session_id": {"type": "string"}
195            },
196            "required": ["answer", "session_id"]
197        });
198        let tool = rmcp::model::Tool::new(name, description, Arc::new(agent_input()))
199            .with_raw_output_schema(Arc::new(object(output)));
200        self.add(Entry {
201            tool,
202            kind: Kind::Agent(Box::new(agent), None),
203        })
204    }
205
206    /// Expose `agent` as a tool that answers with a `T`: each call runs as
207    /// [`Agent::prompt_typed`] does (two retries when the JSON does not parse)
208    /// and the `T` comes back as structured content matching the tool's
209    /// output schema, the schema of `T`.
210    ///
211    /// Another tool with the agent's name makes serving fail with
212    /// [`BuildError::DuplicateTool`].
213    #[must_use]
214    pub fn typed_agent<T>(self, agent: Agent) -> Self
215    where
216        T: schemars::JsonSchema
217            + serde::de::DeserializeOwned
218            + serde::Serialize
219            + Send
220            + Sync
221            + 'static,
222    {
223        let (name, description) = agent_identity(&agent);
224        let schema = serde_json::to_value(schemars::schema_for!(T)).unwrap_or_default();
225        let tool = rmcp::model::Tool::new(name, description, Arc::new(agent_input()))
226            .with_raw_output_schema(Arc::new(object(schema)));
227        let typed: TypedAnswer = Arc::new(|agent, prompt, history| {
228            Box::pin(async move {
229                let response = agent
230                    .prompt_typed::<T>(prompt)
231                    .history(history)
232                    .retries(2)
233                    .await
234                    .map_err(|error| {
235                        let reason = match &error {
236                            StructuredOutputError::Prompt(prompt) => status_message(prompt),
237                            _ => "not a structured answer",
238                        };
239                        tracing::warn!(
240                            kind = "run_failed",
241                            reason = reason,
242                            "typed agent call failed"
243                        );
244                        match &error {
245                            StructuredOutputError::Prompt(prompt) => {
246                                failure_message(prompt).into_owned()
247                            }
248                            _ => "The agent could not produce a structured answer.".to_owned(),
249                        }
250                    })?;
251                let value =
252                    serde_json::to_value(&response.output).map_err(|error| error.to_string())?;
253                Ok((value, response.messages))
254            })
255        });
256        self.add(Entry {
257            tool,
258            kind: Kind::Agent(Box::new(agent), Some(typed)),
259        })
260    }
261
262    /// Expose a Rig tool as itself: same name, description, parameters and
263    /// annotations; called directly, with no model involved.
264    ///
265    /// Another tool with the same name makes serving fail with
266    /// [`BuildError::DuplicateTool`].
267    #[must_use]
268    pub fn tool<T: Tool + 'static>(self, tool: T) -> Self {
269        self.tool_presented(tool, Presentation::default())
270    }
271
272    /// Expose a [`Tool`] as [`tool`](Self::tool) does, with a title and icons
273    /// for clients to show; see [`Presentation`].
274    ///
275    /// Another tool with the same name makes serving fail with
276    /// [`BuildError::DuplicateTool`].
277    #[must_use]
278    pub fn tool_presented<T: Tool + 'static>(self, tool: T, presentation: Presentation) -> Self {
279        let definition = tool_definition(&tool);
280        let adapter = Arc::new(ToolAdapter::new(tool));
281        let run: RunTool = Arc::new(move |args| {
282            let adapter = Arc::clone(&adapter);
283            Box::pin(async move { adapter.run(args).await })
284        });
285        self.add_tool(definition, run, &presentation)
286    }
287
288    /// Expose a [`DynamicTool`] as itself; see [`tool`](Self::tool).
289    ///
290    /// Another tool with the same name makes serving fail with
291    /// [`BuildError::DuplicateTool`].
292    #[must_use]
293    pub fn dynamic_tool(self, tool: DynamicTool) -> Self {
294        self.dynamic_tool_presented(tool, Presentation::default())
295    }
296
297    /// Expose a [`DynamicTool`] with a title and icons; see
298    /// [`tool_presented`](Self::tool_presented).
299    ///
300    /// Another tool with the same name makes serving fail with
301    /// [`BuildError::DuplicateTool`].
302    #[must_use]
303    pub fn dynamic_tool_presented(self, tool: DynamicTool, presentation: Presentation) -> Self {
304        let definition = tool.definition();
305        let tool = Arc::new(tool);
306        let run: RunTool = Arc::new(move |args| {
307            let tool = Arc::clone(&tool);
308            Box::pin(async move { tool.run(args).await })
309        });
310        self.add_tool(definition, run, &presentation)
311    }
312
313    /// Keep agent sessions in memory, at most `max` of them; the oldest one
314    /// started is forgotten first. This is the default, with
315    /// [`DEFAULT_MAX_CONTEXTS`](crate::DEFAULT_MAX_CONTEXTS).
316    #[must_use]
317    pub fn max_sessions(mut self, max: usize) -> Self {
318        self.history = Arc::new(InMemory::new(max));
319        self
320    }
321
322    /// Keep agent sessions in any [`rig_memory`] store (`DirStore` on disk,
323    /// `rig-sqlite`, `rig-postgres`), so they survive restarts and several
324    /// servers can share them.
325    #[must_use]
326    pub fn history_store<S>(mut self, store: S) -> Self
327    where
328        S: AsyncStore + Send + Sync + 'static,
329    {
330        self.history = Arc::new(Persistent(store));
331        self
332    }
333
334    /// Which newest messages of a session each call sends the model.
335    /// Defaults to [`DEFAULT_HISTORY_TOKENS`](crate::DEFAULT_HISTORY_TOKENS)
336    /// tokens; a tool result is never sent without its call.
337    #[must_use]
338    pub fn history_window(mut self, window: impl Recent + 'static) -> Self {
339        self.window = Arc::new(window);
340        self
341    }
342
343    /// Run at most `max` calls at once (at least one); a call beyond that
344    /// gets a "busy" error result before any model call.
345    #[must_use]
346    #[doc(alias = "max_concurrent_tasks")]
347    pub fn max_concurrent_calls(mut self, max: usize) -> Self {
348        self.slots = Arc::new(tokio::sync::Semaphore::new(max.max(1)));
349        self
350    }
351
352    /// Stop an agent run that takes longer than `max`.
353    #[must_use]
354    pub fn max_run_duration(mut self, max: Duration) -> Self {
355        self.max_run = max;
356        self
357    }
358
359    /// How long clients may cache what the server offers from its fixed
360    /// catalog: the `tools/list`, `prompts/list`, `resources/list` and
361    /// `resources/templates/list` results, and reads of static resources.
362    /// Defaults to one minute, so a restarted server is picked up soon.
363    /// Only sent to clients on protocol 2026-07-28 or later. Template reads
364    /// are never cached: their text comes from a callback. A TTL beyond
365    /// `u64::MAX` milliseconds is sent as `u64::MAX`.
366    #[must_use]
367    pub fn list_ttl(mut self, ttl: Duration) -> Self {
368        self.list_ttl = ttl;
369        self
370    }
371
372    /// The `(ttlMs, cacheScope)` hints for results from the fixed catalog.
373    ///
374    /// The catalog is fixed when the server is built and is the same for every
375    /// caller, so the result is `public`, unless a bearer token guards the
376    /// endpoint: then a shared cache could hand one caller's list to someone
377    /// without the token, so it is `private`.
378    fn catalog_hints(&self) -> (u64, CacheScope) {
379        let ttl_ms = u64::try_from(self.list_ttl.as_millis()).unwrap_or(u64::MAX);
380        let scope = if self.bearer.is_some() {
381            CacheScope::Private
382        } else {
383            CacheScope::Public
384        };
385        (ttl_ms, scope)
386    }
387
388    /// Offer a text resource at `uri`, read with `resources/read`. `mime_type`
389    /// tells the client what the text is, such as `text/markdown`.
390    ///
391    /// Another resource with the same URI makes serving fail with
392    /// [`BuildError::DuplicateResource`]. Only fixed contents are offered here;
393    /// for URIs with variables see [`resource_template`](Self::resource_template).
394    /// No subscriptions and no list-changed notifications.
395    #[must_use]
396    pub fn resource(
397        self,
398        uri: impl Into<String>,
399        name: impl Into<String>,
400        mime_type: impl Into<String>,
401        text: impl Into<String>,
402    ) -> Self {
403        self.resource_presented(uri, name, mime_type, text, Presentation::default())
404    }
405
406    /// Offer a binary resource at `uri`. The bytes travel base64-encoded in
407    /// the `resources/read` result, labelled with `mime_type`.
408    ///
409    /// Another resource with the same URI makes serving fail with
410    /// [`BuildError::DuplicateResource`].
411    #[must_use]
412    pub fn binary_resource(
413        self,
414        uri: impl Into<String>,
415        name: impl Into<String>,
416        mime_type: impl Into<String>,
417        bytes: impl AsRef<[u8]>,
418    ) -> Self {
419        use base64::Engine;
420
421        let uri = uri.into();
422        let mime_type = mime_type.into();
423        let resource = Resource::new(uri.clone(), name).with_mime_type(mime_type.clone());
424        let contents = ResourceContents::BlobResourceContents {
425            uri,
426            mime_type: Some(mime_type),
427            blob: base64::engine::general_purpose::STANDARD.encode(bytes.as_ref()),
428            meta: None,
429        };
430        self.add_resource(StaticResource { resource, contents })
431    }
432
433    /// Offer a prompt named `name`. Its `arguments` are listed to the client;
434    /// a call to `prompts/get` without a required one is refused with an
435    /// invalid-params error. `render` turns the arguments the client passed
436    /// (all strings, keyed by name) into the prompt's messages.
437    ///
438    /// Another prompt with the same name makes serving fail with
439    /// [`BuildError::DuplicatePrompt`]. Prompts are fixed: no list-changed
440    /// notifications. Their arguments complete through [`completer`](Self::completer).
441    ///
442    /// ```no_run
443    /// use std::collections::HashMap;
444    /// use rig_mcp_server::{McpServer, rmcp::model::{PromptArgument, PromptMessage, Role}};
445    ///
446    /// let server = McpServer::new("docs").prompt(
447    ///     "explain",
448    ///     "Explain a topic for a reader.",
449    ///     vec![PromptArgument::new("topic").with_required(true)],
450    ///     |args: &HashMap<String, String>| {
451    ///         let topic = args.get("topic").map_or("", String::as_str);
452    ///         vec![PromptMessage::new_text(Role::User, format!("Explain {topic} in plain words."))]
453    ///     },
454    /// );
455    /// ```
456    #[must_use]
457    pub fn prompt<F>(
458        self,
459        name: impl Into<String>,
460        description: impl Into<String>,
461        arguments: Vec<PromptArgument>,
462        render: F,
463    ) -> Self
464    where
465        F: Fn(&HashMap<String, String>) -> Vec<PromptMessage> + Send + Sync + 'static,
466    {
467        self.prompt_presented(
468            name,
469            description,
470            arguments,
471            render,
472            Presentation::default(),
473        )
474    }
475
476    /// Expose a text resource as [`resource`](Self::resource) does, with a title
477    /// and icons for clients to show; see [`Presentation`].
478    ///
479    /// Another resource with the same URI makes serving fail with
480    /// [`BuildError::DuplicateResource`].
481    #[must_use]
482    pub fn resource_presented(
483        self,
484        uri: impl Into<String>,
485        name: impl Into<String>,
486        mime_type: impl Into<String>,
487        text: impl Into<String>,
488        presentation: Presentation,
489    ) -> Self {
490        let uri = uri.into();
491        let mime_type = mime_type.into();
492        let mut resource = Resource::new(uri.clone(), name).with_mime_type(mime_type.clone());
493        presentation.apply_resource(&mut resource);
494        let contents = ResourceContents::TextResourceContents {
495            uri,
496            mime_type: Some(mime_type),
497            text: text.into(),
498            meta: None,
499        };
500        self.add_resource(StaticResource { resource, contents })
501    }
502
503    fn add_resource(mut self, resource: StaticResource) -> Self {
504        self.resources.push(resource);
505        self
506    }
507
508    /// Offer a resource template, listed by `resources/templates/list`. Any URI
509    /// that matches `uri_template` is read with `read`, which gets the variables
510    /// the URI matched and returns the text. `description` and `mime_type` are
511    /// listed to the client.
512    ///
513    /// `uri_template` is an RFC 6570 template with simple `{name}` variables only:
514    /// each name is letters, digits or `_`, used once. A variable matches one path
515    /// segment (no literal `/`) and its value is percent-decoded, so `%2F` reads
516    /// as `/` inside the value. A URI whose value is not valid UTF-8 after decoding
517    /// is not found. For example `memo://{id}`. When two templates match a URI, the
518    /// one registered first is read. A malformed template, or a second one with the
519    /// same text, makes serving fail with
520    /// [`BuildError::InvalidResourceTemplate`] or
521    /// [`BuildError::DuplicateResourceTemplate`]. A static resource with the same
522    /// URI wins over a template.
523    ///
524    /// An error from `read` reaches the client as an internal JSON-RPC error with
525    /// a fixed message; its text is logged by kind only and not sent.
526    ///
527    /// ```no_run
528    /// use rig_mcp_server::{McpServer, TemplateVars};
529    ///
530    /// let server = McpServer::new("notes").resource_template(
531    ///     "memo://{id}",
532    ///     "memo",
533    ///     "A memo, by its id.",
534    ///     "text/plain",
535    ///     |vars: TemplateVars| async move {
536    ///         let id = vars.get("id").unwrap_or_default();
537    ///         Ok::<_, std::io::Error>(format!("memo {id}"))
538    ///     },
539    /// );
540    /// ```
541    #[must_use]
542    pub fn resource_template<F, Fut, E>(
543        self,
544        uri_template: impl Into<String>,
545        name: impl Into<String>,
546        description: impl Into<String>,
547        mime_type: impl Into<String>,
548        read: F,
549    ) -> Self
550    where
551        F: Fn(TemplateVars) -> Fut + Send + Sync + 'static,
552        Fut: Future<Output = Result<String, E>> + Send + 'static,
553        E: std::error::Error + Send + Sync + 'static,
554    {
555        self.resource_template_presented(
556            uri_template,
557            name,
558            description,
559            mime_type,
560            Presentation::default(),
561            read,
562        )
563    }
564
565    /// Offer a resource template as [`resource_template`](Self::resource_template)
566    /// does, with a title and icons for clients to show; see [`Presentation`].
567    ///
568    /// Another template with the same text makes serving fail with
569    /// [`BuildError::DuplicateResourceTemplate`].
570    #[must_use]
571    pub fn resource_template_presented<F, Fut, E>(
572        mut self,
573        uri_template: impl Into<String>,
574        name: impl Into<String>,
575        description: impl Into<String>,
576        mime_type: impl Into<String>,
577        presentation: Presentation,
578        read: F,
579    ) -> Self
580    where
581        F: Fn(TemplateVars) -> Fut + Send + Sync + 'static,
582        Fut: Future<Output = Result<String, E>> + Send + 'static,
583        E: std::error::Error + Send + Sync + 'static,
584    {
585        let mut template = ResourceTemplate::new(uri_template, name)
586            .with_description(description)
587            .with_mime_type(mime_type);
588        presentation.apply_template(&mut template);
589        let read = Arc::new(
590            move |vars: TemplateVars| -> BoxFuture<'static, Result<String, BoxError>> {
591                let answer = read(vars);
592                Box::pin(async move {
593                    answer
594                        .await
595                        .map_err(|error| -> BoxError { Box::new(error) })
596                })
597            },
598        );
599        self.resource_templates
600            .push(StaticTemplate { template, read });
601        self
602    }
603
604    /// Offer a prompt as [`prompt`](Self::prompt) does, with a title and icons
605    /// for clients to show; see [`Presentation`].
606    ///
607    /// Another prompt with the same name makes serving fail with
608    /// [`BuildError::DuplicatePrompt`].
609    #[must_use]
610    pub fn prompt_presented<F>(
611        self,
612        name: impl Into<String>,
613        description: impl Into<String>,
614        arguments: Vec<PromptArgument>,
615        render: F,
616        presentation: Presentation,
617    ) -> Self
618    where
619        F: Fn(&HashMap<String, String>) -> Vec<PromptMessage> + Send + Sync + 'static,
620    {
621        let mut prompt = Prompt::new(name, Some(description), Some(arguments));
622        presentation.apply_prompt(&mut prompt);
623        let render: Render = Arc::new(render);
624        self.add_prompt(StaticPrompt { prompt, render })
625    }
626
627    fn add_prompt(mut self, prompt: StaticPrompt) -> Self {
628        self.prompts.push(prompt);
629        self
630    }
631
632    /// Answer `completion/complete` with `complete`. It gets a
633    /// [`CompletionRequest`] (the prompt or resource, the argument, the value
634    /// typed so far, and the arguments already resolved) and returns the
635    /// candidates. The server sends at most 100 and sets `hasMore` when it cuts
636    /// the list. Filtering by the typed value is up to `complete`.
637    ///
638    /// A request for a prompt, argument, or resource the server does not offer is
639    /// refused with invalid params (`-32602`) before `complete` runs. Setting a
640    /// completer advertises the `completions` capability. Without one, the
641    /// capability is absent and `completion/complete` is refused as an unknown
642    /// method. An error from `complete` reaches the client as an internal
643    /// JSON-RPC error with a fixed message; its text is logged by kind only and
644    /// not sent.
645    ///
646    /// ```no_run
647    /// use rig_mcp_server::{CompletionRequest, CompletionTarget, McpServer};
648    ///
649    /// let server = McpServer::new("docs").completer(|request: CompletionRequest| async move {
650    ///     let topics = ["rust", "ruby", "python"];
651    ///     let matches = match &request.target {
652    ///         CompletionTarget::Prompt(name) if name == "explain" => topics
653    ///             .iter()
654    ///             .filter(|topic| topic.starts_with(request.value.as_str()))
655    ///             .map(|topic| topic.to_string())
656    ///             .collect(),
657    ///         _ => Vec::new(),
658    ///     };
659    ///     Ok::<_, std::io::Error>(matches)
660    /// });
661    /// ```
662    #[must_use]
663    pub fn completer<F, Fut, E>(mut self, complete: F) -> Self
664    where
665        F: Fn(CompletionRequest) -> Fut + Send + Sync + 'static,
666        Fut: Future<Output = Result<Vec<String>, E>> + Send + 'static,
667        E: std::error::Error + Send + Sync + 'static,
668    {
669        self.completer =
670            Some(
671                Arc::new(
672                    move |request: CompletionRequest| -> BoxFuture<
673                        'static,
674                        Result<Vec<String>, crate::completion::BoxError>,
675                    > {
676                        let answer = complete(request);
677                        Box::pin(async move {
678                            answer
679                                .await
680                                .map_err(|error| -> crate::completion::BoxError { Box::new(error) })
681                        })
682                    },
683                ),
684            );
685        self
686    }
687
688    fn add_tool(
689        self,
690        definition: rig_core::completion::ToolDefinition,
691        run: RunTool,
692        presentation: &Presentation,
693    ) -> Self {
694        let mut tool = rmcp::model::Tool::new(
695            definition.name.to_string(),
696            definition.description,
697            Arc::new(object(definition.parameters)),
698        );
699        // Rig's annotations and MCP's have the same wire names (readOnlyHint, ...).
700        if let Some(annotations) = serde_json::to_value(&definition.annotations)
701            .ok()
702            .filter(|value| value.as_object().is_some_and(|fields| !fields.is_empty()))
703            .and_then(|value| serde_json::from_value::<ToolAnnotations>(value).ok())
704        {
705            tool = tool.with_annotations(annotations);
706        }
707        presentation.apply_tool(&mut tool);
708        self.add(Entry {
709            tool,
710            kind: Kind::Tool(run),
711        })
712    }
713
714    fn add(mut self, entry: Entry) -> Self {
715        self.tools.push(entry);
716        self
717    }
718}
719
720/// The title and icons a client may show for a tool, resource or prompt.
721///
722/// Both are optional. An unset title or an empty icon list is left out of the
723/// listing, as before. Icon sources are checked when the server is served, see
724/// [`BuildError::InvalidIcon`].
725#[derive(Debug, Clone, Default, PartialEq)]
726#[non_exhaustive]
727pub struct Presentation {
728    title: Option<String>,
729    icons: Vec<Icon>,
730}
731
732impl Presentation {
733    /// Nothing set: no title, no icons.
734    #[must_use]
735    pub fn new() -> Self {
736        Self::default()
737    }
738
739    /// A human-readable title, such as "Look up weather".
740    #[must_use]
741    pub fn title(mut self, title: impl Into<String>) -> Self {
742        self.title = Some(title.into());
743        self
744    }
745
746    /// Add an icon. Icons keep the order they were added in.
747    #[must_use]
748    pub fn icon(mut self, icon: Icon) -> Self {
749        self.icons.push(icon);
750        self
751    }
752
753    fn icon_list(&self) -> Option<Vec<Icon>> {
754        (!self.icons.is_empty()).then(|| self.icons.clone())
755    }
756
757    fn apply_tool(&self, tool: &mut rmcp::model::Tool) {
758        tool.title.clone_from(&self.title);
759        tool.icons = self.icon_list();
760    }
761
762    fn apply_resource(&self, resource: &mut Resource) {
763        resource.title.clone_from(&self.title);
764        resource.icons = self.icon_list();
765    }
766
767    fn apply_template(&self, template: &mut ResourceTemplate) {
768        template.title.clone_from(&self.title);
769        template.icons = self.icon_list();
770    }
771
772    fn apply_prompt(&self, prompt: &mut Prompt) {
773        prompt.title.clone_from(&self.title);
774        prompt.icons = self.icon_list();
775    }
776}
777
778/// Why an [`McpServer`] could not be served.
779#[derive(Debug, thiserror::Error)]
780#[non_exhaustive]
781pub enum BuildError {
782    /// Two tools (agents, typed agents or plain tools) have the same name, so
783    /// a client could not tell which one it calls.
784    #[error("two tools are named `{0}`")]
785    DuplicateTool(String),
786    /// Two resources have the same URI, so a client could not tell which one
787    /// it reads.
788    #[error("two resources have the URI `{0}`")]
789    DuplicateResource(String),
790    /// Two prompts have the same name, so a client could not tell which one
791    /// it gets.
792    #[error("two prompts are named `{0}`")]
793    DuplicatePrompt(String),
794    /// An icon's `src` is neither an `http://` or `https://` URL nor a `data:`
795    /// URI, so a client could not fetch it. Carries the `src` given.
796    #[error("icon source `{0}` is not an http(s) URL or a data: URI")]
797    InvalidIcon(String),
798    /// A resource template is malformed: an unclosed or empty `{}`, a variable
799    /// name that is not letters, digits or `_`, a stray `}`, or a variable used
800    /// twice. Carries the template given.
801    #[error(
802        "resource template `{0}` is malformed: use `{{name}}` once per name, with letters, digits or `_`"
803    )]
804    InvalidResourceTemplate(String),
805    /// Two resource templates have the same text, so a client could not tell
806    /// which one it reads.
807    #[error("two resource templates have the URI template `{0}`")]
808    DuplicateResourceTemplate(String),
809}
810
811/// The server as an MCP handler, shared by every connection.
812#[derive(Clone)]
813pub(crate) struct Handler(Arc<Inner>);
814
815struct Inner {
816    server: McpServer,
817    by_name: HashMap<String, usize>,
818    /// The parsed pattern of each resource template, in the same order.
819    templates: Vec<Vec<Piece>>,
820}
821
822impl Handler {
823    /// The handler of `server`, refused when two of its tools share a name, two
824    /// resources a URI, or two prompts a name.
825    pub(crate) fn new(server: McpServer) -> Result<Self, BuildError> {
826        let mut by_name = HashMap::with_capacity(server.tools.len());
827        for (index, entry) in server.tools.iter().enumerate() {
828            let name = entry.tool.name.to_string();
829            if by_name.contains_key(&name) {
830                return Err(BuildError::DuplicateTool(name));
831            }
832            by_name.insert(name, index);
833        }
834        let mut uris = HashSet::with_capacity(server.resources.len());
835        for resource in &server.resources {
836            let uri = &resource.resource.uri;
837            if !uris.insert(uri.clone()) {
838                return Err(BuildError::DuplicateResource(uri.clone()));
839            }
840        }
841        let mut names = HashSet::with_capacity(server.prompts.len());
842        for prompt in &server.prompts {
843            let name = &prompt.prompt.name;
844            if !names.insert(name.clone()) {
845                return Err(BuildError::DuplicatePrompt(name.clone()));
846            }
847        }
848        let mut templates = Vec::with_capacity(server.resource_templates.len());
849        let mut texts = HashSet::with_capacity(server.resource_templates.len());
850        for template in &server.resource_templates {
851            let text = &template.template.uri_template;
852            let pieces = crate::catalog::parse(text)
853                .ok_or_else(|| BuildError::InvalidResourceTemplate(text.clone()))?;
854            if !texts.insert(text.clone()) {
855                return Err(BuildError::DuplicateResourceTemplate(text.clone()));
856            }
857            templates.push(pieces);
858        }
859        check_icons(server.icons.iter())?;
860        for entry in &server.tools {
861            check_icons(entry.tool.icons.iter().flatten())?;
862        }
863        for resource in &server.resources {
864            check_icons(resource.resource.icons.iter().flatten())?;
865        }
866        for template in &server.resource_templates {
867            check_icons(template.template.icons.iter().flatten())?;
868        }
869        for prompt in &server.prompts {
870            check_icons(prompt.prompt.icons.iter().flatten())?;
871        }
872        Ok(Self(Arc::new(Inner {
873            server,
874            by_name,
875            templates,
876        })))
877    }
878
879    fn entry(&self, name: &str) -> Option<&Entry> {
880        let index = *self.0.by_name.get(name)?;
881        self.0.server.tools.get(index)
882    }
883}
884
885/// Each icon's `src` must be an `http(s)` URL or a `data:` URI, as the spec
886/// for icons (MCP 2025-11-25) allows.
887fn check_icons<'a>(icons: impl IntoIterator<Item = &'a Icon>) -> Result<(), BuildError> {
888    for icon in icons {
889        let src = icon.src.to_ascii_lowercase();
890        if !(src.starts_with("https://") || src.starts_with("http://") || src.starts_with("data:"))
891        {
892            return Err(BuildError::InvalidIcon(icon.src.clone()));
893        }
894    }
895    Ok(())
896}
897
898impl ServerHandler for Handler {
899    fn get_info(&self) -> ServerConfig {
900        let server = &self.0.server;
901        // Resources and prompts are advertised only when there are some, so a
902        // server without them answers `initialize` as it always did.
903        let mut capabilities = ServerCapabilities::builder().enable_tools().build();
904        if !server.resources.is_empty() || !server.resource_templates.is_empty() {
905            capabilities.resources = Some(ResourcesCapability::default());
906        }
907        if !server.prompts.is_empty() {
908            capabilities.prompts = Some(PromptsCapability::default());
909        }
910        if server.completer.is_some() {
911            capabilities.completions = Some(JsonObject::default());
912        }
913        let mut implementation = Implementation::new(server.name.clone(), server.version.clone());
914        implementation.title.clone_from(&server.title);
915        implementation.icons = (!server.icons.is_empty()).then(|| server.icons.clone());
916        let mut info = InitializeResult::new(capabilities).with_server_info(implementation);
917        if let Some(instructions) = &server.instructions {
918            info = info.with_instructions(instructions.clone());
919        }
920        info
921    }
922
923    async fn list_resources(
924        &self,
925        _request: Option<PaginatedRequestParams>,
926        _context: RequestContext<RoleServer>,
927    ) -> Result<ListResourcesResult, McpError> {
928        let (ttl_ms, scope) = self.0.server.catalog_hints();
929        Ok(ListResourcesResult {
930            resources: self
931                .0
932                .server
933                .resources
934                .iter()
935                .map(|entry| entry.resource.clone())
936                .collect(),
937            ..Default::default()
938        }
939        .with_ttl_ms(ttl_ms)
940        .with_cache_scope(scope))
941    }
942
943    async fn list_resource_templates(
944        &self,
945        _request: Option<PaginatedRequestParams>,
946        _context: RequestContext<RoleServer>,
947    ) -> Result<ListResourceTemplatesResult, McpError> {
948        let (ttl_ms, scope) = self.0.server.catalog_hints();
949        Ok(ListResourceTemplatesResult {
950            resource_templates: self
951                .0
952                .server
953                .resource_templates
954                .iter()
955                .map(|entry| entry.template.clone())
956                .collect(),
957            ..Default::default()
958        }
959        .with_ttl_ms(ttl_ms)
960        .with_cache_scope(scope))
961    }
962
963    async fn read_resource(
964        &self,
965        request: ReadResourceRequestParams,
966        _context: RequestContext<RoleServer>,
967    ) -> Result<ReadResourceResponse, McpError> {
968        // A static resource wins over a template with the same URI.
969        if let Some(entry) = self
970            .0
971            .server
972            .resources
973            .iter()
974            .find(|entry| entry.resource.uri == request.uri)
975        {
976            let (ttl_ms, scope) = self.0.server.catalog_hints();
977            return Ok(ReadResourceResponse::Complete(
978                ReadResourceResult::new(vec![entry.contents.clone()])
979                    .with_ttl_ms(ttl_ms)
980                    .with_cache_scope(scope),
981            ));
982        }
983        for (template, pieces) in self
984            .0
985            .server
986            .resource_templates
987            .iter()
988            .zip(&self.0.templates)
989        {
990            let Some(vars) = crate::catalog::matches(pieces, &request.uri) else {
991                continue;
992            };
993            let text = (template.read)(vars).await.map_err(|_| {
994                tracing::warn!(kind = "resource_template", "resource template read failed");
995                McpError::internal_error("resource read failed", None)
996            })?;
997            let contents = ResourceContents::TextResourceContents {
998                uri: request.uri,
999                mime_type: template.template.mime_type.clone(),
1000                text,
1001                meta: None,
1002            };
1003            // A callback decides this text, and it may differ per caller or
1004            // change at any time, so it is never cached: ttl 0, private.
1005            return Ok(ReadResourceResponse::Complete(
1006                ReadResourceResult::new(vec![contents])
1007                    .with_ttl_ms(0)
1008                    .with_cache_scope(CacheScope::Private),
1009            ));
1010        }
1011        Err(McpError::resource_not_found(
1012            format!("no resource at `{}`", request.uri),
1013            None,
1014        ))
1015    }
1016
1017    async fn list_prompts(
1018        &self,
1019        _request: Option<PaginatedRequestParams>,
1020        _context: RequestContext<RoleServer>,
1021    ) -> Result<ListPromptsResult, McpError> {
1022        let (ttl_ms, scope) = self.0.server.catalog_hints();
1023        Ok(ListPromptsResult {
1024            prompts: self
1025                .0
1026                .server
1027                .prompts
1028                .iter()
1029                .map(|entry| entry.prompt.clone())
1030                .collect(),
1031            ..Default::default()
1032        }
1033        .with_ttl_ms(ttl_ms)
1034        .with_cache_scope(scope))
1035    }
1036
1037    async fn get_prompt(
1038        &self,
1039        request: GetPromptRequestParams,
1040        _context: RequestContext<RoleServer>,
1041    ) -> Result<GetPromptResponse, McpError> {
1042        let entry = self
1043            .0
1044            .server
1045            .prompts
1046            .iter()
1047            .find(|entry| entry.prompt.name == request.name)
1048            .ok_or_else(|| {
1049                McpError::invalid_params(format!("no prompt named `{}`", request.name), None)
1050            })?;
1051        let mut arguments = HashMap::new();
1052        for (name, value) in request.arguments.unwrap_or_default() {
1053            let Value::String(text) = value else {
1054                return Err(McpError::invalid_params(
1055                    format!("argument `{name}` must be a string"),
1056                    None,
1057                ));
1058            };
1059            arguments.insert(name, text);
1060        }
1061        for declared in entry.prompt.arguments.iter().flatten() {
1062            if declared.required == Some(true) && !arguments.contains_key(&declared.name) {
1063                return Err(McpError::invalid_params(
1064                    format!("missing required argument `{}`", declared.name),
1065                    None,
1066                ));
1067            }
1068        }
1069        let messages = (entry.render)(&arguments);
1070        let mut result = GetPromptResult::new(messages);
1071        if let Some(description) = &entry.prompt.description {
1072            result = result.with_description(description.clone());
1073        }
1074        Ok(GetPromptResponse::Complete(result))
1075    }
1076
1077    async fn complete(
1078        &self,
1079        request: CompleteRequestParams,
1080        _context: RequestContext<RoleServer>,
1081    ) -> Result<CompleteResult, McpError> {
1082        let server = &self.0.server;
1083        let Some(completer) = &server.completer else {
1084            return Err(McpError::method_not_found::<CompleteRequestMethod>());
1085        };
1086        let target = match request.r#ref {
1087            Reference::Prompt(prompt) => CompletionTarget::Prompt(prompt.name),
1088            Reference::Resource(resource) => CompletionTarget::Resource(resource.uri),
1089            _ => return Err(McpError::invalid_params("unsupported reference", None)),
1090        };
1091        match &target {
1092            CompletionTarget::Prompt(name) => {
1093                let entry = server
1094                    .prompts
1095                    .iter()
1096                    .find(|entry| entry.prompt.name == *name)
1097                    .ok_or_else(|| {
1098                        McpError::invalid_params(format!("no prompt named `{name}`"), None)
1099                    })?;
1100                let declared = entry
1101                    .prompt
1102                    .arguments
1103                    .iter()
1104                    .flatten()
1105                    .any(|argument| argument.name == request.argument.name);
1106                if !declared {
1107                    return Err(McpError::invalid_params(
1108                        format!(
1109                            "prompt `{name}` has no argument `{}`",
1110                            request.argument.name
1111                        ),
1112                        None,
1113                    ));
1114                }
1115            }
1116            CompletionTarget::Resource(uri) => {
1117                let served = server
1118                    .resources
1119                    .iter()
1120                    .any(|entry| entry.resource.uri == *uri);
1121                if !served {
1122                    // A template is completed by its own text, one variable at a time.
1123                    let index = server
1124                        .resource_templates
1125                        .iter()
1126                        .position(|entry| entry.template.uri_template == *uri);
1127                    let declared = index
1128                        .and_then(|index| self.0.templates.get(index))
1129                        .is_some_and(|pieces| {
1130                            pieces.iter().any(|piece| {
1131                                matches!(piece, Piece::Var(name) if *name == request.argument.name)
1132                            })
1133                        });
1134                    if !declared {
1135                        return Err(McpError::invalid_params(
1136                            format!("no resource at `{uri}`"),
1137                            None,
1138                        ));
1139                    }
1140                }
1141            }
1142        }
1143        let context = request
1144            .context
1145            .and_then(|context| context.arguments)
1146            .unwrap_or_default();
1147        let input = CompletionRequest::new(
1148            target,
1149            request.argument.name,
1150            request.argument.value,
1151            context,
1152        );
1153        let values = completer(input).await.map_err(|_| {
1154            tracing::warn!(kind = "completion", "completer failed");
1155            McpError::internal_error("completion failed", None)
1156        })?;
1157        let found = values.len();
1158        let truncated = found > CompletionInfo::MAX_VALUES;
1159        let values: Vec<String> = values
1160            .into_iter()
1161            .take(CompletionInfo::MAX_VALUES)
1162            .collect();
1163        let total = u32::try_from(found).unwrap_or(u32::MAX);
1164        let info = CompletionInfo::with_pagination(values, Some(total), truncated)
1165            .map_err(|_| McpError::internal_error("completion failed", None))?;
1166        Ok(CompleteResult::new(info))
1167    }
1168
1169    async fn list_tools(
1170        &self,
1171        _request: Option<PaginatedRequestParams>,
1172        _context: RequestContext<RoleServer>,
1173    ) -> Result<ListToolsResult, McpError> {
1174        let (ttl_ms, scope) = self.0.server.catalog_hints();
1175        Ok(ListToolsResult {
1176            tools: self
1177                .0
1178                .server
1179                .tools
1180                .iter()
1181                .map(|entry| entry.tool.clone())
1182                .collect(),
1183            ..Default::default()
1184        }
1185        .with_ttl_ms(ttl_ms)
1186        .with_cache_scope(scope))
1187    }
1188
1189    fn get_tool(&self, name: &str) -> Option<rmcp::model::Tool> {
1190        self.entry(name).map(|entry| entry.tool.clone())
1191    }
1192
1193    async fn call_tool(
1194        &self,
1195        request: CallToolRequestParams,
1196        context: RequestContext<RoleServer>,
1197    ) -> Result<CallToolResponse, McpError> {
1198        let entry = self.entry(&request.name).ok_or_else(|| {
1199            McpError::invalid_params(format!("no tool named `{}`", request.name), None)
1200        })?;
1201        let args = Value::Object(request.arguments.unwrap_or_default());
1202        let Ok(_slot) = Arc::clone(&self.0.server.slots).try_acquire_owned() else {
1203            return Ok(CallToolResponse::Complete(error(
1204                "The server is busy; try again shortly.",
1205            )));
1206        };
1207        let result = match &entry.kind {
1208            // A tool's own failure is a result the model reads, not a protocol error.
1209            Kind::Tool(run) => {
1210                let run = run(args);
1211                #[cfg(feature = "otel")]
1212                let run = {
1213                    let span = tracing::info_span!("mcp.tool_call", mcp.tool = %request.name);
1214                    crate::otel::Incoming::of(&context).continue_in(&span, None);
1215                    tracing::Instrument::instrument(run, span)
1216                };
1217                match run.await {
1218                    Ok(output) => tool_result(output),
1219                    Err(failure) => error(&failure.to_string()),
1220                }
1221            }
1222            Kind::Agent(agent, typed) => {
1223                self.call_agent(agent, typed.as_ref(), args, &context)
1224                    .await?
1225            }
1226        };
1227        Ok(CallToolResponse::Complete(result))
1228    }
1229}
1230
1231#[derive(Deserialize)]
1232struct AgentArgs {
1233    message: String,
1234    session_id: Option<String>,
1235}
1236
1237impl Handler {
1238    async fn call_agent(
1239        &self,
1240        agent: &Agent,
1241        typed: Option<&TypedAnswer>,
1242        args: Value,
1243        context: &RequestContext<RoleServer>,
1244    ) -> Result<CallToolResult, McpError> {
1245        let server = &self.0.server;
1246        let AgentArgs {
1247            message,
1248            session_id,
1249        } = AgentArgs::deserialize(args)
1250            .map_err(|e| McpError::invalid_params(format!("invalid arguments: {e}"), None))?;
1251        let session = session_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
1252        if !valid_context_id(&session) {
1253            return Err(McpError::invalid_params(
1254                "session_id must be 1 to 128 ASCII letters, digits, `-` or `_`",
1255                None,
1256            ));
1257        }
1258        let span = tracing::info_span!("mcp.agent_call", mcp.session_id = %session);
1259        #[cfg(feature = "otel")]
1260        crate::otel::Incoming::of(context).continue_in(&span, Some(&session));
1261        let prior = match server.history.load(&session).await {
1262            Ok(messages) => view(&messages, server.window.as_ref())
1263                .iter()
1264                .map(|message| (**message).clone())
1265                .collect::<Vec<_>>(),
1266            Err(_) => {
1267                tracing::warn!(parent: &span, kind = "store_error", "could not load the session");
1268                return Ok(error("The session could not be loaded."));
1269            }
1270        };
1271        let deadline = tokio::time::Instant::now() + server.max_run;
1272        let prompt = Message::user(message);
1273
1274        if let Some(typed) = typed {
1275            let run =
1276                tracing::Instrument::instrument(typed(agent.clone(), prompt, prior), span.clone());
1277            let outcome = tokio::select! {
1278                _ = context.ct.cancelled() => return Ok(error("Cancelled.")),
1279                outcome = tokio::time::timeout_at(deadline, run) => outcome,
1280            };
1281            return Ok(match outcome {
1282                Err(_) => error("The agent run took longer than allowed."),
1283                Ok(Err(message)) => error(&message),
1284                Ok(Ok((value, messages))) => {
1285                    self.save(&session, messages, &span).await;
1286                    let mut result = CallToolResult::success(vec![
1287                        ContentBlock::text(value.to_string()),
1288                        ContentBlock::text(format!("session_id: {session}")),
1289                    ]);
1290                    result.structured_content = Some(value);
1291                    result
1292                }
1293            });
1294        }
1295
1296        let progress = context.meta.get_progress_token();
1297        let mut stream = span.in_scope(|| agent.prompt(prompt).history(prior).stream());
1298        let mut chunks = 0_u32;
1299        loop {
1300            let item = tokio::select! {
1301                _ = context.ct.cancelled() => return Ok(error("Cancelled.")),
1302                item = tokio::time::timeout_at(deadline, stream.next()) => match item {
1303                    Err(_) => return Ok(error("The agent run took longer than allowed.")),
1304                    Ok(None) => return Ok(error("The agent run ended without an answer.")),
1305                    Ok(Some(item)) => item,
1306                },
1307            };
1308            match item {
1309                Ok(MultiTurnStreamItem::StreamAssistantItem(Item::Event(StreamEvent::Text {
1310                    text,
1311                    ..
1312                }))) => {
1313                    chunks += 1;
1314                    if let Some(token) = &progress {
1315                        // Progress is best effort: a client that went away
1316                        // still gets its answer if it comes back.
1317                        let _ = context
1318                            .peer
1319                            .notify_progress(
1320                                ProgressNotificationParam::new(token.clone(), f64::from(chunks))
1321                                    .with_message(text),
1322                            )
1323                            .await;
1324                    }
1325                }
1326                Ok(MultiTurnStreamItem::FinalResponse(response)) => {
1327                    self.save(&session, response.messages.clone(), &span).await;
1328                    let answer = response.output();
1329                    let mut blocks = vec![ContentBlock::text(answer.clone())];
1330                    blocks.extend(image_blocks(&response.content));
1331                    let mut result = CallToolResult::success(blocks);
1332                    result.structured_content =
1333                        Some(json!({"answer": answer, "session_id": session}));
1334                    return Ok(result);
1335                }
1336                Ok(_) => {}
1337                Err(failure) => {
1338                    tracing::warn!(parent: &span, kind = "run_failed", reason = status_message(&failure), "agent call failed");
1339                    return Ok(error(&failure_message(&failure)));
1340                }
1341            }
1342        }
1343    }
1344
1345    /// Add a finished run to its session. The answer stands if this fails;
1346    /// the next call then starts without this turn.
1347    async fn save(&self, session: &str, messages: Vec<Message>, span: &tracing::Span) {
1348        if self
1349            .0
1350            .server
1351            .history
1352            .append(session, messages)
1353            .await
1354            .is_err()
1355        {
1356            tracing::warn!(parent: span, kind = "store_error", "could not save the session");
1357        }
1358    }
1359}
1360
1361/// What the calling model is told when a run fails: enough to decide whether to
1362/// retry, without the provider's own error text (which can name internals).
1363///
1364/// A failure arrives as the provider's error from an awaited run, or as its
1365/// report from a streamed one; both carry the status and whether to retry.
1366fn failure_message(failure: &PromptError) -> Cow<'static, str> {
1367    if let PromptError::MaxTurns { max_turns, .. } = failure {
1368        return Cow::Owned(if *max_turns <= 1 {
1369            "The agent reached its turn limit (1); agents with tools usually need AgentBuilder::default_max_turns(n) with n >= 2.".to_owned()
1370        } else {
1371            format!(
1372                "The agent reached its turn limit ({max_turns}); raise AgentBuilder::default_max_turns above {max_turns} if the task needs more steps."
1373            )
1374        });
1375    }
1376    Cow::Borrowed(status_message(failure))
1377}
1378
1379fn status_message(failure: &PromptError) -> &'static str {
1380    let (status, retryable) = match failure {
1381        PromptError::Provider(provider) => (
1382            failure
1383                .provider_response_status()
1384                .map(|status| status.as_u16()),
1385            provider.is_retryable(),
1386        ),
1387        PromptError::Report(report) => (
1388            report.http_status.or(report
1389                .provider_response_status()
1390                .map(|status| status.as_u16())),
1391            report.retryable,
1392        ),
1393        _ => (None, false),
1394    };
1395    match status {
1396        Some(429) => "The model provider is rate limiting this server; try again in a moment.",
1397        Some(401 | 403) => "The model provider rejected this server's credentials.",
1398        Some(500..=599) => "The model provider is unavailable right now; try again shortly.",
1399        Some(_) => "The model provider rejected the request.",
1400        None if retryable => "The model provider could not be reached; try again shortly.",
1401        None => "The agent run failed.",
1402    }
1403}
1404
1405fn error(text: &str) -> CallToolResult {
1406    CallToolResult::error(vec![ContentBlock::text(text)])
1407}
1408
1409/// `value` as a JSON Schema object; an empty schema, or one that is not an
1410/// object, becomes the schema of an object with no properties.
1411fn object(value: Value) -> JsonObject {
1412    match value {
1413        Value::Object(map) if !map.is_empty() => map,
1414        _ => JsonObject::from_iter([
1415            ("type".to_owned(), json!("object")),
1416            ("properties".to_owned(), json!({})),
1417        ]),
1418    }
1419}
1420
1421fn agent_input() -> JsonObject {
1422    object(json!({
1423        "type": "object",
1424        "properties": {
1425            "message": {
1426                "type": "string",
1427                "description": "What to ask or tell the agent, self-contained."
1428            },
1429            "session_id": {
1430                "type": "string",
1431                "description": "The session_id of an earlier answer, to continue that conversation."
1432            }
1433        },
1434        "required": ["message"],
1435        "additionalProperties": false
1436    }))
1437}
1438
1439fn agent_identity(agent: &Agent) -> (String, String) {
1440    let name = tool_name(agent.name().unwrap_or("agent"));
1441    let description = format!(
1442        "{} Ask it in plain language; pass the session_id of an earlier answer to continue \
1443         the same conversation.",
1444        agent.description().unwrap_or("A Rig agent.")
1445    );
1446    (name, description)
1447}
1448
1449/// A provider-safe tool name: ASCII letters, digits and `_`, at most 64
1450/// characters, never empty.
1451pub(crate) fn tool_name(name: &str) -> String {
1452    let mut safe: String = name
1453        .trim()
1454        .chars()
1455        .map(|c| {
1456            if c.is_ascii_alphanumeric() {
1457                c.to_ascii_lowercase()
1458            } else {
1459                '_'
1460            }
1461        })
1462        .collect();
1463    safe.truncate(MAX_TOOL_NAME);
1464    let safe = safe.trim_matches('_');
1465    if safe.is_empty() {
1466        "agent".to_owned()
1467    } else {
1468        safe.to_owned()
1469    }
1470}
1471
1472#[cfg(test)]
1473mod tests;