bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
Documentation
//! An agent with a tool that gets an API key from AgentCore Identity.
//!
//! The key belongs to an API key credential provider of AgentCore Identity. Name the
//! provider in `API_KEY_PROVIDER`. AgentCore Runtime sends a workload access token
//! with an invocation whose caller names a user: a `runtimeUserId` with IAM
//! authorization, or a JWT. The request for the key uses it.
//!
//! The Strands Agents SDK writes the agent. It runs each tool call on a task of its
//! own, and the request context of this SDK belongs to the task of the invocation.
//! So the tool carries the `RequestContext` and enters it again with `context::scope`.
//!
//! Run it with `API_KEY_PROVIDER=my-provider cargo run --example api-key`. A local
//! request has no token unless it sends one, so the tool of this one fails with the
//! error for a missing token, and the agent reports that:
//!
//! ```text
//! curl -s localhost:8080/invocations \
//!   -H 'X-Amzn-Bedrock-AgentCore-Runtime-Session-Id: local-session' \
//!   -d '{"prompt": "Get the partner API key."}'
//! ```
//!
//! Add `-H "X-Amz-Bedrock-AgentCore-Identity-WAT: $TOKEN"` with a workload access
//! token of a workload identity to get a key locally. The documentation of the
//! `identity` module shows how to create one for local tests.

use std::sync::Arc;

use aws_config::BehaviorVersion;
use bedrock_agentcore::{RequestContext, context, identity::IdentityClient, runtime::BedrockAgentCoreApp};
use serde::Deserialize;
use serde_json::{Value, json};
use strands::{Agent, ToolError, models::bedrock::BedrockModel, tools};

#[derive(Deserialize)]
struct Request {
    prompt: String,
}

/// The tools of one invocation.
struct Partner {
    identity: IdentityClient,
    provider: String,
    ctx: RequestContext,
}

#[tools]
impl Partner {
    /// Get the API key of the partner service.
    #[tool]
    async fn partner_api_key(&self) -> Result<Value, ToolError> {
        // `send` reads the workload access token of the invocation from the context.
        let key = context::scope(self.ctx.clone(), self.identity.api_key(&self.provider).send())
            .await
            .map_err(|error| ToolError::msg(error.to_string()))?;
        // Give `key.expose()` to the client of the service that needs it. The key
        // stays out of the tool result, so the model and the logs never see it.
        Ok(json!({ "api_key_length": key.expose().len() }))
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    tracing_subscriber::fmt().with_ansi(false).init();
    let provider = std::env::var("API_KEY_PROVIDER")
        .map_err(|_| "set API_KEY_PROVIDER to the name of an API key credential provider")?;

    // One client and one model for all invocations. The client holds no token.
    let config = aws_config::load_defaults(BehaviorVersion::latest()).await;
    let identity = IdentityClient::new(&config);
    let model = BedrockModel::builder().model_id("global.anthropic.claude-sonnet-4-6").max_tokens(4096).build();

    let handle = move |request: Request, ctx: RequestContext| {
        let partner = Arc::new(Partner { identity: identity.clone(), provider: provider.clone(), ctx });
        let model = model.clone();
        async move {
            let mut agent = Agent::builder()
                .model(model)
                .system_prompt(
                    "You get credentials for the partner service with your tools. Report what each tool returned.",
                )
                .tools(partner.tools())
                .printer(false)
                .build()?;
            let result = agent.invoke(request.prompt).await?;
            agent.shutdown().await?;
            Ok::<Value, strands::Error>(json!({ "result": result.to_string() }))
        }
    };
    BedrockAgentCoreApp::builder().invocation(handle).build()?.run().await?;
    Ok(())
}