mcp_apps_server/router.rs
1//! Register rmcp tools and matching HTML resources without owning a transport.
2//!
3//! Routes use send-capable callbacks. A custom [`rmcp::ServerHandler`] can invoke
4//! this router after its own authorization and filtering. Call
5//! [`AppRouter::validate`] before serving when importing a [`ToolRouter`]; an
6//! imported tool may refer to a resource registered later. The router does not
7//! start a runtime, load assets, enforce UI visibility or render a browser app.
8//!
9//! # Register an existing rmcp tool
10//!
11//! ```
12//! use mcp_apps_server::{AppRouter, ToolUi, UiResource, UiResourceRoute, UiResourceUri};
13//! use rmcp::{tool, tool_router};
14//!
15//! struct Inventory;
16//! #[tool_router]
17//! impl Inventory {
18//! #[tool(description = "Read the inventory snapshot")]
19//! fn snapshot(&self) -> String {
20//! "12 items available".into()
21//! }
22//! }
23//!
24//! let view = UiResource::new(UiResourceUri::new("ui://inventory/view")?, "inventory");
25//! let ui = ToolUi::new(view.uri().clone());
26//! let mut router = AppRouter::from_tool_router(Inventory::tool_router());
27//! router.register_resource(UiResourceRoute::static_html(
28//! view, "<!doctype html><html><body>Inventory</body></html>",
29//! ))?;
30//! router.associate_tool("snapshot", &ui)?;
31//! router.validate()?;
32//! assert_eq!(router.list_tools(None)?.tools.len(), 1);
33//! # Ok::<(), Box<dyn std::error::Error>>(())
34//! ```
35
36use std::{collections::BTreeMap, error::Error, fmt, future::Future, pin::Pin};
37
38use rmcp::{
39 ErrorData, RoleServer,
40 handler::server::{
41 router::tool::{IntoToolRoute, ToolRouter},
42 tool::ToolCallContext,
43 },
44 model::{
45 CacheScope, CallToolRequestParams, CallToolResponse, ListResourcesResult, ListToolsResult,
46 MetaObject, PaginatedRequestParams, ReadResourceRequestParams, ReadResourceResponse,
47 ReadResourceResult, ServerCapabilities, Tool,
48 },
49 service::RequestContext,
50};
51
52use crate::{
53 MetadataError, ResourceUi, StaticUiResource, ToolUi, UiResource, UiResourceUri, UiUriError,
54 declare_ui_extension,
55};
56
57/// The send-capable result of an HTML resource callback.
58///
59/// The callback may borrow application state until it finishes. Its error is
60/// returned unchanged; the router adds the registered URI, MIME type and metadata
61/// only to a successful HTML result.
62pub type HtmlFuture<'a> = Pin<Box<dyn Future<Output = Result<String, ErrorData>> + Send + 'a>>;
63
64type HtmlHandler<S> =
65 dyn for<'a> Fn(&'a S, RequestContext<RoleServer>) -> HtmlFuture<'a> + Send + Sync;
66
67enum HtmlSource<S> {
68 Static(String),
69 Callback(Box<HtmlHandler<S>>),
70}
71
72/// A registered HTML source with fixed identity and resource metadata.
73///
74/// Dynamic callbacks receive the application state and original request context,
75/// including cancellation, request metadata and transport extensions. They run
76/// only for reads matching the registered URI. They supply HTML, not a protocol
77/// resource object, so cannot accidentally change its URI or MIME type.
78/// The consuming application owns authorization and HTML validity.
79pub struct UiResourceRoute<S> {
80 resource: UiResource,
81 source: HtmlSource<S>,
82 meta: MetaObject,
83}
84
85impl<S> UiResourceRoute<S> {
86 fn from_static<R: StaticUiResource>() -> Result<Self, RegistrationError> {
87 Ok(Self::static_html(R::resource()?, R::html())
88 .with_meta(R::meta()?)?
89 .with_ui(&R::ui())?)
90 }
91
92 /// Prepare a dynamic HTML callback without executing it.
93 ///
94 /// No file or network access occurs during registration. The callback receives
95 /// the request context when [`AppRouter::read_resource`] dispatches a matching
96 /// read, and may use its extensions for application-specific access checks.
97 ///
98 /// ```
99 /// use mcp_apps_server::{UiResource, UiResourceRoute, UiResourceUri};
100 ///
101 /// struct Application { html: String }
102 /// let resource = UiResource::new(UiResourceUri::new("ui://application/view")?, "view");
103 /// let route = UiResourceRoute::new(resource, |state: &Application, context| {
104 /// Box::pin(async move {
105 /// // Application-specific access checks can inspect context.extensions.
106 /// if context.ct.is_cancelled() {
107 /// return Err(rmcp::ErrorData::internal_error("Read was cancelled", None));
108 /// }
109 /// Ok(state.html.clone())
110 /// })
111 /// });
112 /// # let _ = route;
113 /// # Ok::<(), Box<dyn std::error::Error>>(())
114 /// ```
115 pub fn new(
116 resource: UiResource,
117 callback: impl for<'a> Fn(&'a S, RequestContext<RoleServer>) -> HtmlFuture<'a>
118 + Send
119 + Sync
120 + 'static,
121 ) -> Self {
122 Self {
123 resource,
124 source: HtmlSource::Callback(Box::new(callback)),
125 meta: MetaObject::default(),
126 }
127 }
128
129 /// Prepare caller-supplied static HTML without loading or inspecting assets.
130 ///
131 /// Each successful read returns an owned copy of this HTML, as required by
132 /// rmcp's resource-content representation.
133 pub fn static_html(resource: UiResource, html: impl Into<String>) -> Self {
134 Self {
135 resource,
136 source: HtmlSource::Static(html.into()),
137 meta: MetaObject::default(),
138 }
139 }
140
141 /// Replace the complete resource-content metadata map.
142 ///
143 /// Unknown keys remain available in the supplied map. Use [`Self::with_ui`]
144 /// afterwards to compose a typed UI declaration without discarding them.
145 /// Metadata is emitted on returned HTML content, not on the listing descriptor.
146 ///
147 /// # Errors
148 ///
149 /// Returns [`MetadataError::InvalidUi`] if a supplied root `ui` value is not
150 /// an object. The foundation's serialization errors are also propagated.
151 pub fn with_meta(mut self, mut meta: MetaObject) -> Result<Self, MetadataError> {
152 ResourceUi::default().merge_into(&mut meta)?;
153 self.meta = meta;
154 Ok(self)
155 }
156
157 /// Compose resource UI settings with the current content metadata.
158 ///
159 /// # Errors
160 ///
161 /// Returns the same atomic validation and conflict errors as
162 /// [`ResourceUi::merge_into`]. It does not validate HTML or host-specific CSP
163 /// domain syntax, grant permissions or change the resource's identity.
164 pub fn with_ui(mut self, ui: &ResourceUi) -> Result<Self, MetadataError> {
165 ui.merge_into(&mut self.meta)?;
166 Ok(self)
167 }
168}
169
170/// A registration or finalization failure, before serving requests.
171///
172/// Failed registration, association and merge operations leave the destination
173/// router unchanged. URI and metadata errors preserve their original causes.
174#[derive(Debug)]
175#[non_exhaustive]
176pub enum RegistrationError {
177 /// A tool name is already registered, even if its route is disabled.
178 DuplicateTool {
179 /// The conflicting tool name.
180 name: String,
181 },
182 /// An imported rmcp map key disagrees with its tool's declared name.
183 ToolNameMismatch {
184 /// The name used by rmcp for lookup and dispatch.
185 registered_name: String,
186 /// The name emitted in the tool declaration.
187 declared_name: String,
188 },
189 /// A resource with this exact URI spelling is already registered.
190 DuplicateResource {
191 /// The conflicting resource URI.
192 uri: String,
193 },
194 /// A shared static URI was declared with different content or metadata.
195 ConflictingResource {
196 /// The URI whose existing registration must not be replaced.
197 uri: String,
198 },
199 /// The requested tool association has no registered tool.
200 UnknownTool {
201 /// The missing tool name.
202 name: String,
203 },
204 /// An explicit association omitted its required resource URI.
205 MissingResourceUri {
206 /// The tool that was to be associated.
207 tool: String,
208 },
209 /// An association refers to an HTML resource absent from this router.
210 UnregisteredResource {
211 /// The missing resource URI.
212 uri: String,
213 },
214 /// An existing tool's URI association is not a JSON string.
215 InvalidToolAssociation {
216 /// The tool carrying the malformed declaration.
217 tool: String,
218 /// The malformed protocol field.
219 path: String,
220 },
221 /// A supplied UI resource URI failed validation.
222 Uri(UiUriError),
223 /// UI metadata could not be validated or composed.
224 Metadata(MetadataError),
225}
226
227impl fmt::Display for RegistrationError {
228 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
229 match self {
230 Self::DuplicateTool { name } => {
231 write!(formatter, "tool {name:?} is already registered")
232 }
233 Self::ToolNameMismatch {
234 registered_name,
235 declared_name,
236 } => write!(
237 formatter,
238 "registered tool name {registered_name:?} differs from declaration {declared_name:?}"
239 ),
240 Self::DuplicateResource { uri } => {
241 write!(formatter, "resource {uri:?} is already registered")
242 }
243 Self::ConflictingResource { uri } => {
244 write!(
245 formatter,
246 "resource {uri:?} has a conflicting static declaration"
247 )
248 }
249 Self::UnknownTool { name } => write!(formatter, "tool {name:?} is not registered"),
250 Self::MissingResourceUri { tool } => {
251 write!(
252 formatter,
253 "association for tool {tool:?} requires a resource URI"
254 )
255 }
256 Self::UnregisteredResource { uri } => {
257 write!(formatter, "associated resource {uri:?} is not registered")
258 }
259 Self::InvalidToolAssociation { tool, path } => {
260 write!(formatter, "tool {tool:?} requires a string at {path}")
261 }
262 Self::Uri(error) => write!(formatter, "invalid registered UI URI: {error}"),
263 Self::Metadata(error) => write!(formatter, "invalid registration metadata: {error}"),
264 }
265 }
266}
267
268impl Error for RegistrationError {
269 fn source(&self) -> Option<&(dyn Error + 'static)> {
270 match self {
271 Self::Uri(error) => Some(error),
272 Self::Metadata(error) => Some(error),
273 _ => None,
274 }
275 }
276}
277
278impl From<UiUriError> for RegistrationError {
279 fn from(error: UiUriError) -> Self {
280 Self::Uri(error)
281 }
282}
283
284impl From<MetadataError> for RegistrationError {
285 fn from(error: MetadataError) -> Self {
286 Self::Metadata(error)
287 }
288}
289
290/// An rmcp tool router and exact-URI registry of HTML resources.
291///
292/// Use this directly in a custom [`rmcp::ServerHandler`] when that handler owns
293/// authorization, other resources, prompts, tasks or custom lifecycle behavior.
294/// Request dispatch uses the existing rmcp tool framework. The application state
295/// and callbacks must be `Send + Sync`; this API does not promise rmcp's relaxed
296/// `local` callback support. Imported tools require [`Self::validate`] after all
297/// resources have been registered and before serving.
298pub struct AppRouter<S> {
299 tools: ToolRouter<S>,
300 resources: BTreeMap<String, UiResourceRoute<S>>,
301}
302
303impl<S> Default for AppRouter<S> {
304 fn default() -> Self {
305 Self {
306 tools: ToolRouter::default(),
307 resources: BTreeMap::new(),
308 }
309 }
310}
311
312impl<S: Send + Sync + 'static> AppRouter<S> {
313 /// Construct an empty registration set without performing external effects.
314 pub fn new() -> Self {
315 Self::default()
316 }
317
318 /// Adopt rmcp routes, including their disabled markers and notifier.
319 ///
320 /// This does not validate their existing UI associations: register the
321 /// corresponding resources and call [`Self::validate`] before serving.
322 /// Duplicate names already overwritten by rmcp cannot be recovered here.
323 pub fn from_tool_router(tools: ToolRouter<S>) -> Self {
324 Self {
325 tools,
326 resources: BTreeMap::new(),
327 }
328 }
329
330 /// Register a static or dynamic resource by its exact validated URI.
331 ///
332 /// The callback is not executed. No name restrictions, normalization, asset
333 /// loading or HTML validation are introduced.
334 ///
335 /// # Errors
336 ///
337 /// Returns [`RegistrationError::DuplicateResource`] without replacing the
338 /// existing route when the URI is already registered.
339 pub fn register_resource(
340 &mut self,
341 route: UiResourceRoute<S>,
342 ) -> Result<(), RegistrationError> {
343 let uri = route.resource.uri().to_string();
344 if self.resources.contains_key(&uri) {
345 return Err(RegistrationError::DuplicateResource { uri });
346 }
347 self.resources.insert(uri, route);
348 Ok(())
349 }
350
351 /// Register a statically defined UI resource and its complete content metadata.
352 ///
353 /// Composes [`StaticUiResource::ui`] with [`StaticUiResource::meta`], preserving
354 /// unrelated extension data and rejecting conflicting declarations.
355 ///
356 /// # Errors
357 ///
358 /// Propagates URI and metadata errors from [`StaticUiResource`], or returns
359 /// [`RegistrationError::DuplicateResource`] for an existing URI. Nothing is
360 /// inserted until the complete definition has been prepared successfully.
361 pub fn register_static<R: StaticUiResource>(&mut self) -> Result<(), RegistrationError> {
362 let route = UiResourceRoute::from_static::<R>()?;
363 self.register_resource(route)
364 }
365
366 /// Register or reuse an identical static declaration and return its URI.
367 ///
368 /// Application macros use this when several tools share a view. Reuse requires
369 /// equal descriptors, HTML and prepared content metadata, even when different
370 /// Rust types or type aliases declare the same URI. A dynamic route cannot be
371 /// reused as a static declaration. No callback or filesystem access occurs.
372 /// Open metadata and typed UI settings are composed as in [`Self::register_static`].
373 /// Unlike [`Self::register_static`], an identical registration is accepted.
374 ///
375 /// # Errors
376 ///
377 /// Propagates URI and metadata errors while preparing the declaration, or
378 /// returns [`RegistrationError::ConflictingResource`] if the existing route
379 /// differs. Failure leaves the existing registration unchanged.
380 pub fn ensure_static<R: StaticUiResource>(
381 &mut self,
382 ) -> Result<UiResourceUri, RegistrationError> {
383 let route = UiResourceRoute::from_static::<R>()?;
384 let uri = route.resource.uri().clone();
385 if let Some(existing) = self.resources.get(uri.as_str()) {
386 let same_html = match (&existing.source, &route.source) {
387 (HtmlSource::Static(left), HtmlSource::Static(right)) => left == right,
388 _ => false,
389 };
390 if !same_html
391 || existing.resource.descriptor() != route.resource.descriptor()
392 || existing.meta != route.meta
393 {
394 return Err(RegistrationError::ConflictingResource {
395 uri: uri.to_string(),
396 });
397 }
398 } else {
399 self.resources.insert(uri.to_string(), route);
400 }
401 Ok(uri)
402 }
403
404 /// Register an existing rmcp route without changing its handler or schema.
405 ///
406 /// Associated resources must already be registered. Tool factory functions,
407 /// [`rmcp::handler::server::router::tool::ToolRoute`] and rmcp's other
408 /// [`IntoToolRoute`] implementations are accepted directly.
409 ///
410 /// # Errors
411 ///
412 /// Rejects duplicate names, including disabled routes, and malformed,
413 /// conflicting or unresolved UI associations before inserting anything.
414 pub fn register_tool<R, A>(&mut self, route: R) -> Result<(), RegistrationError>
415 where
416 R: IntoToolRoute<S, A>,
417 {
418 let route = route.into_tool_route();
419 if self.tools.map.contains_key(&route.attr.name) {
420 return Err(RegistrationError::DuplicateTool {
421 name: route.attr.name.to_string(),
422 });
423 }
424 self.validate_tool(&route.attr)?;
425 self.tools.add_route(route);
426 Ok(())
427 }
428
429 /// Associate a registered tool with an already registered resource.
430 ///
431 /// Preserves its handler, schemas, annotations and unrelated metadata. A
432 /// disabled route can be associated without re-enabling it. This operation
433 /// declares UI visibility; it does not enforce access control.
434 ///
435 /// # Errors
436 ///
437 /// Returns [`RegistrationError::UnknownTool`],
438 /// [`RegistrationError::MissingResourceUri`],
439 /// [`RegistrationError::UnregisteredResource`] or the foundation's atomic
440 /// metadata error, leaving the existing tool unchanged.
441 pub fn associate_tool(&mut self, name: &str, ui: &ToolUi) -> Result<(), RegistrationError> {
442 if !self.tools.map.contains_key(name) {
443 return Err(RegistrationError::UnknownTool { name: name.into() });
444 }
445 let uri = ui
446 .resource_uri
447 .as_ref()
448 .ok_or_else(|| RegistrationError::MissingResourceUri { tool: name.into() })?;
449 if !self.contains_resource(uri.as_str()) {
450 return Err(RegistrationError::UnregisteredResource {
451 uri: uri.to_string(),
452 });
453 }
454 let route = self
455 .tools
456 .map
457 .get_mut(name)
458 .ok_or_else(|| RegistrationError::UnknownTool { name: name.into() })?;
459 ui.apply_to(&mut route.attr)?;
460 Ok(())
461 }
462
463 /// Associate a tool with an already registered static resource definition.
464 ///
465 /// # Errors
466 ///
467 /// Propagates the definition's URI error and the same registration or metadata
468 /// errors as [`Self::associate_tool`]. It does not register the resource.
469 pub fn associate_static_tool<R: StaticUiResource>(
470 &mut self,
471 name: &str,
472 ) -> Result<(), RegistrationError> {
473 self.associate_tool(name, &ToolUi::new(R::resource()?.uri().clone()))
474 }
475
476 /// Merge another registration set after checking every name and URI collision.
477 ///
478 /// Both registration sets must have matching tool lookup keys and declared
479 /// names. No destination route changes if an identity mismatch or collision
480 /// exists, even when a resource collision is discovered after checking tools.
481 /// Disabled routes still reserve their names. A source disabled-name marker
482 /// without a route also conflicts with an existing destination tool; it
483 /// cannot implicitly hide that tool. Destination markers for future tools
484 /// and disabled source routes retain rmcp's behavior. The destination notifier
485 /// is preserved; the source notifier is discarded, matching rmcp's merge
486 /// behavior. No notification is emitted by this assembly operation. Validate
487 /// the assembled associations before serving.
488 ///
489 /// # Errors
490 ///
491 /// Returns [`RegistrationError::ToolNameMismatch`],
492 /// [`RegistrationError::DuplicateTool`] or
493 /// [`RegistrationError::DuplicateResource`] without changing the destination.
494 /// The source is consumed even on error.
495 pub fn merge(&mut self, mut other: Self) -> Result<(), RegistrationError> {
496 // rmcp reinserts routes by their declared name, discarding the original
497 // lookup key. Check identities before that can hide an inconsistency.
498 self.validate_tool_names()?;
499 other.validate_tool_names()?;
500 for name in other.tools.map.keys() {
501 if self.tools.map.contains_key(name) {
502 return Err(RegistrationError::DuplicateTool {
503 name: name.to_string(),
504 });
505 }
506 }
507 for name in self.tools.map.keys() {
508 // After route collision checks, these names have no source route.
509 // enable_route detects an orphan marker without emitting a notifier;
510 // a marked source is consumed on this error, never merged.
511 if other.tools.enable_route(name) {
512 return Err(RegistrationError::DuplicateTool {
513 name: name.to_string(),
514 });
515 }
516 }
517 for uri in other.resources.keys() {
518 if self.resources.contains_key(uri) {
519 return Err(RegistrationError::DuplicateResource { uri: uri.clone() });
520 }
521 }
522 self.tools.merge(other.tools);
523 self.resources.extend(other.resources);
524 Ok(())
525 }
526
527 /// Verify every existing tool UI association without mutating registration.
528 ///
529 /// Checks disabled routes too, so re-enabling an imported route cannot reveal
530 /// an unchecked association. Both nested `ui.resourceUri` and deprecated
531 /// `ui/resourceUri` declarations must be strings, valid UI URIs, agree when
532 /// both exist and refer to a registered resource. Unknown metadata is retained.
533 /// Ordinary tools without an association are valid. Imported rmcp map keys
534 /// must agree with their declarations so listing, lookup and dispatch use
535 /// the same tool identity.
536 ///
537 /// # Errors
538 ///
539 /// Returns URI, metadata, malformed-association, tool-name mismatch or
540 /// missing-resource errors.
541 /// It does not establish HTML validity, authorization or host compatibility.
542 pub fn validate(&self) -> Result<(), RegistrationError> {
543 self.validate_tool_names()?;
544 for route in self.tools.map.values() {
545 self.validate_tool(&route.attr)?;
546 }
547 Ok(())
548 }
549
550 /// Return an enabled tool's declaration, including its composed UI metadata.
551 ///
552 /// Disabled and unknown tools return `None`, matching rmcp routing behavior.
553 /// Custom handlers should use this for `ServerHandler::get_tool` as well as
554 /// this router's list and call operations.
555 pub fn get_tool(&self, name: &str) -> Option<Tool> {
556 self.tools.get(name).cloned()
557 }
558
559 /// List all enabled tools, sorted by name, without pagination.
560 ///
561 /// The result has no next cursor and advertises zero cache lifetime with
562 /// private cache scope. A custom handler owns any per-user filtering.
563 ///
564 /// # Errors
565 ///
566 /// Returns an invalid-parameters error for any supplied cursor; this router
567 /// cannot interpret another handler's pagination state.
568 pub fn list_tools(
569 &self,
570 request: Option<PaginatedRequestParams>,
571 ) -> Result<ListToolsResult, ErrorData> {
572 reject_cursor(request)?;
573 Ok(ListToolsResult::with_all_items(self.tools.list_all())
574 .with_ttl_ms(0)
575 .with_cache_scope(CacheScope::Private))
576 }
577
578 /// List registered resources sorted by exact URI, without invoking callbacks.
579 ///
580 /// The result has no next cursor and advertises zero cache lifetime with
581 /// private cache scope. Resource security metadata is returned on HTML content.
582 ///
583 /// # Errors
584 ///
585 /// Returns an invalid-parameters error for any supplied cursor. A custom
586 /// handler must define its own pagination when combining other resource sets.
587 pub fn list_resources(
588 &self,
589 request: Option<PaginatedRequestParams>,
590 ) -> Result<ListResourcesResult, ErrorData> {
591 reject_cursor(request)?;
592 Ok(ListResourcesResult::with_all_items(
593 self.resources
594 .values()
595 .map(|route| route.resource.descriptor())
596 .collect(),
597 )
598 .with_ttl_ms(0)
599 .with_cache_scope(CacheScope::Private))
600 }
601
602 /// Invoke rmcp's existing tool route with the original request and context.
603 ///
604 /// Parameter extraction, tool execution, MRTR input responses and errors retain
605 /// rmcp's behavior. The state is borrowed for the call. The consuming handler
606 /// remains responsible for any authorization before dispatch or within a tool.
607 ///
608 /// # Errors
609 ///
610 /// Propagates rmcp routing or handler errors without inventing fallback routes.
611 pub async fn call_tool(
612 &self,
613 state: &S,
614 request: CallToolRequestParams,
615 context: RequestContext<RoleServer>,
616 ) -> Result<CallToolResponse, ErrorData> {
617 self.tools
618 .call(ToolCallContext::new(state, request, context))
619 .await
620 }
621
622 /// Read matching static HTML or invoke its dynamic callback exactly once.
623 ///
624 /// Successful content receives the registered URI, MCP Apps MIME type and
625 /// immutable prepared metadata. The callback receives the original context.
626 /// The state is borrowed; no runtime or background task is created. Complete
627 /// results have zero cache lifetime and private cache scope.
628 ///
629 /// # Errors
630 ///
631 /// Returns a resource-not-found error before invoking any callback for an
632 /// unknown URI. Callback errors pass through unchanged. rmcp may apply its
633 /// normal version-dependent error mapping when dispatching protocol requests.
634 pub async fn read_resource(
635 &self,
636 state: &S,
637 request: ReadResourceRequestParams,
638 context: RequestContext<RoleServer>,
639 ) -> Result<ReadResourceResponse, ErrorData> {
640 let route = self
641 .resources
642 .get(&request.uri)
643 .ok_or_else(|| ErrorData::resource_not_found("UI resource is not registered", None))?;
644 let html = match &route.source {
645 HtmlSource::Static(html) => html.clone(),
646 HtmlSource::Callback(callback) => callback(state, context).await?,
647 };
648 let content = route
649 .resource
650 .html_contents(html)
651 .with_meta(route.meta.clone());
652 Ok(ReadResourceResult::new(vec![content])
653 .with_ttl_ms(0)
654 .with_cache_scope(CacheScope::Private)
655 .into())
656 }
657
658 /// Check exact resource identity before a custom handler chooses dispatch.
659 ///
660 /// No normalization, resource read or authorization occurs. A positive result
661 /// means registration exists, not that the caller is permitted to read it.
662 pub fn contains_resource(&self, uri: &str) -> bool {
663 self.resources.contains_key(uri)
664 }
665
666 /// Advertise capabilities implemented by registered routes, preserving settings.
667 ///
668 /// Enables tools and resources only when their registration sets are nonempty,
669 /// and the UI extension when resources exist. Existing capabilities, extension
670 /// settings and notifications flags are left intact. This declares support;
671 /// it does not implement callbacks for other capabilities supplied by a server.
672 pub fn declare_capabilities(&self, capabilities: &mut ServerCapabilities) {
673 if !self.tools.map.is_empty() {
674 capabilities.tools.get_or_insert_default();
675 }
676 if !self.resources.is_empty() {
677 capabilities.resources.get_or_insert_default();
678 declare_ui_extension(capabilities);
679 }
680 }
681
682 fn validate_tool_names(&self) -> Result<(), RegistrationError> {
683 for (name, route) in &self.tools.map {
684 if name != &route.attr.name {
685 return Err(RegistrationError::ToolNameMismatch {
686 registered_name: name.to_string(),
687 declared_name: route.attr.name.to_string(),
688 });
689 }
690 }
691 Ok(())
692 }
693
694 fn validate_tool(&self, tool: &Tool) -> Result<(), RegistrationError> {
695 let Some(meta) = &tool.meta else {
696 return Ok(());
697 };
698 let mut candidate = meta.clone();
699 ToolUi::default().merge_into(&mut candidate)?;
700 let nested = meta
701 .0
702 .get("ui")
703 .and_then(|value| value.as_object())
704 .and_then(|ui| ui.get("resourceUri"));
705 let legacy = meta.0.get("ui/resourceUri");
706 let mut association = None;
707 for (value, path) in [
708 (nested, "_meta.ui.resourceUri"),
709 (legacy, "_meta.ui/resourceUri"),
710 ] {
711 if let Some(value) = value {
712 let raw =
713 value
714 .as_str()
715 .ok_or_else(|| RegistrationError::InvalidToolAssociation {
716 tool: tool.name.to_string(),
717 path: path.into(),
718 })?;
719 let uri = UiResourceUri::new(raw)?;
720 // Reuse the foundation's alias agreement and atomic composition
721 // policy instead of introducing a second conflict rule.
722 ToolUi::new(uri.clone()).merge_into(&mut candidate)?;
723 association = Some(uri);
724 }
725 }
726 if let Some(uri) = association
727 && !self.contains_resource(uri.as_str())
728 {
729 return Err(RegistrationError::UnregisteredResource {
730 uri: uri.to_string(),
731 });
732 }
733 Ok(())
734 }
735}
736
737fn reject_cursor(request: Option<PaginatedRequestParams>) -> Result<(), ErrorData> {
738 if request.is_some_and(|request| request.cursor.is_some()) {
739 return Err(ErrorData::invalid_params(
740 "AppRouter lists all entries and does not accept a pagination cursor",
741 None,
742 ));
743 }
744 Ok(())
745}