Skip to main content

Client

Struct Client 

Source
pub struct Client<T: Transport> { /* private fields */ }
Expand description

MCP client for connecting to servers.

Implementations§

Source§

impl<T: Transport> Client<T>

Source

pub fn new(transport: T) -> Self

Create a new client with the given transport.

Uses default client information with the name “pmcp-client” and the current crate version.

§Examples
use pmcp::{Client, StdioTransport};

let transport = StdioTransport::new();
let client = Client::new(transport);
Source

pub fn with_info(transport: T, client_info: Implementation) -> Self

Create a new client with custom info.

Allows specifying custom client name and version information that will be sent to the server during initialization.

§Examples
use pmcp::{Client, StdioTransport, Implementation};

let transport = StdioTransport::new();
let client_info = Implementation::new("my-custom-client", "2.1.0");
let client = Client::with_info(transport, client_info);
Source

pub fn with_options( transport: T, client_info: Implementation, options: ProtocolOptions, ) -> Self

Create a new client with custom protocol options.

§Examples
use pmcp::{Client, StdioTransport, Implementation};
use pmcp::shared::ProtocolOptions;

// Custom options for high-throughput scenarios
let options = ProtocolOptions {
    enforce_strict_capabilities: false,
    debounced_notification_methods: vec![
        "notifications/progress".to_string(),
        "notifications/message".to_string(),
    ],
};

let transport = StdioTransport::new();
let client_info = Implementation::new("high-throughput-client", "1.0.0");

let client = Client::with_options(transport, client_info, options);
Source

pub fn with_client_options(transport: T, options: ClientOptions) -> Self

Construct a client with caller-supplied ClientOptions.

Mirrors Self::new but wires in a ClientOptions value so that Self::list_all_tools / Self::list_all_prompts / etc. honour a custom max_iterations cap.

§ClientBuilder parity

ClientBuilder does not currently expose a .client_options() setter. If you need a custom ClientOptions, construct the client via Self::with_client_options directly.

§Examples
use pmcp::{Client, ClientOptions};

let opts = ClientOptions::default().with_max_iterations(50);
let _client = Client::with_client_options(transport, opts);
Source

pub async fn initialize( &mut self, capabilities: ClientCapabilities, ) -> Result<InitializeResult>

Initialize the connection with the server.

Performs the MCP initialization handshake, negotiating capabilities and receiving server information. This must be called before using other client methods.

§Examples
use pmcp::{Client, StdioTransport, ClientCapabilities};

let transport = StdioTransport::new();
let mut client = Client::new(transport);

let capabilities = ClientCapabilities::default();
let server_info = client.initialize(capabilities).await?;

println!("Server: {} v{}",
         server_info.server_info.name,
         server_info.server_info.version);
§Errors

Returns an error if:

  • The client is already initialized
  • The server rejects the initialization
  • Communication with the server fails
Source

pub fn get_server_capabilities(&self) -> Option<&ServerCapabilities>

Get server capabilities after initialization.

Source

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

Get server version information after initialization.

Source

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

Get server instructions after initialization.

Source

pub async fn ping(&self) -> Result<()>

Send a ping to the server.

Source

pub async fn set_logging_level(&self, level: LoggingLevel) -> Result<()>

Set the logging level on the server.

Source

pub async fn list_tools( &self, cursor: Option<String>, ) -> Result<ListToolsResult>

List available tools.

Retrieves information about all tools available on the server, including their names, descriptions, and input schemas.

§Examples
use pmcp::{Client, StdioTransport, ClientCapabilities};

let transport = StdioTransport::new();
let mut client = Client::new(transport);
client.initialize(ClientCapabilities::default()).await?;

// List all tools
let tools = client.list_tools(None).await?;
for tool in tools.tools {
    println!("Tool: {} - {}",
             tool.name,
             tool.description.unwrap_or_else(|| "No description".to_string()));
}
§Arguments
  • cursor - Optional pagination cursor for retrieving additional results
Source

pub async fn call_tool( &self, name: String, arguments: Value, ) -> Result<CallToolResult>

Call a tool.

Invokes a server-provided tool with the specified name and arguments. The server must have declared the tool via the tools capability during initialization.

§Arguments
  • name - The name of the tool to call
  • arguments - JSON value containing the tool’s arguments
§Examples
use pmcp::{Client, StdioTransport, ClientCapabilities};
use serde_json::json;

let transport = StdioTransport::new();
let mut client = Client::new(transport);
client.initialize(ClientCapabilities::default()).await?;

// Call a simple tool with no arguments
let result = client.call_tool(
    "list_files".to_string(),
    json!({})
).await?;

// Call a tool with specific arguments
let search_result = client.call_tool(
    "search".to_string(),
    json!({
        "query": "rust programming",
        "limit": 10
    })
).await?;

// Tools can return structured data
if let Some(content) = result.content.first() {
    match content {
        pmcp::Content::Text { text } => {
            println!("Tool result: {}", text);
        }
        _ => println!("Non-text tool result"),
    }
}
§Errors

Returns an error if:

  • The client is not initialized
  • The server doesn’t support tools
  • The tool name doesn’t exist
  • The arguments are invalid for the tool
  • Network or protocol errors occur
Source

pub async fn call_tool_with_task( &self, name: String, arguments: Value, ) -> Result<ToolCallResponse>

Call a tool with task augmentation.

Sends a tools/call request with the task field set, signaling to the server that this client supports async task polling. The server may return either a CreateTaskResult (async task created) or a CallToolResult (sync result) depending on the tool’s taskSupport declaration.

Use call_tool instead if you don’t need task support.

§Returns
  • Ok(ToolCallResponse::Task(task)) if the server created an async task. Poll with tasks_get until the task reaches a terminal status.
  • Ok(ToolCallResponse::Result(result)) if the server returned the result synchronously.
Source

pub async fn tasks_get(&self, task_id: &str) -> Result<Task>

Get the current status of a task.

Polls the server for the task’s current state. Call this repeatedly (respecting task.poll_interval) until the task reaches a terminal status (Completed, Failed, or Cancelled).

§Errors

Returns an error if:

  • The server doesn’t support tasks
  • The task ID doesn’t exist or belongs to another owner
Source

pub async fn tasks_result(&self, task_id: &str) -> Result<CallToolResult>

Get the final result of a completed task.

For a task-augmented tools/call, this returns the CallToolResult that the tool would have returned synchronously. Only valid when the task status is Completed.

Source

pub async fn tasks_list( &self, cursor: Option<String>, ) -> Result<ListTasksResult>

List tasks owned by the current client.

Source

pub async fn tasks_cancel(&self, task_id: &str) -> Result<Task>

Cancel a running task.

Source

pub async fn call_tool_and_poll( &self, name: String, arguments: Value, max_polls: usize, ) -> Result<CallToolResult>

Available on non-WebAssembly only.

Call a tool and automatically poll until the task completes.

This is a high-level convenience method that encapsulates the full task lifecycle:

  1. Calls the tool with task augmentation
  2. If the server returns a task, polls tasks/get until terminal status
  3. Returns the final CallToolResult

If the server returns a sync result (no task), returns it immediately.

§Arguments
  • name - Tool name
  • arguments - Tool arguments
  • max_polls - Maximum number of poll attempts before giving up (0 = unlimited)
Source

pub async fn list_prompts( &self, cursor: Option<String>, ) -> Result<ListPromptsResult>

List available prompts.

Retrieves information about all prompts available on the server, including their names, descriptions, and required arguments.

§Arguments
  • cursor - Optional cursor for pagination of large prompt lists
§Examples
use pmcp::{Client, StdioTransport, ClientCapabilities};

let transport = StdioTransport::new();
let mut client = Client::new(transport);
client.initialize(ClientCapabilities::default()).await?;

// List all prompts
let prompts = client.list_prompts(None).await?;
for prompt in prompts.prompts {
    println!("Prompt: {} - {}",
             prompt.name,
             prompt.description.unwrap_or_else(|| "No description".to_string()));
     
    // Show required arguments
    if let Some(args) = prompt.arguments {
        for arg in args {
            println!("  - {}: {} (required: {})",
                     arg.name,
                     arg.description.unwrap_or_else(|| "No description".to_string()),
                     arg.required);
        }
    }
}
§Errors

Returns an error if:

  • The client is not initialized
  • The server doesn’t support prompts
  • Network or protocol errors occur
Source

pub async fn get_prompt( &self, name: String, arguments: HashMap<String, String>, ) -> Result<GetPromptResult>

Get a prompt.

Retrieves a specific prompt from the server with the provided arguments. The prompt is processed by the server and returned with filled-in content.

§Arguments
  • name - The name of the prompt to retrieve
  • arguments - Key-value pairs for prompt arguments
§Examples
use pmcp::{Client, StdioTransport, ClientCapabilities};
use std::collections::HashMap;

let transport = StdioTransport::new();
let mut client = Client::new(transport);
client.initialize(ClientCapabilities::default()).await?;

// Get a prompt with arguments
let mut args = HashMap::new();
args.insert("language".to_string(), "Rust".to_string());
args.insert("topic".to_string(), "async programming".to_string());

let prompt_result = client.get_prompt(
    "code_review".to_string(),
    args
).await?;

println!("Prompt description: {}",
         prompt_result.description.unwrap_or_else(|| "No description".to_string()));

// Process the prompt messages
for message in prompt_result.messages {
    println!("Role: {}", message.role);
    match &message.content {
        pmcp::Content::Text { text } => {
            println!("Content: {}", text);
        }
        _ => println!("Non-text content"),
    }
}
§Errors

Returns an error if:

  • The client is not initialized
  • The server doesn’t support prompts
  • The prompt name doesn’t exist
  • Required arguments are missing
  • Network or protocol errors occur
Source

pub async fn call_tool_typed<A: Serialize + ?Sized + Sync>( &self, name: impl Into<String> + Send, args: &A, ) -> Result<CallToolResult>

Call a tool with typed, serializable arguments.

Serializes args via serde_json::to_value and delegates to Self::call_tool. Serialization failures are mapped to Error::validation with the underlying serde error message.

§Examples
use serde::Serialize;

#[derive(Serialize)]
struct Search { query: String, limit: u32 }

let _ = client.call_tool_typed(
    "search",
    &Search { query: "rust mcp".into(), limit: 10 },
).await?;
Source

pub async fn call_tool_typed_with_task<A: Serialize + ?Sized + Sync>( &self, name: impl Into<String> + Send, args: &A, ) -> Result<ToolCallResponse>

Typed sibling of Self::call_tool_with_task.

Delegates to the two-argument Self::call_tool_with_task; there is no TaskMetadata parameter on the live client API, so none is exposed here.

§Examples
use serde::Serialize;
#[derive(Serialize)]
struct Args { file: String }
let _ = client.call_tool_typed_with_task("scan", &Args { file: "a.rs".into() }).await?;
Source

pub async fn call_tool_typed_and_poll<A: Serialize + ?Sized + Sync>( &self, name: impl Into<String> + Send, args: &A, max_polls: usize, ) -> Result<CallToolResult>

Available on non-WebAssembly only.

Typed sibling of Self::call_tool_and_poll.

Delegates to the three-argument Self::call_tool_and_poll (name, arguments, max_polls: usize). There is no poll_interval or TaskMetadata parameter on the live client API — the server-supplied poll_interval is honoured internally by call_tool_and_poll.

max_polls = 0 means unlimited polls, matching the sibling’s semantics.

§Examples
use serde::Serialize;
#[derive(Serialize)]
struct Args { job: String }
let _ = client.call_tool_typed_and_poll(
    "build",
    &Args { job: "nightly".into() },
    30, // max_polls
).await?;
Source

pub async fn get_prompt_typed<A: Serialize + ?Sized + Sync>( &self, name: impl Into<String> + Send, args: &A, ) -> Result<GetPromptResult>

Get a prompt with typed, serializable arguments.

Serializes args to a JSON object, then coerces each leaf to a String for the wire-level HashMap<String, String> arguments:

  • null entries are omitted
  • string entries pass through unchanged (no JSON-quoting)
  • number and bool entries use Display (e.g. 42, true)
  • array and object entries are re-serialized via serde_json::to_string

Non-object top-level serializations are rejected with Error::validation.

§Examples
use serde::Serialize;

#[derive(Serialize)]
struct SummaryArgs { topic: String, length: u32 }

let _ = client.get_prompt_typed(
    "summarize",
    &SummaryArgs { topic: "rust async".into(), length: 200 },
).await?;
Source

pub async fn list_resources( &self, cursor: Option<String>, ) -> Result<ListResourcesResult>

List available resources.

Retrieves information about all resources available on the server, including their names, descriptions, URIs, and MIME types.

§Arguments
  • cursor - Optional cursor for pagination of large resource lists
§Examples
use pmcp::{Client, StdioTransport, ClientCapabilities};

let transport = StdioTransport::new();
let mut client = Client::new(transport);
client.initialize(ClientCapabilities::default()).await?;

// List all resources
let resources = client.list_resources(None).await?;
for resource in resources.resources {
    println!("Resource: {} ({})", resource.name, resource.uri);
    if let Some(description) = resource.description {
        println!("  Description: {}", description);
    }
    if let Some(mime_type) = resource.mime_type {
        println!("  MIME Type: {}", mime_type);
    }
}
§Errors

Returns an error if:

  • The client is not initialized
  • The server doesn’t support resources
  • Network or protocol errors occur
Source

pub async fn list_resource_templates( &self, cursor: Option<String>, ) -> Result<ListResourceTemplatesResult>

List resource templates.

Retrieves information about all resource templates available on the server. Resource templates define patterns for dynamically generated resources.

§Arguments
  • cursor - Optional cursor for pagination of large template lists
§Examples
use pmcp::{Client, StdioTransport, ClientCapabilities};

let transport = StdioTransport::new();
let mut client = Client::new(transport);
client.initialize(ClientCapabilities::default()).await?;

// List all resource templates
let templates = client.list_resource_templates(None).await?;
for template in templates.resource_templates {
    println!("Template: {} ({})", template.name, template.uri_template);
    if let Some(description) = template.description {
        println!("  Description: {}", description);
    }
}
§Errors

Returns an error if:

  • The client is not initialized
  • The server doesn’t support resource templates
  • Network or protocol errors occur
Source

pub async fn list_all_tools(&self) -> Result<Vec<ToolInfo>>

List all tools across all pages, auto-paginating on next_cursor.

Loops calling Self::list_tools, terminating when the server returns next_cursor: None. Safety cap: if the loop runs more than self.options.max_iterations iterations (default 100), returns Error::Validation instead of continuing or silently truncating.

Empty-string cursors (Some("")) do NOT terminate the loop — only None does. This matches the MCP spec, which treats the cursor as an opaque server token and does not ascribe meaning to the empty string.

§Memory

This helper accumulates all pages in memory before returning. For very large servers, prefer the paginated single-page Self::list_tools and stream the output yourself — this helper is a convenience API and will amplify memory usage proportional to the total tool count.

§Errors
  • Any error surfaced by Self::list_tools propagates unchanged.
  • Cap exceeded → Error::Validation("list_all_tools exceeded max_iterations cap of N pages").
§Examples
let tools = client.list_all_tools().await?;
println!("discovered {} tools", tools.len());
Source

pub async fn list_all_prompts(&self) -> Result<Vec<PromptInfo>>

List all prompts across all pages, auto-paginating on next_cursor.

Semantics identical to Self::list_all_tools: bounded by self.options.max_iterations, terminates only on next_cursor: None, returns Error::Validation on cap exceeded.

§Memory

Accumulates all pages in memory; prefer Self::list_prompts for very large servers.

§Errors
  • Any error surfaced by Self::list_prompts propagates unchanged.
  • Cap exceeded → Error::Validation("list_all_prompts exceeded max_iterations cap of N pages").
§Examples
let prompts = client.list_all_prompts().await?;
println!("discovered {} prompts", prompts.len());
Source

pub async fn list_all_resources(&self) -> Result<Vec<ResourceInfo>>

List all resources across all pages, auto-paginating on next_cursor.

Semantics identical to Self::list_all_tools: bounded by self.options.max_iterations, terminates only on next_cursor: None, returns Error::Validation on cap exceeded.

§Memory

Accumulates all pages in memory; prefer Self::list_resources for very large servers.

§Errors
  • Any error surfaced by Self::list_resources propagates unchanged.
  • Cap exceeded → Error::Validation("list_all_resources exceeded max_iterations cap of N pages").
§Examples
let resources = client.list_all_resources().await?;
println!("discovered {} resources", resources.len());
Source

pub async fn list_all_resource_templates(&self) -> Result<Vec<ResourceTemplate>>

List all resource templates across all pages, auto-paginating on next_cursor.

Uses the distinct resources/templates/list capability path (all other list_all_* helpers hit their own methods). Semantics otherwise identical to Self::list_all_tools: bounded by self.options.max_iterations, terminates only on next_cursor: None, returns Error::Validation on cap exceeded.

§Memory

Accumulates all pages in memory; prefer Self::list_resource_templates for very large servers.

§Errors
  • Any error surfaced by Self::list_resource_templates propagates unchanged.
  • Cap exceeded → Error::Validation("list_all_resource_templates exceeded max_iterations cap of N pages").
§Examples
let templates = client.list_all_resource_templates().await?;
println!("discovered {} templates", templates.len());
Source

pub async fn read_resource(&self, uri: String) -> Result<ReadResourceResult>

Read a resource.

Retrieves the content of a specific resource from the server by its URI. Resources can contain text, binary data, or structured content.

§Arguments
  • uri - The URI of the resource to read
§Examples
use pmcp::{Client, StdioTransport, ClientCapabilities};

let transport = StdioTransport::new();
let mut client = Client::new(transport);
client.initialize(ClientCapabilities::default()).await?;

// Read a text resource
let resource = client.read_resource("file://readme.txt".to_string()).await?;
for content in resource.contents {
    match content {
        pmcp::Content::Text { text } => {
            println!("Text content: {}", text);
        }
        pmcp::Content::Resource { uri, .. } => {
            println!("Resource reference: {}", uri);
        }
        _ => println!("Other content type"),
    }
}
§Errors

Returns an error if:

  • The client is not initialized
  • The server doesn’t support resources
  • The resource URI doesn’t exist
  • Access to the resource is denied
  • Network or protocol errors occur
Source

pub async fn subscribe_resource(&self, uri: String) -> Result<()>

Subscribe to resource updates.

Subscribes to receive notifications when a resource changes. The server will send notifications when the subscribed resource is modified.

§Arguments
  • uri - The URI of the resource to subscribe to
§Examples
use pmcp::{Client, StdioTransport, ClientCapabilities};

let transport = StdioTransport::new();
let mut client = Client::new(transport);
client.initialize(ClientCapabilities::default()).await?;

// Subscribe to a configuration file
client.subscribe_resource("file://config/settings.json".to_string()).await?;

// Now the client will receive notifications when settings.json changes
// Handle notifications in your event loop
§Errors

Returns an error if:

  • The client is not initialized
  • The server doesn’t support resource subscriptions
  • The resource URI doesn’t exist
  • Network or protocol errors occur
Source

pub async fn unsubscribe_resource(&self, uri: String) -> Result<()>

Unsubscribe from resource updates.

Unsubscribes from notifications for a previously subscribed resource. After unsubscribing, the client will no longer receive change notifications.

§Arguments
  • uri - The URI of the resource to unsubscribe from
§Examples
use pmcp::{Client, StdioTransport, ClientCapabilities};

let transport = StdioTransport::new();
let mut client = Client::new(transport);
client.initialize(ClientCapabilities::default()).await?;

// Subscribe to a resource
client.subscribe_resource("file://config/settings.json".to_string()).await?;

// Later, unsubscribe when no longer needed
client.unsubscribe_resource("file://config/settings.json".to_string()).await?;
§Errors

Returns an error if:

  • The client is not initialized
  • The server doesn’t support resource subscriptions
  • The resource URI was not previously subscribed to
  • Network or protocol errors occur
Source

pub async fn complete(&self, params: CompleteRequest) -> Result<CompleteResult>

Request completion from the server.

Requests auto-completion suggestions from the server for a given context. This is useful for implementing IDE-like features with contextual suggestions.

§Arguments
  • params - The completion request parameters
§Examples
use pmcp::{Client, StdioTransport, ClientCapabilities, CompleteRequest};

let transport = StdioTransport::new();
let mut client = Client::new(transport);
client.initialize(ClientCapabilities::default()).await?;

// Request completion for partial text
let completion_request = CompleteRequest {
    r#ref: pmcp::CompletionReference::Resource {
        uri: "file://code.rs".to_string(),
    },
    argument: pmcp::CompletionArgument {
        name: "function_name".to_string(),
        value: "calc_".to_string(),
    },
};

let completions = client.complete(completion_request).await?;
for completion in completions.completion.values {
    println!("Suggestion: {}", completion);
}
§Errors

Returns an error if:

  • The client is not initialized
  • The server doesn’t support completions
  • The completion context is invalid
  • Network or protocol errors occur
Source

pub async fn create_message( &self, params: CreateMessageParams, ) -> Result<CreateMessageResult>

Create a message using sampling (for LLM providers).

Requests the server to generate a message using its language model capabilities. This is typically used by servers that provide LLM functionality.

§Examples
use pmcp::{Client, StdioTransport, ClientCapabilities, CreateMessageParams, SamplingMessage};

let mut capabilities = ClientCapabilities::default();
capabilities.sampling = Some(Default::default());

let transport = StdioTransport::new();
let mut client = Client::new(transport);
client.initialize(capabilities).await?;

// Create a message with the LLM
let msg = SamplingMessage::new(
    pmcp::types::Role::User,
    pmcp::types::SamplingMessageContent::Text {
        text: "Explain how to implement a binary search tree".to_string(),
        meta: None,
    },
);
let prefs = pmcp::types::ModelPreferences::new()
    .with_hints(vec![pmcp::types::ModelHint::new("gpt-4")])
    .with_cost_priority(0.5)
    .with_speed_priority(0.3)
    .with_intelligence_priority(0.2);
let mut request = CreateMessageParams::new(vec![msg])
    .with_model_preferences(prefs)
    .with_system_prompt("You are a helpful programming assistant")
    .with_temperature(0.7)
    .with_max_tokens(1000);
request.include_context = pmcp::types::IncludeContext::ThisServer;

let result = client.create_message(request).await?;
println!("Model: {}", result.model);
println!("Response: {:?}", result.content);
§Errors

Returns an error if:

  • The client is not initialized
  • The server doesn’t support sampling
  • The request parameters are invalid
  • Network or protocol errors occur
Source

pub async fn send_roots_list_changed(&self) -> Result<()>

Send roots list changed notification.

Notifies the server that the client’s root list has changed. This is typically sent when the workspace or project roots are modified.

§Examples
use pmcp::{Client, StdioTransport, ClientCapabilities};

let mut capabilities = ClientCapabilities::default();
// Enable roots list changed capability
capabilities.roots = Some(pmcp::RootsCapabilities {
    list_changed: true,
});

let transport = StdioTransport::new();
let mut client = Client::new(transport);
client.initialize(capabilities).await?;

// Notify server when project roots change
client.send_roots_list_changed().await?;
§Errors

Returns an error if:

  • The client is not initialized
  • The client doesn’t support roots list changed notifications
  • Network or protocol errors occur
Source

pub fn authenticate(&self, auth_info: &AuthInfo) -> Result<()>

Authenticate with the server.

Performs authentication using the provided authentication information. This should be called after initialization if the server requires authentication.

§Examples
use pmcp::{Client, StdioTransport, AuthInfo, AuthScheme};

let transport = StdioTransport::new();
let mut client = Client::new(transport);

// Initialize first
client.initialize(pmcp::ClientCapabilities::default()).await?;

// Authenticate with bearer token
let auth = AuthInfo {
    scheme: AuthScheme::Bearer,
    token: Some("your-api-token".to_string()),
    oauth: None,
    params: Default::default(),
};

client.authenticate(&auth)?;
§Errors

Returns an error if:

  • The client is not initialized
  • Authentication fails
  • The server doesn’t support authentication
Source

pub async fn cancel_request(&self, request_id: &RequestId) -> Result<()>

Cancel a request.

Sends a cancellation notification for an active request. This allows graceful termination of long-running operations.

§Arguments
  • request_id - The ID of the request to cancel
§Examples
use pmcp::{Client, StdioTransport, ClientCapabilities, RequestId};
use serde_json::json;

let transport = StdioTransport::new();
let mut client = Client::new(transport);
client.initialize(ClientCapabilities::default()).await?;

// Start a long-running operation
let request_id = RequestId::String("long-operation-123".to_string());

// Later, cancel the request if needed
client.cancel_request(&request_id).await?;
§Errors

Returns an error if:

  • Network or protocol errors occur while sending the cancellation
Source

pub async fn send_progress(&self, progress: ProgressNotification) -> Result<()>

Send a progress notification.

Sends a progress update for a long-running operation. This allows the server or client to track operation progress.

§Arguments
  • progress - The progress notification to send
§Examples
use pmcp::{Client, StdioTransport, ClientCapabilities, ProgressNotification, RequestId};

let transport = StdioTransport::new();
let mut client = Client::new(transport);
client.initialize(ClientCapabilities::default()).await?;

// Send progress update for a file processing operation
let progress = ProgressNotification::new(
    pmcp::ProgressToken::String("file-processing".to_string()),
    75.0,
    Some("Processing files...".to_string()),
);

client.send_progress(progress).await?;
§Errors

Returns an error if:

  • Network or protocol errors occur while sending the notification

Trait Implementations§

Source§

impl<T: Transport> Clone for Client<T>

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<T: Transport> Debug for Client<T>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T> Freeze for Client<T>

§

impl<T> !RefUnwindSafe for Client<T>

§

impl<T> Send for Client<T>

§

impl<T> Sync for Client<T>

§

impl<T> Unpin for Client<T>

§

impl<T> UnsafeUnpin for Client<T>

§

impl<T> !UnwindSafe for Client<T>

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<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
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 = 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
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,