pub struct McpContext { /* private fields */ }Expand description
MCP context that wraps asupersync’s capability context.
McpContext provides access to:
- Request-scoped identity (request ID, trace context)
- Cancellation checkpoints for cancel-safe handlers
- Budget/deadline awareness for timeout enforcement
- Region-scoped spawning for background work
- Sampling capability for LLM completions (if client supports it)
- Elicitation capability for user input requests (if client supports it)
- Cross-component resource reading (if router is attached)
§Example
async fn my_tool(ctx: &McpContext, args: MyArgs) -> McpResult<Value> {
// Check for client disconnect
ctx.checkpoint()?;
// Do work with budget awareness
let remaining = ctx.budget();
// Request an LLM completion (if available)
let response = ctx.sample("Write a haiku about Rust", 100).await?;
// Request user input (if available)
let input = ctx.elicit_form("Enter your name", schema).await?;
// Read a resource from within a tool
let config = ctx.read_resource("config://app").await?;
// Call another tool from within a tool
let result = ctx.call_tool("other_tool", json!({"arg": "value"})).await?;
// Return result
Ok(json!({"result": response.text}))
}Implementations§
Source§impl McpContext
impl McpContext
Sourcepub fn new(cx: Cx, request_id: u64) -> McpContext
pub fn new(cx: Cx, request_id: u64) -> McpContext
Creates a new MCP context from an asupersync Cx.
This is typically called by the server when processing a new request, creating a new region for the request lifecycle.
Sourcepub fn with_state(cx: Cx, request_id: u64, state: SessionState) -> McpContext
pub fn with_state(cx: Cx, request_id: u64, state: SessionState) -> McpContext
Creates a new MCP context with session state.
Use this constructor when session state should be accessible to handlers.
Sourcepub fn with_progress(
cx: Cx,
request_id: u64,
reporter: ProgressReporter,
) -> McpContext
pub fn with_progress( cx: Cx, request_id: u64, reporter: ProgressReporter, ) -> McpContext
Creates a new MCP context with progress reporting enabled.
Use this constructor when the client has provided a progress token and expects progress notifications.
Sourcepub fn with_state_and_progress(
cx: Cx,
request_id: u64,
state: SessionState,
reporter: ProgressReporter,
) -> McpContext
pub fn with_state_and_progress( cx: Cx, request_id: u64, state: SessionState, reporter: ProgressReporter, ) -> McpContext
Creates a new MCP context with both state and progress reporting.
Sourcepub fn with_sampling(self, sender: Arc<dyn SamplingSender>) -> McpContext
pub fn with_sampling(self, sender: Arc<dyn SamplingSender>) -> McpContext
Sets the sampling sender for this context.
This enables the sample() method to request LLM completions from
the client.
Sourcepub fn with_elicitation(self, sender: Arc<dyn ElicitationSender>) -> McpContext
pub fn with_elicitation(self, sender: Arc<dyn ElicitationSender>) -> McpContext
Sets the elicitation sender for this context.
This enables the elicit() methods to request user input from
the client.
Sourcepub fn with_resource_reader(self, reader: Arc<dyn ResourceReader>) -> McpContext
pub fn with_resource_reader(self, reader: Arc<dyn ResourceReader>) -> McpContext
Sets the resource reader for this context.
This enables the read_resource() methods to read resources from
within tool, resource, or prompt handlers.
Sourcepub fn with_resource_read_depth(self, depth: u32) -> McpContext
pub fn with_resource_read_depth(self, depth: u32) -> McpContext
Sets the resource read depth for this context.
This is used internally to track recursion depth when reading resources from within resource handlers.
Sourcepub fn with_tool_caller(self, caller: Arc<dyn ToolCaller>) -> McpContext
pub fn with_tool_caller(self, caller: Arc<dyn ToolCaller>) -> McpContext
Sets the tool caller for this context.
This enables the call_tool() methods to call other tools from
within tool, resource, or prompt handlers.
Sourcepub fn with_tool_call_depth(self, depth: u32) -> McpContext
pub fn with_tool_call_depth(self, depth: u32) -> McpContext
Sets the tool call depth for this context.
This is used internally to track recursion depth when calling tools from within tool handlers.
Sourcepub fn with_client_capabilities(
self,
capabilities: ClientCapabilityInfo,
) -> McpContext
pub fn with_client_capabilities( self, capabilities: ClientCapabilityInfo, ) -> McpContext
Sets the client capability information for this context.
This enables handlers to check what capabilities the connected client supports.
Sourcepub fn with_server_capabilities(
self,
capabilities: ServerCapabilityInfo,
) -> McpContext
pub fn with_server_capabilities( self, capabilities: ServerCapabilityInfo, ) -> McpContext
Sets the server capability information for this context.
This enables handlers to check what capabilities this server advertises.
Sourcepub fn has_progress_reporter(&self) -> bool
pub fn has_progress_reporter(&self) -> bool
Returns whether progress reporting is enabled for this context.
Sourcepub fn report_progress(&self, progress: f64, message: Option<&str>)
pub fn report_progress(&self, progress: f64, message: Option<&str>)
Reports progress on the current operation.
If progress reporting is not enabled (no progress token was provided), this method does nothing.
§Arguments
progress- Current progress value (0.0 to 1.0 for fractional progress)message- Optional message describing current status
§Example
async fn process_files(ctx: &McpContext, files: &[File]) -> McpResult<()> {
for (i, file) in files.iter().enumerate() {
ctx.report_progress(i as f64 / files.len() as f64, Some("Processing files"));
process_file(file).await?;
}
ctx.report_progress(1.0, Some("Complete"));
Ok(())
}Sourcepub fn report_progress_with_total(
&self,
progress: f64,
total: f64,
message: Option<&str>,
)
pub fn report_progress_with_total( &self, progress: f64, total: f64, message: Option<&str>, )
Reports progress with explicit total for determinate progress bars.
If progress reporting is not enabled, this method does nothing.
§Arguments
progress- Current progress valuetotal- Total expected valuemessage- Optional message describing current status
§Example
async fn process_items(ctx: &McpContext, items: &[Item]) -> McpResult<()> {
let total = items.len() as f64;
for (i, item) in items.iter().enumerate() {
ctx.report_progress_with_total(i as f64, total, Some(&format!("Item {}", i)));
process_item(item).await?;
}
Ok(())
}Sourcepub fn request_id(&self) -> u64
pub fn request_id(&self) -> u64
Returns the unique request identifier.
This corresponds to the JSON-RPC request ID and is useful for logging and tracing across the request lifecycle.
Sourcepub fn region_id(&self) -> RegionId
pub fn region_id(&self) -> RegionId
Returns the underlying region ID from asupersync.
The region represents the request’s lifecycle scope - all spawned tasks belong to this region and will be cleaned up when the request completes or is cancelled.
Sourcepub fn budget(&self) -> Budget
pub fn budget(&self) -> Budget
Returns the current budget.
The budget represents the remaining computational resources (time, polls) available for this request. When exhausted, the request should be cancelled gracefully.
Sourcepub fn is_cancelled(&self) -> bool
pub fn is_cancelled(&self) -> bool
Checks if cancellation has been requested.
This includes client disconnection, timeout, or explicit cancellation. Handlers should check this periodically and exit early if true.
Sourcepub fn checkpoint(&self) -> Result<(), CancelledError>
pub fn checkpoint(&self) -> Result<(), CancelledError>
Cooperative cancellation checkpoint.
Call this at natural suspension points in your handler to allow
graceful cancellation. Returns Err if cancellation is pending.
§Errors
Returns an error if the request has been cancelled and cancellation is not currently masked.
§Example
async fn process_items(ctx: &McpContext, items: Vec<Item>) -> McpResult<()> {
for item in items {
ctx.checkpoint()?; // Allow cancellation between items
process_item(item).await?;
}
Ok(())
}Sourcepub fn trace(&self, message: &str)
pub fn trace(&self, message: &str)
Records a trace event for this request.
Events are associated with the request’s trace context and can be used for debugging and observability.
Sourcepub fn cx(&self) -> &Cx
pub fn cx(&self) -> &Cx
Returns a reference to the underlying asupersync Cx.
Use this when you need direct access to asupersync primitives, such as spawning tasks or using combinators.
Sourcepub fn get_state<T>(&self, key: &str) -> Option<T>where
T: DeserializeOwned,
pub fn get_state<T>(&self, key: &str) -> Option<T>where
T: DeserializeOwned,
Gets a value from session state by key.
Returns None if:
- Session state is not available (context created without state)
- The key doesn’t exist
- Deserialization to type
Tfails
§Example
async fn my_tool(ctx: &McpContext, args: MyArgs) -> McpResult<Value> {
// Get a counter from session state
let count: Option<i32> = ctx.get_state("counter");
let count = count.unwrap_or(0);
// ... use count ...
Ok(json!({"count": count}))
}Sourcepub fn auth(&self) -> Option<AuthContext>
pub fn auth(&self) -> Option<AuthContext>
Returns the authentication context for this request, if available.
Sourcepub fn set_auth(&self, auth: AuthContext) -> bool
pub fn set_auth(&self, auth: AuthContext) -> bool
Stores authentication context into session state.
Returns false if session state is unavailable or serialization fails.
Sourcepub fn set_state<T>(&self, key: impl Into<String>, value: T) -> boolwhere
T: Serialize,
pub fn set_state<T>(&self, key: impl Into<String>, value: T) -> boolwhere
T: Serialize,
Sets a value in session state.
The value persists across requests within the same session.
Returns true if the value was successfully stored.
Returns false if session state is not available or serialization fails.
§Example
async fn my_tool(ctx: &McpContext, args: MyArgs) -> McpResult<Value> {
// Increment a counter in session state
let count: i32 = ctx.get_state("counter").unwrap_or(0);
ctx.set_state("counter", count + 1);
Ok(json!({"new_count": count + 1}))
}Sourcepub fn remove_state(&self, key: &str) -> Option<Value>
pub fn remove_state(&self, key: &str) -> Option<Value>
Removes a value from session state.
Returns the previous value if it existed, or None if:
- Session state is not available
- The key didn’t exist
Sourcepub fn has_state(&self, key: &str) -> bool
pub fn has_state(&self, key: &str) -> bool
Checks if a key exists in session state.
Returns false if session state is not available.
Sourcepub fn has_session_state(&self) -> bool
pub fn has_session_state(&self) -> bool
Returns whether session state is available in this context.
Sourcepub fn client_capabilities(&self) -> Option<&ClientCapabilityInfo>
pub fn client_capabilities(&self) -> Option<&ClientCapabilityInfo>
Returns the client capability information, if available.
Capabilities are set by the server after initialization and reflect what the connected client supports.
Sourcepub fn server_capabilities(&self) -> Option<&ServerCapabilityInfo>
pub fn server_capabilities(&self) -> Option<&ServerCapabilityInfo>
Returns the server capability information, if available.
Reflects what capabilities this server advertises.
Sourcepub fn client_supports_sampling(&self) -> bool
pub fn client_supports_sampling(&self) -> bool
Returns whether the client supports sampling (LLM completions).
This is a convenience method that checks the client capabilities.
Returns false if capabilities are not yet available (before initialization).
Sourcepub fn client_supports_elicitation(&self) -> bool
pub fn client_supports_elicitation(&self) -> bool
Returns whether the client supports elicitation (user input requests).
This is a convenience method that checks the client capabilities.
Returns false if capabilities are not yet available.
Sourcepub fn client_supports_elicitation_form(&self) -> bool
pub fn client_supports_elicitation_form(&self) -> bool
Returns whether the client supports form-mode elicitation.
Sourcepub fn client_supports_elicitation_url(&self) -> bool
pub fn client_supports_elicitation_url(&self) -> bool
Returns whether the client supports URL-mode elicitation.
Sourcepub fn client_supports_roots(&self) -> bool
pub fn client_supports_roots(&self) -> bool
Returns whether the client supports roots listing.
This is a convenience method that checks the client capabilities.
Returns false if capabilities are not yet available.
Sourcepub fn disable_tool(&self, name: impl Into<String>) -> bool
pub fn disable_tool(&self, name: impl Into<String>) -> bool
Disables a tool for this session.
Disabled tools will not appear in tools/list responses and will return
an error if called directly. This is useful for adapting available
functionality based on user permissions, feature flags, or runtime conditions.
Returns true if the operation succeeded, false if session state is unavailable.
§Example
async fn my_tool(ctx: &McpContext) -> McpResult<String> {
// Disable the "admin_tool" for this session
ctx.disable_tool("admin_tool");
Ok("Admin tool disabled".to_string())
}Sourcepub fn enable_tool(&self, name: &str) -> bool
pub fn enable_tool(&self, name: &str) -> bool
Enables a previously disabled tool for this session.
Returns true if the operation succeeded, false if session state is unavailable.
Sourcepub fn is_tool_enabled(&self, name: &str) -> bool
pub fn is_tool_enabled(&self, name: &str) -> bool
Returns whether a tool is enabled (not disabled) for this session.
Tools are enabled by default unless explicitly disabled.
Sourcepub fn disable_resource(&self, uri: impl Into<String>) -> bool
pub fn disable_resource(&self, uri: impl Into<String>) -> bool
Disables a resource for this session.
Disabled resources will not appear in resources/list responses and will
return an error if read directly.
Returns true if the operation succeeded, false if session state is unavailable.
Sourcepub fn enable_resource(&self, uri: &str) -> bool
pub fn enable_resource(&self, uri: &str) -> bool
Enables a previously disabled resource for this session.
Returns true if the operation succeeded, false if session state is unavailable.
Sourcepub fn is_resource_enabled(&self, uri: &str) -> bool
pub fn is_resource_enabled(&self, uri: &str) -> bool
Returns whether a resource is enabled (not disabled) for this session.
Resources are enabled by default unless explicitly disabled.
Sourcepub fn disable_prompt(&self, name: impl Into<String>) -> bool
pub fn disable_prompt(&self, name: impl Into<String>) -> bool
Disables a prompt for this session.
Disabled prompts will not appear in prompts/list responses and will
return an error if retrieved directly.
Returns true if the operation succeeded, false if session state is unavailable.
Sourcepub fn enable_prompt(&self, name: &str) -> bool
pub fn enable_prompt(&self, name: &str) -> bool
Enables a previously disabled prompt for this session.
Returns true if the operation succeeded, false if session state is unavailable.
Sourcepub fn is_prompt_enabled(&self, name: &str) -> bool
pub fn is_prompt_enabled(&self, name: &str) -> bool
Returns whether a prompt is enabled (not disabled) for this session.
Prompts are enabled by default unless explicitly disabled.
Sourcepub fn disabled_tools(&self) -> HashSet<String>
pub fn disabled_tools(&self) -> HashSet<String>
Returns the set of disabled tools for this session.
Sourcepub fn disabled_resources(&self) -> HashSet<String>
pub fn disabled_resources(&self) -> HashSet<String>
Returns the set of disabled resources for this session.
Sourcepub fn disabled_prompts(&self) -> HashSet<String>
pub fn disabled_prompts(&self) -> HashSet<String>
Returns the set of disabled prompts for this session.
Sourcepub fn can_sample(&self) -> bool
pub fn can_sample(&self) -> bool
Returns whether sampling is available in this context.
Sampling is available when the client has advertised sampling capability and a sampling sender has been configured.
Sourcepub async fn sample(
&self,
prompt: impl Into<String>,
max_tokens: u32,
) -> Result<SamplingResponse, McpError>
pub async fn sample( &self, prompt: impl Into<String>, max_tokens: u32, ) -> Result<SamplingResponse, McpError>
Requests an LLM completion from the client.
This is a convenience method for simple text prompts. For more control
over the request, use sample_with_request.
§Arguments
prompt- The prompt text to send (as a user message)max_tokens- Maximum number of tokens to generate
§Errors
Returns an error if:
- The client doesn’t support sampling
- The sampling request fails
§Example
async fn my_tool(ctx: &McpContext, topic: String) -> McpResult<String> {
let response = ctx.sample(&format!("Write a haiku about {topic}"), 100).await?;
Ok(response.text)
}Sourcepub async fn sample_with_request(
&self,
request: SamplingRequest,
) -> Result<SamplingResponse, McpError>
pub async fn sample_with_request( &self, request: SamplingRequest, ) -> Result<SamplingResponse, McpError>
Requests an LLM completion with full control over the request.
§Arguments
request- The full sampling request parameters
§Errors
Returns an error if:
- The client doesn’t support sampling
- The sampling request fails
§Example
async fn my_tool(ctx: &McpContext) -> McpResult<String> {
let request = SamplingRequest::new(
vec![
SamplingRequestMessage::user("Hello!"),
SamplingRequestMessage::assistant("Hi! How can I help?"),
SamplingRequestMessage::user("Tell me a joke."),
],
200,
)
.with_system_prompt("You are a helpful and funny assistant.")
.with_temperature(0.8);
let response = ctx.sample_with_request(request).await?;
Ok(response.text)
}Sourcepub fn can_elicit(&self) -> bool
pub fn can_elicit(&self) -> bool
Returns whether elicitation is available in this context.
Elicitation is available when the client has advertised elicitation capability and an elicitation sender has been configured.
Sourcepub async fn elicit_form(
&self,
message: impl Into<String>,
schema: Value,
) -> Result<ElicitationResponse, McpError>
pub async fn elicit_form( &self, message: impl Into<String>, schema: Value, ) -> Result<ElicitationResponse, McpError>
Requests user input via a form.
This presents a form to the user with fields defined by the JSON schema. The user can accept (submit the form), decline, or cancel.
§Arguments
message- Message to display explaining what input is neededschema- JSON Schema defining the form fields
§Errors
Returns an error if:
- The client doesn’t support elicitation
- The elicitation request fails
§Example
async fn my_tool(ctx: &McpContext) -> McpResult<String> {
let schema = serde_json::json!({
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"}
},
"required": ["name"]
});
let response = ctx.elicit_form("Please enter your details", schema).await?;
if response.is_accepted() {
let name = response.get_string("name").unwrap_or("Unknown");
Ok(format!("Hello, {name}!"))
} else {
Ok("User declined input".to_string())
}
}Sourcepub async fn elicit_url(
&self,
message: impl Into<String>,
url: impl Into<String>,
elicitation_id: impl Into<String>,
) -> Result<ElicitationResponse, McpError>
pub async fn elicit_url( &self, message: impl Into<String>, url: impl Into<String>, elicitation_id: impl Into<String>, ) -> Result<ElicitationResponse, McpError>
Requests user interaction via an external URL.
This directs the user to an external URL for sensitive operations like OAuth flows, payment processing, or credential collection.
§Arguments
message- Message to display explaining why the URL visit is neededurl- The URL the user should navigate toelicitation_id- Unique ID for tracking this elicitation
§Errors
Returns an error if:
- The client doesn’t support elicitation
- The elicitation request fails
§Example
async fn my_tool(ctx: &McpContext) -> McpResult<String> {
let response = ctx.elicit_url(
"Please authenticate with your GitHub account",
"https://github.com/login/oauth/authorize?...",
"github-auth-12345",
).await?;
if response.is_accepted() {
Ok("Authentication successful".to_string())
} else {
Ok("Authentication cancelled".to_string())
}
}Sourcepub async fn elicit_with_request(
&self,
request: ElicitationRequest,
) -> Result<ElicitationResponse, McpError>
pub async fn elicit_with_request( &self, request: ElicitationRequest, ) -> Result<ElicitationResponse, McpError>
Sourcepub fn can_read_resources(&self) -> bool
pub fn can_read_resources(&self) -> bool
Returns whether resource reading is available in this context.
Resource reading is available when a resource reader (Router) has been attached to this context.
Sourcepub fn resource_read_depth(&self) -> u32
pub fn resource_read_depth(&self) -> u32
Returns the current resource read depth.
This is used to track recursion when resources read other resources.
Sourcepub async fn read_resource(
&self,
uri: &str,
) -> Result<ResourceReadResult, McpError>
pub async fn read_resource( &self, uri: &str, ) -> Result<ResourceReadResult, McpError>
Reads a resource by URI.
This allows tools, resources, and prompts to read other resources configured on the same server. This enables composition and code reuse.
§Arguments
uri- The resource URI to read
§Errors
Returns an error if:
- No resource reader is available (context not configured for resource access)
- The resource is not found
- Maximum recursion depth is exceeded
- The resource read fails
§Example
#[tool]
async fn process_config(ctx: &McpContext) -> Result<String, ToolError> {
let config = ctx.read_resource("config://app").await?;
let text = config.first_text()
.ok_or(ToolError::InvalidConfig)?;
Ok(format!("Config loaded: {}", text))
}Sourcepub async fn read_resource_text(&self, uri: &str) -> Result<String, McpError>
pub async fn read_resource_text(&self, uri: &str) -> Result<String, McpError>
Reads a resource and extracts the text content.
This is a convenience method that reads a resource and returns the first text content item.
§Errors
Returns an error if:
- The resource read fails
- The resource has no text content
§Example
let text = ctx.read_resource_text("file://readme.md").await?;
println!("Content: {}", text);Sourcepub async fn read_resource_json<T>(&self, uri: &str) -> Result<T, McpError>where
T: DeserializeOwned,
pub async fn read_resource_json<T>(&self, uri: &str) -> Result<T, McpError>where
T: DeserializeOwned,
Reads a resource and parses it as JSON.
This is a convenience method that reads a resource and deserializes the text content as JSON.
§Errors
Returns an error if:
- The resource read fails
- The resource has no text content
- JSON deserialization fails
§Example
#[derive(Deserialize)]
struct Config {
database_url: String,
}
let config: Config = ctx.read_resource_json("config://app").await?;
println!("Database: {}", config.database_url);Sourcepub fn can_call_tools(&self) -> bool
pub fn can_call_tools(&self) -> bool
Returns whether tool calling is available in this context.
Tool calling is available when a tool caller (Router) has been attached to this context.
Sourcepub fn tool_call_depth(&self) -> u32
pub fn tool_call_depth(&self) -> u32
Returns the current tool call depth.
This is used to track recursion when tools call other tools.
Sourcepub async fn call_tool(
&self,
name: &str,
args: Value,
) -> Result<ToolCallResult, McpError>
pub async fn call_tool( &self, name: &str, args: Value, ) -> Result<ToolCallResult, McpError>
Calls a tool by name with the given arguments.
This allows tools, resources, and prompts to call other tools configured on the same server. This enables composition and code reuse.
§Arguments
name- The tool name to callargs- The arguments as a JSON value
§Errors
Returns an error if:
- No tool caller is available (context not configured for tool access)
- The tool is not found
- Maximum recursion depth is exceeded
- The tool execution fails
§Example
#[tool]
async fn double_add(ctx: &McpContext, a: i32, b: i32) -> Result<i32, ToolError> {
let sum: i32 = ctx.call_tool_json("add", json!({"a": a, "b": b})).await?;
Ok(sum * 2)
}Sourcepub async fn call_tool_text(
&self,
name: &str,
args: Value,
) -> Result<String, McpError>
pub async fn call_tool_text( &self, name: &str, args: Value, ) -> Result<String, McpError>
Calls a tool and extracts the text content.
This is a convenience method that calls a tool and returns the first text content item.
§Errors
Returns an error if:
- The tool call fails
- The tool returns an error result
- The tool has no text content
§Example
let greeting = ctx.call_tool_text("greet", json!({"name": "World"})).await?;
println!("Result: {}", greeting);Sourcepub async fn call_tool_json<T>(
&self,
name: &str,
args: Value,
) -> Result<T, McpError>where
T: DeserializeOwned,
pub async fn call_tool_json<T>(
&self,
name: &str,
args: Value,
) -> Result<T, McpError>where
T: DeserializeOwned,
Calls a tool and parses the result as JSON.
This is a convenience method that calls a tool and deserializes the text content as JSON.
§Errors
Returns an error if:
- The tool call fails
- The tool returns an error result
- The tool has no text content
- JSON deserialization fails
§Example
#[derive(Deserialize)]
struct ComputeResult {
value: i64,
}
let result: ComputeResult = ctx.call_tool_json("compute", json!({"x": 5})).await?;
println!("Result: {}", result.value);Sourcepub async fn join_all<T>(
&self,
futures: Vec<Pin<Box<dyn Future<Output = T> + Send + '_>>>,
) -> Vec<T>where
T: Send + 'static,
pub async fn join_all<T>(
&self,
futures: Vec<Pin<Box<dyn Future<Output = T> + Send + '_>>>,
) -> Vec<T>where
T: Send + 'static,
Waits for all futures to complete and returns their results.
This is the N-of-N combinator: all futures must complete before returning. Results are returned in the same order as input futures.
§Example
let futures = vec![
Box::pin(fetch_user(1)),
Box::pin(fetch_user(2)),
Box::pin(fetch_user(3)),
];
let users = ctx.join_all(futures).await;Sourcepub async fn race<T>(
&self,
futures: Vec<Pin<Box<dyn Future<Output = T> + Send + '_>>>,
) -> Result<T, McpError>where
T: Send + 'static,
pub async fn race<T>(
&self,
futures: Vec<Pin<Box<dyn Future<Output = T> + Send + '_>>>,
) -> Result<T, McpError>where
T: Send + 'static,
Races multiple futures, returning the first to complete.
This is the 1-of-N combinator: the first future to complete wins, and all others are cancelled and drained.
§Example
let futures = vec![
Box::pin(fetch_from_primary()),
Box::pin(fetch_from_replica()),
];
let result = ctx.race(futures).await?;Sourcepub async fn quorum<T>(
&self,
required: usize,
futures: Vec<Pin<Box<dyn Future<Output = Result<T, McpError>> + Send + '_>>>,
) -> Result<QuorumResult<T>, McpError>where
T: Send + 'static,
pub async fn quorum<T>(
&self,
required: usize,
futures: Vec<Pin<Box<dyn Future<Output = Result<T, McpError>> + Send + '_>>>,
) -> Result<QuorumResult<T>, McpError>where
T: Send + 'static,
Waits for M of N futures to complete successfully.
Returns when required futures have completed successfully.
Remaining futures are cancelled.
§Example
let futures = vec![
Box::pin(write_to_replica(1)),
Box::pin(write_to_replica(2)),
Box::pin(write_to_replica(3)),
];
let result = ctx.quorum(2, futures).await?;Sourcepub async fn first_ok<T>(
&self,
futures: Vec<Pin<Box<dyn Future<Output = Result<T, McpError>> + Send + '_>>>,
) -> Result<T, McpError>where
T: Send + 'static,
pub async fn first_ok<T>(
&self,
futures: Vec<Pin<Box<dyn Future<Output = Result<T, McpError>> + Send + '_>>>,
) -> Result<T, McpError>where
T: Send + 'static,
Races futures and returns the first successful result.
Unlike race which returns the first to complete (success or failure),
first_ok returns the first to complete successfully.
§Example
let futures = vec![
Box::pin(try_primary()),
Box::pin(try_fallback()),
];
let result = ctx.first_ok(futures).await?;Trait Implementations§
Source§impl Clone for McpContext
impl Clone for McpContext
Source§fn clone(&self) -> McpContext
fn clone(&self) -> McpContext
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more