rust-claude-sdk
A small typed Rust client for Anthropic's Messages API (POST /v1/messages) and the endpoints around it, over raw HTTPS, following the documented wire format.
- Requests with system prompts (top-level or mid-conversation),
documentblocks with citations, images, tools, thinking and effort settings, task budgets, structured outputs (json_schema, read back withMessage::json),cache_controlbreakpoints and server-side refusalfallbacks(the matchinganthropic-betaheaders are added automatically). - Responses with text, citations, thinking, tool calls and fallback markers. Unknown block, citation, event and delta types are kept as raw JSON (
Other) instead of failing, so a new API feature never breaks decoding and assistant turns echo back intact. - Retries on connection errors, 408, 409, 429 and 5xx (honouring
retry-afterandx-should-retry), bounded by an optional deadline that also cuts retries short. - Streaming over server-sent events, event by event or accumulated into the final message.
- Server tools: web search, web fetch, code execution and tool search, with typed definitions, typed result blocks (errors included), web search citations and
usage.server_tool_use. - A tool-use loop,
Client::run_tools: runs the tools the model calls (a turn's calls concurrently), sends all results back in one turn and resumespause_turn, bounded bymax_requests. POST /v1/messages/count_tokens, Message Batches (results streamed line by line), the Files API and the Models API.
Usage
[]
= "0.4"
use ;
let client = new?;
let request = new
.system_cached
.message;
let message = client.create.await?;
println!;
Tools
Tools: the handler gets each call and returns a string, a ToolOutput, or a Result (an Err goes back to the model as an error result). request.messages keeps the whole conversation, so a run cut short or failed resumes by calling again.
use ;
use json;
let mut request = new
.tool
.user;
let run = client
.run_tools
.await?;
if run.is_finished && !run.message.is_refusal
Web search
use ;
let request = new
.tool
.user;
let message = client.create.await?;
for in message.citations
for in message.server_tool_errors
Batches, files and models
use ;
let batch = client.create_batch.await?;
// ...poll `client.batch(&batch.id)` until `is_ended()`, then:
let mut results = client.batch_results.await?;
while let Some = results.next.await
let file = client.upload_file.await?;
let request = new
.message;
let opus = client.model.await?;
println!;
let page = client.list_models.await?;
API version
Requests go out with anthropic-version: 2026-10-21 (migration guide). On that version:
temperature,top_pandtop_kare removed, adocumentblock directly in an assistant message is rejected, and so iscitationson text in a user message (search_resultblocks included).MessagesRequest::validatechecks these rules, and the client runs it before sending, so such a request fails withError::InvalidRequestand is never sent.MessageParamhas one variant per role (User,Assistant,System). A system message holds text only.role()andcontent()read a message of any role.- An API key is sent as
Authorization: Bearer. For a proxy or gateway that readsx-api-key, useCredential::XApiKey.
To keep the old behaviour for a client, for example sampling with a lower temperature on a model that accepts it, set api_version: LEGACY_API_VERSION.into() in its ClientConfig. Requests on that version are not checked.
Examples
Runnable programs in examples/, each started with ANTHROPIC_API_KEY=... cargo run --example <name>:
| Example | Shows |
|---|---|
grounded |
A streamed answer grounded in documents, with citations, prompt caching, effort and refusal fallbacks |
chat |
A multi-turn terminal chat: streaming, adaptive thinking shown live, echoing assistant turns back |
tools |
The tool-use loop with two local tools (one strict), concurrent calls and a deadline |
web_search |
Web search and web fetch server tools, cited sources, server tool errors and usage |
code_execution |
Server-side code execution, its output, and downloading the files it writes |
files |
Uploading a PDF to the Files API, asking about it by id with citations, deleting it |
batch |
Creating a Message Batch, polling it and streaming its results |
models |
Paging through the Models API with capabilities, and counting tokens |
ANTHROPIC_API_KEY=...
ANTHROPIC_API_KEY=...
Development
Rust ≥ 1.85.
Tests run against a local mock server and need no API key.
Releasing
Bump version in Cargo.toml, merge to main, then push a matching tag:
The Release workflow checks that the tag matches the crate version, runs the checks above and publishes to crates.io with the CARGO_REGISTRY_TOKEN repository secret.
License
Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Originally written as the rogov-anthropic crate in aoprisan/govromania.