1use 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
44pub const DEFAULT_MAX_CONCURRENT_CALLS: usize = 32;
46pub const DEFAULT_MAX_RUN_DURATION: Duration = Duration::from_secs(600);
48const DEFAULT_LIST_TTL: Duration = Duration::from_secs(60);
51
52const 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
67pub 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 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 #[must_use]
143 pub fn ping_route(mut self) -> Self {
144 self.ping = true;
145 self
146 }
147
148 #[must_use]
150 pub fn version(mut self, version: impl Into<String>) -> Self {
151 self.version = version.into();
152 self
153 }
154
155 #[must_use]
158 pub fn title(mut self, title: impl Into<String>) -> Self {
159 self.title = Some(title.into());
160 self
161 }
162
163 #[must_use]
168 pub fn icon(mut self, icon: Icon) -> Self {
169 self.icons.push(icon);
170 self
171 }
172
173 #[must_use]
175 pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
176 self.instructions = Some(instructions.into());
177 self
178 }
179
180 #[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 #[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 #[must_use]
268 pub fn tool<T: Tool + 'static>(self, tool: T) -> Self {
269 self.tool_presented(tool, Presentation::default())
270 }
271
272 #[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 #[must_use]
293 pub fn dynamic_tool(self, tool: DynamicTool) -> Self {
294 self.dynamic_tool_presented(tool, Presentation::default())
295 }
296
297 #[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 #[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 #[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 #[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 #[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 #[must_use]
354 pub fn max_run_duration(mut self, max: Duration) -> Self {
355 self.max_run = max;
356 self
357 }
358
359 #[must_use]
367 pub fn list_ttl(mut self, ttl: Duration) -> Self {
368 self.list_ttl = ttl;
369 self
370 }
371
372 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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#[derive(Debug, Clone, Default, PartialEq)]
726#[non_exhaustive]
727pub struct Presentation {
728 title: Option<String>,
729 icons: Vec<Icon>,
730}
731
732impl Presentation {
733 #[must_use]
735 pub fn new() -> Self {
736 Self::default()
737 }
738
739 #[must_use]
741 pub fn title(mut self, title: impl Into<String>) -> Self {
742 self.title = Some(title.into());
743 self
744 }
745
746 #[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#[derive(Debug, thiserror::Error)]
780#[non_exhaustive]
781pub enum BuildError {
782 #[error("two tools are named `{0}`")]
785 DuplicateTool(String),
786 #[error("two resources have the URI `{0}`")]
789 DuplicateResource(String),
790 #[error("two prompts are named `{0}`")]
793 DuplicatePrompt(String),
794 #[error("icon source `{0}` is not an http(s) URL or a data: URI")]
797 InvalidIcon(String),
798 #[error(
802 "resource template `{0}` is malformed: use `{{name}}` once per name, with letters, digits or `_`"
803 )]
804 InvalidResourceTemplate(String),
805 #[error("two resource templates have the URI template `{0}`")]
808 DuplicateResourceTemplate(String),
809}
810
811#[derive(Clone)]
813pub(crate) struct Handler(Arc<Inner>);
814
815struct Inner {
816 server: McpServer,
817 by_name: HashMap<String, usize>,
818 templates: Vec<Vec<Piece>>,
820}
821
822impl Handler {
823 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
885fn 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 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 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 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 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 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 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 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
1361fn 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
1409fn 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
1449pub(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;