aws-cdk.aws-bedrock-agentcore-alpha 2.239.0a0
The CDK Construct Library for Amazon Bedrock
License: Apache-2.0
Requires Python: ~=3.9

# Amazon Bedrock AgentCore Construct Library

<!--BEGIN STABILITY BANNER-->---


![cdk-constructs: Experimental](https://img.shields.io/badge/cdk--constructs-experimental-important.svg?style=for-the-badge)

> The APIs of higher level constructs in this module are experimental and under active development.
> They are subject to non-backward compatible changes or removal in any future version. These are
> not subject to the [Semantic Versioning](https://semver.org/) model and breaking changes will be
> announced in the release notes. This means that while you may use them, you may need to update
> your source code when upgrading to a newer version of this package.

---
<!--END STABILITY BANNER-->

| **Language**                                                                                   | **Package**                             |
| :--------------------------------------------------------------------------------------------- | --------------------------------------- |
| ![Typescript Logo](https://docs.aws.amazon.com/cdk/api/latest/img/typescript32.png) TypeScript | `@aws-cdk/aws-bedrock-agentcore-alpha` |

[Amazon Bedrock AgentCore](https://aws.amazon.com/bedrock/agentcore/) enables you to deploy and operate highly capable AI agents securely, at scale. It offers infrastructure purpose-built for dynamic agent workloads, powerful tools to enhance agents, and essential controls for real-world deployment. AgentCore services can be used together or independently and work with any framework including CrewAI, LangGraph, LlamaIndex, and Strands Agents, as well as any foundation model in or outside of Amazon Bedrock, giving you ultimate flexibility. AgentCore eliminates the undifferentiated heavy lifting of building specialized agent infrastructure, so you can accelerate agents to production.

This construct library facilitates the deployment of Bedrock AgentCore primitives, enabling you to create sophisticated AI applications that can interact with your systems and data sources.

> **Note:** Users need to ensure their CDK deployment role has the `iam:CreateServiceLinkedRole` permission for AgentCore service-linked roles.

## Table of contents

* [Amazon Bedrock AgentCore Construct Library](#amazon-bedrock-agentcore-construct-library)

  * [Table of contents](#table-of-contents)
  * [AgentCore Runtime](#agentcore-runtime)

    * [Runtime Endpoints](#runtime-endpoints)
    * [AgentCore Runtime Properties](#agentcore-runtime-properties)
    * [Runtime Endpoint Properties](#runtime-endpoint-properties)
    * [Creating a Runtime](#creating-a-runtime)

      * [Option 1: Use an existing image in ECR](#option-1-use-an-existing-image-in-ecr)
      * [Option 2: Use a local asset](#option-2-use-a-local-asset)
      * [Option 3: Use direct code deployment](#option-3-use-direct-code-deployment)
      * [Option 4: Use an ECR container image URI](#option-4-use-an-ecr-container-image-uri)
    * [Granting Permissions to Invoke Bedrock Models or Inference Profiles](#granting-permissions-to-invoke-bedrock-models-or-inference-profiles)
    * [Runtime Versioning](#runtime-versioning)

      * [Managing Endpoints and Versions](#managing-endpoints-and-versions)

        * [Step 1: Initial Deployment](#step-1-initial-deployment)
        * [Step 2: Creating Custom Endpoints](#step-2-creating-custom-endpoints)
        * [Step 3: Runtime Update Deployment](#step-3-runtime-update-deployment)
        * [Step 4: Testing with Staging Endpoints](#step-4-testing-with-staging-endpoints)
        * [Step 5: Promoting to Production](#step-5-promoting-to-production)
    * [Creating Standalone Runtime Endpoints](#creating-standalone-runtime-endpoints)

      * [Example: Creating an endpoint for an existing runtime](#example-creating-an-endpoint-for-an-existing-runtime)
    * [Runtime Authentication Configuration](#runtime-authentication-configuration)

      * [IAM Authentication (Default)](#iam-authentication-default)
      * [Cognito Authentication](#cognito-authentication)
      * [JWT Authentication](#jwt-authentication)
      * [OAuth Authentication](#oauth-authentication)
      * [Using a Custom IAM Role](#using-a-custom-iam-role)
    * [Runtime Network Configuration](#runtime-network-configuration)

      * [Public Network Mode (Default)](#public-network-mode-default)
      * [VPC Network Mode](#vpc-network-mode)
      * [Managing Security Groups with VPC Configuration](#managing-security-groups-with-vpc-configuration)
    * [Runtime IAM Permissions](#runtime-iam-permissions)
    * [Other configuration](#other-configuration)

      * [Lifecycle configuration](#lifecycle-configuration)
      * [Request header configuration](#request-header-configuration)
  * [Browser](#browser)

    * [Browser Network modes](#browser-network-modes)
    * [Browser Properties](#browser-properties)
    * [Basic Browser Creation](#basic-browser-creation)
    * [Browser with Tags](#browser-with-tags)
    * [Browser with VPC](#browser-with-vpc)
    * [Browser with Recording Configuration](#browser-with-recording-configuration)
    * [Browser with Custom Execution Role](#browser-with-custom-execution-role)
    * [Browser with S3 Recording and Permissions](#browser-with-s3-recording-and-permissions)
    * [Browser with Browser signing](#browser-with-browser-signing)
    * [Browser IAM Permissions](#browser-iam-permissions)
  * [Code Interpreter](#code-interpreter)

    * [Code Interpreter Network Modes](#code-interpreter-network-modes)
    * [Code Interpreter Properties](#code-interpreter-properties)
    * [Basic Code Interpreter Creation](#basic-code-interpreter-creation)
    * [Code Interpreter with VPC](#code-interpreter-with-vpc)
    * [Code Interpreter with Sandbox Network Mode](#code-interpreter-with-sandbox-network-mode)
    * [Code Interpreter with Custom Execution Role](#code-interpreter-with-custom-execution-role)
    * [Code Interpreter IAM Permissions](#code-interpreter-iam-permissions)
    * [Code interpreter with tags](#code-interpreter-with-tags)
  * [Gateway](#gateway)

    * [Gateway Properties](#gateway-properties)
    * [Basic Gateway Creation](#basic-gateway-creation)
    * [Protocol configuration](#protocol-configuration)
    * [Inbound authorization](#inbound-authorization)
    * [Gateway with KMS Encryption](#gateway-with-kms-encryption)
    * [Gateway with Custom Execution Role](#gateway-with-custom-execution-role)
    * [Gateway IAM Permissions](#gateway-iam-permissions)
  * [Gateway Target](#gateway-target)

    * [Gateway Target Properties](#gateway-target-properties)
    * [Targets types](#targets-types)
    * [Understanding Tool Naming](#understanding-tool-naming)
    * [Tools schema For Lambda target](#tools-schema-for-lambda-target)
    * [Api schema For OpenAPI and Smithy target](#api-schema-for-openapi-and-smithy-target)
    * [Outbound auth](#outbound-auth)
    * [Basic Gateway Target Creation](#basic-gateway-target-creation)

      * [Using addTarget methods (Recommended)](#using-addtarget-methods-recommended)
      * [Using static factory methods](#using-static-factory-methods)
    * [Advanced Usage: Direct Configuration for gateway target](#advanced-usage-direct-configuration-for-gateway-target)

      * [Configuration Factory Methods](#configuration-factory-methods)
      * [Example: Lambda Target with Custom Configuration](#example-lambda-target-with-custom-configuration)
    * [Gateway Target IAM Permissions](#gateway-target-iam-permissions)
  * [Memory](#memory)

    * [Memory Properties](#memory-properties)
    * [Basic Memory Creation](#basic-memory-creation)
    * [LTM Memory Extraction Stategies](#ltm-memory-extraction-stategies)
    * [Memory with Built-in Strategies](#memory-with-built-in-strategies)
    * [Memory with custom Strategies](#memory-with-custom-strategies)

      * [Memory with Custom Execution Role](#memory-with-custom-execution-role)
    * [Memory with self-managed Strategies](#memory-with-self-managed-strategies)
    * [Memory Strategy Methods](#memory-strategy-methods)

## AgentCore Runtime

The AgentCore Runtime construct enables you to deploy containerized agents on Amazon Bedrock AgentCore.
This L2 construct simplifies runtime creation just pass your ECR repository name
and the construct handles all the configuration with sensible defaults.

### Runtime Endpoints

Endpoints provide a stable way to invoke specific versions of your agent runtime, enabling controlled deployments across different environments.
When you create an agent runtime, Amazon Bedrock AgentCore automatically creates a "DEFAULT" endpoint which always points to the latest version
of runtime.

You can create additional endpoints in two ways:

1. **Using Runtime.addEndpoint()** - Convenient method when creating endpoints alongside the runtime.
2. **Using RuntimeEndpoint** - Flexible approach for existing runtimes.

For example, you might keep a "production" endpoint on a stable version while testing newer versions
through a "staging" endpoint. This separation allows you to test changes thoroughly before promoting them
to production by simply updating the endpoint to point to the newer version.

### AgentCore Runtime Properties

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `runtimeName` | `string` | No | The name of the agent runtime. Valid characters are a-z, A-Z, 0-9, _ (underscore). Must start with a letter and can be up to 48 characters long. If not provided, a unique name will be auto-generated |
| `agentRuntimeArtifact` | `AgentRuntimeArtifact` | Yes | The artifact configuration for the agent runtime containing the container configuration with ECR URI |
| `executionRole` | `iam.IRole` | No | The IAM role that provides permissions for the agent runtime. If not provided, a role will be created automatically |
| `networkConfiguration` | `NetworkConfiguration` | No | Network configuration for the agent runtime. Defaults to `RuntimeNetworkConfiguration.usingPublicNetwork()` |
| `description` | `string` | No | Optional description for the agent runtime |
| `protocolConfiguration` | `ProtocolType` | No | Protocol configuration for the agent runtime. Defaults to `ProtocolType.HTTP` |
| `authorizerConfiguration` | `RuntimeAuthorizerConfiguration` | No | Authorizer configuration for the agent runtime. Use `RuntimeAuthorizerConfiguration` static methods to create configurations for IAM, Cognito, JWT, or OAuth authentication |
| `environmentVariables` | `{ [key: string]: string }` | No | Environment variables for the agent runtime. Maximum 50 environment variables |
| `tags` | `{ [key: string]: string }` | No | Tags for the agent runtime. A list of key:value pairs of tags to apply to this Runtime resource |
| `lifecycleConfiguration` | LifecycleConfiguration | No | The life cycle configuration for the AgentCore Runtime. Defaults to 900 seconds (15 minutes) for idle, 28800 seconds (8 hours) for max life time |
| `requestHeaderConfiguration` | RequestHeaderConfiguration | No | Configuration for HTTP request headers that will be passed through to the runtime. Defaults to no configuration |

### Runtime Endpoint Properties

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `endpointName` | `string` | No | The name of the runtime endpoint. Valid characters are a-z, A-Z, 0-9, _ (underscore). Must start with a letter and can be up to 48 characters long. If not provided, a unique name will be auto-generated |
| `agentRuntimeId` | `string` | Yes | The Agent Runtime ID for this endpoint |
| `agentRuntimeVersion` | `string` | Yes | The Agent Runtime version for this endpoint. Must be between 1 and 5 characters long.|
| `description` | `string` | No | Optional description for the runtime endpoint |
| `tags` | `{ [key: string]: string }` | No | Tags for the runtime endpoint |

### Creating a Runtime

#### Option 1: Use an existing image in ECR

Reference an image available within ECR.

```python
repository = ecr.Repository(self, "TestRepository",
    repository_name="test-agent-runtime"
)

# The runtime by default create ECR permission only for the repository available in the account the stack is being deployed
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

# Create runtime using the built image
runtime = agentcore.Runtime(self, "MyAgentRuntime",
    runtime_name="myAgent",
    agent_runtime_artifact=agent_runtime_artifact
)
```

#### Option 2: Use a local asset

Reference a local directory containing a Dockerfile.
Images are built from a local Docker context directory (with a Dockerfile), uploaded to Amazon Elastic Container Registry (ECR)
by the CDK toolkit,and can be naturally referenced in your CDK app.

```python
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_asset(
    path.join(__dirname, "path to agent dockerfile directory"))

runtime = agentcore.Runtime(self, "MyAgentRuntime",
    runtime_name="myAgent",
    agent_runtime_artifact=agent_runtime_artifact
)
```

#### Option 3: Use direct code deployment

With the container deployment method, developers create a Dockerfile, build ARM-compatible containers, manage ECR repositories, and upload containers for code changes. This works well where container DevOps pipelines have already been established to automate deployments.

However, customers looking for fully managed deployments can benefit from direct code deployment, which can significantly improve developer time and productivity. Direct code deployment provides a secure and scalable path forward for rapid prototyping agent capabilities to deploying production workloads at scale.

With direct code deployment, developers create a zip archive of code and dependencies, upload to Amazon S3, and configure the bucket in the agent configuration. A ZIP archive containing Linux arm64 dependencies needs to be uploaded to S3 as a pre-requisite to Create Agent Runtime.

For more information, please refer to the [documentation](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-get-started-code-deploy.html).

```python
# S3 bucket containing the agent core
code_bucket = s3.Bucket(self, "AgentCode",
    bucket_name="my-code-bucket",
    removal_policy=RemovalPolicy.DESTROY
)

# the bucket above needs to contain the agent code

agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_s3(s3.Location(
    bucket_name=code_bucket.bucket_name,
    object_key="deployment_package.zip"
), agentcore.AgentCoreRuntime.PYTHON_3_12, ["opentelemetry-instrument", "main.py"])

runtime_instance = agentcore.Runtime(self, "MyAgentRuntime",
    runtime_name="myAgent",
    agent_runtime_artifact=agent_runtime_artifact
)
```

Alternatively, you can use local code assets that will be automatically packaged and uploaded to a CDK-managed S3 bucket:

```python
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_code_asset(
    path=path.join(__dirname, "path/to/agent/code"),
    runtime=agentcore.AgentCoreRuntime.PYTHON_3_12,
    entrypoint=["opentelemetry-instrument", "main.py"]
)

runtime_instance = agentcore.Runtime(self, "MyAgentRuntime",
    runtime_name="myAgent",
    agent_runtime_artifact=agent_runtime_artifact
)
```

#### Option 4: Use an ECR container image URI

Reference an ECR container image directly by its URI. This is useful when you have a pre-existing ECR image URI from CloudFormation parameters or cross-stack references. No IAM permissions are automatically granted - you must ensure the runtime has ECR pull permissions.

```python
# Direct URI reference
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_image_uri("123456789012.dkr.ecr.us-east-1.amazonaws.com/my-agent:v1.0.0")

runtime = agentcore.Runtime(self, "MyAgentRuntime",
    runtime_name="myAgent",
    agent_runtime_artifact=agent_runtime_artifact
)
```

You can also use CloudFormation parameters or references:

```python
# Using a CloudFormation parameter
image_uri_param = cdk.CfnParameter(self, "ImageUri",
    type="String",
    description="Container image URI for the agent runtime"
)

agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_image_uri(image_uri_param.value_as_string)

runtime = agentcore.Runtime(self, "MyAgentRuntime",
    runtime_name="myAgent",
    agent_runtime_artifact=agent_runtime_artifact
)
```

### Granting Permissions to Invoke Bedrock Models or Inference Profiles

To grant the runtime permissions to invoke Bedrock models or inference profiles:

```python
# Note: This example uses @aws-cdk/aws-bedrock-alpha which must be installed separately
# runtime: agentcore.Runtime


# Define the Bedrock Foundation Model
model = bedrock.BedrockFoundationModel.ANTHROPIC_CLAUDE_3_7_SONNET_V1_0

# Grant the runtime permissions to invoke the model
model.grant_invoke(runtime)

# Create a cross-region inference profile for Claude 3.7 Sonnet
inference_profile = bedrock.CrossRegionInferenceProfile.from_config(
    geo_region=bedrock.CrossRegionInferenceProfileRegion.US,
    model=bedrock.BedrockFoundationModel.ANTHROPIC_CLAUDE_3_7_SONNET_V1_0
)

# Grant the runtime permissions to invoke the inference profile
inference_profile.grant_invoke(runtime)
```

### Runtime Versioning

Amazon Bedrock AgentCore automatically manages runtime versioning to ensure safe deployments and rollback capabilities.
When you create an agent runtime, AgentCore automatically creates version 1 (V1). Each subsequent update to the
runtime configuration (such as updating the container image, modifying network settings, or changing protocol configurations)
creates a new immutable version. These versions contain complete, self-contained configurations that can be referenced by endpoints,
allowing you to maintain different versions for different environments or gradually roll out updates.

#### Managing Endpoints and Versions

Amazon Bedrock AgentCore automatically manages runtime versioning to provide safe deployments and rollback capabilities. You can follow
the steps below to understand how to use versioning with runtime for controlled deployments across different environments.

##### Step 1: Initial Deployment

When you first create an agent runtime, AgentCore automatically creates Version 1 of your runtime. At this point, a DEFAULT endpoint is
automatically created that points to Version 1. This DEFAULT endpoint serves as the main access point for your runtime.

```python
repository = ecr.Repository(self, "TestRepository",
    repository_name="test-agent-runtime"
)

runtime = agentcore.Runtime(self, "MyAgentRuntime",
    runtime_name="myAgent",
    agent_runtime_artifact=agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
)
```

##### Step 2: Creating Custom Endpoints

After the initial deployment, you can create additional endpoints for different environments. For example, you might create a "production"
endpoint that explicitly points to Version 1. This allows you to maintain stable access points for specific environments while keeping the
flexibility to test newer versions elsewhere.

```python
repository = ecr.Repository(self, "TestRepository",
    repository_name="test-agent-runtime"
)

runtime = agentcore.Runtime(self, "MyAgentRuntime",
    runtime_name="myAgent",
    agent_runtime_artifact=agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
)

prod_endpoint = runtime.add_endpoint("production",
    version="1",
    description="Stable production endpoint - pinned to v1"
)
```

##### Step 3: Runtime Update Deployment

When you update the runtime configuration (such as updating the container image, modifying network settings, or changing protocol
configurations), AgentCore automatically creates a new version (Version 2). Upon this update:

* Version 2 is created automatically with the new configuration
* The DEFAULT endpoint automatically updates to point to Version 2
* Any explicitly pinned endpoints (like the production endpoint) remain on their specified versions

```python
repository = ecr.Repository(self, "TestRepository",
    repository_name="test-agent-runtime"
)

agent_runtime_artifact_new = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v2.0.0")

runtime = agentcore.Runtime(self, "MyAgentRuntime",
    runtime_name="myAgent",
    agent_runtime_artifact=agent_runtime_artifact_new
)
```

##### Step 4: Testing with Staging Endpoints

Once Version 2 exists, you can create a staging endpoint that points to the new version. This staging endpoint allows you to test the
new version in a controlled environment before promoting it to production. This separation ensures that production traffic continues
to use the stable version while you validate the new version.

```python
repository = ecr.Repository(self, "TestRepository",
    repository_name="test-agent-runtime"
)

agent_runtime_artifact_new = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v2.0.0")

runtime = agentcore.Runtime(self, "MyAgentRuntime",
    runtime_name="myAgent",
    agent_runtime_artifact=agent_runtime_artifact_new
)

staging_endpoint = runtime.add_endpoint("staging",
    version="2",
    description="Staging environment for testing new version"
)
```

##### Step 5: Promoting to Production

After thoroughly testing the new version through the staging endpoint, you can update the production endpoint to point to Version 2.
This controlled promotion process ensures that you can validate changes before they affect production traffic.

```python
repository = ecr.Repository(self, "TestRepository",
    repository_name="test-agent-runtime"
)

agent_runtime_artifact_new = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v2.0.0")

runtime = agentcore.Runtime(self, "MyAgentRuntime",
    runtime_name="myAgent",
    agent_runtime_artifact=agent_runtime_artifact_new
)

prod_endpoint = runtime.add_endpoint("production",
    version="2",  # New version added here
    description="Stable production endpoint"
)
```

### Creating Standalone Runtime Endpoints

RuntimeEndpoint can also be created as a standalone resource.

#### Example: Creating an endpoint for an existing runtime

```python
# Reference an existing runtime by its ID
existing_runtime_id = "abc123-runtime-id" # The ID of an existing runtime

# Create a standalone endpoint
endpoint = agentcore.RuntimeEndpoint(self, "MyEndpoint",
    endpoint_name="production",
    agent_runtime_id=existing_runtime_id,
    agent_runtime_version="1",  # Specify which version to use
    description="Production endpoint for existing runtime"
)
```

### Runtime Authentication Configuration

The AgentCore Runtime supports multiple authentication modes to secure access to your agent endpoints. Authentication is configured during runtime creation using the `RuntimeAuthorizerConfiguration` class's static factory methods.

#### IAM Authentication (Default)

IAM authentication is the default mode, when no authorizerConfiguration is set then the underlying service use IAM.

#### Cognito Authentication

To configure AWS Cognito User Pool authentication:

```python
# user_pool: cognito.UserPool
# user_pool_client: cognito.UserPoolClient
# another_user_pool_client: cognito.UserPoolClient


repository = ecr.Repository(self, "TestRepository",
    repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

# Optional: Create custom claims for additional validation
custom_claims = [
    agentcore.RuntimeCustomClaim.with_string_value("department", "engineering"),
    agentcore.RuntimeCustomClaim.with_string_array_value("roles", ["admin"], agentcore.CustomClaimOperator.CONTAINS),
    agentcore.RuntimeCustomClaim.with_string_array_value("permissions", ["read", "write"], agentcore.CustomClaimOperator.CONTAINS_ANY)
]

runtime = agentcore.Runtime(self, "MyAgentRuntime",
    runtime_name="myAgent",
    agent_runtime_artifact=agent_runtime_artifact,
    authorizer_configuration=agentcore.RuntimeAuthorizerConfiguration.using_cognito(user_pool, [user_pool_client, another_user_pool_client], ["audience1"], ["read", "write"], custom_claims)
)
```

You can configure:

* User Pool: The Cognito User Pool that issues JWT tokens
* User Pool Clients: One or more Cognito User Pool App Clients that are allowed to access the runtime
* Allowed audiences: Used to validate that the audiences specified in the Cognito token match or are a subset of the audiences specified in the AgentCore Runtime
* Allowed scopes: Allow access only if the token contains at least one of the required scopes configured here
* Custom claims: A set of rules to match specific claims in the incoming token against predefined values for validating JWT tokens

#### JWT Authentication

To configure custom JWT authentication with your own OpenID Connect (OIDC) provider:

```python
repository = ecr.Repository(self, "TestRepository",
    repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

runtime = agentcore.Runtime(self, "MyAgentRuntime",
    runtime_name="myAgent",
    agent_runtime_artifact=agent_runtime_artifact,
    authorizer_configuration=agentcore.RuntimeAuthorizerConfiguration.using_jWT("https://example.com/.well-known/openid-configuration", ["client1", "client2"], ["audience1"], ["read", "write"])
)
```

You can configure:

* Discovery URL: Enter the Discovery URL from your identity provider (e.g. Okta, Cognito, etc.), typically found in that provider's documentation. This allows your Agent or Tool to fetch login, downstream resource token, and verification settings.
* Allowed audiences: This is used to validate that the audiences specified for the OAuth token matches or are a subset of the audiences specified in the AgentCore Runtime.
* Allowed clients: This is used to validate that the public identifier of the client, as specified in the authorization token, is allowed to access the AgentCore Runtime.
* Allowed scopes: Allow access only if the token contains at least one of the required scopes configured here.
* Custom claims: A set of rules to match specific claims in the incoming token against predefined values for validating JWT tokens.

**Note**: The discovery URL must end with `/.well-known/openid-configuration`.

##### Custom Claims Validation

Custom claims allow you to validate additional fields in JWT tokens beyond the standard audience, client, and scope validations. You can create custom claims using the `RuntimeCustomClaim` class:

```python
repository = ecr.Repository(self, "TestRepository",
    repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

# String claim - validates that the claim exactly equals the specified value
# Uses EQUALS operator automatically
department_claim = agentcore.RuntimeCustomClaim.with_string_value("department", "engineering")

# String array claim with CONTAINS operator (default)
# Validates that the claim array contains a specific string value
# IMPORTANT: CONTAINS requires exactly one value in the array parameter
roles_claim = agentcore.RuntimeCustomClaim.with_string_array_value("roles", ["admin"])

# String array claim with CONTAINS_ANY operator
# Validates that the claim array contains at least one of the specified values
# Use this when you want to check for multiple possible values
permissions_claim = agentcore.RuntimeCustomClaim.with_string_array_value("permissions", ["read", "write"], agentcore.CustomClaimOperator.CONTAINS_ANY)

# Use custom claims in authorizer configuration
runtime = agentcore.Runtime(self, "MyAgentRuntime",
    runtime_name="myAgent",
    agent_runtime_artifact=agent_runtime_artifact,
    authorizer_configuration=agentcore.RuntimeAuthorizerConfiguration.using_jWT("https://example.com/.well-known/openid-configuration", ["client1", "client2"], ["audience1"], ["read", "write"], [department_claim, roles_claim, permissions_claim])
)
```

**Custom Claim Rules**:

* **String claims**: Must use the `EQUALS` operator (automatically set). The claim value must exactly match the specified string.
* **String array claims**: Can use `CONTAINS` (default) or `CONTAINS_ANY` operators:

  * **`CONTAINS`**: Checks if the claim array contains a specific string value. **Requires exactly one value** in the array parameter. For example, `['admin']` will check if the token's claim array contains the string `'admin'`.
  * **`CONTAINS_ANY`**: Checks if the claim array contains at least one of the provided string values. Use this when you want to validate against multiple possible values. For example, `['read', 'write']` will check if the token's claim array contains either `'read'` or `'write'`.

**Example Use Cases**:

* Use `CONTAINS` when you need to verify a user has a specific role: `RuntimeCustomClaim.withStringArrayValue('roles', ['admin'])`
* Use `CONTAINS_ANY` when you need to verify a user has any of several permissions: `RuntimeCustomClaim.withStringArrayValue('permissions', ['read', 'write'], CustomClaimOperator.CONTAINS_ANY)`

#### OAuth Authentication

To configure OAuth 2.0 authentication:

```python
repository = ecr.Repository(self, "TestRepository",
    repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

runtime = agentcore.Runtime(self, "MyAgentRuntime",
    runtime_name="myAgent",
    agent_runtime_artifact=agent_runtime_artifact,
    authorizer_configuration=agentcore.RuntimeAuthorizerConfiguration.using_oAuth("https://github.com/.well-known/openid-configuration", "oauth_client_123", ["audience1"], ["openid", "profile"])
)
```

#### Using a Custom IAM Role

Instead of using the auto-created execution role, you can provide your own IAM role with specific permissions:
The auto-created role includes all necessary baseline permissions for ECR access, CloudWatch logging, and X-Ray tracing. When providing a custom role, ensure these permissions are included.

### Runtime Network Configuration

The AgentCore Runtime supports two network modes for deployment:

#### Public Network Mode (Default)

By default, runtimes are deployed in PUBLIC network mode, which provides internet access suitable for less sensitive or open-use scenarios:

```python
repository = ecr.Repository(self, "TestRepository",
    repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

# Explicitly using public network (this is the default)
runtime = agentcore.Runtime(self, "MyAgentRuntime",
    runtime_name="myAgent",
    agent_runtime_artifact=agent_runtime_artifact,
    network_configuration=agentcore.RuntimeNetworkConfiguration.using_public_network()
)
```

#### VPC Network Mode

For enhanced security and network isolation, you can deploy your runtime within a VPC:

```python
repository = ecr.Repository(self, "TestRepository",
    repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

# Create or use an existing VPC
vpc = ec2.Vpc(self, "MyVpc",
    max_azs=2
)

# Configure runtime with VPC
runtime = agentcore.Runtime(self, "MyAgentRuntime",
    runtime_name="myAgent",
    agent_runtime_artifact=agent_runtime_artifact,
    network_configuration=agentcore.RuntimeNetworkConfiguration.using_vpc(self,
        vpc=vpc,
        vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS)
    )
)
```

#### Managing Security Groups with VPC Configuration

When using VPC mode, the Runtime implements `ec2.IConnectable`, allowing you to manage network access using the `connections` property:

```python
vpc = ec2.Vpc(self, "MyVpc",
    max_azs=2
)

repository = ecr.Repository(self, "TestRepository",
    repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

# Create runtime with VPC configuration
runtime = agentcore.Runtime(self, "MyAgentRuntime",
    runtime_name="myAgent",
    agent_runtime_artifact=agent_runtime_artifact,
    network_configuration=agentcore.RuntimeNetworkConfiguration.using_vpc(self,
        vpc=vpc,
        vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS)
    )
)

# Now you can manage network access using the connections property
# Allow inbound HTTPS traffic from a specific security group
web_server_security_group = ec2.SecurityGroup(self, "WebServerSG", vpc=vpc)
runtime.connections.allow_from(web_server_security_group, ec2.Port.tcp(443), "Allow HTTPS from web servers")

# Allow outbound connections to a database
database_security_group = ec2.SecurityGroup(self, "DatabaseSG", vpc=vpc)
runtime.connections.allow_to(database_security_group, ec2.Port.tcp(5432), "Allow PostgreSQL connection")

# Allow outbound HTTPS to anywhere (for external API calls)
runtime.connections.allow_to_any_ipv4(ec2.Port.tcp(443), "Allow HTTPS outbound")
```

### Runtime IAM Permissions

The Runtime construct provides convenient methods for granting IAM permissions to principals that need to invoke the runtime or manage its execution role.

```python
repository = ecr.Repository(self, "TestRepository",
    repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

# Create a runtime
runtime = agentcore.Runtime(self, "MyRuntime",
    runtime_name="my_runtime",
    agent_runtime_artifact=agent_runtime_artifact
)

# Create a Lambda function that needs to invoke the runtime
invoker_function = lambda_.Function(self, "InvokerFunction",
    runtime=lambda_.Runtime.PYTHON_3_12,
    handler="index.handler",
    code=lambda_.Code.from_inline("""
        import boto3
        def handler(event, context):
            client = boto3.client('bedrock-agentcore')
            # Invoke the runtime...
          """)
)

# Grant permission to invoke the runtime directly
runtime.grant_invoke_runtime(invoker_function)

# Grant permission to invoke the runtime on behalf of a user
# (requires X-Amzn-Bedrock-AgentCore-Runtime-User-Id header)
runtime.grant_invoke_runtime_for_user(invoker_function)

# Grant both invoke permissions (most common use case)
runtime.grant_invoke(invoker_function)

# Grant specific custom permissions to the runtime's execution role
runtime.grant(["bedrock:InvokeModel"], ["arn:aws:bedrock:*:*:*"])

# Add a policy statement to the runtime's execution role
runtime.add_to_role_policy(iam.PolicyStatement(
    actions=["s3:GetObject"],
    resources=["arn:aws:s3:::my-bucket/*"]
))
```

### Other configuration

#### Lifecycle configuration

The LifecycleConfiguration input parameter to CreateAgentRuntime lets you manage the lifecycle of runtime sessions and resources in Amazon Bedrock AgentCore Runtime. This configuration helps optimize resource utilization by automatically cleaning up idle sessions and preventing long-running instances from consuming resources indefinitely.

You can configure:

* idleRuntimeSessionTimeout: Timeout in seconds for idle runtime sessions. When a session remains idle for this duration, it will trigger termination. Termination can last up to 15 seconds due to logging and other process completion. Default: 900 seconds (15 minutes)
* maxLifetime: Maximum lifetime for the instance in seconds. Once reached, instances will initialize termination. Termination can last up to 15 seconds due to logging and other process completion. Default: 28800 seconds (8 hours)

For additional information, please refer to the [documentation](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-lifecycle-settings.html).

```python
repository = ecr.Repository(self, "TestRepository",
    repository_name="test-agent-runtime"
)

agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

agentcore.Runtime(self, "test-runtime",
    runtime_name="test_runtime",
    agent_runtime_artifact=agent_runtime_artifact,
    lifecycle_configuration=agentcore.LifecycleConfiguration(
        idle_runtime_session_timeout=Duration.minutes(10),
        max_lifetime=Duration.hours(4)
    )
)
```

#### Request header configuration

Custom headers let you pass contextual information from your application directly to your agent code without cluttering the main request payload. This includes authentication tokens like JWT (JSON Web Tokens, which contain user identity and authorization claims) through the Authorization header, allowing your agent to make decisions based on who is calling it. You can also pass custom metadata like user preferences, session identifiers, or trace context using headers prefixed with X-Amzn-Bedrock-AgentCore-Runtime-Custom-, giving your agent access to up to 20 pieces of runtime context that travel alongside each request. This information can be also used in downstream systems like AgentCore Memory that you can namespace based on those characteristics like user_id or aud in claims like line of business.

For additional information, please refer to the [documentation](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-header-allowlist.html).

```python
repository = ecr.Repository(self, "TestRepository",
    repository_name="test-agent-runtime"
)

agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

agentcore.Runtime(self, "test-runtime",
    runtime_name="test_runtime",
    agent_runtime_artifact=agent_runtime_artifact,
    request_header_configuration=agentcore.RequestHeaderConfiguration(
        allowlisted_headers=["X-Amzn-Bedrock-AgentCore-Runtime-Custom-H1"]
    )
)
```

## Browser

The Amazon Bedrock AgentCore Browser provides a secure, cloud-based browser that enables AI agents to interact with websites. It includes security features such as session isolation, built-in observability through live viewing, CloudTrail logging, and session replay capabilities.

Additional information about the browser tool can be found in the [official documentation](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/browser-tool.html)

### Browser Network modes

The Browser construct supports the following network modes:

1. **Public Network Mode** (`BrowserNetworkMode.usingPublicNetwork()`) - Default

   * Allows internet access for web browsing and external API calls
   * Suitable for scenarios where agents need to interact with publicly available websites
   * Enables full web browsing capabilities
   * VPC mode is not supported with this option
2. **VPC (Virtual Private Cloud)** (`BrowserNetworkMode.usingVpc()`)

   * Select whether to run the browser in a virtual private cloud (VPC).
   * By configuring VPC connectivity, you enable secure access to private resources such as databases, internal APIs, and services within your VPC.

   While the VPC itself is mandatory, these are optional:

   * Subnets - if not provided, CDK will select appropriate subnets from the VPC
   * Security Groups - if not provided, CDK will create a default security group
   * Specific subnet selection criteria - you can let CDK choose automatically

For more information on VPC connectivity for Amazon Bedrock AgentCore Browser, please refer to the [official documentation](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/agentcore-vpc.html).

### Browser Properties

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `browserCustomName` | `string` | No | The name of the browser. Must start with a letter and can be up to 48 characters long. Pattern: `[a-zA-Z][a-zA-Z0-9_]{0,47}`. If not provided, a unique name will be auto-generated |
| `description` | `string` | No | Optional description for the browser. Can have up to 200 characters |
| `networkConfiguration` | `BrowserNetworkConfiguration` | No | Network configuration for browser. Defaults to PUBLIC network mode |
| `recordingConfig` | `RecordingCo