pub struct CapabilityFilter<T: Filterable> { /* private fields */ }Expand description
A filter for capabilities based on session state.
Use this to control which tools, resources, or prompts are visible to each session.
§Example
use tower_mcp::{CapabilityFilter, DenialBehavior, Tool, Filterable};
// Filter that only shows tools starting with "public_"
let filter = CapabilityFilter::new(|_session, tool: &Tool| {
tool.name().starts_with("public_")
});
// Filter with custom denial behavior
let filter_with_401 = CapabilityFilter::new(|_session, tool: &Tool| {
tool.name() != "admin"
}).denial_behavior(DenialBehavior::Unauthorized);Implementations§
Source§impl<T: Filterable> CapabilityFilter<T>
impl<T: Filterable> CapabilityFilter<T>
Sourcepub fn new<F>(filter: F) -> Self
pub fn new<F>(filter: F) -> Self
Create a new capability filter with the given predicate.
The predicate receives the session state and capability, and returns
true if the capability should be visible to the session.
§Example
use tower_mcp::{CapabilityFilter, Tool, Filterable};
let filter = CapabilityFilter::new(|_session, tool: &Tool| {
// Check session extensions for auth claims
// session.extensions().get::<UserClaims>()...
tool.name() != "admin_only"
});Sourcepub fn denial_behavior(self, behavior: DenialBehavior) -> Self
pub fn denial_behavior(self, behavior: DenialBehavior) -> Self
Set the behavior when a filtered capability is accessed directly.
Default is DenialBehavior::NotFound.
§Example
use tower_mcp::{CapabilityFilter, DenialBehavior, Tool, Filterable};
let filter = CapabilityFilter::new(|_, tool: &Tool| tool.name() != "secret")
.denial_behavior(DenialBehavior::Unauthorized);Sourcepub fn is_visible(&self, session: &SessionState, capability: &T) -> bool
pub fn is_visible(&self, session: &SessionState, capability: &T) -> bool
Check if the given capability is visible to the session.
Sourcepub fn denial_error(&self, name: &str) -> Error
pub fn denial_error(&self, name: &str) -> Error
Get the error to return when access is denied.
Source§impl CapabilityFilter<Tool>
impl CapabilityFilter<Tool>
Sourcepub fn write_guard<F>(is_write_allowed: F) -> Self
pub fn write_guard<F>(is_write_allowed: F) -> Self
Create a filter that blocks non-read-only tools when the predicate returns false.
Read-only tools (those with read_only_hint = true) are always allowed.
Non-read-only tools are only allowed when is_write_allowed returns true
for the current session.
This provides annotation-based write protection without requiring manual guards in every write tool handler.
§Example
use tower_mcp::{CapabilityFilter, Tool};
// Block all write tools unconditionally
let filter = CapabilityFilter::<Tool>::write_guard(|_session| false);
// Allow writes based on session state
// let filter = CapabilityFilter::<Tool>::write_guard(|session| {
// session.get::<WriteEnabled>().is_some()
// });