Skip to main content

RequestContext

Struct RequestContext 

Source
pub struct RequestContext {
    pub request_id: String,
    pub transport: TransportType,
    pub user_id: Option<String>,
    pub session_id: Option<String>,
    pub client_id: Option<String>,
    pub metadata: HashMap<String, Value>,
    pub principal: Option<Principal>,
    pub session: Option<Arc<dyn McpSession>>,
    pub headers: Option<HashMap<String, String>>,
    pub start_time: Option<Instant>,
    pub cancellation_token: Option<Arc<dyn Cancellable>>,
}
Expand description

Canonical per-request context.

Carries request identity, transport information, authentication principal, arbitrary typed metadata, and — when the transport supports bidirectional communication — an McpSession handle that enables server-to-client operations such as sampling and elicitation.

§Thread Safety

RequestContext is Send + Sync on native targets. On WASM targets the Send/Sync bounds are dropped (single-threaded runtime).

Fields§

§request_id: String

Unique request identifier (JSON-RPC id as string, or generated UUID).

§transport: TransportType

Transport type that received this request.

§user_id: Option<String>

Authenticated user identifier, if the request was authenticated.

§session_id: Option<String>

Session identifier for stateful transports (HTTP + session cookie, WS, Streamable HTTP, etc.).

§client_id: Option<String>

Client application identifier reported by the peer.

§metadata: HashMap<String, Value>

Rich typed metadata (headers, trace IDs, custom per-request data).

§principal: Option<Principal>

Authenticated principal, if auth is configured and succeeded.

§session: Option<Arc<dyn McpSession>>

Bidirectional session handle for server-to-client requests.

Populated by the server dispatcher before routing; None on unidirectional transports (e.g., stateless HTTP) or when the request is being synthesized (tests, examples).

§headers: Option<HashMap<String, String>>

HTTP-layer headers for HTTP/WebSocket transports.

Populated by the transport; None for non-HTTP transports. Uses hashbrown::HashMap so it stays available in no_std / WASM builds.

§start_time: Option<Instant>
Available on crate feature std only.

Wall-clock moment at which the server began processing the request.

Used for elapsed() measurements and tracing spans.

§cancellation_token: Option<Arc<dyn Cancellable>>
Available on crate feature std only.

Cooperative-cancellation handle.

Tool bodies should check ctx.is_cancelled() during long operations and abort early. The server wires a tokio_util::sync::CancellationToken in here (via the Cancellable blanket impl in turbomcp-server).

Implementations§

Source§

impl RequestContext

Source

pub fn new() -> RequestContext

Create a new request context with a freshly generated UUID and Stdio transport.

For WASM/no_std builds the request ID is empty; call Self::with_id explicitly to set one.

Source

pub fn with_id_and_transport( request_id: impl Into<String>, transport: TransportType, ) -> RequestContext

Create a context with the given ID and transport.

Source

pub fn with_id(request_id: impl Into<String>) -> RequestContext

Create a context with an explicit request ID (Stdio transport).

Source

pub fn stdio() -> RequestContext

Create a context for STDIO transport with a fresh UUID.

Source

pub fn http() -> RequestContext

Create a context for HTTP transport with a fresh UUID.

Source

pub fn websocket() -> RequestContext

Create a context for WebSocket transport with a fresh UUID.

Source

pub fn tcp() -> RequestContext

Create a context for TCP transport with a fresh UUID.

Source

pub fn unix() -> RequestContext

Create a context for Unix domain socket transport with a fresh UUID.

Source

pub fn wasm() -> RequestContext

Create a context for WASM transport with a fresh UUID.

Source

pub fn channel() -> RequestContext

Create a context for in-process channel transport with a fresh UUID.

Source§

impl RequestContext

Source

pub fn with_request_id(self, id: impl Into<String>) -> RequestContext

Set the request ID.

Source

pub fn with_transport(self, transport: TransportType) -> RequestContext

Set the transport type.

Source

pub fn with_user_id(self, user_id: impl Into<String>) -> RequestContext

Set the authenticated user ID.

Source

pub fn with_session_id(self, session_id: impl Into<String>) -> RequestContext

Set the session ID.

Source

pub fn with_client_id(self, client_id: impl Into<String>) -> RequestContext

Set the client ID.

Source

pub fn with_principal(self, principal: Principal) -> RequestContext

Set the authenticated principal.

Source

pub fn with_metadata( self, key: impl Into<String>, value: impl Into<Value>, ) -> RequestContext

Attach a metadata key/value pair.

Accepts any value convertible to serde_json::Value, so string literals, numbers, and structured data all work.

Source

pub fn with_session(self, session: Arc<dyn McpSession>) -> RequestContext

Attach a bidirectional session handle.

Source

pub fn with_headers(self, headers: HashMap<String, String>) -> RequestContext

Attach HTTP headers (case-sensitive keys; header does case-insensitive lookup).

Source

pub fn with_start_time(self, start: Instant) -> RequestContext

Available on crate feature std only.

Mark the request start time.

Source

pub fn with_cancellation_token( self, token: Arc<dyn Cancellable>, ) -> RequestContext

Available on crate feature std only.

Attach a cancellation handle.

Source§

impl RequestContext

Source

pub fn insert_metadata( &mut self, key: impl Into<String>, value: impl Into<Value>, )

Mutable metadata insert.

Source

pub fn set_principal(&mut self, principal: Principal)

Mutable principal setter.

Source

pub fn clear_principal(&mut self)

Clear the authenticated principal.

Source

pub fn set_session(&mut self, session: Arc<dyn McpSession>)

Mutable session setter.

Source§

impl RequestContext

Source

pub fn request_id(&self) -> &str

Request ID.

Source

pub fn has_request_id(&self) -> bool

Returns true when a non-empty request ID is set.

Source

pub fn transport(&self) -> TransportType

Transport type.

Source

pub fn user_id(&self) -> Option<&str>

Authenticated user ID, if present.

Source

pub fn session_id(&self) -> Option<&str>

Session ID, if present.

Source

pub fn client_id(&self) -> Option<&str>

Client ID, if present.

Source

pub fn get_metadata(&self, key: &str) -> Option<&Value>

Rich metadata lookup.

Source

pub fn get_metadata_str(&self, key: &str) -> Option<&str>

Rich metadata lookup, downcast to &str for string values.

Source

pub fn has_metadata(&self, key: &str) -> bool

Returns true when a metadata key is set.

Source

pub fn principal(&self) -> Option<&Principal>

Authenticated principal, if any.

Source

pub fn is_authenticated(&self) -> bool

Returns true when the request is authenticated.

A request is considered authenticated when it has either a principal or a user_id. Callers with richer auth semantics should read the principal directly.

Source

pub fn subject(&self) -> Option<&str>

Authenticated subject (principal subject, falling back to user_id).

Source

pub fn session(&self) -> Option<&Arc<dyn McpSession>>

Session handle, if attached.

Source

pub fn has_session(&self) -> bool

Returns true when a bidirectional session is attached.

Source

pub fn headers(&self) -> Option<&HashMap<String, String>>

All HTTP headers, if the transport captured any.

Source

pub fn header(&self, name: &str) -> Option<&str>

Case-insensitive HTTP header lookup.

Source

pub fn elapsed(&self) -> Option<Duration>

Available on crate feature std only.

Elapsed time since the request started (if start_time was set).

Source

pub fn is_cancelled(&self) -> bool

Available on crate feature std only.

Returns true when the request has been marked for cancellation.

Source

pub fn roles(&self) -> Vec<String>

Authenticated roles, sourced from the principal or from metadata.

Looks at (in order): principal.roles, metadata["auth"].roles[].

Source

pub fn has_any_role<S>(&self, required: &[S]) -> bool
where S: AsRef<str>,

Returns true when the principal has any of the specified roles. An empty required list always returns true.

Source§

impl RequestContext

Source

pub async fn sample( &self, request: CreateMessageRequest, ) -> Result<CreateMessageResult, McpError>

Request LLM sampling from the connected client.

Requires a bidirectional session; returns McpError::capability_not_supported on unidirectional transports.

Source

pub async fn elicit_form( &self, message: impl Into<String>, schema: Value, ) -> Result<ElicitResult, McpError>

Request form-based user input from the client.

Source

pub async fn elicit_url( &self, message: impl Into<String>, url: impl Into<String>, elicitation_id: impl Into<String>, ) -> Result<ElicitResult, McpError>

Request URL-based user action from the client.

Source

pub async fn notify_client( &self, method: impl AsRef<str>, params: Value, ) -> Result<(), McpError>

Send a JSON-RPC notification to the client.

Trait Implementations§

Source§

impl Clone for RequestContext

Source§

fn clone(&self) -> RequestContext

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · 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<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for RequestContext

Source§

fn default() -> RequestContext

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

impl RequestContextExt for RequestContext

Source§

fn with_enhanced_client_id(self, client_id: ClientId) -> Self

Set client_id from a structured super::client::ClientId and record the authentication method + authenticated flag in metadata.
Source§

fn extract_client_id( self, extractor: &ClientIdExtractor, headers: Option<&HashMap<String, String>>, query_params: Option<&HashMap<String, String>>, ) -> Self

Extract a client ID from headers/query params and apply it via Self::with_enhanced_client_id.
Source§

fn get_enhanced_client_id(&self) -> Option<ClientId>

Rehydrate the structured super::client::ClientId from the context.
Source§

impl RichContextExt for RequestContext

Source§

fn get_state<T: DeserializeOwned>(&self, key: &str) -> Option<T>

Get a value from session state. Read more
Source§

fn try_get_state<T: DeserializeOwned>( &self, key: &str, ) -> Result<Option<T>, StateError>

Try to get a value from session state with detailed error information. Read more
Source§

fn set_state<T: Serialize>(&self, key: &str, value: &T) -> bool

Set a value in session state. Read more
Source§

fn try_set_state<T: Serialize>( &self, key: &str, value: &T, ) -> Result<(), StateError>

Try to set a value in session state with detailed error information.
Source§

fn remove_state(&self, key: &str) -> bool

Remove a value from session state.
Source§

fn clear_state(&self)

Clear all session state.
Source§

fn has_state(&self, key: &str) -> bool

Check if a state key exists.
Source§

async fn debug( &self, message: impl Into<String> + MaybeSend, ) -> Result<(), McpError>

Send a debug-level log message to the client. Read more
Source§

async fn info( &self, message: impl Into<String> + MaybeSend, ) -> Result<(), McpError>

Send an info-level log message to the client. Read more
Source§

async fn warning( &self, message: impl Into<String> + MaybeSend, ) -> Result<(), McpError>

Send a warning-level log message to the client. Read more
Source§

async fn error( &self, message: impl Into<String> + MaybeSend, ) -> Result<(), McpError>

Send an error-level log message to the client. Read more
Source§

async fn log( &self, level: LogLevel, message: impl Into<String> + MaybeSend, logger: Option<String>, ) -> Result<(), McpError>

Send a log message to the client with a specific level. Read more
Source§

async fn report_progress( &self, current: f64, total: f64, message: Option<&str>, ) -> Result<(), McpError>

Report progress on a long-running operation. Read more
Source§

async fn report_progress_with_token( &self, token: impl Into<ProgressToken> + MaybeSend, current: f64, total: Option<f64>, message: Option<&str>, ) -> Result<(), McpError>

Report progress with a custom ProgressToken. 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> 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> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
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
Source§

impl<T> MaybeSend for T
where T: Send + ?Sized,

Source§

impl<T> MaybeSync for T
where T: Sync + ?Sized,