ClaudeClient

Struct ClaudeClient 

Source
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

Source

pub fn new(options: ClaudeAgentOptions) -> Self

Create a new ClaudeClient

§Arguments
  • options - Configuration options for the Claude client
§Example
use claude_agent_sdk_rs::{ClaudeClient, ClaudeAgentOptions};

let client = ClaudeClient::new(ClaudeAgentOptions::default());
Source

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())?;
Source

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
Source

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?;
Source

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 send
  • session_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?;
Source

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?;
Source

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?;
Source

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?);
}
Source

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;
        }
        _ => {}
    }
}
Source

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.

Source

pub async fn set_permission_mode(&self, mode: PermissionMode) -> Result<()>

Change the permission mode dynamically

This is analogous to Python’s client.set_permission_mode().

§Arguments
  • mode - The new permission mode to set
§Errors

Returns an error if the client is not connected or if sending fails.

Source

pub async fn set_model(&self, model: Option<&str>) -> Result<()>

Change the AI model dynamically

This is analogous to Python’s client.set_model().

§Arguments
  • model - The new model name, or None to use default
§Errors

Returns an error if the client is not connected or if sending fails.

Source

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=true in options to track file changes
  • extra_args={"replay-user-messages": None} to receive UserMessage objects with uuid in the response stream
§Arguments
  • user_message_id - UUID of the user message to rewind to. This should be the uuid field from a UserMessage received 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?;
}
Source

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"));
}
Source

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 use
  • prompt - 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?;
Source

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.

Trait Implementations§

Source§

impl Drop for ClaudeClient

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

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

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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, 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<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