Expand description
Strands Agents SDK for Rust.
A model-driven approach to building AI agents: give a model a system prompt and tools, and the agent loop calls the model, runs the tools it asks for and feeds their results back until the model answers.
This is a developer preview: the API may change in any 0.x release.
§Quick start
An agent with a tool, on the default model (Amazon Bedrock, with credentials and region from the AWS default chain), invoked once and then streamed:
use futures::StreamExt;
use strands::{tool, Agent, AgentStreamEvent};
/// Get the current weather for a city.
#[tool]
async fn get_weather(
/// City name, for example "Seattle".
city: String,
) -> Result<String, strands::ToolError> {
Ok(format!("Sunny in {city}"))
}
#[tokio::main]
async fn main() -> Result<(), strands::Error> {
let mut agent = Agent::builder() // default model: Bedrock
.system_prompt("You are a concise assistant.")
.tools([GetWeather])
.build()?;
let result = agent.invoke("What's the weather in Seattle?").await?;
println!("{result}");
{
let mut stream = agent.stream("And in Lisbon?");
while let Some(event) = stream.next().await {
if let AgentStreamEvent::ModelStreamUpdate(update) = event? {
if let Some(text) = update.text_delta() {
print!("{text}");
}
}
}
}
agent.shutdown().await
}The agent module shows the other everyday shapes: the AgentConfig struct, tools with
state through #[tools], hooks, structured output and cancellation. The crate’s
examples/
directory has a runnable program for each provider and feature.
§Features
| Feature | Default | Adds |
|---|---|---|
bedrock | yes | models::BedrockModel, the Amazon Bedrock Converse provider, and the default model |
anthropic | models::anthropic::AnthropicModel, the Anthropic Messages API provider; with bedrock, also AnthropicModel::bedrock and AnthropicBedrockConfig for Claude on Bedrock’s InvokeModel API | |
openai | models::openai::OpenAIModel (Responses and Chat Completions); it does not need bedrock | |
mantle | models::openai::OpenAIModel::bedrock_mantle, Amazon Bedrock’s OpenAI-compatible Mantle endpoint, and BedrockMantleConfig; turns on openai, adds the AWS signing and credential crates and does not need bedrock | |
mcp | mcp::McpClient, Model Context Protocol clients over stdio, streamable HTTP and SSE, and the mcp_router tool | |
otel | OpenTelemetry export of the agent’s spans and metrics (telemetry::setup_tracer, telemetry::setup_meter) | |
cedar | CedarAuthorization, Cedar policy authorization of tool calls | |
dogwood | DogwoodAuthorization, Dogwood policy authorization of tool calls, with temporal rules over earlier calls |
Without bedrock an agent needs an explicit model; a Bedrock model id then fails with
DefaultNotConfiguredError. The otel feature’s opentelemetry, opentelemetry_sdk,
tracing-opentelemetry and tracing-subscriber versions are part of the public API: moving
one to a semver-incompatible version is a breaking strands release.
§Modules
| Module | Contents |
|---|---|
agent | Agent, its builder and AgentConfig, AgentResult, InvokeArgs, InvokeOptions, InvocationState, the request’s InvocationContext with its InvokeLimits, direct tool calls, agents as tools, and the LocalAgent and ToolAgent views |
types | Messages, the content blocks (Bedrock Converse JSON shape), media, citations, tool specs, stop reasons, snapshots and interrupt responses |
models | The Model trait with its ModelRequest, stream aggregation, token counting and summarization, ModelInfo, stream events, Usage and Metrics, prompt caching, ModelRouter, and the providers |
tools | The Tool trait, ToolContext, ToolError, tools::FunctionTool, the tools::ToolRegistry, the executors and structured output |
hooks | The 17 hook events, hooks::HookRegistry and HookOrder, and the AgentStreamEvent records an agent stream yields |
plugins | The plugins::Plugin trait |
middleware | Handlers around the model call and each tool execution |
interrupt | Human-in-the-loop Interrupts |
interventions | InterventionHandlers that gate the agent’s lifecycle |
vended_interventions | Human-in-the-loop approval, Cedar policy authorization (feature cedar) and Dogwood policy authorization (feature dogwood) |
conversation_manager | Keeping history within the context window |
context_manager | The strategy-driven ContextManager, its presets, the archive and message pinning |
injection | Folding just-in-time text into the latest user message |
storage | The Storage trait, InMemoryStorage, LocalFileStorage, namespaces and keyword search |
session | SessionManager, saving and restoring agent snapshots in the layout shared with the other Strands SDKs |
memory | The MemoryManager plugin, the MemoryStore trait and extraction |
vended_memory_stores | FileMemoryStore and TestMemoryStore |
sandbox | The Sandbox trait, where tools run commands and touch files, and NotASandboxLocalEnvironment |
vended_tools | Shell, file, HTTP, notebook, agent-loop and subagent tools, and mcp_router (feature mcp) |
vended_plugins | The context injector and AgentSkills |
multiagent | The authority-mode policies child agents are specified with |
background_tasks | Running tool calls detached from the turn that requested them |
retry | DefaultModelRetryStrategy and the backoff strategies |
state_store | StateStore, JSON state shared with tools and providers |
cancel | CancelHandle and CancelSignal for cooperative cancellation |
telemetry | tracing spans and metrics, AgentMetrics and AgentTrace |
error | Error, with one variant per error type |
testing | Fixtures such as testing::MockModel for testing code built on strands |
mcp | Model Context Protocol clients (feature mcp) |
The crate root re-exports the main public types of these modules.
§Wire compatibility
Every serializable type writes the JSON shared with the other Strands SDKs: the same keys in the
same order, with absent optional fields omitted. Sessions and snapshots that another Strands SDK
writes load in Rust and serialize back unchanged, and blocks a newer SDK wrote load as
UnknownBlock:
use strands::{ContentBlock, Message, Role};
let message = Message::new(Role::User, vec![ContentBlock::text("Hello")]);
assert_eq!(message.text(), "Hello");
let json = serde_json::to_value(&message.content).unwrap();
assert_eq!(json, serde_json::json!([{"text": "Hello"}]));§Versioning
strands follows semver for 0.x crates: a minor release (0.1 to 0.2) may break the API, a patch release does not. The minimum supported Rust version is 1.96; it never drops below what required dependencies declare, and it moves only in minor releases.
§Public dependencies
These crates appear in the public API, so a semver-incompatible release of any of them is a breaking strands release:
| Crate | Where | Feature |
|---|---|---|
serde_json | JsonValue, JsonObject | always |
schemars 1 | the JsonSchema derive that structured output and #[tool] inputs use | always |
futures | the Stream behind BoxStream | always |
async-trait | re-exported as async_trait for extension traits | always |
aws-credential-types, aws-types | credentials and SdkConfig escape hatches on the Bedrock and Mantle configs | bedrock, mantle |
regex, rmcp | MCP tool matchers and the raw MCP types of the McpClient escape hatches | mcp |
opentelemetry, opentelemetry_sdk, tracing-opentelemetry, tracing-subscriber | telemetry setup | otel |
strands and strands-macros release in lockstep: strands depends on an exact
strands-macros version.
Re-exports§
pub use agent::Agent;pub use agent::AgentAsTool;pub use agent::AgentAsToolOptions;pub use agent::AgentBuilder;pub use agent::AgentConfig;pub use agent::AgentResult;pub use agent::AgentStream;pub use agent::DirectToolCallOptions;pub use agent::InvocationContext;pub use agent::InvocationContextUsage;pub use agent::InvocationState;pub use agent::InvokeArgs;pub use agent::InvokeLimits;pub use agent::InvokeOptions;pub use agent::LocalAgent;pub use agent::ModelSource;pub use agent::RefusedCall;pub use agent::SnapshotField;pub use agent::SnapshotPreset;pub use agent::TakeSnapshotOptions;pub use agent::ToolAgent;pub use agent::ToolHandle;pub use background_tasks::BackgroundTasksConfig;pub use cancel::CancelHandle;pub use cancel::CancelOptions;pub use cancel::CancelSignal;pub use conversation_manager::ConversationManager;pub use conversation_manager::ConversationManagerReduceOptions;pub use conversation_manager::NullConversationManager;pub use conversation_manager::ProactiveCompression;pub use conversation_manager::SlidingWindowConversationManager;pub use conversation_manager::SlidingWindowConversationManagerConfig;pub use conversation_manager::SummarizingConversationManager;pub use conversation_manager::SummarizingConversationManagerConfig;pub use error::BoxError;pub use error::ContextWindowOverflowError;pub use error::DefaultNotConfiguredError;pub use error::Error;pub use error::JsonValidationError;pub use error::MaxTokensError;pub use error::ModelError;pub use error::ModelNetworkError;pub use error::ModelThrottledError;pub use error::Result;pub use error::SandboxAbortError;pub use error::SandboxIsADirectoryError;pub use error::SandboxPathNotFoundError;pub use error::SandboxPermissionError;pub use error::SandboxTimeoutError;pub use error::SessionError;pub use error::StorageError;pub use error::StructuredOutputError;pub use error::ToolNotFoundError;pub use error::ToolValidationError;pub use hooks::AfterInvocationEvent;pub use hooks::AfterModelCallEvent;pub use hooks::AfterToolCallEvent;pub use hooks::AfterToolsEvent;pub use hooks::AgentResultEvent;pub use hooks::AgentStreamEvent;pub use hooks::BeforeInvocationEvent;pub use hooks::BeforeModelCallEvent;pub use hooks::BeforeToolCallEvent;pub use hooks::BeforeToolsEvent;pub use hooks::Cancel;pub use hooks::ContentBlockEvent;pub use hooks::EndTurn;pub use hooks::Hook;pub use hooks::HookCallbackOptions;pub use hooks::HookCleanup;pub use hooks::HookOrder;pub use hooks::HookRegistry;pub use hooks::InitializedEvent;pub use hooks::InterruptEvent;pub use hooks::MessageAddedEvent;pub use hooks::ModelMessageEvent;pub use hooks::ModelStopResponse;pub use hooks::ModelStreamUpdateEvent;pub use hooks::ToolResultEvent;pub use hooks::ToolStreamUpdateEvent;pub use hooks::ToolUseData;pub use interrupt::Interrupt;pub use interrupt::InterruptError;pub use interrupt::InterruptSource;pub use interventions::InterventionAction;pub use interventions::InterventionHandler;pub use interventions::InterventionResult;pub use interventions::OnError;pub use mcp::ElicitationCallback;pub use mcp::ElicitationContext;pub use mcp::McpCallToolOptions;pub use mcp::McpClient;pub use mcp::McpClientConfig;pub use mcp::McpClientCredentials;pub use mcp::McpClientOptions;pub use mcp::McpConnectionState;pub use mcp::McpListOptions;pub use mcp::McpListToolsOptions;pub use mcp::McpLoadServersOptions;pub use mcp::McpProgress;pub use mcp::McpProgressCallback;pub use mcp::McpServerConfig;pub use mcp::McpTool;pub use mcp::McpToolFilterCallback;pub use mcp::McpToolFilters;pub use mcp::McpToolMatcher;pub use mcp::McpTransport;pub use mcp::SerializableMcpToolFilters;pub use memory::AddMessagesContext;pub use memory::ExtractionConfig;pub use memory::ExtractionResult;pub use memory::ExtractionTrigger;pub use memory::ExtractionTriggerContext;pub use memory::Extractor;pub use memory::ExtractorContext;pub use memory::InjectionConfig;pub use memory::InjectionContext;pub use memory::InjectionTrigger;pub use memory::IntervalTrigger;pub use memory::IntervalTriggerOptions;pub use memory::InvocationTrigger;pub use memory::MemoryAddOptions;pub use memory::MemoryAddToolConfig;pub use memory::MemoryContentBlockType;pub use memory::MemoryEntry;pub use memory::MemoryInjectionConfig;pub use memory::MemoryManager;pub use memory::MemoryManagerConfig;pub use memory::MemoryMessageFilter;pub use memory::MemorySearchOptions;pub use memory::MemoryStore;pub use memory::MemoryToolConfig;pub use memory::ModelExtractor;pub use memory::ModelExtractorOptions;pub use memory::SearchOptions;pub use middleware::ExecuteToolContext;pub use middleware::ExecuteToolResult;pub use middleware::ExecuteToolStage;pub use middleware::InvokeModelContext;pub use middleware::InvokeModelResult;pub use middleware::InvokeModelStage;pub use middleware::Middleware;pub use middleware::MiddlewareCleanup;pub use middleware::MiddlewareError;pub use middleware::MiddlewareInterruptResult;pub use middleware::MiddlewareNext;pub use middleware::MiddlewarePhase;pub use middleware::MiddlewareStage;pub use middleware::StageItem;pub use middleware::StageResult;pub use middleware::StageStream;pub use models::bedrock::BedrockCacheConfig;pub use models::bedrock::BedrockCacheTtl;pub use models::bedrock::BedrockGuardrailConfig;pub use models::bedrock::BedrockGuardrailRedactionConfig;pub use models::bedrock::BedrockModel;pub use models::bedrock::BedrockModelConfig;pub use models::bedrock::BedrockModelOptions;pub use models::routing::CandidateModel;pub use models::routing::ClassifierStrategy;pub use models::routing::ClassifierStrategyOptions;pub use models::routing::FallbackStrategy;pub use models::routing::ModelRouter;pub use models::routing::ModelRouterOptions;pub use models::routing::RoutingAttempt;pub use models::routing::RoutingCandidate;pub use models::routing::RoutingCandidateOptions;pub use models::routing::RoutingContext;pub use models::routing::RoutingFailure;pub use models::routing::RoutingStrategy;pub use models::streaming::CitationsDelta;pub use models::streaming::ContentBlockDelta;pub use models::streaming::ContentBlockStart;pub use models::streaming::Metrics;pub use models::streaming::ModelContentBlockDeltaEvent;pub use models::streaming::ModelContentBlockStartEvent;pub use models::streaming::ModelContentBlockStopEvent;pub use models::streaming::ModelMessageStartEvent;pub use models::streaming::ModelMessageStopEvent;pub use models::streaming::ModelMetadataEvent;pub use models::streaming::ModelRedactionEvent;pub use models::streaming::ModelStreamEvent;pub use models::streaming::ReasoningContentDelta;pub use models::streaming::RedactInputContent;pub use models::streaming::RedactOutputContent;pub use models::streaming::TextDelta;pub use models::streaming::ToolUseInputDelta;pub use models::streaming::ToolUseStart;pub use models::streaming::Usage;pub use models::AggregatedEvent;pub use models::BaseModelConfig;pub use models::BoxStream;pub use models::CacheConfig;pub use models::CacheKey;pub use models::CacheSectionSetting;pub use models::CacheStrategy;pub use models::CacheTtl;pub use models::CountTokensOptions;pub use models::DeferredToolLoading;pub use models::Model;pub use models::ModelCapabilities;pub use models::ModelInfo;pub use models::ModelLimits;pub use models::ModelRequest;pub use models::PromptCaching;pub use models::Redaction;pub use models::StreamAggregatedResult;pub use models::SummarizeOptions;pub use models::SummarizeResult;pub use plugins::Plugin;pub use retry::BackoffContext;pub use retry::BackoffStrategy;pub use retry::ConstantBackoff;pub use retry::ConstantBackoffOptions;pub use retry::DefaultModelRetryStrategy;pub use retry::DefaultModelRetryStrategyOptions;pub use retry::ExponentialBackoff;pub use retry::ExponentialBackoffOptions;pub use retry::IsRetryable;pub use retry::JitterKind;pub use retry::LinearBackoff;pub use retry::LinearBackoffOptions;pub use retry::ModelRetryContext;pub use retry::ModelRetryStrategy;pub use retry::RetryDecision;pub use retry::RetryStrategy;pub use sandbox::ExecuteOptions;pub use sandbox::ExecutionResult;pub use sandbox::ExecutionStream;pub use sandbox::ExecutionStreamItem;pub use sandbox::FileInfo;pub use sandbox::OutputFile;pub use sandbox::PosixShellSandbox;pub use sandbox::Sandbox;pub use sandbox::StreamChunk;pub use sandbox::StreamType;pub use session::SaveLatestStrategy;pub use session::SessionManager;pub use session::SessionManagerConfig;pub use session::SnapshotManifest;pub use session::SnapshotTriggerCallback;pub use session::SnapshotTriggerParams;pub use state_store::StateStore;pub use storage::Storage;pub use telemetry::AgentMetrics;pub use telemetry::AgentTrace;pub use tools::ConcurrentToolExecutor;pub use tools::FunctionTool;pub use tools::SequentialToolExecutor;pub use tools::Tool;pub use tools::ToolContext;pub use tools::ToolError;pub use tools::ToolExecutorStrategy;pub use tools::ToolOutcome;pub use tools::ToolSource;pub use tools::ToolStream;pub use tools::ToolStreamEvent;pub use tools::ToolStreamItem;pub use types::AgentMetadata;pub use types::AudioBlock;pub use types::AudioFormat;pub use types::AudioSource;pub use types::CachePointBlock;pub use types::CacheType;pub use types::Citation;pub use types::CitationGeneratedContent;pub use types::CitationLocation;pub use types::CitationSourceContent;pub use types::CitationsBlock;pub use types::ContentBlock;pub use types::DocumentBlock;pub use types::DocumentCharLocation;pub use types::DocumentChunkLocation;pub use types::DocumentCitations;pub use types::DocumentContentBlock;pub use types::DocumentFormat;pub use types::DocumentPageLocation;pub use types::DocumentSource;pub use types::GuardContentBlock;pub use types::GuardContentImage;pub use types::GuardContentText;pub use types::GuardImageFormat;pub use types::GuardImageSource;pub use types::GuardQualifier;pub use types::ImageBlock;pub use types::ImageFormat;pub use types::ImageSource;pub use types::InjectedBlock;pub use types::InterruptParams;pub use types::InterruptResponse;pub use types::InterruptResponseContent;pub use types::JsonBlock;pub use types::JsonObject;pub use types::JsonValue;pub use types::Message;pub use types::MessageMetadata;pub use types::OffloadMethod;pub use types::Offloaded;pub use types::ReasoningBlock;pub use types::ReasoningProviderData;pub use types::Role;pub use types::S3Location;pub use types::SNAPSHOT_SCHEMA_VERSION;pub use types::Scope;pub use types::SearchResultLocation;pub use types::Snapshot;pub use types::StopReason;pub use types::SummaryBlock;pub use types::SystemContentBlock;pub use types::SystemPrompt;pub use types::TextBlock;pub use types::Toggle;pub use types::ToolChoice;pub use types::ToolReferenceBlock;pub use types::ToolResultBlock;pub use types::ToolResultContent;pub use types::ToolResultError;pub use types::ToolResultStatus;pub use types::ToolSpec;pub use types::ToolUse;pub use types::ToolUseBlock;pub use types::UnknownBlock;pub use types::UnknownStopReason;pub use types::VideoBlock;pub use types::VideoFormat;pub use types::VideoSource;pub use types::WebLocation;
Modules§
- agent
- The agent:
Agentand its configuration, the invocation API and its result, the per-invocation state, the request context, direct tool calls, agents as tools, and the agent views:LocalAgentfor sequential hooks and plugins,ToolAgentfor tools and per-tool hooks. - background_
tasks - Background tool execution.
- cancel
- Cooperative cancellation:
CancelHandle,CancelSignalandCancelOptions. - context_
manager - Strategy-driven context management.
- conversation_
manager - Conversation history management.
- error
- The SDK’s error types.
- hooks
- Hooks: the 17 hook events, the typed
HookRegistryand the stream records (AgentStreamEvent). - injection
- Context injection: the configuration shared by the
ContextInjectorplugin and theMemoryManager’s injection, and the crate-internal engine that folds text into the latest user message before a model call. - interrupt
- Human-in-the-loop interrupts and their persisted state.
- interventions
- Interventions: policies that inspect and gate the agent’s lifecycle.
- mcp
- Model Context Protocol clients (feature
mcp), built on [rmcp]. - memory
- Cross-session memory: the
MemoryManagerplugin, theMemoryStoretrait backends implement, andextractionof memories from the conversation. - middleware
- Middleware: handlers that wrap the model call
(
InvokeModelStage) and each tool execution (ExecuteToolStage). - models
- Model abstractions: the
Modeltrait, its request and result types, stream events and what the SDK knows about models (ModelInfo). - multiagent
- Multi-agent building blocks. For now the authority-mode policies of the agent spec that the
subagenttool uses; Graph and Swarm come in a later release. - plugins
- Plugins: the
Plugintrait. - retry
- Retry strategies for failed model calls and the backoff math they use.
- sandbox
- Sandboxes: where tools run commands and code and read and write files.
- session
- Session persistence.
- state_
store - Key-value JSON state outside the conversation.
- storage
- Unified byte storage.
- telemetry
- Telemetry: spans, metrics and the local
AgentMetricsandAgentTraceanAgentResultcarries. - testing
- Test fixtures for code built on strands.
- tools
- Tools: the
Tooltrait and its stream,ToolContext,ToolError,FunctionTool, theToolRegistry, structured output, input schemas and theexecutors. - types
- Core data types: messages, content blocks, media, citations, tools, stop reasons, snapshots and interrupt responses.
- vended_
interventions - Ready-made intervention handlers.
- vended_
memory_ stores - Ready-made memory stores:
file_memory_storekeeps markdown entries in aStorage, andtest_memory_storeis a zero-infrastructure JSON-file store for prototyping and tests. - vended_
plugins - Ready-made plugins.
- vended_
tools - Ready-made tools.
Macros§
- tool_
list - Builds a
Vec<ToolSource>from items of different types.
Attribute Macros§
- async_
trait - tool
- Turns an
async fninto a Strands tool. - tools
- Generates tools from the
#[tool]methods of animplblock, for tools with state.