pub struct ClaudeClient { /* private fields */ }Expand description
Client for bidirectional streaming interactions with Claude
This client provides the same functionality as Python’s ClaudeSDKClient, supporting bidirectional communication, streaming responses, and dynamic control over the Claude session.
§Example
use claude_agent_sdk_rs::{ClaudeClient, ClaudeAgentOptions};
use futures::StreamExt;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = ClaudeClient::new(ClaudeAgentOptions::default());
// Connect to Claude
client.connect().await?;
// Send a query
client.query("Hello Claude!").await?;
// Receive response as a stream
{
let mut stream = client.receive_response();
while let Some(message) = stream.next().await {
println!("Received: {:?}", message?);
}
}
// Disconnect
client.disconnect().await?;
Ok(())
}Implementations§
Source§impl ClaudeClient
impl ClaudeClient
Sourcepub fn new(options: ClaudeAgentOptions) -> Self
pub fn new(options: ClaudeAgentOptions) -> Self
Sourcepub fn try_new(options: ClaudeAgentOptions) -> Result<Self>
pub fn try_new(options: ClaudeAgentOptions) -> Result<Self>
Create a new ClaudeClient with early validation
Unlike new(), this validates the configuration eagerly by attempting
to create the transport. This catches issues like invalid working directory
or missing CLI before connect() is called.
§Arguments
options- Configuration options for the Claude client
§Errors
Returns an error if:
- The working directory does not exist or is not a directory
- Claude CLI cannot be found
§Example
use claude_agent_sdk_rs::{ClaudeClient, ClaudeAgentOptions};
let client = ClaudeClient::try_new(ClaudeAgentOptions::default())?;Sourcepub async fn connect(&mut self) -> Result<()>
pub async fn connect(&mut self) -> Result<()>
Connect to Claude (analogous to Python’s aenter)
This establishes the connection to the Claude Code CLI and initializes the bidirectional communication channel.
§Errors
Returns an error if:
- Claude CLI cannot be found or started
- The initialization handshake fails
- Hook registration fails
Sourcepub async fn query(&mut self, prompt: impl Into<String>) -> Result<()>
pub async fn query(&mut self, prompt: impl Into<String>) -> Result<()>
Send a query to Claude
This sends a new user prompt to Claude. Claude will remember the context of previous queries within the same session.
§Arguments
prompt- The user prompt to send
§Errors
Returns an error if the client is not connected or if sending fails.
§Example
client.query("What is 2 + 2?").await?;Sourcepub async fn query_with_session(
&mut self,
prompt: impl Into<String>,
session_id: impl Into<String>,
) -> Result<()>
pub async fn query_with_session( &mut self, prompt: impl Into<String>, session_id: impl Into<String>, ) -> Result<()>
Send a query to Claude with a specific session ID
This sends a new user prompt to Claude. Different session IDs maintain separate conversation contexts.
§Arguments
prompt- The user prompt to sendsession_id- Session identifier for the conversation
§Errors
Returns an error if the client is not connected or if sending fails.
§Example
// Separate conversation contexts
client.query_with_session("First question", "session-1").await?;
client.query_with_session("Different question", "session-2").await?;Sourcepub async fn query_with_content(
&mut self,
content: impl Into<Vec<UserContentBlock>>,
) -> Result<()>
pub async fn query_with_content( &mut self, content: impl Into<Vec<UserContentBlock>>, ) -> Result<()>
Send a query with structured content blocks (supports images)
This method enables multimodal queries in bidirectional streaming mode. Use it to send images alongside text for vision-related tasks.
§Arguments
content- A vector of content blocks (text and/or images)
§Errors
Returns an error if:
- The content vector is empty (must include at least one text or image block)
- The client is not connected (call
connect()first) - Sending the message fails
§Example
let base64_data = "iVBORw0KGgo..."; // base64 encoded image
client.query_with_content(vec![
UserContentBlock::text("What's in this image?"),
UserContentBlock::image_base64("image/png", base64_data)?,
]).await?;Sourcepub async fn query_with_content_and_session(
&mut self,
content: impl Into<Vec<UserContentBlock>>,
session_id: impl Into<String>,
) -> Result<()>
pub async fn query_with_content_and_session( &mut self, content: impl Into<Vec<UserContentBlock>>, session_id: impl Into<String>, ) -> Result<()>
Send a query with structured content blocks and a specific session ID
This method enables multimodal queries with session management for maintaining separate conversation contexts.
§Arguments
content- A vector of content blocks (text and/or images)session_id- Session identifier for the conversation
§Errors
Returns an error if:
- The content vector is empty (must include at least one text or image block)
- The client is not connected (call
connect()first) - Sending the message fails
§Example
client.query_with_content_and_session(
vec![
UserContentBlock::text("Analyze this chart"),
UserContentBlock::image_url("https://example.com/chart.png"),
],
"analysis-session",
).await?;Sourcepub fn receive_messages(
&self,
) -> Pin<Box<dyn Stream<Item = Result<Message>> + Send + '_>>
pub fn receive_messages( &self, ) -> Pin<Box<dyn Stream<Item = Result<Message>> + Send + '_>>
Receive all messages as a stream (continuous)
This method returns a stream that yields all messages from Claude indefinitely until the stream is closed or an error occurs.
Use this when you want to process all messages, including multiple responses and system events.
§Returns
A stream of Result<Message> that continues until the connection closes.
§Example
let mut stream = client.receive_messages();
while let Some(message) = stream.next().await {
println!("Received: {:?}", message?);
}Sourcepub fn receive_response(
&self,
) -> Pin<Box<dyn Stream<Item = Result<Message>> + Send + '_>>
pub fn receive_response( &self, ) -> Pin<Box<dyn Stream<Item = Result<Message>> + Send + '_>>
Receive messages until a ResultMessage
This method returns a stream that yields messages until it encounters
a ResultMessage, which signals the completion of a Claude response.
This is the most common pattern for handling Claude responses, as it processes one complete “turn” of the conversation.
§Returns
A stream of Result<Message> that ends when a ResultMessage is received.
§Example
let mut stream = client.receive_response();
while let Some(message) = stream.next().await {
match message? {
Message::Assistant(msg) => println!("Assistant: {:?}", msg),
Message::Result(result) => {
println!("Done! Cost: ${:?}", result.total_cost_usd);
break;
}
_ => {}
}
}Sourcepub async fn interrupt(&self) -> Result<()>
pub async fn interrupt(&self) -> Result<()>
Send an interrupt signal to stop the current Claude operation
This is analogous to Python’s client.interrupt().
§Errors
Returns an error if the client is not connected or if sending fails.
Sourcepub async fn set_permission_mode(&self, mode: PermissionMode) -> Result<()>
pub async fn set_permission_mode(&self, mode: PermissionMode) -> Result<()>
Sourcepub async fn rewind_files(&self, user_message_id: &str) -> Result<()>
pub async fn rewind_files(&self, user_message_id: &str) -> Result<()>
Rewind tracked files to their state at a specific user message.
This is analogous to Python’s client.rewind_files().
§Requirements
enable_file_checkpointing=truein options to track file changesextra_args={"replay-user-messages": None}to receive UserMessage objects withuuidin the response stream
§Arguments
user_message_id- UUID of the user message to rewind to. This should be theuuidfield from aUserMessagereceived during the conversation.
§Errors
Returns an error if the client is not connected or if sending fails.
§Example
let options = ClaudeAgentOptions::builder()
.enable_file_checkpointing(true)
.extra_args(HashMap::from([("replay-user-messages".to_string(), None)]))
.build();
let mut client = ClaudeClient::new(options);
client.connect().await?;
client.query("Make some changes to my files").await?;
let mut checkpoint_id = None;
{
let mut stream = client.receive_response();
use futures::StreamExt;
while let Some(Ok(msg)) = stream.next().await {
if let Message::User(user_msg) = &msg {
if let Some(uuid) = &user_msg.uuid {
checkpoint_id = Some(uuid.clone());
}
}
}
}
// Later, rewind to that point
if let Some(id) = checkpoint_id {
client.rewind_files(&id).await?;
}Sourcepub async fn get_server_info(&self) -> Option<Value>
pub async fn get_server_info(&self) -> Option<Value>
Get server initialization info including available commands and output styles
Returns initialization information from the Claude Code server including:
- Available commands (slash commands, system commands, etc.)
- Current and available output styles
- Server capabilities
This is analogous to Python’s client.get_server_info().
§Returns
Dictionary with server info, or None if not connected
§Example
if let Some(info) = client.get_server_info().await {
println!("Commands available: {}", info.get("commands").map(|c| c.as_array().map(|a| a.len()).unwrap_or(0)).unwrap_or(0));
println!("Output style: {:?}", info.get("output_style"));
}Sourcepub async fn new_session(
&mut self,
session_id: impl Into<String>,
prompt: impl Into<String>,
) -> Result<()>
pub async fn new_session( &mut self, session_id: impl Into<String>, prompt: impl Into<String>, ) -> Result<()>
Start a new session by switching to a different session ID
This is a convenience method that creates a new conversation context.
It’s equivalent to calling query_with_session() with a new session ID.
To completely clear memory and start fresh, use ClaudeAgentOptions::builder().fork_session(true).build()
when creating a new client.
§Arguments
session_id- The new session ID to useprompt- Initial message for the new session
§Errors
Returns an error if the client is not connected or if sending fails.
§Example
// First conversation
client.query("Hello").await?;
// Start new conversation with different context
client.new_session("session-2", "Tell me about Rust").await?;Sourcepub async fn disconnect(&mut self) -> Result<()>
pub async fn disconnect(&mut self) -> Result<()>
Disconnect from Claude (analogous to Python’s aexit)
This cleanly shuts down the connection to Claude Code CLI.
§Errors
Returns an error if disconnection fails.