Skip to main content

ResourceBuilder

Struct ResourceBuilder 

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

Builder for creating resources with a fluent API

§Example

use tower_mcp::resource::ResourceBuilder;
use tower_mcp::protocol::{ReadResourceResult, ResourceContent};

let resource = ResourceBuilder::new("file:///config.json")
    .name("Configuration")
    .description("Application configuration file")
    .mime_type("application/json")
    .handler(|| async {
        Ok(ReadResourceResult {
            contents: vec![ResourceContent {
                uri: "file:///config.json".to_string(),
                mime_type: Some("application/json".to_string()),
                text: Some(r#"{"setting": "value"}"#.to_string()),
                blob: None,
                meta: None,
            }],
            meta: None,
        })
    })
    .build();

assert_eq!(resource.uri, "file:///config.json");

Implementations§

Source§

impl ResourceBuilder

Source

pub fn new(uri: impl Into<String>) -> Self

Create a new resource builder with the given URI.

Source

pub fn name(self, name: impl Into<String>) -> Self

Set the resource name (human-readable)

Source

pub fn title(self, title: impl Into<String>) -> Self

Set a human-readable title for the resource

Source

pub fn description(self, description: impl Into<String>) -> Self

Set the resource description

Source

pub fn mime_type(self, mime_type: impl Into<String>) -> Self

Set the MIME type of the resource

Source

pub fn icon(self, src: impl Into<String>) -> Self

Add an icon for the resource

Source

pub fn icon_with_meta( self, src: impl Into<String>, mime_type: Option<String>, sizes: Option<Vec<String>>, ) -> Self

Add an icon with metadata

Source

pub fn size(self, size: u64) -> Self

Set the size of the resource in bytes

Source

pub fn annotations(self, annotations: ContentAnnotations) -> Self

Set annotations (audience, priority hints) for this resource

Source

pub fn handler<F, Fut>(self, handler: F) -> ResourceBuilderWithHandler<F>
where F: Fn() -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<ReadResourceResult>> + Send + 'static,

Set the handler function for reading the resource.

Returns a [ResourceBuilderWithHandler] that can be used to apply middleware layers via .layer() or build the resource directly via .build().

§Sharing State

Capture an Arc in the closure to share state across handler invocations or with other parts of your application:

use std::sync::Arc;
use tokio::sync::RwLock;
use tower_mcp::resource::ResourceBuilder;
use tower_mcp::protocol::{ReadResourceResult, ResourceContent};

let db = Arc::new(RwLock::new(vec!["initial".to_string()]));

let db_clone = Arc::clone(&db);
let resource = ResourceBuilder::new("app://entries")
    .name("Entries")
    .handler(move || {
        let db = Arc::clone(&db_clone);
        async move {
            let entries = db.read().await;
            Ok(ReadResourceResult {
                contents: vec![ResourceContent {
                    uri: "app://entries".to_string(),
                    mime_type: Some("text/plain".to_string()),
                    text: Some(entries.join("\n")),
                    blob: None,
                    meta: None,
                }],
                meta: None,
            })
        }
    })
    .build();
Source

pub fn handler_with_context<F, Fut>( self, handler: F, ) -> ResourceBuilderWithContextHandler<F>
where F: Fn(RequestContext) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<ReadResourceResult>> + Send + 'static,

Set a context-aware handler for reading the resource.

The handler receives a RequestContext for progress reporting and cancellation checking.

Returns a [ResourceBuilderWithContextHandler] that can be used to apply middleware layers via .layer() or build the resource directly via .build().

Source

pub fn text(self, content: impl Into<String>) -> Resource

Create a static text resource (convenience method)

Source

pub fn json(self, value: Value) -> Resource

Create a static JSON resource (convenience method)

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<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<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: 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, 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<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