RequestContext

Struct RequestContext 

Source
pub struct RequestContext {
    pub request_id: String,
    pub user_id: Option<String>,
    pub session_id: Option<String>,
    pub client_id: Option<String>,
    pub timestamp: Timestamp,
    pub start_time: Instant,
    pub metadata: Arc<HashMap<String, Value>>,
    pub cancellation_token: Option<Arc<CancellationToken>>,
    /* private fields */
}
Expand description

Context information for a single MCP request, carried through its entire lifecycle.

This struct contains essential metadata for processing, logging, and tracing a request, including unique identifiers, authentication information, and mechanisms for cancellation and server-initiated communication.

Fields§

§request_id: String

A unique identifier for the request, typically a UUID.

§user_id: Option<String>

The identifier for the user making the request, if authenticated.

§session_id: Option<String>

The identifier for the session to which this request belongs.

§client_id: Option<String>

The identifier for the client application making the request.

§timestamp: Timestamp

The timestamp when the request was received.

§start_time: Instant

The Instant when request processing started, used for performance tracking.

§metadata: Arc<HashMap<String, Value>>

A collection of custom metadata for application-specific use cases.

§cancellation_token: Option<Arc<CancellationToken>>

A token that can be used to signal cancellation of the request.

Implementations§

Source§

impl RequestContext

Source

pub fn new() -> Self

Creates a new RequestContext with a generated UUIDv4 as the request ID.

Source

pub fn with_id(id: impl Into<String>) -> Self

Creates a new RequestContext with a specific request ID.

Source

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

Sets the user ID for this context, returning the modified context.

§Example
let ctx = RequestContext::new().with_user_id("user-123");
assert_eq!(ctx.user_id, Some("user-123".to_string()));
Source

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

Sets the session ID for this context, returning the modified context.

Source

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

Sets the client ID for this context, returning the modified context.

Source

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

Adds a key-value pair to the metadata, returning the modified context.

§Example
let ctx = RequestContext::new().with_metadata("tenant", json!("acme-corp"));
assert_eq!(ctx.get_metadata("tenant"), Some(&json!("acme-corp")));
Source

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

Retrieves a value from the metadata by key.

Source

pub fn elapsed(&self) -> Duration

Returns the elapsed time since the request processing started.

Source

pub fn is_cancelled(&self) -> bool

Checks if the request has been marked for cancellation.

Source

pub fn with_server_to_client( self, capabilities: Arc<dyn ServerToClientRequests>, ) -> Self

Sets the server-to-client requests interface for this context.

This enables tools to make server-initiated requests (sampling, elicitation, roots) with full context propagation for tracing and attribution. This is typically called by the server implementation.

Source

pub fn with_cancellation_token(self, token: Arc<CancellationToken>) -> Self

Sets the cancellation token for cooperative cancellation. This is typically called by the server implementation.

Source

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

Returns the user ID from the request context, if available.

Source

pub fn is_authenticated(&self) -> bool

Checks if the request is from an authenticated client. This is determined by metadata set during the authentication process.

Source

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

Returns the user roles from the request context, if available. Roles are typically populated from an authentication token.

Source

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

Checks if the user has any of the specified roles. Returns true if the required roles list is empty or if the user has at least one of the roles.

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
Source§

impl Default for RequestContext

Source§

fn default() -> Self

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

Sets the client ID using the structured ClientId enum, which includes the method of identification.
Source§

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

Extracts a client ID from headers or query parameters and sets it on the context.
Source§

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

Gets the structured ClientId enum from the context, if available.

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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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