Skip to main content

strands/
lib.rs

1//! Strands Agents SDK for Rust.
2//!
3//! A model-driven approach to building AI agents: give a model a system prompt and tools, and the
4//! agent loop calls the model, runs the tools it asks for and feeds their results back until the
5//! model answers.
6//!
7//! This is a developer preview: the API may change in any 0.x release.
8//!
9//! # Quick start
10//!
11//! An agent with a tool, on the default model (Amazon Bedrock, with credentials and region from
12//! the AWS default chain), invoked once and then streamed:
13//!
14//! ```
15//! use futures::StreamExt;
16//! use strands::{tool, Agent, AgentStreamEvent};
17//!
18//! /// Get the current weather for a city.
19//! #[tool]
20//! async fn get_weather(
21//!     /// City name, for example "Seattle".
22//!     city: String,
23//! ) -> Result<String, strands::ToolError> {
24//!     Ok(format!("Sunny in {city}"))
25//! }
26//!
27//! #[tokio::main]
28//! async fn main() -> Result<(), strands::Error> {
29//!     let mut agent = Agent::builder()            // default model: Bedrock
30//! #       .model(strands::testing::MockModel::from_turns(["It is sunny.", "It is mild."]))
31//! #       .printer(false)
32//!         .system_prompt("You are a concise assistant.")
33//!         .tools([GetWeather])
34//!         .build()?;
35//!
36//!     let result = agent.invoke("What's the weather in Seattle?").await?;
37//!     println!("{result}");
38//!
39//!     {
40//!         let mut stream = agent.stream("And in Lisbon?");
41//!         while let Some(event) = stream.next().await {
42//!             if let AgentStreamEvent::ModelStreamUpdate(update) = event? {
43//!                 if let Some(text) = update.text_delta() {
44//!                     print!("{text}");
45//!                 }
46//!             }
47//!         }
48//!     }
49//!     agent.shutdown().await
50//! }
51//! ```
52//!
53//! The [`agent`] module shows the other everyday shapes: the [`AgentConfig`] struct, tools with
54//! state through `#[tools]`, hooks, structured output and cancellation. The crate's
55//! [`examples/`](https://github.com/strands-agents/harness-sdk/tree/main/strands-rs/strands/examples)
56//! directory has a runnable program for each provider and feature.
57//!
58//! # Features
59//!
60//! | Feature | Default | Adds |
61//! |---|---|---|
62//! | `bedrock` | yes | `models::BedrockModel`, the Amazon Bedrock Converse provider, and the default model |
63//! | `anthropic` | | `models::anthropic::AnthropicModel`, the Anthropic Messages API provider; with `bedrock`, also `AnthropicModel::bedrock` and `AnthropicBedrockConfig` for Claude on Bedrock's InvokeModel API |
64//! | `openai` | | `models::openai::OpenAIModel` (Responses and Chat Completions); it does not need `bedrock` |
65//! | `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` |
66//! | `mcp` | | `mcp::McpClient`, Model Context Protocol clients over stdio, streamable HTTP and SSE, and the `mcp_router` tool |
67//! | `otel` | | OpenTelemetry export of the agent's spans and metrics (`telemetry::setup_tracer`, `telemetry::setup_meter`) |
68//! | `cedar` | | `CedarAuthorization`, Cedar policy authorization of tool calls |
69//! | `dogwood` | | `DogwoodAuthorization`, Dogwood policy authorization of tool calls, with temporal rules over earlier calls |
70//!
71//! Without `bedrock` an agent needs an explicit model; a Bedrock model id then fails with
72//! [`DefaultNotConfiguredError`]. The `otel` feature's `opentelemetry`, `opentelemetry_sdk`,
73//! `tracing-opentelemetry` and `tracing-subscriber` versions are part of the public API: moving
74//! one to a semver-incompatible version is a breaking strands release.
75//!
76//! # Modules
77//!
78//! | Module | Contents |
79//! |---|---|
80//! | [`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 |
81//! | [`types`] | Messages, the content blocks (Bedrock Converse JSON shape), media, citations, tool specs, stop reasons, snapshots and interrupt responses |
82//! | [`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 |
83//! | [`mod@tools`] | The [`Tool`] trait, [`ToolContext`], [`ToolError`], [`tools::FunctionTool`], the [`tools::ToolRegistry`], the executors and structured output |
84//! | [`hooks`] | The 17 hook events, [`hooks::HookRegistry`] and [`HookOrder`], and the [`AgentStreamEvent`] records an agent stream yields |
85//! | [`plugins`] | The [`plugins::Plugin`] trait |
86//! | [`middleware`] | Handlers around the model call and each tool execution |
87//! | [`interrupt`] | Human-in-the-loop [`Interrupt`]s |
88//! | [`interventions`] | [`InterventionHandler`]s that gate the agent's lifecycle |
89//! | [`vended_interventions`] | Human-in-the-loop approval, Cedar policy authorization (feature `cedar`) and Dogwood policy authorization (feature `dogwood`) |
90//! | [`conversation_manager`] | Keeping history within the context window |
91//! | [`context_manager`] | The strategy-driven `ContextManager`, its presets, the archive and message pinning |
92//! | [`injection`] | Folding just-in-time text into the latest user message |
93//! | [`storage`] | The [`Storage`] trait, `InMemoryStorage`, `LocalFileStorage`, namespaces and keyword search |
94//! | [`session`] | [`SessionManager`], saving and restoring agent snapshots in the layout shared with the other Strands SDKs |
95//! | [`memory`] | The [`MemoryManager`] plugin, the [`MemoryStore`] trait and extraction |
96//! | [`vended_memory_stores`] | `FileMemoryStore` and `TestMemoryStore` |
97//! | [`sandbox`] | The [`Sandbox`] trait, where tools run commands and touch files, and `NotASandboxLocalEnvironment` |
98//! | [`vended_tools`] | Shell, file, HTTP, notebook, agent-loop and subagent tools, and `mcp_router` (feature `mcp`) |
99//! | [`vended_plugins`] | The context injector and [`AgentSkills`](vended_plugins::skills::AgentSkills) |
100//! | [`multiagent`] | The authority-mode policies child agents are specified with |
101//! | [`background_tasks`] | Running tool calls detached from the turn that requested them |
102//! | [`retry`] | [`DefaultModelRetryStrategy`] and the backoff strategies |
103//! | [`state_store`] | [`StateStore`], JSON state shared with tools and providers |
104//! | [`cancel`] | [`CancelHandle`] and [`CancelSignal`] for cooperative cancellation |
105//! | [`telemetry`] | `tracing` spans and metrics, [`AgentMetrics`] and [`AgentTrace`] |
106//! | [`error`] | [`Error`], with one variant per error type |
107//! | [`testing`] | Fixtures such as [`testing::MockModel`] for testing code built on strands |
108//! | `mcp` | Model Context Protocol clients (feature `mcp`) |
109//!
110//! The crate root re-exports the main public types of these modules.
111//!
112//! # Wire compatibility
113//!
114//! Every serializable type writes the JSON shared with the other Strands SDKs: the same keys in the
115//! same order, with absent optional fields omitted. Sessions and snapshots that another Strands SDK
116//! writes load in Rust and serialize back unchanged, and blocks a newer SDK wrote load as
117//! [`UnknownBlock`]:
118//!
119//! ```
120//! use strands::{ContentBlock, Message, Role};
121//!
122//! let message = Message::new(Role::User, vec![ContentBlock::text("Hello")]);
123//! assert_eq!(message.text(), "Hello");
124//! let json = serde_json::to_value(&message.content).unwrap();
125//! assert_eq!(json, serde_json::json!([{"text": "Hello"}]));
126//! ```
127//!
128//! # Versioning
129//!
130//! strands follows semver for 0.x crates: a minor release (0.1 to 0.2) may break the API, a patch
131//! release does not. The minimum supported Rust version is 1.96; it never drops below what
132//! required dependencies declare, and it moves only in minor releases.
133//!
134//! # Public dependencies
135//!
136//! These crates appear in the public API, so a semver-incompatible release of any of them is a
137//! breaking strands release:
138//!
139//! | Crate | Where | Feature |
140//! |---|---|---|
141//! | `serde_json` | [`JsonValue`], [`JsonObject`] | always |
142//! | `schemars` 1 | the `JsonSchema` derive that structured output and `#[tool]` inputs use | always |
143//! | `futures` | the `Stream` behind [`BoxStream`] | always |
144//! | `async-trait` | re-exported as [`async_trait`](macro@async_trait) for extension traits | always |
145//! | `aws-credential-types`, `aws-types` | credentials and `SdkConfig` escape hatches on the Bedrock and Mantle configs | `bedrock`, `mantle` |
146//! | `regex`, `rmcp` | MCP tool matchers and the raw MCP types of the `McpClient` escape hatches | `mcp` |
147//! | `opentelemetry`, `opentelemetry_sdk`, `tracing-opentelemetry`, `tracing-subscriber` | telemetry setup | `otel` |
148//!
149//! `strands` and `strands-macros` release in lockstep: `strands` depends on an exact
150//! `strands-macros` version.
151
152#![cfg_attr(docsrs, feature(doc_cfg))]
153
154/// Compiles the README's code blocks as doctests.
155#[cfg(doctest)]
156#[doc = include_str!("../README.md")]
157struct ReadmeDoctests;
158
159#[doc(hidden)]
160pub mod __private;
161pub mod agent;
162pub mod background_tasks;
163mod callback;
164pub mod cancel;
165mod clock;
166pub mod context_manager;
167pub mod conversation_manager;
168pub mod error;
169pub mod hooks;
170pub mod injection;
171pub mod interrupt;
172pub mod interventions;
173mod logging;
174#[cfg(feature = "mcp")]
175pub mod mcp;
176pub mod memory;
177pub mod middleware;
178mod mime;
179pub mod models;
180pub mod multiagent;
181pub mod plugins;
182pub mod retry;
183pub mod sandbox;
184pub mod session;
185pub mod state_store;
186pub mod storage;
187pub mod telemetry;
188#[cfg(test)]
189mod test_support;
190pub mod testing;
191pub mod tools;
192pub mod types;
193pub mod vended_interventions;
194pub mod vended_memory_stores;
195pub mod vended_plugins;
196pub mod vended_tools;
197
198pub use agent::{
199    Agent, AgentAsTool, AgentAsToolOptions, AgentBuilder, AgentConfig, AgentResult, AgentStream, DirectToolCallOptions,
200    InvocationContext, InvocationContextUsage, InvocationState, InvokeArgs, InvokeLimits, InvokeOptions, LocalAgent,
201    ModelSource, RefusedCall, SnapshotField, SnapshotPreset, TakeSnapshotOptions, ToolAgent, ToolHandle,
202};
203pub use async_trait::async_trait;
204pub use background_tasks::BackgroundTasksConfig;
205pub use cancel::{CancelHandle, CancelOptions, CancelSignal};
206pub use conversation_manager::{
207    ConversationManager, ConversationManagerReduceOptions, NullConversationManager, ProactiveCompression,
208    SlidingWindowConversationManager, SlidingWindowConversationManagerConfig, SummarizingConversationManager,
209    SummarizingConversationManagerConfig,
210};
211pub use error::{
212    BoxError, ContextWindowOverflowError, DefaultNotConfiguredError, Error, JsonValidationError, MaxTokensError,
213    ModelError, ModelNetworkError, ModelThrottledError, Result, SandboxAbortError, SandboxIsADirectoryError,
214    SandboxPathNotFoundError, SandboxPermissionError, SandboxTimeoutError, SessionError, StorageError,
215    StructuredOutputError, ToolNotFoundError, ToolValidationError,
216};
217pub use hooks::{
218    AfterInvocationEvent, AfterModelCallEvent, AfterToolCallEvent, AfterToolsEvent, AgentResultEvent, AgentStreamEvent,
219    BeforeInvocationEvent, BeforeModelCallEvent, BeforeToolCallEvent, BeforeToolsEvent, Cancel, ContentBlockEvent,
220    EndTurn, Hook, HookCallbackOptions, HookCleanup, HookOrder, HookRegistry, InitializedEvent, InterruptEvent,
221    MessageAddedEvent, ModelMessageEvent, ModelStopResponse, ModelStreamUpdateEvent, ToolResultEvent,
222    ToolStreamUpdateEvent, ToolUseData,
223};
224pub use interrupt::{Interrupt, InterruptError, InterruptSource};
225pub use interventions::{InterventionAction, InterventionHandler, InterventionResult, OnError};
226#[cfg(feature = "mcp")]
227pub use mcp::{
228    ElicitationCallback, ElicitationContext, McpCallToolOptions, McpClient, McpClientConfig, McpClientCredentials,
229    McpClientOptions, McpConnectionState, McpListOptions, McpListToolsOptions, McpLoadServersOptions, McpProgress,
230    McpProgressCallback, McpServerConfig, McpTool, McpToolFilterCallback, McpToolFilters, McpToolMatcher, McpTransport,
231    SerializableMcpToolFilters,
232};
233pub use memory::{
234    AddMessagesContext, ExtractionConfig, ExtractionResult, ExtractionTrigger, ExtractionTriggerContext, Extractor,
235    ExtractorContext, InjectionConfig, InjectionContext, InjectionTrigger, IntervalTrigger, IntervalTriggerOptions,
236    InvocationTrigger, MemoryAddOptions, MemoryAddToolConfig, MemoryContentBlockType, MemoryEntry,
237    MemoryInjectionConfig, MemoryManager, MemoryManagerConfig, MemoryMessageFilter, MemorySearchOptions, MemoryStore,
238    MemoryToolConfig, ModelExtractor, ModelExtractorOptions, SearchOptions,
239};
240pub use middleware::{
241    ExecuteToolContext, ExecuteToolResult, ExecuteToolStage, InvokeModelContext, InvokeModelResult, InvokeModelStage,
242    Middleware, MiddlewareCleanup, MiddlewareError, MiddlewareInterruptResult, MiddlewareNext, MiddlewarePhase,
243    MiddlewareStage, StageItem, StageResult, StageStream,
244};
245#[cfg(feature = "bedrock")]
246pub use models::bedrock::{
247    BedrockCacheConfig, BedrockCacheTtl, BedrockGuardrailConfig, BedrockGuardrailRedactionConfig, BedrockModel,
248    BedrockModelConfig, BedrockModelOptions,
249};
250pub use models::routing::{
251    CandidateModel, ClassifierStrategy, ClassifierStrategyOptions, FallbackStrategy, ModelRouter, ModelRouterOptions,
252    RoutingAttempt, RoutingCandidate, RoutingCandidateOptions, RoutingContext, RoutingFailure, RoutingStrategy,
253};
254pub use models::streaming::{
255    CitationsDelta, ContentBlockDelta, ContentBlockStart, Metrics, ModelContentBlockDeltaEvent,
256    ModelContentBlockStartEvent, ModelContentBlockStopEvent, ModelMessageStartEvent, ModelMessageStopEvent,
257    ModelMetadataEvent, ModelRedactionEvent, ModelStreamEvent, ReasoningContentDelta, RedactInputContent,
258    RedactOutputContent, TextDelta, ToolUseInputDelta, ToolUseStart, Usage,
259};
260pub use models::{
261    AggregatedEvent, BaseModelConfig, BoxStream, CacheConfig, CacheKey, CacheSectionSetting, CacheStrategy, CacheTtl,
262    CountTokensOptions, DeferredToolLoading, Model, ModelCapabilities, ModelInfo, ModelLimits, ModelRequest,
263    PromptCaching, Redaction, StreamAggregatedResult, SummarizeOptions, SummarizeResult,
264};
265pub use plugins::Plugin;
266pub use retry::{
267    BackoffContext, BackoffStrategy, ConstantBackoff, ConstantBackoffOptions, DefaultModelRetryStrategy,
268    DefaultModelRetryStrategyOptions, ExponentialBackoff, ExponentialBackoffOptions, IsRetryable, JitterKind,
269    LinearBackoff, LinearBackoffOptions, ModelRetryContext, ModelRetryStrategy, RetryDecision, RetryStrategy,
270};
271pub use sandbox::{
272    ExecuteOptions, ExecutionResult, ExecutionStream, ExecutionStreamItem, FileInfo, OutputFile, PosixShellSandbox,
273    Sandbox, StreamChunk, StreamType,
274};
275pub use session::{
276    SaveLatestStrategy, SessionManager, SessionManagerConfig, SnapshotManifest, SnapshotTriggerCallback,
277    SnapshotTriggerParams,
278};
279pub use state_store::StateStore;
280pub use storage::Storage;
281pub use strands_macros::{tool, tools};
282pub use telemetry::{AgentMetrics, AgentTrace};
283pub use tools::{
284    ConcurrentToolExecutor, FunctionTool, SequentialToolExecutor, Tool, ToolContext, ToolError, ToolExecutorStrategy,
285    ToolOutcome, ToolSource, ToolStream, ToolStreamEvent, ToolStreamItem,
286};
287pub use types::{
288    AgentMetadata, AudioBlock, AudioFormat, AudioSource, CachePointBlock, CacheType, Citation,
289    CitationGeneratedContent, CitationLocation, CitationSourceContent, CitationsBlock, ContentBlock, DocumentBlock,
290    DocumentCharLocation, DocumentChunkLocation, DocumentCitations, DocumentContentBlock, DocumentFormat,
291    DocumentPageLocation, DocumentSource, GuardContentBlock, GuardContentImage, GuardContentText, GuardImageFormat,
292    GuardImageSource, GuardQualifier, ImageBlock, ImageFormat, ImageSource, InjectedBlock, InterruptParams,
293    InterruptResponse, InterruptResponseContent, JsonBlock, JsonObject, JsonValue, Message, MessageMetadata,
294    OffloadMethod, Offloaded, ReasoningBlock, ReasoningProviderData, Role, S3Location, SNAPSHOT_SCHEMA_VERSION, Scope,
295    SearchResultLocation, Snapshot, StopReason, SummaryBlock, SystemContentBlock, SystemPrompt, TextBlock, Toggle,
296    ToolChoice, ToolReferenceBlock, ToolResultBlock, ToolResultContent, ToolResultError, ToolResultStatus, ToolSpec,
297    ToolUse, ToolUseBlock, UnknownBlock, UnknownStopReason, VideoBlock, VideoFormat, VideoSource, WebLocation,
298};