Skip to main content

RequestContext

Struct RequestContext 

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

Context for a request, providing progress, cancellation, and client request support

Implementations§

Source§

impl RequestContext

Source

pub fn new(request_id: RequestId) -> Self

Create a new request context

Source

pub fn with_progress_token(self, token: ProgressToken) -> Self

Set the progress token

Source

pub fn with_notification_sender(self, tx: NotificationSender) -> Self

Set the notification sender

Source

pub fn with_client_requester(self, requester: ClientRequesterHandle) -> Self

Set the client requester for server-to-client requests

Source

pub fn with_extensions(self, extensions: Arc<Extensions>) -> Self

Set the extensions for this request context.

Extensions allow router-level state and middleware data to flow to handlers.

Source

pub fn extension<T: Send + Sync + 'static>(&self) -> Option<&T>

Get a reference to a value from the extensions map.

Returns None if no value of the given type has been inserted.

§Example
#[derive(Clone)]
struct CurrentUser { id: String }

// In a handler:
if let Some(user) = ctx.extension::<CurrentUser>() {
    println!("User: {}", user.id);
}
Source

pub fn extensions_mut(&mut self) -> &mut Extensions

Get a mutable reference to the extensions.

This allows middleware to insert data that handlers can access via the Extension<T> extractor.

Source

pub fn extensions(&self) -> &Extensions

Get a reference to the extensions.

Source

pub fn request_id(&self) -> &RequestId

Get the request ID

Source

pub fn progress_token(&self) -> Option<&ProgressToken>

Get the progress token (if any)

Source

pub fn is_cancelled(&self) -> bool

Check if the request has been cancelled

Source

pub fn cancel(&self)

Mark the request as cancelled

Source

pub fn cancellation_token(&self) -> CancellationToken

Get a cancellation token that can be shared

Source

pub async fn report_progress( &self, progress: f64, total: Option<f64>, message: Option<&str>, )

Report progress to the client

This is a no-op if no progress token was provided or no notification sender is configured.

Source

pub fn report_progress_sync( &self, progress: f64, total: Option<f64>, message: Option<&str>, )

Report progress synchronously (non-async version)

This is a no-op if no progress token was provided or no notification sender is configured.

Source

pub fn send_log(&self, params: LoggingMessageParams)

Send a log message notification to the client

This is a no-op if no notification sender is configured.

§Example
use tower_mcp::protocol::{LoggingMessageParams, LogLevel};

async fn my_tool(ctx: RequestContext) {
    ctx.send_log(
        LoggingMessageParams::new(LogLevel::Info)
            .with_logger("my-tool")
            .with_data(serde_json::json!("Processing..."))
    );
}
Source

pub fn can_sample(&self) -> bool

Check if sampling is available

Returns true if a client requester is configured and the transport supports bidirectional communication.

Source

pub async fn sample( &self, params: CreateMessageParams, ) -> Result<CreateMessageResult>

Request an LLM completion from the client

This sends a sampling/createMessage request to the client and waits for the response. The client is expected to forward this to an LLM and return the result.

Returns an error if sampling is not available (no client requester configured).

§Example
use tower_mcp::{CreateMessageParams, SamplingMessage};

async fn my_tool(ctx: RequestContext, input: MyInput) -> Result<CallToolResult> {
    let params = CreateMessageParams::new(
        vec![SamplingMessage::user("Summarize: ...")],
        500,
    );

    let result = ctx.sample(params).await?;
    Ok(CallToolResult::text(format!("{:?}", result.content)))
}
Source

pub fn can_elicit(&self) -> bool

Check if elicitation is available

Returns true if a client requester is configured and the transport supports bidirectional communication. Note that this only checks if the mechanism is available, not whether the client supports elicitation.

Source

pub async fn elicit_form( &self, params: ElicitFormParams, ) -> Result<ElicitResult>

Request user input via a form from the client

This sends an elicitation/create request to the client with a form schema. The client renders the form to the user and returns their response.

Returns an error if elicitation is not available (no client requester configured).

§Example
use tower_mcp::{ElicitFormParams, ElicitFormSchema, ElicitMode, ElicitAction};

async fn my_tool(ctx: RequestContext, input: MyInput) -> Result<CallToolResult> {
    let params = ElicitFormParams {
        mode: ElicitMode::Form,
        message: "Please enter your details".to_string(),
        requested_schema: ElicitFormSchema::new()
            .string_field("name", Some("Your name"), true),
        meta: None,
    };

    let result = ctx.elicit_form(params).await?;
    match result.action {
        ElicitAction::Accept => {
            // Use result.content
            Ok(CallToolResult::text("Got your input!"))
        }
        _ => Ok(CallToolResult::text("User declined"))
    }
}
Source

pub async fn elicit_url(&self, params: ElicitUrlParams) -> Result<ElicitResult>

Request user input via URL redirect from the client

This sends an elicitation/create request to the client with a URL. The client directs the user to the URL for out-of-band input collection. The server receives the result via a callback notification.

Returns an error if elicitation is not available (no client requester configured).

§Example
use tower_mcp::{ElicitUrlParams, ElicitMode, ElicitAction};

async fn my_tool(ctx: RequestContext, input: MyInput) -> Result<CallToolResult> {
    let params = ElicitUrlParams {
        mode: ElicitMode::Url,
        elicitation_id: "unique-id-123".to_string(),
        message: "Please authorize via the link".to_string(),
        url: "https://example.com/auth?id=unique-id-123".to_string(),
        meta: None,
    };

    let result = ctx.elicit_url(params).await?;
    match result.action {
        ElicitAction::Accept => Ok(CallToolResult::text("Authorization complete!")),
        _ => Ok(CallToolResult::text("Authorization cancelled"))
    }
}

Trait Implementations§

Source§

impl Clone for RequestContext

Source§

fn clone(&self) -> RequestContext

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for RequestContext

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. 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<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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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