# 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](https://docs.rs/bedrock-agentcore) · [Rust examples](examples/) · [AgentCore developer guide](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/what-is-bedrock-agentcore.html) · [TypeScript SDK](https://github.com/aws/bedrock-agentcore-sdk-typescript) · [Python SDK](https://github.com/aws/bedrock-agentcore-sdk-python)
## 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](examples/streaming.rs), [background work](examples/background.rs), [custom routes](examples/custom_routes.rs), [warmup](examples/warmup.rs) |
| `identity` | A client built on the AWS SDK for Rust that retrieves API keys and OAuth tokens from AgentCore Identity. | [API keys](examples/api_key.rs), [machine-to-machine OAuth](examples/oauth2_m2m.rs), [user consent](examples/user_federation.rs) |
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.
```sh
cargo new --bin echo-agent
cd echo-agent
```
Replace the `[dependencies]` section in `Cargo.toml` with the dependencies for the runtime quick start.
```toml
[dependencies]
bedrock-agentcore = { version = "0.1.0", default-features = false, features = ["runtime"] }
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
```
## Quick start
This handler echoes its input locally without AWS credentials. Save it as `src/main.rs`.
```rust
use bedrock_agentcore::{RequestContext, runtime::BedrockAgentCoreApp};
use serde_json::{Value, json};
async fn handle(payload: Value, ctx: RequestContext) -> Result<Value, std::convert::Infallible> {
Ok(json!({ "echo": payload, "session_id": ctx.session_id() }))
}
#[tokio::main]
async fn main() -> Result<(), bedrock_agentcore::Error> {
BedrockAgentCoreApp::builder().invocation(handle).build()?.run().await
}
```
Start the server.
```sh
cargo generate-lockfile
cargo run --locked
```
In another terminal, send a JSON request with a session ID. The app also serves `GET /ping` on the same port.
```sh
curl http://localhost:8080/invocations \
-H 'Content-Type: application/json' \
-H 'X-Amzn-Bedrock-AgentCore-Runtime-Session-Id: local-session' \
-d '{"prompt":"hello"}'
```
```json
{"echo":{"prompt":"hello"},"session_id":"local-session"}
```
### 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.
```sh
cargo run --locked --example streaming
```
Use the `curl -N` command in the streaming example to see the reply as it arrives. [Streaming example](examples/streaming.rs) · [Agent with a weather tool](examples/echo.rs) · [Strands Agents SDK for Rust](https://github.com/strands-agents/harness-sdk/tree/9c5d95105a8660e78b166ca40a7ba99f8d67d0f9/strands-rs)
## 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](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/getting-started-custom.html)
## 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>`.
- `Req` is the JSON body of the request: any type that implements `serde::de::DeserializeOwned`, or `serde_json::Value`.
- `O` is the reply: any type that implements `serde::Serialize`, or a `runtime::Response` for a status, a stream or a raw HTTP response. A value is sent as JSON unless the `Accept` header of the request asks for text or bytes.
- `E` is any error that converts into `Box<dyn std::error::Error + Send + Sync>`. An `Err` becomes `500 {"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 an `Arc`.
- A handler must not block its thread. Run blocking work with `tokio::task::spawn_blocking`. The server answers `GET /ping` on 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 /ping` says `Healthy`. 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:
```rust
use bedrock_agentcore::runtime::Response;
use futures_util::{StreamExt, stream};
async fn handle(prompt: String) -> Result<Response, std::convert::Infallible> {
// The work runs inside the stream, so the reply starts at once.
let words = stream::once(async move { answer(prompt).await }).flat_map(stream::iter);
Ok(Response::stream(words.map(Ok::<_, std::convert::Infallible>)))
}
```
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](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:
```rust
use bedrock_agentcore::{RequestContext, context};
async fn handle(job: Job, ctx: RequestContext) -> Result<&'static str, std::convert::Infallible> {
let work = ctx.tasks().tracked("report", write_report(job));
tokio::spawn(context::scope(ctx.clone(), work));
Ok("started")
}
```
[examples/background.rs](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](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-lifecycle-hooks.html). The hook needs platform version V2.
```rust
use bedrock_agentcore::runtime::{BedrockAgentCoreApp, WarmupHook};
use serde_json::Value;
async fn invoke(payload: Value) -> Result<Value, std::convert::Infallible> {
Ok(payload)
}
async fn load_model() -> Result<(), std::io::Error> {
// Load what every session needs in memory.
Ok(())
}
async fn read_startup_files() -> Result<(), std::io::Error> {
// Read the files that a session reads when it starts.
Ok(())
}
#[tokio::main]
async fn main() -> Result<(), bedrock_agentcore::Error> {
BedrockAgentCoreApp::builder()
.invocation(invoke)
.warmup_hook(WarmupHook::new("/warmup").memory(load_model).disk(read_startup_files))
.build()?
.run()
.await
}
```
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:
```json
{
"build": {
"warmup": {
"action": {
"httpPost": { "path": "/warmup" }
}
}
}
}
```
[examples/warmup.rs](examples/warmup.rs) is a complete agent.
## Get credentials from AgentCore Identity
```rust
use bedrock_agentcore::identity::IdentityClient;
async fn call_orders(identity: &IdentityClient) -> Result<(), bedrock_agentcore::Error> {
let key = identity.api_key("orders-api").send().await?;
// Pass `key.expose()` to the orders client where the request is made.
Ok(())
}
```
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](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:
```rust
use bedrock_agentcore::identity::{AuthFlow, IdentityClient};
async fn call_orders(identity: &IdentityClient) -> Result<(), bedrock_agentcore::Error> {
let token = identity.oauth2_token("orders", AuthFlow::M2m).scopes(["orders/read"]).send().await?;
// Pass `token.expose()` to the orders client where the request is made.
Ok(())
}
```
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:
```rust
use bedrock_agentcore::identity::{AuthFlow, AuthorizationUrl, IdentityClient};
async fn deliver(url: AuthorizationUrl) -> Result<(), std::io::Error> {
// Send `url.expose()` to the user who started the request, and to nobody else.
Ok(())
}
async fn read_calendar(identity: &IdentityClient) -> Result<(), bedrock_agentcore::Error> {
let token = identity
.oauth2_token("calendar", AuthFlow::UserFederation)
.scopes(["calendar.read"])
.callback_url("https://app.example/oauth2/callback")
.on_auth_url(deliver)
.send()
.await?;
Ok(())
}
```
The application also needs a callback endpoint that completes the consent for the right user. See [OAuth2 authorization URL session binding](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/oauth2-authorization-url-session-binding.html). 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](examples/user_federation.rs)
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.
```rust
let reply = identity
.data_plane()
.invoke_agent_runtime()
.agent_runtime_arn(other_agent_arn)
.payload(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:
```rust
use bedrock_agentcore::identity::WorkloadIdentityCredentials;
let config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
let config = WorkloadIdentityCredentials::configure(&config);
let s3 = aws_sdk_s3::Client::new(&config);
```
- 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::spawn` needs `context::scope`, as for the workload access token.
- A child process, such as the AWS CLI, uses the execution role credentials.
## Development
```sh
just build
just test
just check
```
[integration/README.md](integration/README.md) describes the socket, container and live tests.
## Security
See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information.
## License
This project is licensed under the Apache-2.0 License.