pub struct RequestContext { /* private fields */ }Expand description
Context for a request, providing progress, cancellation, and client request support
Implementations§
Source§impl RequestContext
impl RequestContext
Sourcepub fn with_progress_token(self, token: ProgressToken) -> Self
pub fn with_progress_token(self, token: ProgressToken) -> Self
Set the progress token
Sourcepub fn with_notification_sender(self, tx: NotificationSender) -> Self
pub fn with_notification_sender(self, tx: NotificationSender) -> Self
Set the notification sender
Sourcepub fn with_min_log_level(self, level: Arc<RwLock<LogLevel>>) -> Self
pub fn with_min_log_level(self, level: Arc<RwLock<LogLevel>>) -> Self
Set the minimum log level for filtering outgoing log notifications
This is shared with the router so that logging/setLevel updates
are immediately visible to all request contexts.
Sourcepub fn with_client_requester(self, requester: ClientRequesterHandle) -> Self
pub fn with_client_requester(self, requester: ClientRequesterHandle) -> Self
Set the client requester for server-to-client requests
Sourcepub fn with_extensions(self, extensions: Arc<Extensions>) -> Self
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.
Sourcepub fn extensions_mut(&mut self) -> &mut Extensions
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.
Sourcepub fn extensions(&self) -> &Extensions
pub fn extensions(&self) -> &Extensions
Get a reference to the extensions.
Sourcepub fn request_id(&self) -> &RequestId
pub fn request_id(&self) -> &RequestId
Get the request ID
Sourcepub fn progress_token(&self) -> Option<&ProgressToken>
pub fn progress_token(&self) -> Option<&ProgressToken>
Get the progress token (if any)
Sourcepub fn is_cancelled(&self) -> bool
pub fn is_cancelled(&self) -> bool
Check if the request has been cancelled
Sourcepub fn cancellation_token(&self) -> CancellationToken
pub fn cancellation_token(&self) -> CancellationToken
Get a cancellation token that can be shared
Sourcepub async fn report_progress(
&self,
progress: f64,
total: Option<f64>,
message: Option<&str>,
)
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.
Sourcepub fn report_progress_sync(
&self,
progress: f64,
total: Option<f64>,
message: Option<&str>,
)
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.
Sourcepub fn send_log(&self, params: LoggingMessageParams)
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, serde_json::json!("Processing..."))
.with_logger("my-tool")
);
}Sourcepub fn can_sample(&self) -> bool
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.
Sourcepub async fn sample(
&self,
params: CreateMessageParams,
) -> Result<CreateMessageResult>
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)))
}Sourcepub fn can_elicit(&self) -> bool
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.
Sourcepub async fn elicit_form(
&self,
params: ElicitFormParams,
) -> Result<ElicitResult>
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: Some(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"))
}
}Sourcepub async fn elicit_url(&self, params: ElicitUrlParams) -> Result<ElicitResult>
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: Some(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"))
}
}Sourcepub async fn confirm(&self, message: impl Into<String>) -> Result<bool>
pub async fn confirm(&self, message: impl Into<String>) -> Result<bool>
Request simple confirmation from the user.
This is a convenience method for simple yes/no confirmation dialogs.
It creates an elicitation form with a single boolean “confirm” field
and returns true if the user accepts, false otherwise.
Returns an error if elicitation is not available (no client requester configured).
§Example
use tower_mcp::{RequestContext, CallToolResult};
async fn delete_item(ctx: RequestContext) -> Result<CallToolResult> {
let confirmed = ctx.confirm("Are you sure you want to delete this item?").await?;
if confirmed {
// Perform deletion
Ok(CallToolResult::text("Item deleted"))
} else {
Ok(CallToolResult::text("Deletion cancelled"))
}
}Sourcepub async fn list_tasks(
&self,
status: Option<TaskStatus>,
) -> Result<ListTasksResult>
pub async fn list_tasks( &self, status: Option<TaskStatus>, ) -> Result<ListTasksResult>
List tasks tracked by the connected client (SEP-1686).
Sends a tasks/list request to the client and returns the result.
Pass Some(status) to filter to a single status, or None for all
tasks. Pagination is exposed via ListTasksResult::next_cursor;
use request_raw for cursor-driven calls.
Returns an error if no client requester is configured or the client does not advertise task support.
Sourcepub async fn get_task_info(
&self,
task_id: impl Into<String>,
) -> Result<TaskObject>
pub async fn get_task_info( &self, task_id: impl Into<String>, ) -> Result<TaskObject>
Fetch metadata for a single task tracked by the client (SEP-1686).
Sends a tasks/get request and returns the task object, including
the current status, timestamps, and TTL.
Sourcepub async fn get_task_result(
&self,
task_id: impl Into<String>,
) -> Result<CallToolResult>
pub async fn get_task_result( &self, task_id: impl Into<String>, ) -> Result<CallToolResult>
Fetch the terminal result for a task tracked by the client (SEP-1686).
Sends a tasks/result request. The client is expected to block until
the task reaches a terminal state and then return the underlying
CallToolResult. For long-running tasks, prefer polling with
get_task_info and only call this once the
status is terminal.
Sourcepub async fn cancel_task(
&self,
task_id: impl Into<String>,
reason: Option<String>,
) -> Result<TaskObject>
pub async fn cancel_task( &self, task_id: impl Into<String>, reason: Option<String>, ) -> Result<TaskObject>
Cancel a task tracked by the client (SEP-1686).
Sends a tasks/cancel request and returns the resulting task object,
which will reflect the cancelled status.
Trait Implementations§
Source§impl Clone for RequestContext
impl Clone for RequestContext
Source§fn clone(&self) -> RequestContext
fn clone(&self) -> RequestContext
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more