View a markdown version of this page

AgentCore Rust SDK reference - Amazon Bedrock AgentCore

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.

This reference contains the following topics.

Runtime

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.

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

pub struct BedrockAgentCoreApp

An HTTP server that implements the AgentCore Runtime contract.

BedrockAgentCoreApp::builder

pub fn builder() -> Builder

Starts the configuration of an app.

BedrockAgentCoreApp::run

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

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

BedrockAgentCoreApp::serve

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

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

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

pub fn tasks(&self) -> &AsyncTasks

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

Builder

pub struct Builder

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

Builder::invocation

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

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

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

Specifies the address that BedrockAgentCoreApp::run listens on.

Builder::body_limit

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

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

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

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

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

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

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

Builds the app.

Response

pub struct Response

The reply of an invocation handler.

Response::json

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

A 200 reply holding value.

Response::with_status

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

A reply with the given status holding value.

Response::from_http

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

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

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

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

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

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

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

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

The text of the status in the ping reply.

IntoInvocationResponse

pub trait IntoInvocationResponse

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

IntoInvocationResponse::into_invocation_response

fn into_invocation_response(self) -> Response

Converts self into a response.

InvocationHandler

pub trait InvocationHandler<Marker>: Sealed<Marker>

An async function that handles /invocations.

Request context

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.

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

RequestContext

pub struct RequestContext

Metadata of one invocation.

RequestContext::builder

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

Starts a context for the session session_id.

RequestContext::session_id

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

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

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

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

RequestContext::oauth2_callback_url

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

The OAuth2 callback URL from the OAuth2CallbackUrl header.

RequestContext::headers

pub fn headers(&self) -> &HeaderMap

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

RequestContext::request_headers

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

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

pub struct RequestContextBuilder

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

RequestContextBuilder::request_id

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

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

Specifies the workload access token.

RequestContextBuilder::oauth2_callback_url

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

Specifies the OAuth2 callback URL.

RequestContextBuilder::workload_identity_context

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

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

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

Adds one entry to RequestContext::request_headers.

RequestContextBuilder::tasks

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

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

RequestContextBuilder::build

pub fn build(mut self) -> RequestContext

Builds the context.

WorkloadAccessToken

pub struct WorkloadAccessToken

A workload access token of AgentCore Identity.

WorkloadAccessToken::new

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

Wraps a token value.

WorkloadAccessToken::expose

pub fn expose(&self) -> &str

The token value. Keep it out of logs.

current

pub fn current() -> Option<RequestContext>

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

scope

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

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

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

Errors

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.

The operations of the SDK return the following error type.

Error

pub struct Error

Error returned by this crate.

Error::kind

pub fn kind(&self) -> ErrorKind

The category of this error.

ErrorKind

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.