Skip to main content

Ctx

Struct Ctx 

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

Context of the request being handled. Declare a Ctx parameter in a tool to receive it; it is excluded from the tool’s input schema.

Cloning is cheap.

Implementations§

Source§

impl Ctx

Source

pub fn client_supports_apps(&self) -> bool

Whether the client can render MCP Apps interfaces (it declared the extension with the text/html;profile=mcp-app MIME type). A tool can return a richer text answer when it cannot.

Source§

impl Ctx

Source

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

The caller authenticated by the HTTP transport’s OAuth layer; None when the server does not require authorization (or over stdio).

Source§

impl Ctx

Source

pub fn request_id(&self) -> &RequestId

The JSON-RPC id of the request.

Source

pub fn protocol_version(&self) -> &str

The protocol version the client used for this request.

Source

pub fn client_capabilities(&self) -> &ClientCapabilities

The capabilities the client declared for this request.

Source

pub fn client_info(&self) -> Option<&Implementation>

The client’s self-reported identity. Informational only: never use it for security decisions.

Source

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

The progress token, when the client asked for progress notifications.

Source

pub fn client_supports_extension(&self, id: &str) -> bool

Whether the client declared support for an extension.

Source

pub fn cancellation(&self) -> &CancellationToken

A token cancelled when the client cancels the request (stdio notifications/cancelled, or the HTTP response stream closing). Long-running tools should stop work when it fires.

Source

pub fn is_cancelled(&self) -> bool

Whether the request has been cancelled.

Source

pub fn transport(&self) -> &TransportContext

Values attached by the transport.

Source

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

Shared state registered with ServerBuilder::state.

Source§

impl Ctx

Source

pub fn input_round(&self) -> u32

The number of input rounds completed before this attempt: 0 on the first call, 1 after the client answered once, and so on.

Source

pub fn input_response<T: DeserializeOwned>( &self, key: &str, ) -> Result<Option<T>, ToolError>

The client’s answer for key, decoded as T, if it sent one in this round or an earlier one.

§Errors

Returns an invalid-params error (-32602) if the answer does not decode as T.

Source

pub async fn elicit<T: DeserializeOwned + JsonSchema>( &self, key: &str, message: impl Into<String>, ) -> Result<T, ToolError>

Asks the user for structured input with a form generated from T (a flat struct of strings, numbers, booleans and enums). Declining or cancelling becomes a ToolError::user; use elicit_with_action to handle them.

key identifies the question across rounds and must be unique within the handler. Several questions can be asked in one round by awaiting them together (for example with tokio::join!).

§Errors

Fails with an “input required” error when the answer is not available yet (propagate it with ?), -32021 if the client does not support form elicitation, and -32602 if the answer is malformed.

Source

pub async fn elicit_with_action<T: DeserializeOwned + JsonSchema>( &self, key: &str, message: impl Into<String>, ) -> Result<Elicitation<T>, ToolError>

Like elicit, but returns declined and cancelled answers instead of failing.

§Errors

See elicit.

Source

pub async fn elicit_with_schema( &self, key: &str, message: impl Into<String>, requested_schema: Value, ) -> Result<Elicitation<Map<String, Value>>, ToolError>

Like elicit_with_action, with a hand-written requestedSchema (for default values, titled enums or multi-select fields, which a derived schema cannot express). The accepted content comes back as JSON, for the handler to validate.

§Errors

See elicit.

Source

pub async fn sample( &self, key: &str, params: CreateMessageRequestParams, ) -> Result<CreateMessageResult, ToolError>

👎Deprecated:

Sampling is deprecated as of protocol version 2026-07-28 (SEP-2577).

Asks the client to sample from a language model.

§Errors

Fails with an “input required” error when the answer is not available yet (propagate it with ?), -32021 if the client does not support sampling, and -32602 if the answer is malformed.

Source

pub async fn list_roots(&self, key: &str) -> Result<ListRootsResult, ToolError>

👎Deprecated:

Roots are deprecated as of protocol version 2026-07-28 (SEP-2577).

Asks the client for its filesystem roots.

§Errors

Fails with an “input required” error when the answer is not available yet (propagate it with ?), -32021 if the client does not support roots, and -32602 if the answer is malformed.

Source§

impl Ctx

Source

pub fn progress(&self, progress: f64, total: impl Into<Option<f64>>)

Reports progress to the client (notifications/progress), when it asked for it with a progressToken; otherwise does nothing.

Never blocks: if the client reads slowly, only the latest update is kept, and it arrives before the result. progress must increase from one call to the next (smaller values are ignored); total may be omitted with None.

ⓘ
for (i, file) in files.iter().enumerate() {
    ctx.progress(i as f64, files.len() as f64);
    load(file).await;
}
Source

pub fn progress_message( &self, progress: f64, total: impl Into<Option<f64>>, message: impl AsRef<str>, )

Like progress, with a human-readable message.

Source

pub fn wants_progress(&self) -> bool

Whether the client asked for progress notifications.

Source

pub fn log(&self, level: LoggingLevel, data: impl Serialize)

👎Deprecated:

Logging is deprecated as of protocol version 2026-07-28 (SEP-2577); log to stderr with tracing instead.

Sends a log message to the client (notifications/message), when it asked for messages at this level or above; otherwise does nothing. Never blocks; messages beyond the buffer are dropped.

Do not include secrets or internal details: the client sees data. For the server’s own logs, use tracing (stderr).

Trait Implementations§

Source§

impl Clone for Ctx

Source§

fn clone(&self) -> Self

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 Ctx

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Ctx

§

impl !UnwindSafe for Ctx

§

impl Freeze for Ctx

§

impl Send for Ctx

§

impl Sync for Ctx

§

impl Unpin for Ctx

§

impl UnsafeUnpin for Ctx

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<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

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> Same for T

Source§

type Output = T

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

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

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