Skip to main content

Context

Struct Context 

Source
pub struct Context<'a> {
    pub request_id: &'a RequestId,
    pub progress_token: Option<&'a ProgressToken>,
    pub client_caps: &'a ClientCapabilities,
    pub server_caps: &'a ServerCapabilities,
    pub protocol_version: ProtocolVersion,
    /* private fields */
}
Expand description

Request context passed to handler methods.

The context uses lifetime references to avoid 'static requirements and Arc overhead. This enables:

  • Single-threaded async without Arc overhead
  • !Send types in handlers (important for some runtimes)
  • Users who need spawning can wrap in Arc themselves

Per the plan: “Request context - passed by reference, NO ’static requirement”

Fields§

§request_id: &'a RequestId

The request ID for this operation.

§progress_token: Option<&'a ProgressToken>

Optional progress token for reporting progress.

§client_caps: &'a ClientCapabilities

Client capabilities negotiated during initialization.

§server_caps: &'a ServerCapabilities

Server capabilities advertised during initialization.

§protocol_version: ProtocolVersion

The negotiated protocol version.

Use this to check version-specific feature availability via methods like supports_tasks(), supports_elicitation(), etc.

Implementations§

Source§

impl<'a> Context<'a>

Source

pub fn new( request_id: &'a RequestId, progress_token: Option<&'a ProgressToken>, client_caps: &'a ClientCapabilities, server_caps: &'a ServerCapabilities, protocol_version: ProtocolVersion, peer: &'a dyn Peer, ) -> Self

Create a new context with all required references.

Source

pub fn with_cancellation( request_id: &'a RequestId, progress_token: Option<&'a ProgressToken>, client_caps: &'a ClientCapabilities, server_caps: &'a ServerCapabilities, protocol_version: ProtocolVersion, peer: &'a dyn Peer, cancel: CancellationToken, ) -> Self

Create a new context with a custom cancellation token.

Source

pub fn for_notification( client_caps: &'a ClientCapabilities, server_caps: &'a ServerCapabilities, protocol_version: ProtocolVersion, peer: &'a dyn Peer, ) -> Self

Create a context for handling an inbound client notification.

Notifications carry no JSON-RPC request id, so request_id is a documented sentinel (__notification__) that must not be treated as a real id. The context is still outbound-capable: a hook may call list_roots or send notifications, and those server-to-client requests allocate their own ids via the peer.

Associate this context with a task.

Every outbound request made through it then carries _meta["io.modelcontextprotocol/related-task"] with task_id, which the spec requires of messages related to a task:

All requests, notifications, and responses related to a task MUST include the io.modelcontextprotocol/related-task key in their _meta field […] an elicitation that a task-augmented tool call depends on MUST share the same related task ID with that tool call’s task.

Applied automatically by the task-augmented tool path; call this only when driving a task yourself.

Source

pub const fn related_task(&self) -> Option<&TaskId>

The task this request is part of, if any.

Source

pub fn is_cancelled(&self) -> bool

Check if the request has been cancelled.

Source

pub fn cancelled(&self) -> impl Future<Output = ()> + '_

Get a future that completes when the request is cancelled.

Source

pub const fn cancellation_token(&self) -> &CancellationToken

Get the cancellation token for this context.

Source

pub async fn notify( &self, method: &str, params: Option<Value>, ) -> Result<(), McpError>

Send a notification to the client.

§Arguments
  • method - The notification method name
  • params - Optional notification parameters
§Errors

Returns an error if the notification could not be sent.

Source

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

Report progress for this operation.

This sends a progress notification to the client if a progress token was provided with the request.

§Arguments
  • current - Current progress value
  • total - Total progress value (if known)
  • message - Optional progress message
§Errors

Returns an error if the notification could not be sent.

Source

pub async fn log( &self, level: LoggingLevel, logger: Option<&str>, data: Value, ) -> Result<(), McpError>

Emit a notifications/message log to the client at level, optionally tagged with a logger name and carrying arbitrary JSON data.

§Errors

Returns an error if the notification could not be sent.

Source

pub async fn request( &self, method: impl Into<Cow<'static, str>>, params: Option<Value>, ) -> Result<Value, McpError>

Send a request to the client and await its response.

This is the basis for server-initiated requests (e.g. elicitation, sampling). The peer assigns the request id and correlates the response; the request is aborted if this context is cancelled.

§Errors

Returns an error if the request was cancelled, the peer does not support requests, the request timed out, or the response carried a JSON-RPC error.

Source

pub async fn elicit( &self, request: ElicitRequest, ) -> Result<ElicitResult, McpError>

Request structured input from the user through the client (form-mode elicitation).

Sends an elicitation/create request and awaits the user’s response (accept with content, decline, or cancel). This requires the client to have declared the elicitation capability and the negotiated protocol version to support elicitation.

§Errors

Returns an error if the client did not declare elicitation support, the negotiated protocol version predates elicitation, the request was cancelled or timed out, or the response could not be parsed.

Source

pub async fn list_roots(&self) -> Result<Vec<Root>, McpError>

Request the roots this client exposes (roots/list).

Requires the client to have declared the roots capability.

§Errors

Returns an error if the client did not declare roots support, or the request fails, times out, or the response could not be parsed.

Source

pub async fn elicit_url( &self, request: UrlElicitRequest, ) -> Result<ElicitResult, McpError>

Request a URL-mode elicitation: ask the client to have the user navigate to a URL for an out-of-band interaction (e.g. authorization or payment).

Returns the client’s ElicitResult action once the user consents to open the URL. When the out-of-band interaction later finishes, notify the client with ServerNotifier::elicitation_complete(elicitation_id).

Gated on the client’s elicitation.url sub-capability (which is only declared on 2025-11-25+).

§Security

Per the MCP spec, the caller MUST use an unguessable elicitation_id bound to a verified user identity and MUST NOT place credentials in the URL. mcpkit provides the mechanism; associating the id with a user is the application’s responsibility (see the session-binding helpers, #86).

§Errors

Returns an error if the negotiated protocol version does not support elicitation, the client did not declare URL-mode elicitation, or the request fails.

Source

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

Request the client to run an LLM completion (sampling).

Sends a sampling/createMessage request and awaits the generated message. This requires the client to have declared the sampling capability (sampling is available in every protocol version).

§Errors

Returns an error if the client did not declare sampling support, the request was cancelled or timed out, or the response could not be parsed.

Trait Implementations§

Source§

impl Debug for Context<'_>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'a> !RefUnwindSafe for Context<'a>

§

impl<'a> !UnwindSafe for Context<'a>

§

impl<'a> Freeze for Context<'a>

§

impl<'a> Send for Context<'a>

§

impl<'a> Sync for Context<'a>

§

impl<'a> Unpin for Context<'a>

§

impl<'a> UnsafeUnpin for Context<'a>

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<D> OwoColorize for D

Source§

fn fg<C>(&self) -> FgColorDisplay<'_, C, Self>
where C: Color,

Set the foreground color generically Read more
Source§

fn bg<C>(&self) -> BgColorDisplay<'_, C, Self>
where C: Color,

Set the background color generically. Read more
Source§

fn black(&self) -> FgColorDisplay<'_, Black, Self>

Change the foreground color to black
Source§

fn on_black(&self) -> BgColorDisplay<'_, Black, Self>

Change the background color to black
Source§

fn red(&self) -> FgColorDisplay<'_, Red, Self>

Change the foreground color to red
Source§

fn on_red(&self) -> BgColorDisplay<'_, Red, Self>

Change the background color to red
Source§

fn green(&self) -> FgColorDisplay<'_, Green, Self>

Change the foreground color to green
Source§

fn on_green(&self) -> BgColorDisplay<'_, Green, Self>

Change the background color to green
Source§

fn yellow(&self) -> FgColorDisplay<'_, Yellow, Self>

Change the foreground color to yellow
Source§

fn on_yellow(&self) -> BgColorDisplay<'_, Yellow, Self>

Change the background color to yellow
Source§

fn blue(&self) -> FgColorDisplay<'_, Blue, Self>

Change the foreground color to blue
Source§

fn on_blue(&self) -> BgColorDisplay<'_, Blue, Self>

Change the background color to blue
Source§

fn magenta(&self) -> FgColorDisplay<'_, Magenta, Self>

Change the foreground color to magenta
Source§

fn on_magenta(&self) -> BgColorDisplay<'_, Magenta, Self>

Change the background color to magenta
Source§

fn purple(&self) -> FgColorDisplay<'_, Magenta, Self>

Change the foreground color to purple
Source§

fn on_purple(&self) -> BgColorDisplay<'_, Magenta, Self>

Change the background color to purple
Source§

fn cyan(&self) -> FgColorDisplay<'_, Cyan, Self>

Change the foreground color to cyan
Source§

fn on_cyan(&self) -> BgColorDisplay<'_, Cyan, Self>

Change the background color to cyan
Source§

fn white(&self) -> FgColorDisplay<'_, White, Self>

Change the foreground color to white
Source§

fn on_white(&self) -> BgColorDisplay<'_, White, Self>

Change the background color to white
Source§

fn default_color(&self) -> FgColorDisplay<'_, Default, Self>

Change the foreground color to the terminal default
Source§

fn on_default_color(&self) -> BgColorDisplay<'_, Default, Self>

Change the background color to the terminal default
Source§

fn bright_black(&self) -> FgColorDisplay<'_, BrightBlack, Self>

Change the foreground color to bright black
Source§

fn on_bright_black(&self) -> BgColorDisplay<'_, BrightBlack, Self>

Change the background color to bright black
Source§

fn bright_red(&self) -> FgColorDisplay<'_, BrightRed, Self>

Change the foreground color to bright red
Source§

fn on_bright_red(&self) -> BgColorDisplay<'_, BrightRed, Self>

Change the background color to bright red
Source§

fn bright_green(&self) -> FgColorDisplay<'_, BrightGreen, Self>

Change the foreground color to bright green
Source§

fn on_bright_green(&self) -> BgColorDisplay<'_, BrightGreen, Self>

Change the background color to bright green
Source§

fn bright_yellow(&self) -> FgColorDisplay<'_, BrightYellow, Self>

Change the foreground color to bright yellow
Source§

fn on_bright_yellow(&self) -> BgColorDisplay<'_, BrightYellow, Self>

Change the background color to bright yellow
Source§

fn bright_blue(&self) -> FgColorDisplay<'_, BrightBlue, Self>

Change the foreground color to bright blue
Source§

fn on_bright_blue(&self) -> BgColorDisplay<'_, BrightBlue, Self>

Change the background color to bright blue
Source§

fn bright_magenta(&self) -> FgColorDisplay<'_, BrightMagenta, Self>

Change the foreground color to bright magenta
Source§

fn on_bright_magenta(&self) -> BgColorDisplay<'_, BrightMagenta, Self>

Change the background color to bright magenta
Source§

fn bright_purple(&self) -> FgColorDisplay<'_, BrightMagenta, Self>

Change the foreground color to bright purple
Source§

fn on_bright_purple(&self) -> BgColorDisplay<'_, BrightMagenta, Self>

Change the background color to bright purple
Source§

fn bright_cyan(&self) -> FgColorDisplay<'_, BrightCyan, Self>

Change the foreground color to bright cyan
Source§

fn on_bright_cyan(&self) -> BgColorDisplay<'_, BrightCyan, Self>

Change the background color to bright cyan
Source§

fn bright_white(&self) -> FgColorDisplay<'_, BrightWhite, Self>

Change the foreground color to bright white
Source§

fn on_bright_white(&self) -> BgColorDisplay<'_, BrightWhite, Self>

Change the background color to bright white
Source§

fn bold(&self) -> BoldDisplay<'_, Self>

Make the text bold
Source§

fn dimmed(&self) -> DimDisplay<'_, Self>

Make the text dim
Source§

fn italic(&self) -> ItalicDisplay<'_, Self>

Make the text italicized
Source§

fn underline(&self) -> UnderlineDisplay<'_, Self>

Make the text underlined
Make the text blink
Make the text blink (but fast!)
Source§

fn reversed(&self) -> ReversedDisplay<'_, Self>

Swap the foreground and background colors
Source§

fn hidden(&self) -> HiddenDisplay<'_, Self>

Hide the text
Source§

fn strikethrough(&self) -> StrikeThroughDisplay<'_, Self>

Cross out the text
Source§

fn color<Color>(&self, color: Color) -> FgDynColorDisplay<'_, Color, Self>
where Color: DynColor,

Set the foreground color at runtime. Only use if you do not know which color will be used at compile-time. If the color is constant, use either OwoColorize::fg or a color-specific method, such as OwoColorize::green, Read more
Source§

fn on_color<Color>(&self, color: Color) -> BgDynColorDisplay<'_, Color, Self>
where Color: DynColor,

Set the background color at runtime. Only use if you do not know what color to use at compile-time. If the color is constant, use either OwoColorize::bg or a color-specific method, such as OwoColorize::on_yellow, Read more
Source§

fn fg_rgb<const R: u8, const G: u8, const B: u8>( &self, ) -> FgColorDisplay<'_, CustomColor<R, G, B>, Self>

Set the foreground color to a specific RGB value.
Source§

fn bg_rgb<const R: u8, const G: u8, const B: u8>( &self, ) -> BgColorDisplay<'_, CustomColor<R, G, B>, Self>

Set the background color to a specific RGB value.
Source§

fn truecolor(&self, r: u8, g: u8, b: u8) -> FgDynColorDisplay<'_, Rgb, Self>

Sets the foreground color to an RGB value.
Source§

fn on_truecolor(&self, r: u8, g: u8, b: u8) -> BgDynColorDisplay<'_, Rgb, Self>

Sets the background color to an RGB value.
Source§

fn style(&self, style: Style) -> Styled<&Self>

Apply a runtime-determined style
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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