Skip to main content

Router

Struct Router 

Source
pub struct Router { /* private fields */ }
Expand description

Routes MCP requests to the appropriate handlers.

Implementations§

Source§

impl Router

Source

pub fn new() -> Self

Creates a new empty router.

Source

pub fn set_list_page_size(&mut self, page_size: Option<usize>)

Sets the list pagination page size.

When set, list methods (tools/list, resources/list, resources/templates/list, and prompts/list) will page results using opaque base64 cursors.

Source

pub fn set_final_cache_hint_policy( &mut self, list_ttl_ms: CacheTtl, resource_read_ttl_ms: CacheTtl, scope: CacheScope, )

Sets the cache hints emitted by final catalog and resource-read responses. The default is a five-minute private catalog TTL and a one-hour private resource-read TTL.

Source

pub fn final_cache_hint_policy(&self) -> (&CacheTtl, &CacheTtl, CacheScope)

Returns the active final cache-hint policy as (&list_ttl_ms, &resource_read_ttl_ms, scope).

Source

pub fn set_strict_input_validation(&mut self, strict: bool)

Sets whether to use strict input validation.

When enabled, tool input validation will reject any properties not explicitly defined in the tool’s input schema (enforces additionalProperties: false).

When disabled (default), extra properties are allowed unless the schema explicitly sets additionalProperties: false.

Source

pub fn strict_input_validation(&self) -> bool

Returns whether strict input validation is enabled.

Source

pub fn add_tool<H: ToolHandler + 'static>( &mut self, handler: H, ) -> McpResult<()>

Adds a tool handler.

If a tool with the same name already exists, it will be replaced. Use add_tool_with_behavior for finer control over duplicate handling.

Source

pub fn add_legacy_tool<H: ToolHandler + 'static>( &mut self, handler: H, ) -> McpResult<()>

Adds an intentionally exact-2024-only tool handler.

This is the explicit escape hatch for a legacy definition that cannot satisfy final schema admission. The tool remains available to exact MCP 2024-11-05 list and call routes, but is absent from every modern catalog and modern dispatch lookup. Ordinary Self::add_tool never falls back to this path.

Source

pub fn add_tool_with_behavior<H: ToolHandler + 'static>( &mut self, handler: H, behavior: DuplicateBehavior, ) -> Result<(), McpError>

Adds a tool handler with specified duplicate behavior.

Returns Err if duplicate policy rejects the name or if the candidate’s immutable definition, schemas, final metadata, or required error mapper cannot be admitted. Every error is returned before catalog mutation.

Source

pub fn add_legacy_tool_with_behavior<H: ToolHandler + 'static>( &mut self, handler: H, behavior: DuplicateBehavior, ) -> Result<(), McpError>

Adds an intentionally exact-2024-only tool with duplicate policy.

The definition is snapshotted before mutation, but no final definition, schema, metadata, or error-mapper hook is read. This prevents an explicitly legacy-only registration from accidentally claiming modern support while retaining the same duplicate semantics as ordinary tools.

Source

pub fn add_completion_handler<H: CompletionHandler + 'static>( &mut self, handler: H, )

Registers the handler for completion/complete.

This is the server-wide fallback for final completion dispatch and the sole route for exact MCP 2024-11-05. A final provider registered for a specific prompt or resource template takes precedence. Re-registering replaces the prior fallback, matching ordinary component registration semantics.

Source

pub fn add_legacy_completion_handler<H: CompletionHandler + 'static>( &mut self, handler: H, )

Registers a completion handler for exact MCP 2024-11-05 dispatch only.

Source

pub fn add_prompt_completion_handler<H: CompletionHandler + 'static>( &mut self, prompt_name: impl Into<String>, handler: H, )

Registers a final completion provider for one exact prompt name.

The provider is selected only after final prompt and argument admission succeeds. It never changes exact MCP 2024-11-05’s server-wide route.

Source

pub fn add_resource_template_completion_handler<H: CompletionHandler + 'static>( &mut self, uri_template: impl Into<String>, handler: H, )

Registers a final completion provider for one exact resource-template URI.

The provider is selected only after the resource template and requested template variable have been admitted for final dispatch.

Source

pub fn has_completion_handler(&self) -> bool

Returns whether a completion/complete handler is installed.

Source

pub fn add_resource<H: ResourceHandler + 'static>(&mut self, handler: H)

Adds a resource handler.

If a resource with the same URI already exists, it will be replaced. Use add_resource_with_behavior for finer control over duplicate handling.

Source

pub fn add_legacy_resource<H: ResourceHandler + 'static>(&mut self, handler: H)

Adds an intentionally exact-2024-only resource handler.

Source

pub fn add_resource_with_behavior<H: ResourceHandler + 'static>( &mut self, handler: H, behavior: DuplicateBehavior, ) -> Result<(), McpError>

Adds a resource handler with specified duplicate behavior.

Returns Err if behavior is crate::DuplicateBehavior::Error and the resource URI already exists.

Source

pub fn add_legacy_resource_with_behavior<H: ResourceHandler + 'static>( &mut self, handler: H, behavior: DuplicateBehavior, ) -> Result<(), McpError>

Adds an exact-2024-only resource handler with duplicate handling.

Source

pub fn add_resource_template(&mut self, template: ResourceTemplate)

Adds a resource template definition.

If a template with the same URI template already exists, its definition is replaced while any registered handler is retained. Use add_resource_template_with_behavior for finer control over duplicate handling.

Source

pub fn add_legacy_resource_template(&mut self, template: ResourceTemplate)

Adds an exact-2024-only resource template definition.

Source

pub fn add_resource_template_with_behavior( &mut self, template: ResourceTemplate, behavior: DuplicateBehavior, ) -> Result<(), McpError>

Adds a resource template definition with specified duplicate behavior.

Replacing a definition retains an existing handler registered for the same URI template. Returns Err when behavior is crate::DuplicateBehavior::Error and the URI template already exists.

Source

pub fn add_legacy_resource_template_with_behavior( &mut self, template: ResourceTemplate, behavior: DuplicateBehavior, ) -> Result<(), McpError>

Adds an exact-2024-only resource template with duplicate handling.

Source

pub fn add_prompt<H: PromptHandler + 'static>(&mut self, handler: H)

Adds a prompt handler.

If a prompt with the same name already exists, it will be replaced. Use add_prompt_with_behavior for finer control over duplicate handling.

Source

pub fn add_legacy_prompt<H: PromptHandler + 'static>(&mut self, handler: H)

Adds an intentionally exact-2024-only prompt handler.

Source

pub fn add_prompt_with_behavior<H: PromptHandler + 'static>( &mut self, handler: H, behavior: DuplicateBehavior, ) -> Result<(), McpError>

Adds a prompt handler with specified duplicate behavior.

Returns Err if behavior is crate::DuplicateBehavior::Error and the prompt name already exists.

Source

pub fn add_legacy_prompt_with_behavior<H: PromptHandler + 'static>( &mut self, handler: H, behavior: DuplicateBehavior, ) -> Result<(), McpError>

Adds an exact-2024-only prompt with duplicate handling.

Source

pub fn tools(&self) -> Vec<Tool>

Returns all tool definitions.

Source

pub fn tools_filtered( &self, session_state: Option<&SessionState>, tag_filters: Option<&TagFilters<'_>>, ) -> Vec<Tool>

Returns tool definitions filtered by session state and tags.

Tools that have been disabled in the session state will not be included. If tag filters are provided, tools must match the include/exclude criteria.

Source

pub fn resources(&self) -> Vec<Resource>

Returns all resource definitions.

Source

pub fn resources_filtered( &self, session_state: Option<&SessionState>, tag_filters: Option<&TagFilters<'_>>, ) -> Vec<Resource>

Returns resource definitions filtered by session state and tags.

Resources that have been disabled in the session state will not be included. If tag filters are provided, resources must match the include/exclude criteria.

Source

pub fn resource_templates(&self) -> Vec<ResourceTemplate>

Returns all resource templates.

Source

pub fn resource_templates_filtered( &self, session_state: Option<&SessionState>, tag_filters: Option<&TagFilters<'_>>, ) -> Vec<ResourceTemplate>

Returns resource templates filtered by session state and tags.

Templates that have been disabled in the session state will not be included. If tag filters are provided, templates must match the include/exclude criteria.

Source

pub fn prompts(&self) -> Vec<Prompt>

Returns all prompt definitions.

Source

pub fn prompts_filtered( &self, session_state: Option<&SessionState>, tag_filters: Option<&TagFilters<'_>>, ) -> Vec<Prompt>

Returns prompt definitions filtered by session state and tags.

Prompts that have been disabled in the session state will not be included. If tag filters are provided, prompts must match the include/exclude criteria.

Source

pub fn tools_count(&self) -> usize

Returns the number of registered tools.

Source

pub fn resources_count(&self) -> usize

Returns the number of registered resources.

Source

pub fn resource_templates_count(&self) -> usize

Returns the number of registered resource templates.

Source

pub fn prompts_count(&self) -> usize

Returns the number of registered prompts.

Source

pub fn get_tool(&self, name: &str) -> Option<&Box<dyn ToolHandler>>

Gets a tool handler by name.

Source

pub fn get_resource(&self, uri: &str) -> Option<&Box<dyn ResourceHandler>>

Gets a resource handler by URI.

Source

pub fn get_resource_template( &self, uri_template: &str, ) -> Option<&ResourceTemplate>

Gets a resource template by URI template.

Source

pub fn resource_exists(&self, uri: &str) -> bool

Returns true if a resource exists for the given URI (static or template match).

Source

pub fn get_prompt(&self, name: &str) -> Option<&Box<dyn PromptHandler>>

Gets a prompt handler by name.

Source

pub fn handle_initialize( &self, request_ctx: &McpContext, session: &mut Session, params: InitializeParams, instructions: Option<&str>, ) -> McpResult<InitializeResult>

Handles the initialize request.

Source

pub fn handle_completion_legacy( &self, request_ctx: &McpContext, params: LegacyCompletionParams, ) -> McpResult<LegacyCompletionResult>

Handles one exact MCP 2024-11-05 completion request.

Source

pub fn handle_tools_list( &self, request_ctx: &McpContext, params: ListToolsParams, session_state: Option<&SessionState>, ) -> McpResult<ListToolsResult>

Handles the tools/list request.

If session_state is provided, disabled tools will be filtered out. If include_tags/exclude_tags are provided, tools are filtered by tags.

Source

pub fn handle_tools_call( &self, request_ctx: &McpContext, params: CallToolParams, session_state: SessionState, notification_sender: Option<&NotificationSender>, bidirectional_senders: Option<&BidirectionalSenders>, ) -> McpResult<CallToolResult>

Handles the tools/call request.

§Arguments
  • request_ctx - Request authority for cancellation, identity, auth, and accounting
  • params - The tool call parameters including tool name and arguments
  • session_state - Session state for per-session storage
  • notification_sender - Optional callback for sending progress notifications
  • bidirectional_senders - Optional senders for sampling/elicitation
Source

pub fn handle_resources_list( &self, request_ctx: &McpContext, params: ListResourcesParams, session_state: Option<&SessionState>, ) -> McpResult<ListResourcesResult>

Handles the resources/list request.

If session_state is provided, disabled resources will be filtered out. If include_tags/exclude_tags are provided, resources are filtered by tags.

Source

pub fn handle_resource_templates_list( &self, request_ctx: &McpContext, params: ListResourceTemplatesParams, session_state: Option<&SessionState>, ) -> McpResult<ListResourceTemplatesResult>

Handles the resources/templates/list request.

If session_state is provided, disabled resource templates will be filtered out. If include_tags/exclude_tags are provided, templates are filtered by tags.

Source

pub fn handle_resources_read( &self, request_ctx: &McpContext, params: &ReadResourceParams, session_state: SessionState, notification_sender: Option<&NotificationSender>, bidirectional_senders: Option<&BidirectionalSenders>, ) -> McpResult<ReadResourceResult>

Handles the resources/read request.

§Arguments
  • request_ctx - Request authority for cancellation, identity, auth, and accounting
  • params - The resource read parameters including URI
  • session_state - Session state for per-session storage
  • notification_sender - Optional callback for sending progress notifications
  • bidirectional_senders - Optional senders for sampling/elicitation
Source

pub fn handle_prompts_list( &self, request_ctx: &McpContext, params: ListPromptsParams, session_state: Option<&SessionState>, ) -> McpResult<ListPromptsResult>

Handles the prompts/list request.

If session_state is provided, disabled prompts will be filtered out. If include_tags/exclude_tags are provided, prompts are filtered by tags.

Source

pub fn handle_prompts_get( &self, request_ctx: &McpContext, params: GetPromptParams, session_state: SessionState, notification_sender: Option<&NotificationSender>, bidirectional_senders: Option<&BidirectionalSenders>, ) -> McpResult<GetPromptResult>

Handles the prompts/get request.

§Arguments
  • request_ctx - Request authority for cancellation, identity, auth, and accounting
  • params - The prompt get parameters including name and arguments
  • session_state - Session state for per-session storage
  • notification_sender - Optional callback for sending progress notifications
  • bidirectional_senders - Optional senders for sampling/elicitation
Source§

impl Router

Source

pub fn mount(&mut self, other: Router, prefix: Option<&str>) -> MountResult

Mounts all handlers from another router with an optional prefix.

This consumes the source router and moves its handlers into this router. Names/URIs are prefixed with prefix/ if a prefix is provided.

§Example
let mut main_router = Router::new();
let db_router = Router::new();
// ... add handlers to db_router ...

main_router.mount(db_router, Some("db"));
// Tool "query" becomes "db/query"
Source

pub fn mount_with_behavior( &mut self, other: Router, prefix: Option<&str>, behavior: DuplicateBehavior, ) -> MountResult

Mounts all handlers using the specified duplicate behavior.

Prefix validation happens before any destination mutation. With crate::DuplicateBehavior::Error, every selected component is preflighted and any conflict rejects the entire mount atomically.

Source

pub fn mount_namespaced_with_behavior( &mut self, other: Router, prefix: Option<&str>, behavior: DuplicateBehavior, ) -> MountResult

Mounts tools and prompts with an optional name prefix, and keeps resource and template keys exact.

A nonempty {prefix}/{uri} key is not an absolute final URI. Callers that need a modern resource catalog after namespacing tools/prompts must preserve the child’s resource URIs instead of prefixing them.

Source

pub fn mount_tools( &mut self, other: Router, prefix: Option<&str>, ) -> MountResult

Mounts only tools from a router.

Source

pub fn mount_tools_with_behavior( &mut self, other: Router, prefix: Option<&str>, behavior: DuplicateBehavior, ) -> MountResult

Mounts only tools using the specified duplicate behavior.

Source

pub fn mount_resources( &mut self, other: Router, prefix: Option<&str>, ) -> MountResult

Mounts only resources from a router.

Source

pub fn mount_resources_with_behavior( &mut self, other: Router, prefix: Option<&str>, behavior: DuplicateBehavior, ) -> MountResult

Mounts resources and resource templates using the specified duplicate behavior.

Source

pub fn mount_prompts( &mut self, other: Router, prefix: Option<&str>, ) -> MountResult

Mounts only prompts from a router.

Source

pub fn mount_prompts_with_behavior( &mut self, other: Router, prefix: Option<&str>, behavior: DuplicateBehavior, ) -> MountResult

Mounts only prompts using the specified duplicate behavior.

Trait Implementations§

Source§

impl Default for Router

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, _span: NoopSpan) -> Self

Instruments this future with a span (no-op when disabled).
Source§

fn in_current_span(self) -> Self

Instruments this future with the current span (no-op when disabled).
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more