

# AgentCore Rust SDK reference

This reference documents the public Amazon Bedrock AgentCore Rust SDK releases.

For the full reference, including trait implementations and feature flags, see the [bedrock-agentcore crate documentation on docs.rs](https://docs.rs/bedrock-agentcore).

This reference contains the following topics.

**Topics**
+ [Runtime](#rust-sdk-runtime)
+ [Request context](#rust-sdk-context)
+ [Errors](#rust-sdk-errors)

## Runtime
<a name="rust-sdk-runtime"></a>

 *Generated from `bedrock-agentcore` v0.0.1 with rustdoc. Do not edit by hand.* 

Each entry shows the signature and a summary. For the full description of an item, see [the crate documentation on docs.rs](https://docs.rs/bedrock-agentcore).

Use the `runtime` module to host an agent on Amazon Bedrock AgentCore Runtime (AgentCore Runtime). The module provides the HTTP server that AgentCore Runtime calls.

### BedrockAgentCoreApp
<a name="_bedrockagentcoreapp"></a>

```rust
pub struct BedrockAgentCoreApp
```

An HTTP server that implements the AgentCore Runtime contract.

#### BedrockAgentCoreApp::builder
<a name="_bedrockagentcoreappbuilder"></a>

```rust
pub fn builder() -> Builder
```

Starts the configuration of an app.

#### BedrockAgentCoreApp::run
<a name="_bedrockagentcoreapprun"></a>

```rust
pub async fn run(self) -> Result<(), Error>
```

Binds the configured address and serves until the process receives SIGTERM or Ctrl-C.

#### BedrockAgentCoreApp::serve
<a name="_bedrockagentcoreappserve"></a>

```rust
pub async fn serve(self, listener: tokio::net::TcpListener) -> Result<(), Error>
```

Serves on a listener that the caller has bound, until the process receives SIGTERM or Ctrl-C. Shutdown works as described for `run`.

#### BedrockAgentCoreApp::serve\_with\_shutdown
<a name="_bedrockagentcoreappserve_with_shutdown"></a>

```rust
pub async fn serve_with_shutdown(
    self,
    listener: tokio::net::TcpListener,
    shutdown: impl Future<Output = ()> + Send + 'static,
) -> Result<(), Error>
```

Serves on a listener that the caller has bound, until `shutdown` completes. Shutdown then works as described for `run`. This method installs no signal handlers.

#### BedrockAgentCoreApp::router
<a name="_bedrockagentcoreapprouter"></a>

```rust
pub fn router(&self) -> Router
```

The routes of the app as an axum router: `/invocations`, `/ping`, the warmup hook and the routes given to `Builder::routes`. Use it to mount the app in a server that you run yourself, for example with `Router::merge`, or to wrap it in middleware with `Router::layer`. A layer that you add wraps the app’s routes, so it sees each request before the app does.

#### BedrockAgentCoreApp::tasks
<a name="_bedrockagentcoreapptasks"></a>

```rust
pub fn tasks(&self) -> &AsyncTasks
```

The registry of background work of this app. Every invocation’s `RequestContext::tasks` returns the same registry.

### Builder
<a name="_builder"></a>

```rust
pub struct Builder
```

Configures a `BedrockAgentCoreApp`. Create one with `BedrockAgentCoreApp::builder`.

#### Builder::invocation
<a name="_builderinvocation"></a>

```rust
pub fn invocation<H, M>(mut self, handler: H) -> Self
where
    H: InvocationHandler<M>,
```

Specifies the handler for `/invocations`. This setting is required.

#### Builder::ping
<a name="_builderping"></a>

```rust
pub fn ping<F, S>(mut self, handler: F) -> Self
where
    F: Fn() -> S + Send + Sync + 'static,
    S: Into<Option<PingStatus>>,
```

Specifies a function that decides the status of `/ping`.

#### Builder::bind
<a name="_builderbind"></a>

```rust
pub fn bind(mut self, addr: SocketAddr) -> Self
```

Specifies the address that `BedrockAgentCoreApp::run` listens on.

#### Builder::body\_limit
<a name="_builderbody_limit"></a>

```rust
pub fn body_limit(mut self, bytes: usize) -> Self
```

Specifies the largest accepted invocation body in bytes. The default is 1 MiB.

#### Builder::stream\_heartbeat
<a name="_builderstream_heartbeat"></a>

```rust
pub fn stream_heartbeat(mut self, interval: Duration) -> Self
```

Specifies how often a quiet `Response::stream` sends an SSE comment line to keep the connection open. The default is 30 seconds. The interval must be greater than zero. With `Duration::MAX` a stream sends no comment lines.

#### Builder::shutdown\_grace
<a name="_buildershutdown_grace"></a>

```rust
pub fn shutdown_grace(mut self, grace: Duration) -> Self
```

Specifies how long a shutdown waits for requests in flight and tracked background tasks. The default is 8 seconds. See `BedrockAgentCoreApp::run`.

#### Builder::routes
<a name="_builderroutes"></a>

```rust
pub fn routes(mut self, routes: Router) -> Self
```

Adds routes of your own to the app. Call it more than once to add more.

#### Builder::layer
<a name="_builderlayer"></a>

```rust
pub fn layer<L>(mut self, layer: L) -> Self
where
    L: Layer<Route> + Clone + Send + Sync + 'static,
    L::Service: Service<Request> + Clone + Send + Sync + 'static,
    <L::Service as Service<Request>>::Response: IntoResponse + 'static,
    <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
    <L::Service as Service<Request>>::Future: Send + 'static,
```

Wraps the whole app in a tower layer, as `axum::Router::layer` does for a router. Use it for middleware such as request tracing, an authorization check or metrics.

#### Builder::warmup\_hook
<a name="_builderwarmup_hook"></a>

```rust
pub fn warmup_hook(mut self, hook: WarmupHook) -> Self
```

Serves the build warmup hook of AgentCore Runtime on the path of `hook`, on the same port as the other routes of the app. A later call replaces the hook of an earlier one.

#### Builder::build
<a name="_builderbuild"></a>

```rust
pub fn build(self) -> Result<BedrockAgentCoreApp, Error>
```

Builds the app.

### Response
<a name="_response"></a>

```rust
pub struct Response
```

The reply of an invocation handler.

#### Response::json
<a name="_responsejson"></a>

```rust
pub fn json<T: Serialize>(value: T) -> Self
```

A `200` reply holding `value`.

#### Response::with\_status
<a name="_responsewith_status"></a>

```rust
pub fn with_status<T: Serialize>(status: StatusCode, value: T) -> Self
```

A reply with the given status holding `value`.

#### Response::from\_http
<a name="_responsefrom_http"></a>

```rust
pub fn from_http(response: http::Response<Body>) -> Self
```

A raw HTTP response. The server sends its status, headers and body unchanged and does not look at the `Accept` header.

#### Response::stream
<a name="_responsestream"></a>

```rust
pub fn stream<S, T, E>(stream: S) -> Self
where
    S: Stream<Item = Result<T, E>> + Send + 'static,
    T: Serialize,
    E: Into<BoxError>,
```

A stream of Server-Sent Events. Each item is sent as soon as the stream yields it, as one event whose data is the JSON encoding of the item:

### WarmupHook
<a name="_warmuphook"></a>

```rust
pub struct WarmupHook
```

The build warmup hook of AgentCore Runtime: the path that serves it and a handler for each of its two calls. Give it to `Builder::warmup_hook`.

#### WarmupHook::new
<a name="_warmuphooknew"></a>

```rust
pub fn new(path: impl Into<String>) -> Self
```

Creates a hook that is served on `path`, with no handlers. A warmup type without a handler gets the `skipped` reply.

#### WarmupHook::memory
<a name="_warmuphookmemory"></a>

```rust
pub fn memory<F, Fut, E>(mut self, handler: F) -> Self
where
    F: Fn() -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<(), E>> + Send + 'static,
    E: Into<BoxError>,
```

Specifies the handler of the `memory` call, which runs before the snapshot. What the process holds in memory when it returns is the state that every new session starts with. A later call replaces the handler of an earlier one.

#### WarmupHook::disk
<a name="_warmuphookdisk"></a>

```rust
pub fn disk<F, Fut, E>(mut self, handler: F) -> Self
where
    F: Fn() -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<(), E>> + Send + 'static,
    E: Into<BoxError>,
```

Specifies the handler of the `disk` call, which runs after the snapshot. The files that the agent reads during this call become fast to read for new sessions. State that the handler puts in memory is not part of what sessions start with. A later call replaces the handler of an earlier one.

### PingStatus
<a name="_pingstatus"></a>

```rust
pub enum PingStatus
```

The health that `/ping` reports to AgentCore Runtime.

 **Variants** 

 `Healthy`   
The agent is idle. The service may end an idle session.

 `HealthyBusy`   
The agent is working in the background. The service keeps the session.

#### PingStatus::as\_str
<a name="_pingstatusas_str"></a>

```rust
pub fn as_str(self) -> &'static str
```

The text of the status in the ping reply.

### IntoInvocationResponse
<a name="_intoinvocationresponse"></a>

```rust
pub trait IntoInvocationResponse
```

Conversion of a handler’s return value into a `Response`.

#### IntoInvocationResponse::into\_invocation\_response
<a name="_intoinvocationresponseinto_invocation_response"></a>

```rust
fn into_invocation_response(self) -> Response
```

Converts `self` into a response.

### InvocationHandler
<a name="_invocationhandler"></a>

```rust
pub trait InvocationHandler<Marker>: Sealed<Marker>
```

An async function that handles `/invocations`.

## Request context
<a name="rust-sdk-context"></a>

 *Generated from `bedrock-agentcore` v0.0.1 with rustdoc. Do not edit by hand.* 

Each entry shows the signature and a summary. For the full description of an item, see [the crate documentation on docs.rs](https://docs.rs/bedrock-agentcore).

Use the `context` module to read the metadata of the current invocation, such as the session ID and the request headers.

### RequestContext
<a name="_requestcontext"></a>

```rust
pub struct RequestContext
```

Metadata of one invocation.

#### RequestContext::builder
<a name="_requestcontextbuilder"></a>

```rust
pub fn builder(session_id: impl Into<String>) -> RequestContextBuilder
```

Starts a context for the session `session_id`.

#### RequestContext::session\_id
<a name="_requestcontextsession_id"></a>

```rust
pub fn session_id(&self) -> &str
```

The runtime session ID. It comes from the `X-Amzn-Bedrock-AgentCore-Runtime-Session-Id` header, or from the top-level `sessionId` string of the request body when the header is absent.

#### RequestContext::request\_id
<a name="_requestcontextrequest_id"></a>

```rust
pub fn request_id(&self) -> &str
```

The request ID. It comes from the `X-Amzn-Bedrock-AgentCore-Runtime-Request-Id` header. The SDK generates a universally unique identifier (UUID) when the header is absent.

#### RequestContext::workload\_access\_token
<a name="_requestcontextworkload_access_token"></a>

```rust
pub fn workload_access_token(&self) -> Option<&WorkloadAccessToken>
```

The workload access token that AgentCore Runtime sent with this invocation.

#### RequestContext::oauth2\_callback\_url
<a name="_requestcontextoauth2_callback_url"></a>

```rust
pub fn oauth2_callback_url(&self) -> Option<&str>
```

The OAuth2 callback URL from the `OAuth2CallbackUrl` header.

#### RequestContext::headers
<a name="_requestcontextheaders"></a>

```rust
pub fn headers(&self) -> &HeaderMap
```

The request headers that an agent may forward to other services.

#### RequestContext::request\_headers
<a name="_requestcontextrequest_headers"></a>

```rust
pub fn request_headers(&self) -> &HeaderMap
```

The headers of the request as the server received them. They include the headers that the `requestHeaderAllowlist` of the agent runtime lets through, such as an `X-Api-Key` header, and the `Accept` header.

#### RequestContext::tasks
<a name="_requestcontexttasks"></a>

```rust
pub fn tasks(&self) -> &AsyncTasks
```

The registry of background work of the app that received this invocation. Work tracked here makes the app report `HealthyBusy`. See `crate::tasks`.

### RequestContextBuilder
<a name="_requestcontextbuilder_2"></a>

```rust
pub struct RequestContextBuilder
```

Builds a `RequestContext`. Create one with `RequestContext::builder`.

#### RequestContextBuilder::request\_id
<a name="_requestcontextbuilderrequest_id"></a>

```rust
pub fn request_id(mut self, request_id: impl Into<String>) -> Self
```

Specifies the request ID. The default is a new UUID.

#### RequestContextBuilder::workload\_access\_token
<a name="_requestcontextbuilderworkload_access_token"></a>

```rust
pub fn workload_access_token(mut self, token: WorkloadAccessToken) -> Self
```

Specifies the workload access token.

#### RequestContextBuilder::oauth2\_callback\_url
<a name="_requestcontextbuilderoauth2_callback_url"></a>

```rust
pub fn oauth2_callback_url(mut self, url: impl Into<String>) -> Self
```

Specifies the OAuth2 callback URL.

#### RequestContextBuilder::workload\_identity\_context
<a name="_requestcontextbuilderworkload_identity_context"></a>

```rust
pub fn workload_identity_context(self, context: impl Into<String>) -> Self
```

Specifies the encrypted workload identity context of the session. The runtime server reads it from the `X-Amzn-Bedrock-AgentCore-Runtime-Encrypted-Workload-Identity-Context` header and keeps it for later invocations of the session. It is not in `RequestContext::headers` and `Debug` does not show it.

#### RequestContextBuilder::header
<a name="_requestcontextbuilderheader"></a>

```rust
pub fn header(mut self, name: HeaderName, mut value: HeaderValue) -> Self
```

Adds one entry to `RequestContext::headers`. The builder applies no filter.

#### RequestContextBuilder::request\_header
<a name="_requestcontextbuilderrequest_header"></a>

```rust
pub fn request_header(mut self, name: HeaderName, mut value: HeaderValue) -> Self
```

Adds one entry to `RequestContext::request_headers`.

#### RequestContextBuilder::tasks
<a name="_requestcontextbuildertasks"></a>

```rust
pub fn tasks(mut self, tasks: AsyncTasks) -> Self
```

Specifies the registry returned by `RequestContext::tasks`. The default is a new empty registry.

#### RequestContextBuilder::build
<a name="_requestcontextbuilderbuild"></a>

```rust
pub fn build(mut self) -> RequestContext
```

Builds the context.

### WorkloadAccessToken
<a name="_workloadaccesstoken"></a>

```rust
pub struct WorkloadAccessToken
```

A workload access token of AgentCore Identity.

#### WorkloadAccessToken::new
<a name="_workloadaccesstokennew"></a>

```rust
pub fn new(token: impl Into<String>) -> Self
```

Wraps a token value.

#### WorkloadAccessToken::expose
<a name="_workloadaccesstokenexpose"></a>

```rust
pub fn expose(&self) -> &str
```

The token value. Keep it out of logs.

### current
<a name="_current"></a>

```rust
pub fn current() -> Option<RequestContext>
```

The context of the invocation that the calling code runs in.

### scope
<a name="_scope"></a>

```rust
pub fn scope<F: Future>(ctx: RequestContext, future: F) -> impl Future<Output = F::Output>
```

Runs `future` with `ctx` as the ambient context returned by `current`.

### workload\_access\_token
<a name="_workload_access_token"></a>

```rust
pub fn workload_access_token() -> Result<WorkloadAccessToken, Error>
```

The workload access token of the invocation that the calling code runs in.

## Errors
<a name="rust-sdk-errors"></a>

 *Generated from `bedrock-agentcore` v0.0.1 with rustdoc. Do not edit by hand.* 

Each entry shows the signature and a summary. For the full description of an item, see [the crate documentation on docs.rs](https://docs.rs/bedrock-agentcore).

The operations of the SDK return the following error type.

### Error
<a name="_error"></a>

```rust
pub struct Error
```

Error returned by this crate.

#### Error::kind
<a name="_errorkind"></a>

```rust
pub fn kind(&self) -> ErrorKind
```

The category of this error.

### ErrorKind
<a name="_errorkind_2"></a>

```rust
pub enum ErrorKind
```

The reason an SDK operation failed. Read it with `Error::kind`.

 **Variants** 

 `Bind`   
The server could not bind its listen address, for example because the port is in use.

 `Serve`   
The server could not install its shutdown signal handlers, or it stopped because of an I/O error.

 `InvalidConfig`   
The builder configuration is incomplete or invalid.

 `ShutdownTimeout`   
The server received its shutdown signal, and requests or tracked background tasks were still running when the grace period ended. The server has cancelled its requests by then. Tracked background tasks may still be running.

 `MissingWorkloadToken`   
An Identity operation had no workload access token: none was given to the operation, and the request context held none or the call ran outside one.

 `NoApiKey`   
AgentCore Identity answered successfully and returned no API key.

 `NoTokenOrAuthUrl`   
AgentCore Identity answered a request for an OAuth2 token with neither a token nor an authorization URL.

 `AuthorizationCallbackFailed`   
The application’s function for the authorization URL returned an error, which is the `source`.

 `AuthorizationTimedOut`   
No OAuth2 token arrived in the time allowed for the user to give consent.

 `Service`   
A call to AgentCore Identity failed. The text of the error names the operation, the error code of the service and the request ID, for example `GetResourceApiKey failed: AccessDeniedException (request ID: …​)`. A failure without a response has the classification of the AWS SDK instead, such as `dispatch failure`. `source` is the `SdkError` of the generated operation.