pub struct Client<T: Transport> { /* private fields */ }Expand description
MCP client for connecting to servers.
Implementations§
Source§impl<T: Transport> Client<T>
impl<T: Transport> Client<T>
Sourcepub fn new(transport: T) -> Self
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);Sourcepub fn with_info(transport: T, client_info: Implementation) -> Self
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);Sourcepub fn with_options(
transport: T,
client_info: Implementation,
options: ProtocolOptions,
) -> Self
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);Sourcepub fn with_client_options(transport: T, options: ClientOptions) -> Self
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);Sourcepub async fn initialize(
&mut self,
capabilities: ClientCapabilities,
) -> Result<InitializeResult>
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
Sourcepub fn get_server_capabilities(&self) -> Option<&ServerCapabilities>
pub fn get_server_capabilities(&self) -> Option<&ServerCapabilities>
Get server capabilities after initialization.
Sourcepub fn get_server_version(&self) -> Option<&Implementation>
pub fn get_server_version(&self) -> Option<&Implementation>
Get server version information after initialization.
Sourcepub fn get_instructions(&self) -> Option<&str>
pub fn get_instructions(&self) -> Option<&str>
Get server instructions after initialization.
Sourcepub async fn set_logging_level(&self, level: LoggingLevel) -> Result<()>
pub async fn set_logging_level(&self, level: LoggingLevel) -> Result<()>
Set the logging level on the server.
Sourcepub async fn list_tools(
&self,
cursor: Option<String>,
) -> Result<ListToolsResult>
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
Sourcepub async fn call_tool(
&self,
name: String,
arguments: Value,
) -> Result<CallToolResult>
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 callarguments- 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
Sourcepub async fn call_tool_with_task(
&self,
name: String,
arguments: Value,
) -> Result<ToolCallResponse>
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 withtasks_getuntil the task reaches a terminal status.Ok(ToolCallResponse::Result(result))if the server returned the result synchronously.
Sourcepub async fn tasks_get(&self, task_id: &str) -> Result<Task>
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
Sourcepub async fn tasks_result(&self, task_id: &str) -> Result<CallToolResult>
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.
Sourcepub async fn tasks_list(
&self,
cursor: Option<String>,
) -> Result<ListTasksResult>
pub async fn tasks_list( &self, cursor: Option<String>, ) -> Result<ListTasksResult>
List tasks owned by the current client.
Sourcepub async fn tasks_cancel(&self, task_id: &str) -> Result<Task>
pub async fn tasks_cancel(&self, task_id: &str) -> Result<Task>
Cancel a running task.
Sourcepub async fn call_tool_and_poll(
&self,
name: String,
arguments: Value,
max_polls: usize,
) -> Result<CallToolResult>
Available on non-WebAssembly only.
pub async fn call_tool_and_poll( &self, name: String, arguments: Value, max_polls: usize, ) -> Result<CallToolResult>
Call a tool and automatically poll until the task completes.
This is a high-level convenience method that encapsulates the full task lifecycle:
- Calls the tool with task augmentation
- If the server returns a task, polls
tasks/getuntil terminal status - Returns the final
CallToolResult
If the server returns a sync result (no task), returns it immediately.
§Arguments
name- Tool namearguments- Tool argumentsmax_polls- Maximum number of poll attempts before giving up (0 = unlimited)
Sourcepub async fn list_prompts(
&self,
cursor: Option<String>,
) -> Result<ListPromptsResult>
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
Sourcepub async fn get_prompt(
&self,
name: String,
arguments: HashMap<String, String>,
) -> Result<GetPromptResult>
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 retrievearguments- 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
Sourcepub async fn call_tool_typed<A: Serialize + ?Sized + Sync>(
&self,
name: impl Into<String> + Send,
args: &A,
) -> Result<CallToolResult>
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?;Sourcepub async fn call_tool_typed_with_task<A: Serialize + ?Sized + Sync>(
&self,
name: impl Into<String> + Send,
args: &A,
) -> Result<ToolCallResponse>
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?;Sourcepub 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.
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>
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?;Sourcepub async fn get_prompt_typed<A: Serialize + ?Sized + Sync>(
&self,
name: impl Into<String> + Send,
args: &A,
) -> Result<GetPromptResult>
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:
nullentries are omittedstringentries pass through unchanged (no JSON-quoting)numberandboolentries useDisplay(e.g.42,true)arrayandobjectentries are re-serialized viaserde_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?;Sourcepub async fn list_resources(
&self,
cursor: Option<String>,
) -> Result<ListResourcesResult>
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
Sourcepub async fn list_resource_templates(
&self,
cursor: Option<String>,
) -> Result<ListResourceTemplatesResult>
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
Sourcepub async fn list_all_tools(&self) -> Result<Vec<ToolInfo>>
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_toolspropagates 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());Sourcepub async fn list_all_prompts(&self) -> Result<Vec<PromptInfo>>
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_promptspropagates 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());Sourcepub async fn list_all_resources(&self) -> Result<Vec<ResourceInfo>>
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_resourcespropagates 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());Sourcepub async fn list_all_resource_templates(&self) -> Result<Vec<ResourceTemplate>>
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_templatespropagates 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());Sourcepub async fn read_resource(&self, uri: String) -> Result<ReadResourceResult>
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
Sourcepub async fn subscribe_resource(&self, uri: String) -> Result<()>
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
Sourcepub async fn unsubscribe_resource(&self, uri: String) -> Result<()>
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
Sourcepub async fn complete(&self, params: CompleteRequest) -> Result<CompleteResult>
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
Sourcepub async fn create_message(
&self,
params: CreateMessageParams,
) -> Result<CreateMessageResult>
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
Sourcepub async fn send_roots_list_changed(&self) -> Result<()>
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
Sourcepub fn authenticate(&self, auth_info: &AuthInfo) -> Result<()>
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
Sourcepub async fn cancel_request(&self, request_id: &RequestId) -> Result<()>
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
Sourcepub async fn send_progress(&self, progress: ProgressNotification) -> Result<()>
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