Amazon Bedrock AgentCore SDK for Rust
Host Rust agents on Amazon Bedrock AgentCore Runtime and use AgentCore Identity to get credentials for the services they call.
Rust API reference · Rust examples · AgentCore developer guide · TypeScript SDK · Python SDK
Features
| Cargo feature | What it provides | Examples |
|---|---|---|
runtime |
An HTTP server that runs your async handler and manages invocation context, streaming, and health checks. | Streaming, background work, custom routes, warmup |
identity |
A client built on the AWS SDK for Rust that retrieves API keys and OAuth tokens from AgentCore Identity. | API keys, machine-to-machine OAuth, user consent |
Both features are enabled by default. To use just one, set default-features = false and list the feature you need in features. With neither feature, the crate has no networking dependencies.
Installation
The SDK requires Rust 1.94.1 or later. Create a binary crate for the quick start.
Replace the [dependencies] section in Cargo.toml with the dependencies for the runtime quick start.
[]
= { = "0.1.0", = false, = ["runtime"] }
= "1"
= { = "1", = ["macros", "rt-multi-thread"] }
Quick start
This handler echoes its input locally without AWS credentials. Save it as src/main.rs.
use ;
use ;
async
async
Start the server.
In another terminal, send a JSON request with a session ID. The app also serves GET /ping on the same port.
Try a model-backed agent
You can use any agent framework that you can call from an async Rust handler. The streaming example uses Strands and requires Rust 1.96 or later. Configure AWS credentials and a Region with access to the example's Bedrock model, then stop the echo server and run this command from a checkout of this repository.
Use the curl -N command in the streaming example to see the reply as it arrives. Streaming example · Agent with a weather tool · Strands Agents SDK for Rust
Deployment
Package your Rust binary in a container image that matches the runtime's CPU architecture (ARM64 by default). Push the image to Amazon ECR and create an AgentCore Runtime with the image URI and an execution role. The SDK serves the default HTTP endpoints on port 8080. The deployment guide walks through creating the runtime and invoking the deployed agent. Custom agent deployment guide
Host an agent on AgentCore Runtime
Handlers
A handler is an async fn(Req) -> Result<O, E> or an async fn(Req, RequestContext) -> Result<O, E>.
Reqis the JSON body of the request: any type that implementsserde::de::DeserializeOwned, orserde_json::Value.Ois the reply: any type that implementsserde::Serialize, or aruntime::Responsefor a status, a stream or a raw HTTP response. A value is sent as JSON unless theAcceptheader of the request asks for text or bytes.Eis any error that converts intoBox<dyn std::error::Error + Send + Sync>. AnErrbecomes500 {"error": "<its text>"}, and the log has the text and the sources of the error. The source of an Identity error of this crate stays out of the log, because it can hold a credential.- The handler and its future must be
Send. Keep shared state in a closure that clones anArc. - A handler must not block its thread. Run blocking work with
tokio::task::spawn_blocking. The server answersGET /pingon a thread of its own, so a handler that blocks delays other handlers and not the health check. - AgentCore Runtime ends a session that sends no reply data for its idle timeout while
GET /pingsaysHealthy. An invocation that runs longer must stream its reply or track its work, as the next two sections show.
Streaming
Response::stream sends each item of a stream as a Server-Sent Event:
use Response;
use ;
async
A request with no Accept header, or one that allows text/event-stream, gets the stream. Any other request gets 406. An Err item ends the stream with an error event. While the stream is quiet, the server sends a comment line every 30 seconds. examples/streaming.rs is a complete agent.
Background work
Work that outlives its invocation must be tracked. While a task is tracked, GET /ping reports HealthyBusy, and AgentCore Runtime keeps the session:
use ;
async
examples/background.rs is a complete agent.
Shutdown
On SIGTERM the server logs the invocations in flight and the tracked tasks, then waits up to 8 seconds for them. After that it cancels the requests that are still in flight, and their callers get 503. AgentCore Runtime ends the process about 10 seconds after the signal, so a grace period of 10 seconds or more has no effect there.
Build warmup hook
AgentCore Runtime can call the agent while it prepares it, so that sessions start faster. See Configure lifecycle hooks. The hook needs platform version V2.
use ;
use Value;
async
async
async
async
The service sends two POST requests to the hook path and takes a snapshot of the agent between them. The memory handler runs before the snapshot, and what the process holds in memory when it returns is what every new session starts with. The disk handler runs after the snapshot, and the files that it reads become fast to read for new sessions. An Err from a handler fails the create or update of the agent runtime. Run blocking work with tokio::task::spawn_blocking, because the app must keep answering GET /ping.
Set the same path as hooksConfiguration on CreateAgentRuntime or UpdateAgentRuntime, and leave port unset:
examples/warmup.rs is a complete agent.
Get credentials from AgentCore Identity
use IdentityClient;
async
Create one IdentityClient at startup from the AWS configuration of the application. Inside an invocation, each request uses the workload access token that AgentCore Runtime sent with it. Elsewhere, give the request a token with .workload_access_token(..). examples/api_key.rs is a complete agent.
An agent framework can run a tool on a task of its own, where the request context of the invocation is missing. Strands does so. A tool that calls AgentCore Identity then carries the RequestContext and enters it again with context::scope, as the tool in the example does.
AgentCore Runtime sends a workload access token only when the caller names a user: a runtimeUserId with IAM authorization, which needs the bedrock-agentcore:InvokeAgentRuntimeForUser permission, or a JWT. The documentation of the identity module shows how to get a token for a local call.
An OAuth2 access token is requested the same way:
use ;
async
With AuthFlow::OnBehalfOfTokenExchange AgentCore Identity exchanges the token of the user for a token of the provider. The request is the same, and .custom_parameters(..) carries what the provider needs for the exchange.
With AuthFlow::UserFederation the agent acts for a user. When the user has to give consent, send passes the authorization URL to the function given to .on_auth_url(..) and then waits up to ten minutes for the token. .timeout(..) changes that time:
use ;
async
async
The application also needs a callback endpoint that completes the consent for the right user. See OAuth2 authorization URL session binding. AgentCore Runtime does not send the URL of that endpoint to the agent, so set it with .callback_url(..).
With .into_stream(), send an Oauth2Event::AuthorizationUrl only to the user who started the request. When the stream yields Oauth2Event::Token, use the access token inside the agent to call the downstream service. Return the service result or an authorization status to the caller. User consent example
To call another AgentCore service for the same user, use the generated client of the IdentityClient. Its Invoke* operations, such as InvokeAgentRuntime and InvokeCodeInterpreter, forward the current invocation's workload access token by default.
let reply = identity
.data_plane
.invoke_agent_runtime
.agent_runtime_arn
.payload
.send
.await?;
Call AWS services with the workload identity of the agent
AgentCore Runtime can send an encrypted workload identity context with an invocation. WorkloadIdentityCredentials exchanges it for credentials of the execution role that carry the workload identity of the agent. Build the AWS clients of the agent from the configuration that configure returns:
use WorkloadIdentityCredentials;
let config = load_defaults.await;
let config = configure;
let s3 = new;
- Until an invocation carries a context, the clients use the execution role credentials.
- Each session has its own context, credentials and refresh token. A session keeps its context for a later invocation that carries none.
- After that, a call fails when the exchange fails, or when its session sent no context. It does not go back to the execution role credentials.
- Where the service does not support the exchange, the clients use the execution role credentials.
- A task started with
tokio::spawnneedscontext::scope, as for the workload access token. - A child process, such as the AWS CLI, uses the execution role credentials.
Development
integration/README.md describes the socket, container and live tests.
Security
See CONTRIBUTING for more information.
License
This project is licensed under the Apache-2.0 License.