bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
Documentation
//! An agent that acts for a user, who gives consent in a browser when needed.
//!
//! A tool of the agent asks AgentCore Identity for a token of an OAuth2 credential
//! provider with the authorization code grant. Name the provider in `OAUTH2_PROVIDER`
//! and a scope in `OAUTH2_SCOPE`. When AgentCore Identity has no token for the user
//! yet, the agent streams the authorization URL to its caller and the tool keeps
//! waiting. Once the user has given consent, the tool returns and the stream goes on
//! with the reply of the agent.
//!
//! 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`.
//!
//! The consent completes at the callback endpoint of your application, which checks
//! that the browser belongs to the user who started the request and then calls
//! `CompleteResourceTokenAuth`. This example does not include that endpoint. See
//! <https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/oauth2-authorization-url-session-binding.html>.
//! Name the URL of that endpoint in `OAUTH2_CALLBACK_URL`. It must be one of the
//! allowed return URLs of the workload identity. AgentCore Runtime does not send
//! this URL to the agent.
//!
//! Run it with
//! `OAUTH2_PROVIDER=my-provider OAUTH2_SCOPE=profile OAUTH2_CALLBACK_URL=https://app.example/oauth2/callback cargo run --example user-federation`,
//! then:
//!
//! ```text
//! curl -N localhost:8080/invocations \
//!   -H 'X-Amzn-Bedrock-AgentCore-Runtime-Session-Id: local-session' \
//!   -H "X-Amz-Bedrock-AgentCore-Identity-WAT: $TOKEN" \
//!   -d '{"prompt": "Connect my account at the partner service."}'
//! ```
//!
//! `$TOKEN` is a workload access token for the user, for example from
//! `GetWorkloadAccessTokenForUserId`.

use std::{sync::Arc, time::Duration};

use aws_config::BehaviorVersion;
use bedrock_agentcore::{
    RequestContext, context,
    identity::{AuthFlow, AuthorizationUrl, IdentityClient},
    runtime::{BedrockAgentCoreApp, Response},
};
use futures_util::StreamExt;
use serde::Deserialize;
use serde_json::{Value, json};
use strands::{Agent, AgentStreamEvent, ToolError, models::bedrock::BedrockModel, tools};
use tokio::sync::mpsc;

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

/// The tools of one invocation.
struct Partner {
    identity: IdentityClient,
    provider: String,
    scope: String,
    callback_url: String,
    ctx: RequestContext,
    /// Hands the authorization URL to the stream of the invocation.
    urls: mpsc::Sender<AuthorizationUrl>,
}

#[tools]
impl Partner {
    /// Connect to the user's account at the partner service. Returns when the user has given consent.
    #[tool]
    async fn connect_account(&self) -> Result<Value, ToolError> {
        let urls = self.urls.clone();
        let request = self
            .identity
            .oauth2_token(&self.provider, AuthFlow::UserFederation)
            .scopes([&self.scope])
            .callback_url(&self.callback_url)
            // Behind AgentCore Runtime the agent does not learn that its caller has
            // left: the request then asks for the token until this time has passed.
            .timeout(Duration::from_secs(300))
            .on_auth_url(move |url| {
                let urls = urls.clone();
                async move { urls.send(url).await.map_err(|_| "the caller is gone") }
            });
        // `send` finds the workload access token in the context.
        let token = context::scope(self.ctx.clone(), request.send())
            .await
            .map_err(|error| ToolError::msg(error.to_string()))?;
        // Give `token.expose()` to the client of the service that needs it. The token
        // and the authorization URL stay out of the tool result, so the model never
        // sees them.
        Ok(json!({ "authorized": true, "access_token_length": token.expose().len() }))
    }
}

fn variable(name: &str) -> Result<String, String> {
    std::env::var(name).map_err(|_| format!("set the environment variable {name}"))
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    tracing_subscriber::fmt().with_ansi(false).init();
    let provider = variable("OAUTH2_PROVIDER")?;
    let scope = variable("OAUTH2_SCOPE")?;
    let callback_url = variable("OAUTH2_CALLBACK_URL")?;

    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| {
        // The tool hands the authorization URL to the stream through this channel.
        let (urls, mut received) = mpsc::channel(1);
        let partner = Arc::new(Partner {
            identity: identity.clone(),
            provider: provider.clone(),
            scope: scope.clone(),
            callback_url: callback_url.clone(),
            ctx,
            urls,
        });
        let model = model.clone();
        async move {
            let mut agent = Agent::builder()
                .model(model)
                .system_prompt(
                    "You connect the user's account at the partner service with your tool. Report the outcome.",
                )
                .tools(partner.tools())
                .printer(false)
                .build()?;

            // The stream runs after this function returns, so it owns the agent. When
            // the caller disconnects, the stream is dropped with the agent and its
            // tool call, and the polling stops.
            let events = async_stream::try_stream! {
                {
                    let mut events = agent.stream(request.prompt);
                    loop {
                        // The URL arrives while the tool call, and so the agent, waits.
                        let event = tokio::select! {
                            biased;
                            Some(url) = received.recv() => {
                                // The URL goes to the caller that started this request and is not logged.
                                yield json!({ "authorization_url": url.expose() });
                                continue;
                            }
                            event = events.next() => event,
                        };
                        match event {
                            Some(Ok(AgentStreamEvent::ModelStreamUpdate(update))) => {
                                if let Some(text) = update.text_delta() {
                                    yield json!({ "text": text });
                                }
                            }
                            Some(Ok(AgentStreamEvent::AgentResult(result))) => {
                                yield json!({ "done": result.stop_reason().to_string() });
                            }
                            Some(Ok(_)) => {}
                            Some(Err(error)) => Err(error)?,
                            None => break,
                        }
                    }
                }
                agent.shutdown().await?;
            };
            Ok::<_, strands::Error>(Response::stream(events.map(|event: strands::Result<_>| event)))
        }
    };
    BedrockAgentCoreApp::builder().invocation(handle).build()?.run().await?;
    Ok(())
}