1use crate::prompt::{ToolPrefix, not_found};
14use rmcp::model::{
15 CallToolRequestParams, CallToolResponse, ContentBlock, GetPromptRequestParams,
16 GetPromptResponse, Implementation, ListPromptsResult, ListToolsResult, PaginatedRequestParams,
17 Prompt, PromptsCapability, ServerCapabilities, ServerConfig, Tool,
18};
19use rmcp::service::{RequestContext, RoleServer};
20use rmcp::{ErrorData as McpError, ServerHandler};
21use std::future::Future;
22use std::pin::Pin;
23
24pub const COMBINED: &str = "mcp";
26
27type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
28
29pub trait ToolHandler: Send + Sync + 'static {
32 fn info(&self) -> ServerConfig;
34 fn tool(&self, name: &str) -> Option<Tool>;
36 fn list(
38 &self,
39 context: RequestContext<RoleServer>,
40 ) -> BoxFuture<'_, Result<Vec<Tool>, McpError>>;
41 fn call(
43 &self,
44 request: CallToolRequestParams,
45 context: RequestContext<RoleServer>,
46 ) -> BoxFuture<'_, Result<CallToolResponse, McpError>>;
47 fn prompts(
49 &self,
50 context: RequestContext<RoleServer>,
51 ) -> BoxFuture<'_, Result<Vec<Prompt>, McpError>>;
52 fn prompt(
54 &self,
55 request: GetPromptRequestParams,
56 context: RequestContext<RoleServer>,
57 ) -> BoxFuture<'_, Result<GetPromptResponse, McpError>>;
58}
59
60impl<S: ServerHandler> ToolHandler for S {
61 fn info(&self) -> ServerConfig {
62 self.get_info()
63 }
64
65 fn tool(&self, name: &str) -> Option<Tool> {
66 self.get_tool(name)
67 }
68
69 fn list(
71 &self,
72 context: RequestContext<RoleServer>,
73 ) -> BoxFuture<'_, Result<Vec<Tool>, McpError>> {
74 Box::pin(async move { Ok(self.list_tools(None, context).await?.tools) })
75 }
76
77 fn call(
78 &self,
79 request: CallToolRequestParams,
80 context: RequestContext<RoleServer>,
81 ) -> BoxFuture<'_, Result<CallToolResponse, McpError>> {
82 Box::pin(self.call_tool(request, context))
83 }
84
85 fn prompts(
87 &self,
88 context: RequestContext<RoleServer>,
89 ) -> BoxFuture<'_, Result<Vec<Prompt>, McpError>> {
90 Box::pin(async move { Ok(self.list_prompts(None, context).await?.prompts) })
91 }
92
93 fn prompt(
94 &self,
95 request: GetPromptRequestParams,
96 context: RequestContext<RoleServer>,
97 ) -> BoxFuture<'_, Result<GetPromptResponse, McpError>> {
98 Box::pin(self.get_prompt(request, context))
99 }
100}
101
102pub struct DynHandler(Box<dyn ToolHandler>);
104
105impl DynHandler {
106 pub fn new(handler: impl ToolHandler) -> Self {
108 Self(Box::new(handler))
109 }
110}
111
112impl ServerHandler for DynHandler {
113 fn get_info(&self) -> ServerConfig {
114 self.0.info()
115 }
116
117 fn get_tool(&self, name: &str) -> Option<Tool> {
118 self.0.tool(name)
119 }
120
121 async fn list_tools(
122 &self,
123 _request: Option<PaginatedRequestParams>,
124 context: RequestContext<RoleServer>,
125 ) -> Result<ListToolsResult, McpError> {
126 Ok(ListToolsResult::with_all_items(self.0.list(context).await?))
127 }
128
129 async fn call_tool(
130 &self,
131 request: CallToolRequestParams,
132 context: RequestContext<RoleServer>,
133 ) -> Result<CallToolResponse, McpError> {
134 self.0.call(request, context).await
135 }
136
137 async fn list_prompts(
138 &self,
139 _request: Option<PaginatedRequestParams>,
140 context: RequestContext<RoleServer>,
141 ) -> Result<ListPromptsResult, McpError> {
142 Ok(ListPromptsResult::with_all_items(
143 self.0.prompts(context).await?,
144 ))
145 }
146
147 async fn get_prompt(
148 &self,
149 request: GetPromptRequestParams,
150 context: RequestContext<RoleServer>,
151 ) -> Result<GetPromptResponse, McpError> {
152 self.0.prompt(request, context).await
153 }
154}
155
156pub fn prefixed_name(service: &str, tool: &str) -> String {
158 format!("{service}_{tool}")
159}
160
161fn prefixed(service: &str, mut tool: Tool) -> Tool {
162 tool.name = prefixed_name(service, &tool.name).into();
163 tool
164}
165
166fn prefix_tool_names(service: &str, tools: &[String], text: &str) -> String {
171 let mut out = String::with_capacity(text.len());
172 let mut word = String::new();
173 let flush = |word: &mut String, out: &mut String| {
174 if tools.iter().any(|t| t == word) {
175 out.push_str(&prefixed_name(service, word));
176 } else {
177 out.push_str(word);
178 }
179 word.clear();
180 };
181 for c in text.chars() {
182 if c.is_ascii_alphanumeric() || c == '_' {
183 word.push(c);
184 } else {
185 flush(&mut word, &mut out);
186 out.push(c);
187 }
188 }
189 flush(&mut word, &mut out);
190 out
191}
192
193fn prefixed_prompt(service: &str, mut prompt: Prompt) -> Prompt {
194 prompt.name = prefixed_name(service, &prompt.name);
195 prompt
196}
197
198fn with_full_name(error: McpError, own: &str, full: &str) -> McpError {
201 if error == not_found(own) {
202 return not_found(full);
203 }
204 error
205}
206
207fn split<'a>(services: &[&str], name: &'a str) -> Option<(usize, &'a str)> {
210 let (service, tool) = name.split_once('_')?;
211 let index = services.iter().position(|s| *s == service)?;
212 (!tool.is_empty()).then_some((index, tool))
213}
214
215fn instructions(services: &[(&str, Option<String>)]) -> String {
217 let prefixes: Vec<String> = services.iter().map(|(s, _)| format!("{s}_")).collect();
218 let mut text = format!(
219 "This server combines several services. Each tool and prompt name starts with its service: {}. \
220 The notes below, tool descriptions and error messages name tools without that prefix.",
221 prefixes.join(", ")
222 );
223 for (service, own) in services {
224 if let Some(own) = own.as_deref().filter(|t| !t.trim().is_empty()) {
225 text.push_str(&format!("\n\n{service}:\n{}", own.trim()));
226 }
227 }
228 text
229}
230
231pub struct Combined {
233 info: ServerConfig,
234 names: Vec<&'static str>,
235 handlers: Vec<DynHandler>,
236}
237
238impl Combined {
239 pub fn new(server_info: Implementation, services: Vec<(&'static str, DynHandler)>) -> Self {
242 let own: Vec<(&str, Option<String>)> = services
243 .iter()
244 .map(|(name, h)| (*name, h.get_info().instructions))
245 .collect();
246 let mut capabilities = ServerCapabilities::builder().enable_tools().build();
247 if services
248 .iter()
249 .any(|(_, h)| h.get_info().capabilities.prompts.is_some())
250 {
251 capabilities.prompts = Some(PromptsCapability::default());
252 }
253 let info = ServerConfig::new(capabilities)
254 .with_server_info(server_info)
255 .with_instructions(instructions(&own));
256 let (names, handlers) = services.into_iter().unzip();
257 Self {
258 info,
259 names,
260 handlers,
261 }
262 }
263}
264
265impl ServerHandler for Combined {
266 fn get_info(&self) -> ServerConfig {
267 self.info.clone()
268 }
269
270 fn get_tool(&self, name: &str) -> Option<Tool> {
271 let (index, tool) = split(&self.names, name)?;
272 self.handlers[index]
273 .get_tool(tool)
274 .map(|t| prefixed(self.names[index], t))
275 }
276
277 async fn list_tools(
278 &self,
279 _request: Option<PaginatedRequestParams>,
280 context: RequestContext<RoleServer>,
281 ) -> Result<ListToolsResult, McpError> {
282 let mut tools = Vec::new();
283 for (service, handler) in self.names.iter().zip(&self.handlers) {
284 let listed = handler.list_tools(None, context.clone()).await?.tools;
285 tools.extend(listed.into_iter().map(|t| prefixed(service, t)));
286 }
287 Ok(ListToolsResult::with_all_items(tools))
288 }
289
290 async fn call_tool(
291 &self,
292 mut request: CallToolRequestParams,
293 context: RequestContext<RoleServer>,
294 ) -> Result<CallToolResponse, McpError> {
295 let Some((index, tool)) = split(&self.names, &request.name) else {
296 return Err(McpError::invalid_params("tool not found", None));
297 };
298 request.name = tool.to_string().into();
299 self.handlers[index].call_tool(request, context).await
300 }
301
302 async fn list_prompts(
303 &self,
304 _request: Option<PaginatedRequestParams>,
305 context: RequestContext<RoleServer>,
306 ) -> Result<ListPromptsResult, McpError> {
307 let mut prompts = Vec::new();
308 for (service, handler) in self.names.iter().zip(&self.handlers) {
309 let listed = handler.list_prompts(None, context.clone()).await?.prompts;
310 prompts.extend(listed.into_iter().map(|p| prefixed_prompt(service, p)));
311 }
312 Ok(ListPromptsResult::with_all_items(prompts))
313 }
314
315 async fn get_prompt(
320 &self,
321 mut request: GetPromptRequestParams,
322 mut context: RequestContext<RoleServer>,
323 ) -> Result<GetPromptResponse, McpError> {
324 let Some((index, prompt)) = split(&self.names, &request.name) else {
325 return Err(not_found(&request.name));
326 };
327 let prompt = prompt.to_string();
328 let full = std::mem::replace(&mut request.name, prompt.clone());
329 let service = self.names[index];
330 let handler = &self.handlers[index];
331 context
332 .extensions
333 .insert(ToolPrefix(prefixed_name(service, "")));
334 let response = handler
335 .get_prompt(request, context.clone())
336 .await
337 .map_err(|e| with_full_name(e, &prompt, &full))?;
338 let GetPromptResponse::Complete(mut result) = response else {
339 return Ok(response);
340 };
341 let tools: Vec<String> = handler
342 .list_tools(None, context)
343 .await?
344 .tools
345 .into_iter()
346 .map(|t| t.name.to_string())
347 .collect();
348 for message in &mut result.messages {
349 if let ContentBlock::Text(t) = &mut message.content {
350 t.text = prefix_tool_names(service, &tools, &t.text);
351 }
352 }
353 Ok(GetPromptResponse::Complete(result))
354 }
355}
356
357#[cfg(test)]
358mod tests {
359 use super::*;
360 use std::sync::Arc;
361
362 #[test]
363 fn names_are_prefixed_with_their_service() {
364 assert_eq!(
365 prefixed_name("companies", "search_companies"),
366 "companies_search_companies"
367 );
368 let tool = Tool::new("get_company", "d", Arc::new(serde_json::Map::new()));
369 assert_eq!(prefixed("companies", tool).name, "companies_get_company");
370 }
371
372 #[test]
373 fn a_prefixed_name_routes_to_its_service_and_original_tool() {
374 let services = ["companies", "streaming"];
375 assert_eq!(
376 split(&services, "streaming_read_stream"),
377 Some((1, "read_stream"))
378 );
379 assert_eq!(
380 split(&services, "companies_get_company"),
381 Some((0, "get_company"))
382 );
383 assert_eq!(split(&services, "get_company"), None);
384 assert_eq!(split(&services, "filing_submit"), None);
385 assert_eq!(split(&services, "companies_"), None);
386 assert_eq!(split(&services, "companies"), None);
387 }
388
389 #[test]
390 fn instructions_name_the_prefixes_and_keep_each_services_own() {
391 let text = instructions(&[
392 ("companies", Some("Find companies.\n".into())),
393 ("streaming", None),
394 ("filing", Some("File changes.".into())),
395 ]);
396 assert_eq!(
397 text,
398 "This server combines several services. Each tool and prompt name starts with its service: \
399companies_, streaming_, filing_. The notes below, tool descriptions and error messages name \
400tools without that prefix.\n\ncompanies:\nFind companies.\n\nfiling:\nFile changes."
401 );
402 }
403
404 #[test]
405 fn tool_names_in_prompt_text_get_their_prefix() {
406 let tools = vec!["get_company".to_string(), "list_officers".to_string()];
407 assert_eq!(
408 prefix_tool_names(
409 "companies",
410 &tools,
411 "Call get_company, then list_officers (not get_company_registers, my_get_company \
412 or companies_get_company)."
413 ),
414 "Call companies_get_company, then companies_list_officers (not get_company_registers, \
415 my_get_company or companies_get_company)."
416 );
417 }
418
419 #[test]
420 fn prompt_names_are_prefixed_with_their_service() {
421 let prompt = Prompt::new("plan_week", Some("d"), None);
422 assert_eq!(
423 prefixed_prompt("calendar", prompt).name,
424 "calendar_plan_week"
425 );
426 let services = ["mail", "calendar", "contacts"];
427 assert_eq!(
428 split(&services, "contacts_clean_up_duplicates"),
429 Some((2, "clean_up_duplicates"))
430 );
431 }
432
433 #[test]
434 fn an_unknown_prompt_is_reported_with_the_name_the_client_sent() {
435 let e = with_full_name(not_found("nope"), "nope", "contacts_nope");
436 assert_eq!(e.code, rmcp::model::ErrorCode::INVALID_PARAMS);
437 assert_eq!(e.message, "prompt 'contacts_nope' not found");
438 let other = McpError::invalid_params("limit must be a string", None);
439 assert_eq!(
440 with_full_name(other.clone(), "nope", "contacts_nope"),
441 other
442 );
443 }
444
445 struct Bare(bool);
446
447 impl ServerHandler for Bare {
448 fn get_info(&self) -> ServerConfig {
449 let mut capabilities = ServerCapabilities::builder().enable_tools().build();
450 if self.0 {
451 capabilities.prompts = Some(PromptsCapability::default());
452 }
453 ServerConfig::new(capabilities)
454 }
455 }
456
457 fn combined_info(with_prompts: &[bool]) -> ServerConfig {
458 let services = with_prompts
459 .iter()
460 .zip(["a", "b"])
461 .map(|(p, name)| (name, DynHandler::new(Bare(*p))))
462 .collect();
463 Combined::new(Implementation::new("t", "1"), services).get_info()
464 }
465
466 #[test]
467 fn prompts_are_offered_when_any_service_has_them() {
468 let info = combined_info(&[false, true]);
469 assert!(info.capabilities.prompts.is_some());
470 assert!(info.capabilities.tools.is_some());
471 let info = combined_info(&[false, false]);
472 assert!(info.capabilities.prompts.is_none());
473 assert!(info.capabilities.tools.is_some());
474 }
475}