Skip to main content

ClaudeClient

Struct ClaudeClient 

Source
pub struct ClaudeClient { /* private fields */ }
Expand description

Bidirectional client for streaming Claude interactions.

ClaudeClient provides a full-featured interface for interactive conversations with Claude. Unlike the simple query function, this client maintains a persistent connection and supports multiple queries, callbacks, and runtime configuration changes.

§Examples

§Basic Usage

use claude_agents_sdk::ClaudeClient;
use tokio_stream::StreamExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = ClaudeClient::new(None);
    client.connect().await?;

    // Send first query
    client.query("What is Rust?").await?;

    // Process responses
    while let Some(msg) = client.receive_messages().next().await {
        println!("{:?}", msg?);
    }

    client.disconnect().await?;
    Ok(())
}

§With Tool Permission Callback

use claude_agents_sdk::{ClaudeClient, ClaudeAgentOptions, PermissionResult};
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let options = ClaudeAgentOptions::new()
        .with_can_use_tool(|tool_name, input, _ctx| async move {
            println!("Tool request: {} with {:?}", tool_name, input);
            PermissionResult::allow()
        });

    let mut client = ClaudeClient::new(Some(options));
    client.connect().await?;

    // Queries will now invoke the callback for tool permissions

    Ok(())
}

Implementations§

Source§

impl ClaudeClient

Source

pub fn new(options: Option<ClaudeAgentOptions>) -> Self

Create a new Claude client.

§Arguments
  • options - Optional configuration for the client
§Examples
use claude_agents_sdk::{ClaudeClient, ClaudeAgentOptions, PermissionMode};

// Default configuration
let client = ClaudeClient::new(None);

// With custom options
let options = ClaudeAgentOptions::new()
    .with_model("claude-3-opus")
    .with_permission_mode(PermissionMode::AcceptEdits);
let client = ClaudeClient::new(Some(options));
Source

pub async fn connect(&mut self) -> Result<()>

Connect to the Claude CLI.

This establishes a connection to the CLI process and initializes the streaming session. Must be called before sending queries.

§Errors

Returns an error if:

  • The CLI is not found
  • The CLI version is incompatible
  • Connection fails
§Examples
use claude_agents_sdk::ClaudeClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = ClaudeClient::new(None);
    client.connect().await?;
    // Client is now ready for queries
    Ok(())
}
Source

pub async fn query(&mut self, prompt: &str) -> Result<()>

Send a query to Claude.

Sends a new prompt to Claude. Responses can be received using receive_messages or receive_response.

§Arguments
  • prompt - The prompt to send
§Errors

Returns an error if the client is not connected.

§Examples
use claude_agents_sdk::ClaudeClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = ClaudeClient::new(None);
    client.connect().await?;

    client.query("Hello!").await?;
    client.query("Follow-up question").await?;

    Ok(())
}
Source

pub fn receive_messages(&mut self) -> impl Stream<Item = Result<Message>> + '_

Get a stream of messages from the current query.

Returns a stream that yields messages as they are received from Claude. The stream ends when a result message is received.

§Examples
use claude_agents_sdk::{ClaudeClient, Message};
use tokio_stream::StreamExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = ClaudeClient::new(None);
    client.connect().await?;
    client.query("Tell me a joke").await?;

    while let Some(msg) = client.receive_messages().next().await {
        match msg? {
            Message::Assistant(asst) => println!("{}", asst.text()),
            Message::Result(_) => break,
            _ => {}
        }
    }

    Ok(())
}
Source

pub async fn receive_response(&mut self) -> Result<(String, ResultMessage)>

Receive the complete response for the current query.

Collects all messages until a result message is received and returns the combined response text along with the result metadata.

§Returns

A tuple of (response_text, result_message).

§Examples
use claude_agents_sdk::ClaudeClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = ClaudeClient::new(None);
    client.connect().await?;
    client.query("What is 2 + 2?").await?;

    let (response, result) = client.receive_response().await?;
    println!("Response: {}", response);
    println!("Turns: {}", result.num_turns);

    Ok(())
}
Source

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

Interrupt the current operation.

Sends an interrupt signal to Claude, stopping the current response.

§Examples
use claude_agents_sdk::ClaudeClient;
use tokio::time::{timeout, Duration};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = ClaudeClient::new(None);
    client.connect().await?;
    client.query("Write a very long story").await?;

    // Interrupt after 5 seconds
    tokio::time::sleep(Duration::from_secs(5)).await;
    client.interrupt().await?;

    Ok(())
}
Source

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

Change the permission mode for the session.

§Arguments
  • mode - The new permission mode
§Examples
use claude_agents_sdk::{ClaudeClient, PermissionMode};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = ClaudeClient::new(None);
    client.connect().await?;

    // Switch to accept edits mode
    client.set_permission_mode(PermissionMode::AcceptEdits).await?;

    Ok(())
}
Source

pub async fn set_model(&self, model: impl Into<String>) -> Result<()>

Change the model for the session.

§Arguments
  • model - The new model identifier
§Examples
use claude_agents_sdk::ClaudeClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = ClaudeClient::new(None);
    client.connect().await?;

    // Switch to a different model
    client.set_model("claude-3-opus").await?;

    Ok(())
}
Source

pub async fn rewind_files( &self, user_message_id: impl Into<String>, ) -> Result<()>

Rewind files to a specific user message.

This is only available when file checkpointing is enabled.

§Arguments
  • user_message_id - The UUID of the user message to rewind to
§Examples
use claude_agents_sdk::{ClaudeClient, ClaudeAgentOptions};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut options = ClaudeAgentOptions::new();
    options.enable_file_checkpointing = true;

    let mut client = ClaudeClient::new(Some(options));
    client.connect().await?;

    // Later, rewind to a previous state
    client.rewind_files("user-message-uuid").await?;

    Ok(())
}
Source

pub async fn get_server_info(&self) -> Option<Value>

Get server initialization info.

Returns the initialization response from the CLI, which includes available commands, output styles, and server capabilities.

§Returns

Some(Value) with server info if connected and initialized, None otherwise.

§Examples
use claude_agents_sdk::ClaudeClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = ClaudeClient::new(None);
    client.connect().await?;

    if let Some(info) = client.get_server_info().await {
        println!("Commands: {:?}", info.get("commands"));
        println!("Output style: {:?}", info.get("output_style"));
    }

    Ok(())
}
Source

pub async fn get_mcp_status(&self) -> Result<Value>

Get current MCP server connection status (streaming mode only).

Source

pub async fn disconnect(&mut self) -> Result<()>

Disconnect from the Claude CLI.

Gracefully closes the connection to the CLI process.

§Examples
use claude_agents_sdk::ClaudeClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = ClaudeClient::new(None);
    client.connect().await?;

    // Use the client...

    client.disconnect().await?;
    Ok(())
}
Source

pub fn is_connected(&self) -> bool

Check if the client is connected.

Source§

impl ClaudeClient

Source

pub fn into_guard(self) -> ClientGuard

Convert this client into a guard that automatically disconnects on drop.

This is the Rust equivalent of Python’s async with ClaudeSDKClient() as client: pattern.

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