The claw code API client lives in rust/crates/api/src/client.rs and serves as the sole interface between the agent runtime and the Anthropic LLM backend. It wraps a reqwest::Client with authentication, base URL configuration, and a configurable retry policy. Every message sent to and received from the Claude API flows through this crate.
AnthropicClient
The AnthropicClient struct is the central type. It holds the HTTP client, authentication source, base URL, and retry configuration. Two primary methods handle all API communication:
send_message(request)— Non-streaming call. Sends aMessageRequestand returns a fully materializedMessageResponse.stream_message(request)— Streaming call. Returns aMessageStreamthat wraps the rawreqwest::Responsewith anSseParser. Callnext_event()to yieldOption<StreamEvent>values incrementally.
Constants
| Constant | Value |
|---|---|
DEFAULT_BASE_URL | https://api.anthropic.com |
ANTHROPIC_VERSION | 2023-06-01 |
DEFAULT_MAX_RETRIES | 2 |
DEFAULT_INITIAL_BACKOFF | 200ms |
DEFAULT_MAX_BACKOFF | 2s |
Authentication
The claw code API client supports multiple authentication modes through the AuthSource enum:
Two factory methods construct the client from environment state:
from_env()— ReadsANTHROPIC_API_KEYandANTHROPIC_AUTH_TOKENfrom the environment.from_env_or_saved()— Also checks for saved OAuth credentials at~/.claude/credentials.json(or$CLAUDE_CONFIG_HOME/credentials.json).
OAuth PKCE Flow
For browser-based authentication, the claw code API client implements the full OAuth PKCE (Proof Key for Code Exchange) flow:
generate_pkce_pair()— Creates a cryptographic code verifier and S256 challenge.loopback_redirect_uri(port)— Constructs the redirect URI pointing to a local callback listener.- The user is directed to the browser for authorization.
- A local server captures the callback with the authorization code.
exchange_oauth_code(config, request)— Exchanges the code for tokens.refresh_oauth_token(config, request)— Refreshes expired tokens.
Credentials are persisted as an OAuthTokenSet containing access_token, refresh_token, expires_at, and scopes. The save operation uses atomic temp-file rename to prevent corruption.
API Types
MessageRequest
The request payload sent to the Messages API:
| Field | Type | Description |
|---|---|---|
model | String | Model identifier (e.g., claude-sonnet-4-20250514) |
max_tokens | u32 | Maximum tokens in the response |
messages | Vec<Message> | Conversation history |
system | Option<String> | System prompt |
tools | Option<Vec<Tool>> | Available tools for the model |
tool_choice | Option<ToolChoice> | Tool selection policy |
stream | bool | Whether to stream the response |
MessageResponse
| Field | Type | Description |
|---|---|---|
id | String | Unique message identifier |
kind | String | Message type |
role | String | Always "assistant" |
content | Vec<OutputContentBlock> | Response content blocks (text, tool use) |
model | String | Model that generated the response |
stop_reason | Option<String> | Why generation stopped |
stop_sequence | Option<String> | The stop sequence that triggered, if any |
usage | Usage | Token usage metrics |
request_id | Option<String> | Server-assigned request ID |
Streaming and SSE Parsing
The claw code API client processes streaming responses using Server-Sent Events (SSE). The SseParser handles raw byte chunks from the HTTP response:
push(chunk)— Feed a raw byte chunk into the parser buffer.finish()— Signal that the stream has ended.parse_frame— Processesevent:anddata:lines, ignoringpingframes and[DONE]sentinels.
StreamEvent Enum
| Variant | Description |
|---|---|
MessageStart | Stream opened, includes initial message metadata |
MessageDelta | Message-level updates (stop reason, usage) |
ContentBlockStart | New content block beginning |
ContentBlockDelta | Incremental content — TextDelta for text, InputJsonDelta for tool input |
ContentBlockStop | Content block complete |
MessageStop | Stream complete |
Usage Tracking
Every response includes a Usage struct that tracks token usage across four dimensions:
| Field | Description |
|---|---|
input_tokens | Tokens consumed by the input prompt |
cache_creation_input_tokens | Tokens used to create a new cache entry |
cache_read_input_tokens | Tokens served from an existing cache entry |
output_tokens | Tokens generated in the response |
The total_tokens() method returns the sum of all four fields.
Retry Policy
The claw code API client automatically retries failed requests for transient HTTP errors. The following status codes are considered retryable:
Retries use exponential backoff starting at 200ms, capped at 2 seconds, with a maximum of 2 retry attempts by default.
Error Types
The ApiError enum covers every failure mode in the API client:
| Variant | Description |
|---|---|
MissingApiKey | No API key or token found in environment or saved credentials |
ExpiredOAuthToken | OAuth token has expired and refresh failed |
Auth | Authentication rejected by the server (401/403) |
Http | HTTP transport error (connection, DNS, TLS) |
Io | File system I/O error (credential read/write) |
Json | JSON serialization/deserialization error |
Api | API-level error with status, error_type, message, and retryable flag |
RetriesExhausted | All retry attempts failed |
InvalidSseFrame | Malformed SSE frame during streaming |
BackoffOverflow | Backoff calculation overflowed (extremely unlikely) |