AWSCDK::BedrockAgentCore

254 types

Amazon Bedrock AgentCore Construct Library

Language Package
Typescript Logo TypeScript aws-cdk-lib/aws-bedrockagentcore

Amazon 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

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
runtime_name 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
agent_runtime_artifact AgentRuntimeArtifact Yes The artifact configuration for the agent runtime containing the container configuration with ECR URI
execution_role iam.IRole No The IAM role that provides permissions for the agent runtime. If not provided, a role will be created automatically
network_configuration NetworkConfiguration No Network configuration for the agent runtime. Defaults to RuntimeNetworkConfiguration.usingPublicNetwork()
description string No Optional description for the agent runtime
protocol_configuration ProtocolType No Protocol configuration for the agent runtime. Defaults to ProtocolType.HTTP
authorizer_configuration RuntimeAuthorizerConfiguration No Authorizer configuration for the agent runtime. Use RuntimeAuthorizerConfiguration static methods to create configurations for IAM, Cognito, JWT, or OAuth authentication
environment_variables { [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
lifecycle_configuration 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
request_header_configuration 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
endpoint_name 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
agent_runtime_id string Yes The Agent Runtime ID for this endpoint
agent_runtime_version 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.

repository = AWSCDK::ECR::Repository.new(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 = AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

# Create runtime using the built image
runtime = AWSCDK::BedrockAgentCore::Runtime.new(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.

agent_runtime_artifact = AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_asset(path.join(__dirname, "path to agent dockerfile directory"))

runtime = AWSCDK::BedrockAgentCore::Runtime.new(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.

# S3 bucket containing the agent core
code_bucket = AWSCDK::S3::Bucket.new(self, "AgentCode", {
    bucket_name: "my-code-bucket",
    removal_policy: AWSCDK::RemovalPolicy::DESTROY,
})

# the bucket above needs to contain the agent code

agent_runtime_artifact = AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_s3({
    bucket_name: code_bucket.bucket_name,
    object_key: "deployment_package.zip",
}, AWSCDK::BedrockAgentCore::AgentCoreRuntime.PYTHON_3_12, ["opentelemetry-instrument", "main.py"])

runtime_instance = AWSCDK::BedrockAgentCore::Runtime.new(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:

agent_runtime_artifact = AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_code_asset({
    path: path.join(__dirname, "path/to/agent/code"),
    runtime: AWSCDK::BedrockAgentCore::AgentCoreRuntime.PYTHON_3_12,
    entrypoint: ["opentelemetry-instrument", "main.py"],
})

runtime_instance = AWSCDK::BedrockAgentCore::Runtime.new(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.

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

runtime = AWSCDK::BedrockAgentCore::Runtime.new(self, "MyAgentRuntime", {
    runtime_name: "myAgent",
    agent_runtime_artifact: agent_runtime_artifact,
})

You can also use CloudFormation parameters or references:

# Using a CloudFormation parameter
image_uri_param = AWSCDK::CfnParameter.new(self, "ImageUri", {
    type: "String",
    description: "Container image URI for the agent runtime",
})

agent_runtime_artifact = AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_image_uri(image_uri_param.value_as_string)

runtime = AWSCDK::BedrockAgentCore::Runtime.new(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:

# Note: This example uses aws-cdk-lib/aws-bedrock for foundation model references
runtime = nil # AWSCDK::BedrockAgentCore::Runtime


# Define the Bedrock Foundation Model
model = AWSCDK::Bedrock::FoundationModel.from_foundation_model_id(self, "Model", AWSCDK::Bedrock::FoundationModelIdentifier.ANTHROPIC_CLAUDE_3_7_SONNET_20250219_V1_0)

# Grant the runtime permissions to invoke the model
runtime.role.add_to_principal_policy(AWSCDK::IAM::PolicyStatement.new({
    actions: ["bedrock:InvokeModel"],
    resources: [model.model_arn],
}))

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.

repository = AWSCDK::ECR::Repository.new(self, "TestRepository", {
    repository_name: "test-agent-runtime",
})

runtime = AWSCDK::BedrockAgentCore::Runtime.new(self, "MyAgentRuntime", {
    runtime_name: "myAgent",
    agent_runtime_artifact: AWSCDK::BedrockAgentCore::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.

repository = AWSCDK::ECR::Repository.new(self, "TestRepository", {
    repository_name: "test-agent-runtime",
})

runtime = AWSCDK::BedrockAgentCore::Runtime.new(self, "MyAgentRuntime", {
    runtime_name: "myAgent",
    agent_runtime_artifact: AWSCDK::BedrockAgentCore::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:

repository = AWSCDK::ECR::Repository.new(self, "TestRepository", {
    repository_name: "test-agent-runtime",
})

agent_runtime_artifact_new = AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_ecr_repository(repository, "v2.0.0")

runtime = AWSCDK::BedrockAgentCore::Runtime.new(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.

repository = AWSCDK::ECR::Repository.new(self, "TestRepository", {
    repository_name: "test-agent-runtime",
})

agent_runtime_artifact_new = AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_ecr_repository(repository, "v2.0.0")

runtime = AWSCDK::BedrockAgentCore::Runtime.new(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.

repository = AWSCDK::ECR::Repository.new(self, "TestRepository", {
    repository_name: "test-agent-runtime",
})

agent_runtime_artifact_new = AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_ecr_repository(repository, "v2.0.0")

runtime = AWSCDK::BedrockAgentCore::Runtime.new(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

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

# Create a standalone endpoint
endpoint = AWSCDK::BedrockAgentCore::RuntimeEndpoint.new(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:

user_pool = nil # AWSCDK::Cognito::UserPool
user_pool_client = nil # AWSCDK::Cognito::UserPoolClient
another_user_pool_client = nil # AWSCDK::Cognito::UserPoolClient


repository = AWSCDK::ECR::Repository.new(self, "TestRepository", {
    repository_name: "test-agent-runtime",
})
agent_runtime_artifact = AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

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

runtime = AWSCDK::BedrockAgentCore::Runtime.new(self, "MyAgentRuntime", {
    runtime_name: "myAgent",
    agent_runtime_artifact: agent_runtime_artifact,
    authorizer_configuration: AWSCDK::BedrockAgentCore::RuntimeAuthorizerConfiguration.using_cognito(user_pool, [user_pool_client, another_user_pool_client], ["audience1"], ["read", "write"], custom_claims),
})

You can configure:

JWT Authentication

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

repository = AWSCDK::ECR::Repository.new(self, "TestRepository", {
    repository_name: "test-agent-runtime",
})
agent_runtime_artifact = AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

runtime = AWSCDK::BedrockAgentCore::Runtime.new(self, "MyAgentRuntime", {
    runtime_name: "myAgent",
    agent_runtime_artifact: agent_runtime_artifact,
    authorizer_configuration: AWSCDK::BedrockAgentCore::RuntimeAuthorizerConfiguration.using_jwt("https://example.com/.well-known/openid-configuration", ["client1", "client2"], ["audience1"], ["read", "write"]),
})

You can configure:

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:

repository = AWSCDK::ECR::Repository.new(self, "TestRepository", {
    repository_name: "test-agent-runtime",
})
agent_runtime_artifact = AWSCDK::BedrockAgentCore::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 = AWSCDK::BedrockAgentCore::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 = AWSCDK::BedrockAgentCore::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 = AWSCDK::BedrockAgentCore::RuntimeCustomClaim.with_string_array_value("permissions", ["read", "write"], AWSCDK::BedrockAgentCore::CustomClaimOperator::CONTAINS_ANY)

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

Custom Claim Rules:

Example Use Cases:

OAuth Authentication

To configure OAuth 2.0 authentication:

repository = AWSCDK::ECR::Repository.new(self, "TestRepository", {
    repository_name: "test-agent-runtime",
})
agent_runtime_artifact = AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

runtime = AWSCDK::BedrockAgentCore::Runtime.new(self, "MyAgentRuntime", {
    runtime_name: "myAgent",
    agent_runtime_artifact: agent_runtime_artifact,
    authorizer_configuration: AWSCDK::BedrockAgentCore::RuntimeAuthorizerConfiguration.using_o_auth("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:

repository = AWSCDK::ECR::Repository.new(self, "TestRepository", {
    repository_name: "test-agent-runtime",
})
agent_runtime_artifact = AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

# Explicitly using public network (this is the default)
runtime = AWSCDK::BedrockAgentCore::Runtime.new(self, "MyAgentRuntime", {
    runtime_name: "myAgent",
    agent_runtime_artifact: agent_runtime_artifact,
    network_configuration: AWSCDK::BedrockAgentCore::RuntimeNetworkConfiguration.using_public_network,
})

VPC Network Mode

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

repository = AWSCDK::ECR::Repository.new(self, "TestRepository", {
    repository_name: "test-agent-runtime",
})
agent_runtime_artifact = AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

# Create or use an existing VPC
vpc = AWSCDK::EC2::VPC.new(self, "MyVpc", {
    max_azs: 2,
})

# Configure runtime with VPC
runtime = AWSCDK::BedrockAgentCore::Runtime.new(self, "MyAgentRuntime", {
    runtime_name: "myAgent",
    agent_runtime_artifact: agent_runtime_artifact,
    network_configuration: AWSCDK::BedrockAgentCore::RuntimeNetworkConfiguration.using_vpc(self, {
        vpc: vpc,
        vpc_subnets: {subnet_type: AWSCDK::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:

vpc = AWSCDK::EC2::VPC.new(self, "MyVpc", {
    max_azs: 2,
})

repository = AWSCDK::ECR::Repository.new(self, "TestRepository", {
    repository_name: "test-agent-runtime",
})
agent_runtime_artifact = AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

# Create runtime with VPC configuration
runtime = AWSCDK::BedrockAgentCore::Runtime.new(self, "MyAgentRuntime", {
    runtime_name: "myAgent",
    agent_runtime_artifact: agent_runtime_artifact,
    network_configuration: AWSCDK::BedrockAgentCore::RuntimeNetworkConfiguration.using_vpc(self, {
        vpc: vpc,
        vpc_subnets: {subnet_type: AWSCDK::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 = AWSCDK::EC2::SecurityGroup.new(self, "WebServerSG", {vpc: vpc})
runtime.connections.allow_from(web_server_security_group, AWSCDK::EC2::Port.tcp(443), "Allow HTTPS from web servers")

# Allow outbound connections to a database
database_security_group = AWSCDK::EC2::SecurityGroup.new(self, "DatabaseSG", {vpc: vpc})
runtime.connections.allow_to(database_security_group, AWSCDK::EC2::Port.tcp(5432), "Allow PostgreSQL connection")

# Allow outbound HTTPS to anywhere (for external API calls)
runtime.connections.allow_to_any_ipv4(AWSCDK::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.

repository = AWSCDK::ECR::Repository.new(self, "TestRepository", {
    repository_name: "test-agent-runtime",
})
agent_runtime_artifact = AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

# Create a runtime
runtime = AWSCDK::BedrockAgentCore::Runtime.new(self, "MyRuntime", {
    runtime_name: "my_runtime",
    agent_runtime_artifact: agent_runtime_artifact,
})

# Create a Lambda function that needs to invoke the runtime
invoker_function = AWSCDK::Lambda::Function.new(self, "InvokerFunction", {
    runtime: AWSCDK::Lambda::Runtime.PYTHON_3_12,
    handler: "index.handler",
    code: AWSCDK::Lambda::Code.from_inline(<<-'HERE'

    import boto3
    def handler(event, context):
        client = boto3.client('bedrock-agentcore')
        # Invoke the runtime...

    HERE),
})

# 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(AWSCDK::IAM::PolicyStatement.new({
    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:

For additional information, please refer to the documentation.

repository = AWSCDK::ECR::Repository.new(self, "TestRepository", {
    repository_name: "test-agent-runtime",
})

agent_runtime_artifact = AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

AWSCDK::BedrockAgentCore::Runtime.new(self, "test-runtime", {
    runtime_name: "test_runtime",
    agent_runtime_artifact: agent_runtime_artifact,
    lifecycle_configuration: {
        idle_runtime_session_timeout: AWSCDK::Duration.minutes(10),
        max_lifetime: AWSCDK::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.

repository = AWSCDK::ECR::Repository.new(self, "TestRepository", {
    repository_name: "test-agent-runtime",
})

agent_runtime_artifact = AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

AWSCDK::BedrockAgentCore::Runtime.new(self, "test-runtime", {
    runtime_name: "test_runtime",
    agent_runtime_artifact: agent_runtime_artifact,
    request_header_configuration: {
        allowlisted_headers: ["X-Amzn-Bedrock-AgentCore-Runtime-Custom-H1"],
    },
})

Observability configuration

The Runtime construct supports observability features including X-Ray tracing and logging to CloudWatch Logs, S3, or Kinesis Data Firehose. This allows you to monitor and debug your agent runtime invocations.

You can configure:

For additional information, please refer to the Set up logging and tracing for AgentCore.

repository = AWSCDK::ECR::Repository.new(self, "TestRepository", {
    repository_name: "test-agent-runtime",
})

agent_runtime_artifact = AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")

# Create logging destinations
log_group = AWSCDK::Logs::LogGroup.new(self, "RuntimeLogGroup")
log_bucket = AWSCDK::S3::Bucket.new(self, "RuntimeLogBucket")
firehose_stream = AWSCDK::KinesisFirehose::DeliveryStream.new(self, "RuntimeLogStream", {
    destination: AWSCDK::KinesisFirehose::S3Bucket.new(log_bucket),
})

AWSCDK::BedrockAgentCore::Runtime.new(self, "test-runtime", {
    runtime_name: "test_runtime",
    agent_runtime_artifact: agent_runtime_artifact,
    tracing_enabled: true,
    logging_configs: [
        {
            log_type: AWSCDK::BedrockAgentCore::LogType.APPLICATION_LOGS,
            destination: AWSCDK::BedrockAgentCore::LoggingDestination.cloud_watch_logs(log_group),
        },
        {
            log_type: AWSCDK::BedrockAgentCore::LogType.APPLICATION_LOGS,
            destination: AWSCDK::BedrockAgentCore::LoggingDestination.s3(log_bucket),
        },
        {
            log_type: AWSCDK::BedrockAgentCore::LogType.APPLICATION_LOGS,
            destination: AWSCDK::BedrockAgentCore::LoggingDestination.firehose(firehose_stream),
        },
    ],
})

Application log group

Every Runtime has a default endpoint whose stdout is written to the AgentCore-managed log group at /aws/bedrock-agentcore/runtimes/{agentRuntimeId}-DEFAULT. The Runtime construct exposes this log group as application_log_group so you can attach metric filters, subscription filters, or alarms without hardcoding the path:

repository = AWSCDK::ECR::Repository.new(self, "TestRepository")

runtime = AWSCDK::BedrockAgentCore::Runtime.new(self, "Runtime", {
    agent_runtime_artifact: AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0"),
})

AWSCDK::Logs::MetricFilter.new(self, "ToolErrors", {
    log_group: runtime.application_log_group,
    filter_pattern: AWSCDK::Logs::FilterPattern.string_value("$.tool_status", "=", "error"),
    metric_namespace: "MyApp",
    metric_name: "ToolExecutionErrors",
})

The log group itself is created by the AgentCore service on the runtime's first invocation, not by CDK. Constructs that require the log group to exist at deploy time may race the first invocation; if that is a concern, pre-create the log group with a LogRetention resource using the same name.

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

Browser Network modes

The Browser construct supports the following network modes:

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

While the VPC itself is mandatory, these are optional:

For more information on VPC connectivity for Amazon Bedrock AgentCore Browser, please refer to the official documentation.

Browser Properties

Name Type Required Description
browser_custom_name 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
network_configuration BrowserNetworkConfiguration No Network configuration for browser. Defaults to PUBLIC network mode
recording_config RecordingConfig No Recording configuration for browser. Defaults to no recording
execution_role iam.IRole No The IAM role that provides permissions for the browser to access AWS services. A new role will be created if not provided
tags { [key: string]: string } No Tags to apply to the browser resource
browser_signing BrowserSigning No Browser signing configuration. Defaults to DISABLED

Basic Browser Creation

# Create a basic browser with public network access
browser = AWSCDK::BedrockAgentCore::BrowserCustom.new(self, "MyBrowser", {
    browser_custom_name: "my_browser",
    description: "A browser for web automation",
})

Browser with Tags

# Create a browser with custom tags
browser = AWSCDK::BedrockAgentCore::BrowserCustom.new(self, "MyBrowser", {
    browser_custom_name: "my_browser",
    description: "A browser for web automation with tags",
    network_configuration: AWSCDK::BedrockAgentCore::BrowserNetworkConfiguration.using_public_network,
    tags: {
        Environment: "Production",
        Team: "AI/ML",
        Project: "AgentCore",
    },
})

Browser with VPC

browser = AWSCDK::BedrockAgentCore::BrowserCustom.new(self, "BrowserVpcWithRecording", {
    browser_custom_name: "browser_recording",
    network_configuration: AWSCDK::BedrockAgentCore::BrowserNetworkConfiguration.using_vpc(self, {
        vpc: AWSCDK::EC2::VPC.new(self, "VPC", {restrict_default_security_group: false}),
    }),
})

Browser exposes a connections property. This property returns a connections object, which simplifies the process of defining and managing ingress and egress rules for security groups in your AWS CDK applications. Instead of directly manipulating security group rules, you interact with the Connections object of a construct, which then translates your connectivity requirements into the appropriate security group rules. For instance:

vpc = AWSCDK::EC2::VPC.new(self, "testVPC")

browser = AWSCDK::BedrockAgentCore::BrowserCustom.new(self, "test-browser", {
    browser_custom_name: "test_browser",
    network_configuration: AWSCDK::BedrockAgentCore::BrowserNetworkConfiguration.using_vpc(self, {
        vpc: vpc,
    }),
})

browser.connections.add_security_group(AWSCDK::EC2::SecurityGroup.new(self, "AdditionalGroup", {vpc: vpc}))

So security groups can be added after the browser construct creation. You can use methods like allowFrom() and allowTo() to grant ingress access to/egress access from a specified peer over a given portRange. The Connections object automatically adds the necessary ingress or egress rules to the security group(s) associated with the calling construct.

Browser with Recording Configuration

# Create an S3 bucket for recordings
recording_bucket = AWSCDK::S3::Bucket.new(self, "RecordingBucket", {
    bucket_name: "my-browser-recordings",
    removal_policy: AWSCDK::RemovalPolicy::DESTROY,
})

# Create browser with recording enabled
browser = AWSCDK::BedrockAgentCore::BrowserCustom.new(self, "MyBrowser", {
    browser_custom_name: "my_browser",
    description: "Browser with recording enabled",
    network_configuration: AWSCDK::BedrockAgentCore::BrowserNetworkConfiguration.using_public_network,
    recording_config: {
        enabled: true,
        s3_location: {
            bucket_name: recording_bucket.bucket_name,
            object_key: "browser-recordings/",
        },
    },
})

Browser with Custom Execution Role

# Create a custom execution role
execution_role = AWSCDK::IAM::Role.new(self, "BrowserExecutionRole", {
    assumed_by: AWSCDK::IAM::ServicePrincipal.new("bedrock-agentcore.amazonaws.com"),
    managed_policies: [
        AWSCDK::IAM::ManagedPolicy.from_aws_managed_policy_name("AmazonBedrockAgentCoreBrowserExecutionRolePolicy"),
    ],
})

# Create browser with custom execution role
browser = AWSCDK::BedrockAgentCore::BrowserCustom.new(self, "MyBrowser", {
    browser_custom_name: "my_browser",
    description: "Browser with custom execution role",
    network_configuration: AWSCDK::BedrockAgentCore::BrowserNetworkConfiguration.using_public_network,
    execution_role: execution_role,
})

Browser with S3 Recording and Permissions

# Create an S3 bucket for recordings
recording_bucket = AWSCDK::S3::Bucket.new(self, "RecordingBucket", {
    bucket_name: "my-browser-recordings",
    removal_policy: AWSCDK::RemovalPolicy::DESTROY,
})

# Create browser with recording enabled
browser = AWSCDK::BedrockAgentCore::BrowserCustom.new(self, "MyBrowser", {
    browser_custom_name: "my_browser",
    description: "Browser with recording enabled",
    network_configuration: AWSCDK::BedrockAgentCore::BrowserNetworkConfiguration.using_public_network,
    recording_config: {
        enabled: true,
        s3_location: {
            bucket_name: recording_bucket.bucket_name,
            object_key: "browser-recordings/",
        },
    },
})

Browser with Browser signing

AI agents need to browse the web on your behalf. When your agent visits a website to gather information, complete a form, or verify data, it encounters the same defenses designed to stop unwanted bots: CAPTCHAs, rate limits, and outright blocks.

Amazon Bedrock AgentCore Browser supports Web Bot Auth. Web Bot Auth is a draft IETF protocol that gives agents verifiable cryptographic identities. When you enable Web Bot Auth in AgentCore Browser, the service issues cryptographic credentials that websites can verify. The agent presents these credentials with every request. The WAF may now additionally check the signature, confirm it matches a trusted directory, and allow the request through if verified bots are allowed by the domain owner and other WAF checks are clear.

To enable the browser to sign requests using the Web Bot Auth protocol, create a browser tool with the browserSigning configuration:

browser = AWSCDK::BedrockAgentCore::BrowserCustom.new(self, "test-browser", {
    browser_custom_name: "test_browser",
    browser_signing: AWSCDK::BedrockAgentCore::BrowserSigning::ENABLED,
})

Browser IAM Permissions

The Browser construct provides convenient methods for granting IAM permissions:

# Create a browser
browser = AWSCDK::BedrockAgentCore::BrowserCustom.new(self, "MyBrowser", {
    browser_custom_name: "my_browser",
    description: "Browser for web automation",
    network_configuration: AWSCDK::BedrockAgentCore::BrowserNetworkConfiguration.using_public_network,
})

# Create a role that needs access to the browser
user_role = AWSCDK::IAM::Role.new(self, "UserRole", {
    assumed_by: AWSCDK::IAM::ServicePrincipal.new("lambda.amazonaws.com"),
})

# Grant read permissions (Get and List actions)
browser.grant_read(user_role)

# Grant use permissions (Start, Update, Stop actions)
browser.grant_use(user_role)

# Grant specific custom permissions
browser.grant(user_role, "bedrock-agentcore:GetBrowserSession")

Code Interpreter

The Amazon Bedrock AgentCore Code Interpreter enables AI agents to write and execute code securely in sandbox environments, enhancing their accuracy and expanding their ability to solve complex end-to-end tasks. This is critical in Agentic AI applications where the agents may execute arbitrary code that can lead to data compromise or security risks. The AgentCore Code Interpreter tool provides secure code execution, which helps you avoid running into these issues.

For more information about code interpreter, please refer to the official documentation

Code Interpreter Network Modes

The Code Interpreter construct supports the following network modes:

  1. Public Network Mode (CodeInterpreterNetworkMode.usingPublicNetwork()) - Default

While the VPC itself is mandatory, these are optional:

For more information on VPC connectivity for Amazon Bedrock AgentCore Browser, please refer to the official documentation.

Code Interpreter Properties

Name Type Required Description
code_interpreter_custom_name string No The name of the code interpreter. 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 code interpreter. Can have up to 200 characters
execution_role iam.IRole No The IAM role that provides permissions for the code interpreter to access AWS services. A new role will be created if not provided
network_configuration CodeInterpreterNetworkConfiguration No Network configuration for code interpreter. Defaults to PUBLIC network mode
tags { [key: string]: string } No Tags to apply to the code interpreter resource

Basic Code Interpreter Creation

# Create a basic code interpreter with public network access
code_interpreter = AWSCDK::BedrockAgentCore::CodeInterpreterCustom.new(self, "MyCodeInterpreter", {
    code_interpreter_custom_name: "my_code_interpreter",
    description: "A code interpreter for Python execution",
})

Code Interpreter with VPC

code_interpreter = AWSCDK::BedrockAgentCore::CodeInterpreterCustom.new(self, "MyCodeInterpreter", {
    code_interpreter_custom_name: "my_sandbox_interpreter",
    description: "Code interpreter with isolated network access",
    network_configuration: AWSCDK::BedrockAgentCore::BrowserNetworkConfiguration.using_vpc(self, {
        vpc: AWSCDK::EC2::VPC.new(self, "VPC", {restrict_default_security_group: false}),
    }),
})

Code Interpreter exposes a connections property. This property returns a connections object, which simplifies the process of defining and managing ingress and egress rules for security groups in your AWS CDK applications. Instead of directly manipulating security group rules, you interact with the Connections object of a construct, which then translates your connectivity requirements into the appropriate security group rules. For instance:

vpc = AWSCDK::EC2::VPC.new(self, "testVPC")

code_interpreter = AWSCDK::BedrockAgentCore::CodeInterpreterCustom.new(self, "MyCodeInterpreter", {
    code_interpreter_custom_name: "my_sandbox_interpreter",
    description: "Code interpreter with isolated network access",
    network_configuration: AWSCDK::BedrockAgentCore::BrowserNetworkConfiguration.using_vpc(self, {
        vpc: vpc,
    }),
})

code_interpreter.connections.add_security_group(AWSCDK::EC2::SecurityGroup.new(self, "AdditionalGroup", {vpc: vpc}))

So security groups can be added after the browser construct creation. You can use methods like allowFrom() and allowTo() to grant ingress access to/egress access from a specified peer over a given portRange. The Connections object automatically adds the necessary ingress or egress rules to the security group(s) associated with the calling construct.

Code Interpreter with Sandbox Network Mode

# Create code interpreter with sandbox network mode (isolated)
code_interpreter = AWSCDK::BedrockAgentCore::CodeInterpreterCustom.new(self, "MyCodeInterpreter", {
    code_interpreter_custom_name: "my_sandbox_interpreter",
    description: "Code interpreter with isolated network access",
    network_configuration: AWSCDK::BedrockAgentCore::CodeInterpreterNetworkConfiguration.using_sandbox_network,
})

Code Interpreter with Custom Execution Role

# Create a custom execution role
execution_role = AWSCDK::IAM::Role.new(self, "CodeInterpreterExecutionRole", {
    assumed_by: AWSCDK::IAM::ServicePrincipal.new("bedrock-agentcore.amazonaws.com"),
})

# Create code interpreter with custom execution role
code_interpreter = AWSCDK::BedrockAgentCore::CodeInterpreterCustom.new(self, "MyCodeInterpreter", {
    code_interpreter_custom_name: "my_code_interpreter",
    description: "Code interpreter with custom execution role",
    network_configuration: AWSCDK::BedrockAgentCore::CodeInterpreterNetworkConfiguration.using_public_network,
    execution_role: execution_role,
})

Code Interpreter IAM Permissions

The Code Interpreter construct provides convenient methods for granting IAM permissions:

# Create a code interpreter
code_interpreter = AWSCDK::BedrockAgentCore::CodeInterpreterCustom.new(self, "MyCodeInterpreter", {
    code_interpreter_custom_name: "my_code_interpreter",
    description: "Code interpreter for Python execution",
    network_configuration: AWSCDK::BedrockAgentCore::CodeInterpreterNetworkConfiguration.using_public_network,
})

# Create a role that needs access to the code interpreter
user_role = AWSCDK::IAM::Role.new(self, "UserRole", {
    assumed_by: AWSCDK::IAM::ServicePrincipal.new("lambda.amazonaws.com"),
})

# Grant read permissions (Get and List actions)
code_interpreter.grant_read(user_role)

# Grant use permissions (Start, Invoke, Stop actions)
code_interpreter.grant_use(user_role)

# Grant specific custom permissions
code_interpreter.grant(user_role, "bedrock-agentcore:GetCodeInterpreterSession")

Code interpreter with tags

# Create code interpreter with sandbox network mode (isolated)
code_interpreter = AWSCDK::BedrockAgentCore::CodeInterpreterCustom.new(self, "MyCodeInterpreter", {
    code_interpreter_custom_name: "my_sandbox_interpreter",
    description: "Code interpreter with isolated network access",
    network_configuration: AWSCDK::BedrockAgentCore::CodeInterpreterNetworkConfiguration.using_public_network,
    tags: {
        Environment: "Production",
        Team: "AI/ML",
        Project: "AgentCore",
    },
})

Gateway

The Gateway construct provides a way to create Amazon Bedrock Agent Core Gateways, which serve as integration points between agents and external services.

Gateway Properties

Name Type Required Description
gateway_name string No The name of the gateway. Valid characters are a-z, A-Z, 0-9, _ (underscore) and - (hyphen). Maximum 100 characters. If not provided, a unique name will be auto-generated
description string No Optional description for the gateway. Maximum 200 characters
protocol_configuration IGatewayProtocolConfig No The protocol configuration for the gateway. Defaults to MCP protocol
authorizer_configuration IGatewayAuthorizerConfig No The authorizer configuration for the gateway. Defaults to Cognito
exception_level GatewayExceptionLevel No The verbosity of exception messages. Use DEBUG mode to see granular exception messages
kms_key kms.IKey No The AWS KMS key used to encrypt data associated with the gateway
role iam.IRole No The IAM role that provides permissions for the gateway to access AWS services. A new role will be created if not provided
tags { [key: string]: string } No Tags for the gateway. A list of key:value pairs of tags to apply to this Gateway resource

Basic Gateway Creation

The protocol configuration defaults to MCP and the inbound auth configuration uses Cognito (it is automatically created on your behalf).

# Create a basic gateway with default MCP protocol and Cognito authorizer
gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
})

Protocol configuration

Currently MCP is the only protocol available. To configure it, use the protocol property with McpProtocolConfiguration:

gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
    protocol_configuration: AWSCDK::BedrockAgentCore::McpProtocolConfiguration.new({
        instructions: "Use this gateway to connect to external MCP tools",
        search_type: AWSCDK::BedrockAgentCore::McpGatewaySearchType.SEMANTIC,
        supported_versions: [AWSCDK::BedrockAgentCore::MCPProtocolVersion.MCP_2025_03_26],
    }),
})

Inbound authorization

Before you create your gateway, you must set up inbound authorization. Inbound authorization validates users who attempt to access targets through your AgentCore gateway. By default, if not provided, the construct will create and configure Cognito as the default identity provider (inbound Auth setup). AgentCore supports the following types of inbound authorization:

JSON Web Token (JWT) – A secure and compact token used for authorization. After creating the JWT, you specify it as the authorization configuration when you create the gateway. You can create a JWT with any of the identity providers at Provider setup and configuration.

You can configure a custom authorization provider using the authorizer_configuration property with GatewayAuthorizer.usingCustomJwt(). You need to specify an OAuth discovery server and client IDs/audiences when you create the gateway. You can specify the following:

# Optional: Create custom claims (CustomClaimOperator and GatewayCustomClaim from agentcore)
custom_claims = [
    AWSCDK::BedrockAgentCore::GatewayCustomClaim.with_string_value("department", "engineering"),
    AWSCDK::BedrockAgentCore::GatewayCustomClaim.with_string_array_value("roles", ["admin"], AWSCDK::BedrockAgentCore::CustomClaimOperator::CONTAINS),
    AWSCDK::BedrockAgentCore::GatewayCustomClaim.with_string_array_value("permissions", ["read", "write"], AWSCDK::BedrockAgentCore::CustomClaimOperator::CONTAINS_ANY),
]

gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
    authorizer_configuration: AWSCDK::BedrockAgentCore::GatewayAuthorizer.using_custom_jwt({
        discovery_url: "https://auth.example.com/.well-known/openid-configuration",
        allowed_audience: ["my-app"],
        allowed_clients: ["my-client-id"],
        allowed_scopes: ["read", "write"],
        custom_claims: custom_claims,
    }),
})

IAM – Authorizes through the credentials of the AWS IAM identity trying to access the gateway.

gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
    authorizer_configuration: AWSCDK::BedrockAgentCore::GatewayAuthorizer.using_aws_iam,
})

# Grant access to a Lambda function's role
lambda_role = AWSCDK::IAM::Role.new(self, "LambdaRole", {
    assumed_by: AWSCDK::IAM::ServicePrincipal.new("lambda.amazonaws.com"),
})

# The Lambda needs permission to invoke the gateway
gateway.grant_invoke(lambda_role)

No Authorization – Creates a gateway with no inbound authorization. This is useful for building public MCP servers, or when you want to skip gateway-level authentication and enforce tool execution-level authentication using Gateway Interceptors.

gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
    authorizer_configuration: AWSCDK::BedrockAgentCore::GatewayAuthorizer.with_no_auth,
})

⚠️ Important: Do not use No Authorization gateways for production workloads unless you have implemented all the security best practices. No Authorization gateways are most appropriate for testing and development purposes. See Security Best Practices for required compensating controls.

For more information, see No Authorization.

Cognito with M2M (Machine-to-Machine) Authentication (Default) – When no authorizer is specified, the construct automatically creates a Cognito User Pool configured for OAuth 2.0 client credentials flow. This enables machine-to-machine authentication suitable for AI agents and service-to-service communication.

For more information, see Setting up Amazon Cognito for Gateway inbound authorization.

# Create a gateway with default Cognito M2M authorizer
gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
})

# Access the Cognito resources for authentication setup
user_pool = gateway.user_pool
user_pool_client = gateway.user_pool_client

# Get the token endpoint URL and OAuth scopes for client credentials flow
token_endpoint_url = gateway.token_endpoint_url
oauth_scopes = gateway.oauth_scopes

Using Cognito User Pool Explicitly with Custom Claims – You can also use an existing Cognito User Pool with custom claims:

user_pool = nil # AWSCDK::Cognito::UserPool
user_pool_client = nil # AWSCDK::Cognito::UserPoolClient


# Optional: Create custom claims (CustomClaimOperator and GatewayCustomClaim from agentcore)
custom_claims = [
    AWSCDK::BedrockAgentCore::GatewayCustomClaim.with_string_value("department", "engineering"),
    AWSCDK::BedrockAgentCore::GatewayCustomClaim.with_string_array_value("roles", ["admin"], AWSCDK::BedrockAgentCore::CustomClaimOperator::CONTAINS),
    AWSCDK::BedrockAgentCore::GatewayCustomClaim.with_string_array_value("permissions", ["read", "write"], AWSCDK::BedrockAgentCore::CustomClaimOperator::CONTAINS_ANY),
]

gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
    authorizer_configuration: AWSCDK::BedrockAgentCore::GatewayAuthorizer.using_cognito({
        user_pool: user_pool,
        allowed_clients: [user_pool_client],
        allowed_audiences: ["audience1"],
        allowed_scopes: ["read", "write"],
        custom_claims: custom_claims,
    }),
})

To authenticate with the gateway, request an access token using the client credentials flow and use it to call Gateway endpoints. For more information about the token endpoint, see The token issuer endpoint.

The following is an example of a token request using curl:

curl -X POST "${TOKEN_ENDPOINT_URL}" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials" \
  -d "client_id=${USER_POOL_CLIENT_ID}" \
  -d "client_secret=${CLIENT_SECRET}" \
  -d "scope=${OAUTH_SCOPES}"

Gateway with KMS Encryption

You can provide a KMS key, and configure the authorizer as well as the protocol configuration.

# Create a KMS key for encryption
encryption_key = AWSCDK::KMS::Key.new(self, "GatewayEncryptionKey", {
    enable_key_rotation: true,
    description: "KMS key for gateway encryption",
})

# Create gateway with KMS encryption
gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-encrypted-gateway",
    description: "Gateway with KMS encryption",
    protocol_configuration: AWSCDK::BedrockAgentCore::McpProtocolConfiguration.new({
        instructions: "Use this gateway to connect to external MCP tools",
        search_type: AWSCDK::BedrockAgentCore::McpGatewaySearchType.SEMANTIC,
        supported_versions: [AWSCDK::BedrockAgentCore::MCPProtocolVersion.MCP_2025_03_26],
    }),
    authorizer_configuration: AWSCDK::BedrockAgentCore::GatewayAuthorizer.using_custom_jwt({
        discovery_url: "https://auth.example.com/.well-known/openid-configuration",
        allowed_audience: ["my-app"],
        allowed_clients: ["my-client-id"],
        allowed_scopes: ["read", "write"],
    }),
    kms_key: encryption_key,
    exception_level: AWSCDK::BedrockAgentCore::GatewayExceptionLevel.DEBUG,
})

Gateway with Custom Execution Role

# Create a custom execution role
execution_role = AWSCDK::IAM::Role.new(self, "GatewayExecutionRole", {
    assumed_by: AWSCDK::IAM::ServicePrincipal.new("bedrock-agentcore.amazonaws.com"),
    managed_policies: [
        AWSCDK::IAM::ManagedPolicy.from_aws_managed_policy_name("AmazonBedrockAgentCoreGatewayExecutionRolePolicy"),
    ],
})

# Create gateway with custom execution role
gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
    description: "Gateway with custom execution role",
    protocol_configuration: AWSCDK::BedrockAgentCore::McpProtocolConfiguration.new({
        instructions: "Use this gateway to connect to external MCP tools",
        search_type: AWSCDK::BedrockAgentCore::McpGatewaySearchType.SEMANTIC,
        supported_versions: [AWSCDK::BedrockAgentCore::MCPProtocolVersion.MCP_2025_03_26],
    }),
    authorizer_configuration: AWSCDK::BedrockAgentCore::GatewayAuthorizer.using_custom_jwt({
        discovery_url: "https://auth.example.com/.well-known/openid-configuration",
        allowed_audience: ["my-app"],
        allowed_clients: ["my-client-id"],
        allowed_scopes: ["read", "write"],
    }),
    role: execution_role,
})

Gateway IAM Permissions

The Gateway construct provides convenient methods for granting IAM permissions:

# Create a gateway
gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
    description: "Gateway for external service integration",
    protocol_configuration: AWSCDK::BedrockAgentCore::McpProtocolConfiguration.new({
        instructions: "Use this gateway to connect to external MCP tools",
        search_type: AWSCDK::BedrockAgentCore::McpGatewaySearchType.SEMANTIC,
        supported_versions: [AWSCDK::BedrockAgentCore::MCPProtocolVersion.MCP_2025_03_26],
    }),
    authorizer_configuration: AWSCDK::BedrockAgentCore::GatewayAuthorizer.using_custom_jwt({
        discovery_url: "https://auth.example.com/.well-known/openid-configuration",
        allowed_audience: ["my-app"],
        allowed_clients: ["my-client-id"],
        allowed_scopes: ["read", "write"],
    }),
})

# Create a role that needs access to the gateway
user_role = AWSCDK::IAM::Role.new(self, "UserRole", {
    assumed_by: AWSCDK::IAM::ServicePrincipal.new("lambda.amazonaws.com"),
})

# Grant read permissions (Get and List actions)
gateway.grant_read(user_role)

# Grant manage permissions (Create, Update, Delete actions)
gateway.grant_manage(user_role)

# Grant specific custom permissions
gateway.grant(user_role, "bedrock-agentcore:GetGateway")

Gateway Target

After Creating gateways, you can add targets which define the tools that your gateway will host. Gateway supports multiple target types including Lambda functions and API specifications (either OpenAPI schemas or Smithy models). Gateway allows you to attach multiple targets to a Gateway and you can change the targets / tools attached to a gateway at any point. Each target can have its own credential provider attached enabling you to securely access targets whether they need IAM, API Key, or OAuth credentials.

Gateway Target Properties

Name Type Required Description
gateway_target_name string No The name of the gateway target. Valid characters are a-z, A-Z, 0-9, _ (underscore) and - (hyphen). If not provided, a unique name will be auto-generated
description string No Optional description for the gateway target. Maximum 200 characters
gateway IGateway Yes The gateway this target belongs to
target_configuration ITargetConfiguration Yes The target configuration (Lambda, OpenAPI, Smithy, or API Gateway). Note: Users typically don't create this directly. When using convenience methods like GatewayTarget.forLambda(), GatewayTarget.forOpenApi(), GatewayTarget.forSmithy(), GatewayTarget.forApiGateway(), GatewayTarget.forMcpServer() or the gateway's add_lambda_target(), add_open_api_target(), add_smithy_target(), add_api_gateway_target(), add_mcp_server_target() methods, this configuration is created internally for you. Only needed when using the GatewayTarget constructor directly for advanced scenarios.
credential_provider_configurations IGatewayCredentialProvider[] No Credential providers for authentication. Defaults to [GatewayCredentialProvider.fromIamRole()]. With Token Vault L2 constructs, prefer GatewayCredentialProvider.fromApiKeyIdentity() / from_oauth_identity(); otherwise use from_api_key_identity_arn() / from_oauth_identity_arn(), or from_iam_role()
validate_open_api_schema boolean No (OpenAPI targets only) Whether to validate the OpenAPI schema at synthesis time. Defaults to true. Only applies to inline and local asset schemas. For more information refer here https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-schema-openapi.html

This approach gives you full control over the configuration but is typically not necessary for most use cases.

Targets types

You can create the following targets types:

Lambda Target: Lambda targets allow you to connect your gateway to AWS Lambda functions that implement your tools. This is useful when you want to execute custom code in response to tool invocations.

OpenAPI Schema Target : OpenAPI widely used standard for describing RESTful APIs. Gateway supports OpenAPI 3.0 specifications for defining API targets. It connects to REST APIs using OpenAPI specifications

Smithy Model Target : Smithy is a language for defining services and software development kits (SDKs). Smithy models provide a more structured approach to defining APIs compared to OpenAPI, and are particularly useful for connecting to AWS services. AgentCore Gateway supports built-in AWS service models only. It connects to services using Smithy model definitions

Note: For Smithy model targets that access AWS services, your Gateway's execution role needs permissions to access those services. For example, for a DynamoDB target, your execution role needs permissions to perform DynamoDB operations. This is not managed by the construct due to the large number of options. Please refer to Smithy Model Permission for example.

MCP Server Target: Model Context Protocol (MCP) servers provide external tools, data access, and custom functions for AI agents. MCP servers enable agents to interact with external systems and services through a standardized protocol. Gateway automatically discovers and indexes available tools from MCP servers through synchronization.

Key Features:

Synchronization Behavior:

MCP Server targets require synchronization to discover and index available tools:

Authentication & Permissions:

When using OAuth2, the Gateway service role automatically receives:

For explicit synchronization, use grant_sync() to grant bedrock-agentcore:SynchronizeGatewayTargets permission to your operator roles.

For more information, refer to the MCP Server Target documentation.

Understanding Tool Naming

When tools are exposed through gateway targets, AgentCore Gateway prefixes each tool name with the target name to ensure uniqueness across multiple targets. This is important to understand when building your application logic.

Naming Pattern:

Example:

If your target is named my-lambda-target and provides a tool called calculate_price, agents will discover and invoke it as my-lambda-target__calculate_price.

Important Considerations:

This naming convention ensures that:

For more details, see the Gateway Tool Naming Documentation.

Tools schema For Lambda target

The lambda target need tools schema to understand the fuunction lambda provides. You can upload the tool schema by following 3 ways:

tool_schema = AWSCDK::BedrockAgentCore::ToolSchema.from_local_asset(path.join(__dirname, "schemas", "my-tool-schema.json"))
tool_schema = AWSCDK::BedrockAgentCore::ToolSchema.from_s3_file(AWSCDK::S3::Bucket.from_bucket_name(self, "SchemasBucket", "my-schemas-bucket"), "tools/complex-tool-schema.json", "123456789012")
tool_schema = AWSCDK::BedrockAgentCore::ToolSchema.from_inline([
    {
        name: "hello_world",
        description: "A simple hello world tool",
        input_schema: {
            type: AWSCDK::BedrockAgentCore::SchemaDefinitionType.OBJECT,
            properties: {
                name: {
                    type: AWSCDK::BedrockAgentCore::SchemaDefinitionType.STRING,
                    description: "The name to greet",
                },
            },
            required: ["name"],
        },
    },
])

Api schema For OpenAPI and Smithy target

The OpenAPI and Smithy target need API Schema. The Gateway construct provide three ways to upload API schema for your target:

# When using ApiSchema.fromLocalAsset, you must bind the schema to a scope
schema = AWSCDK::BedrockAgentCore::APISchema.from_local_asset(path.join(__dirname, "mySchema.yml"))

schema.bind(self)
inline_schema = AWSCDK::BedrockAgentCore::APISchema.from_inline(<<-'HERE'

openapi: 3.0.3
info:
  title: Library API
  version: 1.0.0
paths:
  /search:
    get:
      summary: Search for books
      operationId: searchBooks
      parameters:
        - name: query
          in: query
          required: true
          schema:
            type: string

HERE)
bucket = AWSCDK::S3::Bucket.from_bucket_name(self, "ExistingBucket", "my-schema-bucket")
s3_schema = AWSCDK::BedrockAgentCore::APISchema.from_s3_file(bucket, "schemas/action-group.yaml")

Outbound auth

Outbound authorization lets Amazon Bedrock AgentCore gateways securely access gateway targets on behalf of users authenticated and authorized during Inbound Auth.

AgentCore Gateway supports the following types of outbound authorization:

IAM-based outbound authorization – The gateway uses its execution role to authenticate with AWS services. This is the default and most common approach for Lambda targets and AWS service integrations. Use GatewayCredentialProvider.fromIamRole(); by default the gateway infers the SigV4 signing service and region from the target endpoint. For MCP Server and OpenAPI targets, you can override the service, and optionally the region too — useful for cross-region calls or when the service can't be inferred from the URL:

AWSCDK::BedrockAgentCore::GatewayCredentialProvider.from_iam_role({
    service: "bedrock-runtime",
     # SigV4 signing name (typically the endpoint prefix); see the AWS service authorization reference
    region: "us-east-1",
})

The Bedrock AgentCore service only accepts IamCredentialProvider with explicit service / region for MCP Server and OpenAPI targets. Lambda, API Gateway and Smithy targets must use the bare GatewayCredentialProvider.fromIamRole() (with no arguments); the CDK enforces this with a synth-time validation.

2-legged OAuth (OAuth 2LO) – Use OAuth 2.0 two-legged flow (2LO) for targets that require OAuth authentication. The gateway authenticates on its own behalf, not on behalf of a user.

API key – Use the AgentCore service/AWS console to generate an API key to authenticate access to the gateway target.

**Note > You need to set up the outbound identity before you can create a gateway target.

Token Vault credential providers

AgentCore stores outbound API key and OAuth2 client credentials in Token Vault. This module includes L2 constructs that create those resources and connect them to gateway targets.

Shared OAuth2 fields — Every OAuth2CredentialProvider factory accepts the same client_id and client_secret, plus optional o_auth2_credential_provider_name and tags. Extra properties appear only when an IdP needs them (for example tenant_id for Microsoft, or issuer / endpoint overrides for Okta and other included configurations).

Vendor factories — Prefer OAuth2CredentialProvider.usingSlack, .usingGithub, .usingGoogle, .usingMicrosoft, .usingOkta, .usingAuth0, .usingCognito, and the other using* helpers for known providers. Each maps to the matching CloudFormation included provider configuration.

Custom OAuth2 (using_custom) — Supply exactly one of:

Do not pass both. The construct validates this at synthesis time when values are known; if you use CDK tokens, ensure the resolved template still satisfies the service rules.

Wiring to gateway targets — After you create a provider in CDK, pass the construct to GatewayCredentialProvider.fromOauthIdentity() or from_api_key_identity() (optional API key header/query settings go in the second argument for API keys). Alternatively, call bind_for_gateway_o_auth_target / bind_for_gateway_api_key_target on the provider and pass that object to from_oauth_identity_arn / from_api_key_identity_arn. You can still pass raw ARNs from the console or API when the provider already exists.

Example: GitHub OAuth2 and an MCP target

gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
})

oauth = AWSCDK::BedrockAgentCore::OAuth2CredentialProvider.using_github(self, "GhOAuth", {
    o_auth2_credential_provider_name: "github-oauth",
    client_id: "your-client-id",
    client_secret: AWSCDK::SecretValue.unsafe_plain_text("your-client-secret"),
})

gateway.add_mcp_server_target("Mcp", {
    gateway_target_name: "mcp-server",
    description: "MCP with GitHub OAuth",
    endpoint: "https://my-mcp-server.example.com",
    credential_provider_configurations: [
        AWSCDK::BedrockAgentCore::GatewayCredentialProvider.from_oauth_identity(oauth, {
            scopes: ["read:user"],
        }),
    ],
})

Example: custom IdP with a discovery URL

AWSCDK::BedrockAgentCore::OAuth2CredentialProvider.using_custom(self, "CustomOAuth", {
    o_auth2_credential_provider_name: "custom-idp",
    client_id: "your-client-id",
    client_secret: AWSCDK::SecretValue.unsafe_plain_text("your-client-secret"),
    discovery_url: "https://idp.example.com/.well-known/openid-configuration",
})

Example: custom IdP with explicit authorization server metadata

AWSCDK::BedrockAgentCore::OAuth2CredentialProvider.using_custom(self, "CustomOAuthMeta", {
    client_id: "your-client-id",
    client_secret: AWSCDK::SecretValue.unsafe_plain_text("your-client-secret"),
    authorization_server_metadata: {
        issuer: "https://idp.example.com",
        authorization_endpoint: "https://idp.example.com/oauth2/authorize",
        token_endpoint: "https://idp.example.com/oauth2/token",
    },
})

Workload identities

A workload identity is the stable identity of an agent in your AWS account within the AgentCore Identity model. It ties together IAM roles, OAuth2 flows, API keys, and workload access tokens so agents can authenticate consistently across environments. For conceptual background, see Understanding workload identities.

Agent identity directory — Each account has a single logical directory that holds every workload identity, whether it was created by AgentCore Runtime, AgentCore Gateway, or manually (for example through CloudFormation or the control-plane API). The directory is created automatically when the first workload identity exists. Resource ARNs follow the pattern described in Understanding the agent identity directory (workload-identity-directory/default and child workload-identity/<name> entries).

When to create one in CDK — Runtime and Gateway can create workload identities for you during deployment. Use the WorkloadIdentity L2 when you need a manually defined identity (custom name, allowed OAuth2 return URLs, tags) or when integrating workloads that are not driven by those services.

ConstructWorkloadIdentity maps to AWS::BedrockAgentCore::WorkloadIdentity. It exposes workload_identity_arn, workload_identity_name, and workload_identity_ref for wiring into IAM or other AgentCore resources. Import an existing identity with WorkloadIdentity.fromWorkloadIdentityAttributes. Grant helpers (grant_read, grant_admin, grant_full_access) align with directory-level IAM patterns such as listing identities on the directory resource and scoping mutations to specific identity ARNs.

Example

AWSCDK::BedrockAgentCore::WorkloadIdentity.new(self, "MyWorkloadIdentity", {
    workload_identity_name: "customer-support-agent-prod",
    allowed_resource_oauth2_return_urls: ["https://app.example.com/oauth/callback"],
    tags: {team: "agents", env: "prod"},
})

Basic Gateway Target Creation

You can create targets in two ways: using the static factory methods on GatewayTarget or using the convenient add_target methods on the gateway instance.

This approach is recommended for most use cases, especially when creating targets alongside the gateway. It provides a cleaner, more fluent API by eliminating the need to explicitly pass the gateway reference.

Below are the examples on how you can create Lambda, Smithy, OpenAPI, MCP Server, and API Gateway targets using add_target methods.

# Create a gateway first
gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
})

lambda_function = AWSCDK::Lambda::Function.new(self, "MyFunction", {
    runtime: AWSCDK::Lambda::Runtime.NODEJS_22_X,
    handler: "index.handler",
    code: AWSCDK::Lambda::Code.from_inline(<<-'HERE'

        exports.handler = async (event) => {
          return {
            statusCode: 200,
            body: JSON.stringify({ message: 'Hello from Lambda!' })
          };
        };

    HERE),
})

lambda_target = gateway.add_lambda_target("MyLambdaTarget", {
    gateway_target_name: "my-lambda-target",
    description: "Lambda function target",
    lambda_function: lambda_function,
    tool_schema: AWSCDK::BedrockAgentCore::ToolSchema.from_inline([
        {
            name: "hello_world",
            description: "A simple hello world tool",
            input_schema: {
                type: AWSCDK::BedrockAgentCore::SchemaDefinitionType.OBJECT,
                properties: {
                    name: {
                        type: AWSCDK::BedrockAgentCore::SchemaDefinitionType.STRING,
                        description: "The name to greet",
                    },
                },
                required: ["name"],
            },
        },
    ]),
})
gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
})

# Create an API key credential provider in Token Vault
api_key_provider = AWSCDK::BedrockAgentCore::APIKeyCredentialProvider.new(self, "MyApiKeyProvider", {
    api_key_credential_provider_name: "my-apikey",
})

bucket = AWSCDK::S3::Bucket.from_bucket_name(self, "ExistingBucket", "my-schema-bucket")
s3my_schema = AWSCDK::BedrockAgentCore::APISchema.from_s3_file(bucket, "schemas/myschema.yaml")

# Add an OpenAPI target using the L2 construct directly
target = gateway.add_open_api_target("MyTarget", {
    gateway_target_name: "my-api-target",
    description: "Target for external API integration",
    api_schema: s3my_schema,
    credential_provider_configurations: [
        AWSCDK::BedrockAgentCore::GatewayCredentialProvider.from_api_key_identity(api_key_provider, {
            credential_location: AWSCDK::BedrockAgentCore::APIKeyCredentialLocation.header({
                credential_parameter_name: "X-API-Key",
            }),
        }),
    ],
})

# This makes sure your s3 bucket is available before target
target.node.add_dependency(bucket)
gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
})

# ARNs from the console/API, or from ApiKeyCredentialProvider + bindForGatewayApiKeyTarget
api_key_provider_arn = "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/apikeycredentialprovider/my-apikey"
api_key_secret_arn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-apikey-secret-abc123"

bucket = AWSCDK::S3::Bucket.from_bucket_name(self, "ExistingBucket", "my-schema-bucket")
s3my_schema = AWSCDK::BedrockAgentCore::APISchema.from_s3_file(bucket, "schemas/myschema.yaml")

# Add an OpenAPI target using ARNs directly
target = gateway.add_open_api_target("MyTarget", {
    gateway_target_name: "my-api-target",
    description: "Target for external API integration",
    api_schema: s3my_schema,
    credential_provider_configurations: [
        AWSCDK::BedrockAgentCore::GatewayCredentialProvider.from_api_key_identity_arn({
            provider_arn: api_key_provider_arn,
            secret_arn: api_key_secret_arn,
            credential_location: AWSCDK::BedrockAgentCore::APIKeyCredentialLocation.header({
                credential_parameter_name: "X-API-Key",
            }),
        }),
    ],
})

# This makes sure your s3 bucket is available before target
target.node.add_dependency(bucket)
gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
})

smithy_schema = AWSCDK::BedrockAgentCore::APISchema.from_local_asset(path.join(__dirname, "models", "smithy-model.json"))
smithy_schema.bind(self)

smithy_target = gateway.add_smithy_target("MySmithyTarget", {
    gateway_target_name: "my-smithy-target",
    description: "Smithy model target",
    smithy_model: smithy_schema,
})
gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
})

# OAuth2 (recommended): use OAuth2CredentialProvider + bindForGatewayOAuthTarget, or ARNs from console/API
oauth_provider_arn = "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/oauth2credentialprovider/my-oauth"
oauth_secret_arn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-oauth-secret-abc123"

# Add an MCP server target directly to the gateway
mcp_target = gateway.add_mcp_server_target("MyMcpServer", {
    gateway_target_name: "my-mcp-server",
    description: "External MCP server integration",
    endpoint: "https://my-mcp-server.example.com",
    credential_provider_configurations: [
        AWSCDK::BedrockAgentCore::GatewayCredentialProvider.from_oauth_identity_arn({
            provider_arn: oauth_provider_arn,
            secret_arn: oauth_secret_arn,
            scopes: ["mcp-runtime-server/invoke"],
        }),
    ],
})

# Grant sync permission to a Lambda function that will trigger synchronization
sync_function = AWSCDK::Lambda::Function.new(self, "SyncFunction", {
    runtime: AWSCDK::Lambda::Runtime.PYTHON_3_12,
    handler: "index.handler",
    code: AWSCDK::Lambda::Code.from_inline(<<-'HERE'

    import boto3

    def handler(event, context):
        client = boto3.client('bedrock-agentcore')
        response = client.synchronize_gateway_targets(
            gatewayIdentifier=event['gatewayId'],
            targetIds=[event['targetId']]
        )
        return response

    HERE),
})

mcp_target.grant_sync(sync_function)
gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
})

api = AWSCDK::APIGateway::RestAPI.new(self, "MyApi", {
    rest_api_name: "my-api",
})

# Uses IAM authorization for outbound auth by default
api_gateway_target = gateway.add_api_gateway_target("MyApiGatewayTarget", {
    rest_api: api,
    api_gateway_tool_configuration: {
        tool_filters: [
            {
                filter_path: "/pets/*",
                methods: [AWSCDK::BedrockAgentCore::APIGatewayHttpMethod.GET],
            },
        ],
    },
})

Using static factory methods

Use static factory methods when working with imported gateways, creating targets in different constructs/stacks, or when you need more explicit control over the construct tree hierarchy.

Create Gateway target using static convenience methods.

gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
})

lambda_function = AWSCDK::Lambda::Function.new(self, "MyFunction", {
    runtime: AWSCDK::Lambda::Runtime.NODEJS_22_X,
    handler: "index.handler",
    code: AWSCDK::Lambda::Code.from_inline(<<-'HERE'

            exports.handler = async (event) => {
                return {
                    statusCode: 200,
                    body: JSON.stringify({ message: 'Hello from Lambda!' })
                };
            };

    HERE),
})

# Create a gateway target with Lambda and tool schema
target = AWSCDK::BedrockAgentCore::GatewayTarget.for_lambda(self, "MyLambdaTarget", {
    gateway_target_name: "my-lambda-target",
    description: "Target for Lambda function integration",
    gateway: gateway,
    lambda_function: lambda_function,
    tool_schema: AWSCDK::BedrockAgentCore::ToolSchema.from_local_asset(path.join(__dirname, "schemas", "my-tool-schema.json")),
})
gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
})

# Outbound auth: ApiKeyCredentialProvider + bindForGatewayApiKeyTarget, or ARNs from console/API
api_key_identity_arn = "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/apikeycredentialprovider/my-apikey"
api_key_secret_arn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-apikey-secret-abc123"

opneapi_schema = AWSCDK::BedrockAgentCore::APISchema.from_local_asset(path.join(__dirname, "mySchema.yml"))
opneapi_schema.bind(self)

# Create a gateway target with OpenAPI Schema
target = AWSCDK::BedrockAgentCore::GatewayTarget.for_open_api(self, "MyTarget", {
    gateway_target_name: "my-api-target",
    description: "Target for external API integration",
    gateway: gateway,
     # Note: you need to pass the gateway reference
    api_schema: opneapi_schema,
    credential_provider_configurations: [
        AWSCDK::BedrockAgentCore::GatewayCredentialProvider.from_api_key_identity_arn({
            provider_arn: api_key_identity_arn,
            secret_arn: api_key_secret_arn,
        }),
    ],
})
gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
})

smithy_schema = AWSCDK::BedrockAgentCore::APISchema.from_local_asset(path.join(__dirname, "models", "smithy-model.json"))
smithy_schema.bind(self)

# Create a gateway target with Smithy Model and OAuth
target = AWSCDK::BedrockAgentCore::GatewayTarget.for_smithy(self, "MySmithyTarget", {
    gateway_target_name: "my-smithy-target",
    description: "Target for Smithy model integration",
    gateway: gateway,
    smithy_model: smithy_schema,
})
gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
})

# OAuth2 (recommended): use OAuth2CredentialProvider + bindForGatewayOAuthTarget, or ARNs from console/API
oauth_provider_arn = "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/oauth2credentialprovider/my-oauth"
oauth_secret_arn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-oauth-secret-abc123"

# Create a gateway target with MCP Server
mcp_target = AWSCDK::BedrockAgentCore::GatewayTarget.for_mcp_server(self, "MyMcpServer", {
    gateway_target_name: "my-mcp-server",
    description: "External MCP server integration",
    gateway: gateway,
    endpoint: "https://my-mcp-server.example.com",
    credential_provider_configurations: [
        AWSCDK::BedrockAgentCore::GatewayCredentialProvider.from_oauth_identity_arn({
            provider_arn: oauth_provider_arn,
            secret_arn: oauth_secret_arn,
            scopes: ["mcp-runtime-server/invoke"],
        }),
    ],
})
gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
})

api = AWSCDK::APIGateway::RestAPI.new(self, "MyApi", {
    rest_api_name: "my-api",
})

# Create a gateway target using the static factory method
api_gateway_target = AWSCDK::BedrockAgentCore::GatewayTarget.for_api_gateway(self, "MyApiGatewayTarget", {
    gateway_target_name: "my-api-gateway-target",
    description: "Target for API Gateway REST API integration",
    gateway: gateway,
    rest_api: api,
    api_gateway_tool_configuration: {
        tool_filters: [
            {
                filter_path: "/pets/*",
                methods: [AWSCDK::BedrockAgentCore::APIGatewayHttpMethod.GET, AWSCDK::BedrockAgentCore::APIGatewayHttpMethod.POST],
            },
        ],
    },
    metadata_configuration: {
        allowed_request_headers: ["X-User-Id"],
        allowed_query_parameters: ["limit"],
    },
})

Advanced Usage: Direct Configuration for gateway target

For advanced use cases where you need full control over the target configuration, you can create configurations manually using the static factory methods and use the GatewayTarget constructor directly.

Configuration Factory Methods

Each target type has a corresponding configuration class with a static create() method:

Example: Lambda Target with Custom Configuration

gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
})

my_lambda_function = AWSCDK::Lambda::Function.new(self, "MyFunction", {
    runtime: AWSCDK::Lambda::Runtime.NODEJS_22_X,
    handler: "index.handler",
    code: AWSCDK::Lambda::Code.from_inline(<<-'HERE'

        exports.handler = async (event) => ({ statusCode: 200 });

    HERE),
})

my_tool_schema = AWSCDK::BedrockAgentCore::ToolSchema.from_inline([
    {
        name: "my_tool",
        description: "My custom tool",
        input_schema: {
            type: AWSCDK::BedrockAgentCore::SchemaDefinitionType.OBJECT,
            properties: {},
        },
    },
])

# Create a custom Lambda configuration
custom_config = AWSCDK::BedrockAgentCore::LambdaTargetConfiguration.create(my_lambda_function, my_tool_schema)

# Use the GatewayTarget constructor directly
target = AWSCDK::BedrockAgentCore::GatewayTarget.new(self, "AdvancedTarget", {
    gateway: gateway,
    gateway_target_name: "advanced-target",
    target_configuration: custom_config,
     # Manually created configuration
    credential_provider_configurations: [
        AWSCDK::BedrockAgentCore::GatewayCredentialProvider.from_iam_role,
    ],
})

This approach gives you full control over the configuration but is typically not necessary for most use cases. The convenience methods (GatewayTarget.forLambda(), GatewayTarget.forOpenApi(), GatewayTarget.forSmithy(), GatewayTarget.forApiGateway()) handle all of this internally.

Gateway Interceptors

Gateway interceptors allow you to run custom code during each gateway invocation to implement fine-grained access control, transform requests and responses, or implement custom authorization logic. A gateway can have at most one REQUEST interceptor and one RESPONSE interceptor.

Interceptor Types:

Security Best Practices:

  1. Keep pass_request_headers disabled unless absolutely necessary (default: false)
  2. Implement idempotent Lambda functions (gateway may retry on failures)
  3. Restrict gateway execution role to specific Lambda functions
  4. Avoid logging sensitive information in your interceptor

For more information, see the Gateway Interceptors documentation.

Adding Interceptors via Constructor

# Create Lambda functions for interceptors
request_interceptor_fn = AWSCDK::Lambda::Function.new(self, "RequestInterceptor", {
    runtime: AWSCDK::Lambda::Runtime.PYTHON_3_12,
    handler: "index.handler",
    code: AWSCDK::Lambda::Code.from_inline(<<-'HERE'

    def handler(event, context):
        # Validate and transform request
        return {
            "interceptorOutputVersion": "1.0",
            "mcp": {
                "transformedGatewayRequest": event["mcp"]["gatewayRequest"]
            }
        }

    HERE),
})

response_interceptor_fn = AWSCDK::Lambda::Function.new(self, "ResponseInterceptor", {
    runtime: AWSCDK::Lambda::Runtime.PYTHON_3_12,
    handler: "index.handler",
    code: AWSCDK::Lambda::Code.from_inline(<<-'HERE'

    def handler(event, context):
        # Filter or transform response
        return {
            "interceptorOutputVersion": "1.0",
            "mcp": {
                "transformedGatewayResponse": event["mcp"]["gatewayResponse"]
            }
        }

    HERE),
})

# Create gateway with interceptors
gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
    interceptor_configurations: [
        AWSCDK::BedrockAgentCore::LambdaInterceptor.for_request(request_interceptor_fn, {
            pass_request_headers: true,
        }),
        AWSCDK::BedrockAgentCore::LambdaInterceptor.for_response(response_interceptor_fn),
    ],
})

Automatic Permission Granting:

When you add a Lambda interceptor to a gateway (either via constructor or add_interceptor()), the gateway's IAM role automatically receives lambda:InvokeFunction permission on the Lambda function. This permission grant happens internally during the bind process - you do not need to manually configure these IAM permissions.

Adding Interceptors Dynamically

# Create a gateway first
gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
})

# Create Lambda functions for interceptors
request_interceptor_fn = AWSCDK::Lambda::Function.new(self, "RequestInterceptor", {
    runtime: AWSCDK::Lambda::Runtime.PYTHON_3_12,
    handler: "index.handler",
    code: AWSCDK::Lambda::Code.from_inline(<<-'HERE'

    def handler(event, context):
        # Custom request validation logic
        return {
            "interceptorOutputVersion": "1.0",
            "mcp": {
                "transformedGatewayRequest": event["mcp"]["gatewayRequest"]
            }
        }

    HERE),
})

response_interceptor_fn = AWSCDK::Lambda::Function.new(self, "ResponseInterceptor", {
    runtime: AWSCDK::Lambda::Runtime.PYTHON_3_12,
    handler: "index.handler",
    code: AWSCDK::Lambda::Code.from_inline(<<-'HERE'

    def handler(event, context):
        # Filter sensitive data from response
        return {
            "interceptorOutputVersion": "1.0",
            "mcp": {
                "transformedGatewayResponse": event["mcp"]["gatewayResponse"]
            }
        }

    HERE),
})

gateway.add_interceptor(AWSCDK::BedrockAgentCore::LambdaInterceptor.for_request(request_interceptor_fn, {
    pass_request_headers: false,
}))

gateway.add_interceptor(AWSCDK::BedrockAgentCore::LambdaInterceptor.for_response(response_interceptor_fn))

Gateway Target IAM Permissions

The Gateway Target construct provides convenient methods for granting IAM permissions:

# Create a gateway and target
gateway = AWSCDK::BedrockAgentCore::Gateway.new(self, "MyGateway", {
    gateway_name: "my-gateway",
})

smithy_schema = AWSCDK::BedrockAgentCore::APISchema.from_local_asset(path.join(__dirname, "models", "smithy-model.json"))
smithy_schema.bind(self)

# Create a gateway target with Smithy Model and OAuth
target = AWSCDK::BedrockAgentCore::GatewayTarget.for_smithy(self, "MySmithyTarget", {
    gateway_target_name: "my-smithy-target",
    description: "Target for Smithy model integration",
    gateway: gateway,
    smithy_model: smithy_schema,
})

# Create a role that needs access to the gateway target
user_role = AWSCDK::IAM::Role.new(self, "UserRole", {
    assumed_by: AWSCDK::IAM::ServicePrincipal.new("lambda.amazonaws.com"),
})

# Grant read permissions (Get and List actions)
target.grant_read(user_role)

# Grant manage permissions (Create, Update, Delete actions)
target.grant_manage(user_role)

# Grant specific custom permissions
target.grant(user_role, "bedrock-agentcore:GetGatewayTarget")

# Grants permission to invoke this Gateway
gateway.grant_invoke(user_role)

Memory

Memory is a critical component of intelligence. While Large Language Models (LLMs) have impressive capabilities, they lack persistent memory across conversations. Amazon Bedrock AgentCore Memory addresses this limitation by providing a managed service that enables AI agents to maintain context over time, remember important facts, and deliver consistent, personalized experiences.

AgentCore Memory operates on two levels:

When you interact with the memory via the CreateEvent API, you store interactions in Short-Term Memory (STM) instantly. These interactions can include everything from user messages, assistant responses, to tool actions.

To write to long-term memory, you need to configure extraction strategies which define how and where to store information from conversations for future use. These strategies are asynchronously processed from raw events after every few turns based on the strategy that was selected. You can't create long term memory records directly, as they are extracted asynchronously by AgentCore Memory.

Memory Properties

Name Type Required Description
memory_name string No The name of the memory. If not provided, a unique name will be auto-generated
expiration_duration Duration No Short-term memory expiration in days (between 7 and 365). Default: 90 days
description string No Optional description for the memory. Default: no description.
kms_key IKey No Custom KMS key to use for encryption. Default: Your data is encrypted with a key that AWS owns and manages for you
memory_strategies MemoryStrategyBase[] No Built-in extraction strategies to use for this memory. Default: No extraction strategies (short term memory only)
execution_role iam.IRole No The IAM role that provides permissions for the memory to access AWS services. Default: A new role will be created.
tags { [key: string]: string } No Tags for memory. Default: no tags.

Basic Memory Creation

Below you can find how to configure a simple short-term memory (STM) with no long-term memory extraction strategies. Note how you set expiration_duration, which defines the time the events will be stored in the short-term memory before they expire.

# Create a basic memory with default settings, no LTM strategies
memory = AWSCDK::BedrockAgentCore::Memory.new(self, "MyMemory", {
    memory_name: "my_memory",
    description: "A memory for storing user interactions for a period of 90 days",
    expiration_duration: AWSCDK::Duration.days(90),
})

Basic Memory with Custom KMS Encryption

# Create a custom KMS key for encryption
encryption_key = AWSCDK::KMS::Key.new(self, "MemoryEncryptionKey", {
    enable_key_rotation: true,
    description: "KMS key for memory encryption",
})

# Create memory with custom encryption
memory = AWSCDK::BedrockAgentCore::Memory.new(self, "MyMemory", {
    memory_name: "my_encrypted_memory",
    description: "Memory with custom KMS encryption",
    expiration_duration: AWSCDK::Duration.days(90),
    kms_key: encryption_key,
})

LTM Memory Extraction Stategies

If you need long-term memory for context recall across sessions, you can setup memory extraction strategies to extract the relevant memory from the raw events.

Amazon Bedrock AgentCore Memory has different memory strategies for extracting and organizing information:

You can use built-in extraction strategies for quick setup, or create custom extraction strategies with specific models and prompt templates.

Memory with Built-in Strategies

The library provides four built-in LTM strategies. These are default strategies for organizing and extracting memory data, each optimized for specific use cases.

For example: An agent helps multiple users with cloud storage setup. From these conversations, see how each strategy processes users expressing confusion about account connection:

  1. Summarization Strategy (MemoryStrategy.usingBuiltInSummarization()) This strategy compresses conversations into concise overviews, preserving essential context and key insights for quick recall. Extracted memory example: Users confused by cloud setup during onboarding.
# Create memory with built-in strategies
memory = AWSCDK::BedrockAgentCore::Memory.new(self, "MyMemory", {
    memory_name: "my_memory",
    description: "Memory with built-in strategies",
    expiration_duration: AWSCDK::Duration.days(90),
    memory_strategies: [
        AWSCDK::BedrockAgentCore::MemoryStrategy.using_built_in_summarization,
        AWSCDK::BedrockAgentCore::MemoryStrategy.using_built_in_semantic,
        AWSCDK::BedrockAgentCore::MemoryStrategy.using_built_in_user_preference,
        AWSCDK::BedrockAgentCore::MemoryStrategy.using_built_in_episodic,
    ],
})

The name generated for each built in memory strategy is as follows:

Memory with custom Strategies

With Long-Term Memory, organization is managed through Namespaces.

An actor refers to entity such as end users or agent/user combinations. For example, in a coding support chatbot, the actor is usually the developer asking questions. Using the actor ID helps the system know which user the memory belongs to, keeping each user's data separate and organized.

A session is usually a single conversation or interaction period between the user and the AI agent. It groups all related messages and events that happen during that conversation.

A namespace is used to logically group and organize long-term memories. It ensures data stays neat, separate, and secure.

With AgentCore Memory, you need to add a namespace when you define a memory strategy. This namespace helps define where the long-term memory will be logically grouped. Every time a new long-term memory is extracted using this memory strategy, it is saved under the namespace you set. This means that all long-term memories are scoped to their specific namespace, keeping them organized and preventing any mix-ups with other users or sessions. You should use a hierarchical format separated by forward slashes /. This helps keep memories organized clearly. As needed, you can choose to use the below pre-defined variables within braces in the namespace based on your applications' organization needs:

For example, if you define the following namespace as the input to your strategy in CreateMemory operation:

/strategy/{memoryStrategyId}/actor/{actorId}/session/{sessionId}

After memory creation, this namespace might look like:

/strategy/summarization-93483043//actor/actor-9830m2w3/session/session-9330sds8

You can customise the namespace, i.e. where the memories are stored by using the following methods:

  1. Summarization Strategy (MemoryStrategy.usingSummarization(props))
  2. Semantic Memory Strategy (MemoryStrategy.usingSemantic(props))
  3. User Preference Strategy (MemoryStrategy.usingUserPreference(props))
  4. Episodic Memory Strategy (MemoryStrategy.usingEpisodic(props))
# Create memory with custom strategies
memory = AWSCDK::BedrockAgentCore::Memory.new(self, "MyMemory", {
    memory_name: "my_memory",
    description: "Memory with custom strategies",
    expiration_duration: AWSCDK::Duration.days(90),
    memory_strategies: [
        AWSCDK::BedrockAgentCore::MemoryStrategy.using_user_preference({
            strategy_name: "CustomerPreferences",
            namespaces: ["support/customer/{actorId}/preferences"],
        }),
        AWSCDK::BedrockAgentCore::MemoryStrategy.using_semantic({
            strategy_name: "CustomerSupportSemantic",
            namespaces: ["support/customer/{actorId}/semantic"],
        }),
        AWSCDK::BedrockAgentCore::MemoryStrategy.using_episodic({
            strategy_name: "customerJourneyEpisodic",
            namespaces: ["/journey/customer/{actorId}/episodes"],
            reflection_configuration: {
                namespaces: ["/journey/customer/{actorId}/reflections"],
            },
        }),
    ],
})

Custom memory strategies let you tailor memory extraction and consolidation to your specific domain or use case. You can override the prompts for extracting and consolidating semantic, summary, or user preferences. You can also choose the model that you want to use for extraction and consolidation.

The custom prompts you create are appended to a non-editable system prompt.

Since a custom strategy requires you to invoke certain FMs, you need a role with appropriate permissions. For that, you can:

Memory with Custom Execution Role

Keep in mind that memories that do not use custom strategies do not require a service role. So even if you provide it, it will be ignored as it will never be used.

# Create a custom execution role
execution_role = AWSCDK::IAM::Role.new(self, "MemoryExecutionRole", {
    assumed_by: AWSCDK::IAM::ServicePrincipal.new("bedrock-agentcore.amazonaws.com"),
    managed_policies: [
        AWSCDK::IAM::ManagedPolicy.from_aws_managed_policy_name("AmazonBedrockAgentCoreMemoryBedrockModelInferenceExecutionRolePolicy"),
    ],
})

# Create memory with custom execution role
memory = AWSCDK::BedrockAgentCore::Memory.new(self, "MyMemory", {
    memory_name: "my_memory",
    description: "Memory with custom execution role",
    expiration_duration: AWSCDK::Duration.days(90),
    execution_role: execution_role,
})

In customConsolidation and customExtraction, the model property uses IModel from aws-cdk-lib/aws-bedrock.

# Create a custom semantic memory strategy
custom_semantic_strategy = AWSCDK::BedrockAgentCore::MemoryStrategy.using_semantic({
    strategy_name: "customSemanticStrategy",
    description: "Custom semantic memory strategy",
    namespaces: ["/custom/strategies/{memoryStrategyId}/actors/{actorId}"],
    custom_consolidation: {
        model: AWSCDK::Bedrock::FoundationModel.from_foundation_model_id(self, "ConsolidationModel", AWSCDK::Bedrock::FoundationModelIdentifier.ANTHROPIC_CLAUDE_3_5_SONNET_20241022_V2_0),
        append_to_prompt: "Custom consolidation prompt for semantic memory",
    },
    custom_extraction: {
        model: AWSCDK::Bedrock::FoundationModel.from_foundation_model_id(self, "ExtractionModel", AWSCDK::Bedrock::FoundationModelIdentifier.ANTHROPIC_CLAUDE_3_5_SONNET_20241022_V2_0),
        append_to_prompt: "Custom extraction prompt for semantic memory",
    },
})

# Create memory with custom strategy
memory = AWSCDK::BedrockAgentCore::Memory.new(self, "MyMemory", {
    memory_name: "my-custom-memory",
    description: "Memory with custom strategy",
    expiration_duration: AWSCDK::Duration.days(90),
    memory_strategies: [custom_semantic_strategy],
})

Memory with self-managed Strategies

A self-managed strategy in Amazon Bedrock AgentCore Memory gives you complete control over your memory extraction and consolidation pipelines. With a self-managed strategy, you can build custom memory processing workflows while leveraging Amazon Bedrock AgentCore for storage and retrieval.

For additional information, you can refer to the developer guide for self managed strategies.

Create the required AWS resources including:

The construct will apply the correct permissions to the memory execution role to access these resources.

bucket = AWSCDK::S3::Bucket.new(self, "memoryBucket", {
    bucket_name: "test-memory",
    removal_policy: AWSCDK::RemovalPolicy::DESTROY,
    auto_delete_objects: true,
})

topic = AWSCDK::SNS::Topic.new(self, "topic")

# Create a custom semantic memory strategy
self_managed_strategy = AWSCDK::BedrockAgentCore::MemoryStrategy.using_self_managed({
    strategy_name: "selfManagedStrategy",
    description: "self managed memory strategy",
    historical_context_window_size: 5,
    invocation_configuration: {
        topic: topic,
        s3_location: {
            bucket_name: bucket.bucket_name,
            object_key: "memory/",
        },
    },
    trigger_conditions: {
        message_based_trigger: 1,
        time_based_trigger: AWSCDK::Duration.seconds(10),
        token_based_trigger: 100,
    },
})

# Create memory with custom strategy
memory = AWSCDK::BedrockAgentCore::Memory.new(self, "MyMemory", {
    memory_name: "my-custom-memory",
    description: "Memory with custom strategy",
    expiration_duration: AWSCDK::Duration.days(90),
    memory_strategies: [self_managed_strategy],
})

Memory Strategy Methods

You can add new memory strategies to the memory construct using the add_memory_strategy() method, for instance:

# Create memory without initial strategies
memory = AWSCDK::BedrockAgentCore::Memory.new(self, "test-memory", {
    memory_name: "test_memory_add_strategy",
    description: "A test memory for testing addMemoryStrategy method",
    expiration_duration: AWSCDK::Duration.days(90),
})

# Add strategies after instantiation
memory.add_memory_strategy(AWSCDK::BedrockAgentCore::MemoryStrategy.using_built_in_summarization)
memory.add_memory_strategy(AWSCDK::BedrockAgentCore::MemoryStrategy.using_built_in_semantic)

Online Evaluation

The Online Evaluation construct enables continuous monitoring and assessment of your agent's performance using live traffic. It automatically samples agent traces from CloudWatch Logs or Agent Endpoints and applies built-in evaluators to assess quality metrics like helpfulness, correctness, and safety.

Prerequisites

Before creating an OnlineEvaluationConfig, ensure the following are configured in your account:

For full details, see AgentCore Evaluations Prerequisites.

Online Evaluation Properties

Name Type Required Description
online_evaluation_config_name string Yes The name of the online evaluation configuration. Must start with a letter and can contain a-z, A-Z, 0-9, _ (underscore). Maximum 48 characters
evaluators EvaluatorSelector[] Yes The list of built-in evaluators to apply during evaluation. Minimum 1, maximum 10
data_source DataSourceConfig Yes The data source configuration specifying where to read agent traces from
execution_role iam.IRole No The IAM role for evaluation. If not provided, a role will be created automatically
description string No Description of the evaluation configuration. Maximum 200 characters
sampling_percentage number No Percentage of traces to sample (0.01-100). Default: 10
filters FilterConfig[] No Filters to determine which traces to evaluate. Use FilterValue.string(), FilterValue.number(), or FilterValue.boolean() for typed filter values. Maximum 5
session_timeout Duration No Duration of inactivity before a session is considered complete (1-1440 minutes). Default: Duration.minutes(15)
tags { [key: string]: string } No Tags for the evaluation configuration

Basic Online Evaluation Creation

Create an online evaluation configuration with built-in evaluators:

evaluation = AWSCDK::BedrockAgentCore::OnlineEvaluationConfig.new(self, "MyEvaluation", {
    online_evaluation_config_name: "my_evaluation",
    evaluators: [
        AWSCDK::BedrockAgentCore::EvaluatorSelector.builtin(AWSCDK::BedrockAgentCore::BuiltinEvaluator.HELPFULNESS),
        AWSCDK::BedrockAgentCore::EvaluatorSelector.builtin(AWSCDK::BedrockAgentCore::BuiltinEvaluator.CORRECTNESS),
    ],
    data_source: AWSCDK::BedrockAgentCore::DataSourceConfig.from_cloud_watch_logs({
        log_group_names: ["/aws/bedrock-agentcore/my-agent"],
        service_names: ["my-agent.default"],
    }),
})

Built-in Evaluators

Amazon Bedrock AgentCore provides 13 built-in evaluators that assess different aspects of agent performance:

Session-Level Evaluators:

Trace-Level Evaluators:

Tool Call-Level Evaluators:

evaluation = AWSCDK::BedrockAgentCore::OnlineEvaluationConfig.new(self, "ComprehensiveEval", {
    online_evaluation_config_name: "comprehensive_evaluation",
    evaluators: [
        AWSCDK::BedrockAgentCore::EvaluatorSelector.builtin(AWSCDK::BedrockAgentCore::BuiltinEvaluator.GOAL_SUCCESS_RATE),
        AWSCDK::BedrockAgentCore::EvaluatorSelector.builtin(AWSCDK::BedrockAgentCore::BuiltinEvaluator.HELPFULNESS),
        AWSCDK::BedrockAgentCore::EvaluatorSelector.builtin(AWSCDK::BedrockAgentCore::BuiltinEvaluator.CORRECTNESS),
        AWSCDK::BedrockAgentCore::EvaluatorSelector.builtin(AWSCDK::BedrockAgentCore::BuiltinEvaluator.COHERENCE),
        AWSCDK::BedrockAgentCore::EvaluatorSelector.builtin(AWSCDK::BedrockAgentCore::BuiltinEvaluator.HARMFULNESS),
        AWSCDK::BedrockAgentCore::EvaluatorSelector.builtin(AWSCDK::BedrockAgentCore::BuiltinEvaluator.STEREOTYPING),
        AWSCDK::BedrockAgentCore::EvaluatorSelector.builtin(AWSCDK::BedrockAgentCore::BuiltinEvaluator.TOOL_SELECTION_ACCURACY),
    ],
    data_source: AWSCDK::BedrockAgentCore::DataSourceConfig.from_cloud_watch_logs({
        log_group_names: ["/aws/bedrock-agentcore/my-agent"],
        service_names: ["my-agent.default"],
    }),
})

Custom Evaluators

Custom evaluators let you define evaluation logic tailored to your specific use cases. You can create custom evaluators using two strategies:

Property Type Required Description
evaluator_name string Yes Name of the evaluator. Must start with a letter, a-z, A-Z, 0-9, _ only. Maximum 48 characters
evaluator_config EvaluatorConfig Yes Configuration defining how the evaluator assesses performance
level EvaluationLevel Yes The level at which the evaluator operates: TOOL_CALL, TRACE, or SESSION
description string No Description of the evaluator. Maximum 200 characters
tags { [key: string]: string } No Tags for the evaluator. A list of key:value pairs to apply to this Evaluator resource

LLM-as-a-Judge Evaluator

Create a custom evaluator that uses a foundation model to assess agent performance:

# LLM-as-a-Judge with categorical rating scale
categorical_evaluator = AWSCDK::BedrockAgentCore::Evaluator.new(self, "CategoricalEvaluator", {
    evaluator_name: "domain_accuracy_evaluator",
    level: AWSCDK::BedrockAgentCore::EvaluationLevel.SESSION,
    description: "Evaluates domain-specific accuracy of agent responses",
    evaluator_config: AWSCDK::BedrockAgentCore::EvaluatorConfig.llm_as_a_judge({
        instructions: "Evaluate whether the agent response is accurate within the healthcare domain.",
        model_id: "us.anthropic.claude-sonnet-4-6",
        rating_scale: AWSCDK::BedrockAgentCore::EvaluatorRatingScale.categorical([
            {label: "Accurate", definition: "The response contains factually correct healthcare information."},
            {label: "Inaccurate", definition: "The response contains incorrect or misleading healthcare information."},
        ]),
    }),
})

# LLM-as-a-Judge with numerical rating scale and inference config
numerical_evaluator = AWSCDK::BedrockAgentCore::Evaluator.new(self, "NumericalEvaluator", {
    evaluator_name: "response_quality_evaluator",
    level: AWSCDK::BedrockAgentCore::EvaluationLevel.TRACE,
    evaluator_config: AWSCDK::BedrockAgentCore::EvaluatorConfig.llm_as_a_judge({
        instructions: "Rate the overall quality of the agent response on a scale of 1 to 5.",
        model_id: "us.anthropic.claude-sonnet-4-6",
        rating_scale: AWSCDK::BedrockAgentCore::EvaluatorRatingScale.numerical([
            {label: "Poor", definition: "Inadequate response.", value: 1},
            {label: "Below Average", definition: "Partially addresses the query.", value: 2},
            {label: "Average", definition: "Adequately addresses the query.", value: 3},
            {label: "Good", definition: "Well-structured and accurate response.", value: 4},
            {label: "Excellent", definition: "Outstanding response exceeding expectations.", value: 5},
        ]),
        inference_config: {
            max_tokens: 1024,
            temperature: 0.1,
        },
    }),
})

The model_id accepts standard Bedrock model IDs and cross-region inference profile IDs with region prefixes (e.g., us., eu., global.).

Instructions placeholders: Instructions must contain placeholders appropriate for the evaluation level (e.g., {context}, {available_tools} for SESSION level). Evaluators using reference-input placeholders (e.g., {expected_tool_trajectory}, {assertions}) are only compatible with on-demand evaluation, not online evaluation. See the custom evaluators documentation for allowed placeholders per level.

Code-Based Evaluator

Create a custom evaluator that uses a Lambda function for evaluation logic:

eval_function = nil # AWSCDK::Lambda::IFunction


code_evaluator = AWSCDK::BedrockAgentCore::Evaluator.new(self, "CodeEvaluator", {
    evaluator_name: "custom_code_evaluator",
    level: AWSCDK::BedrockAgentCore::EvaluationLevel.TOOL_CALL,
    description: "Evaluates tool call accuracy using custom logic",
    evaluator_config: AWSCDK::BedrockAgentCore::EvaluatorConfig.code_based({
        lambda_function: eval_function,
        timeout: AWSCDK::Duration.seconds(30),
    }),
})

For code-based evaluators, the construct automatically grants the bedrock-agentcore.amazonaws.com service principal permission to invoke the Lambda function, scoped to the specific evaluator resource with aws:SourceAccount and aws:SourceArn conditions for confused deputy prevention.

Using Custom Evaluators with Online Evaluation

Custom evaluators are used in OnlineEvaluationConfig via EvaluatorSelector.custom(), alongside built-in evaluators:

custom_evaluator = nil # AWSCDK::BedrockAgentCore::Evaluator


evaluation = AWSCDK::BedrockAgentCore::OnlineEvaluationConfig.new(self, "MixedEvaluation", {
    online_evaluation_config_name: "mixed_evaluation",
    evaluators: [
        AWSCDK::BedrockAgentCore::EvaluatorSelector.builtin(AWSCDK::BedrockAgentCore::BuiltinEvaluator.HELPFULNESS),
        AWSCDK::BedrockAgentCore::EvaluatorSelector.builtin(AWSCDK::BedrockAgentCore::BuiltinEvaluator.CORRECTNESS),
        AWSCDK::BedrockAgentCore::EvaluatorSelector.custom(custom_evaluator),
    ],
    data_source: AWSCDK::BedrockAgentCore::DataSourceConfig.from_cloud_watch_logs({
        log_group_names: ["/aws/bedrock-agentcore/my-agent"],
        service_names: ["my-agent.default"],
    }),
})

Data Source Configuration

Online evaluation supports two types of data sources:

AgentCore Runtime Data Source (Recommended):

For runtimes created within your CDK app, use from_agent_runtime_endpoint() which automatically derives the CloudWatch log group and service name:

repository = AWSCDK::ECR::Repository.new(self, "TestRepository", {
    repository_name: "test-agent-runtime",
})

runtime = AWSCDK::BedrockAgentCore::Runtime.new(self, "MyRuntime", {
    runtime_name: "my_agent",
    agent_runtime_artifact: AWSCDK::BedrockAgentCore::AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0"),
})

# Using default endpoint (simplest)
evaluation = AWSCDK::BedrockAgentCore::OnlineEvaluationConfig.new(self, "RuntimeEval", {
    online_evaluation_config_name: "runtime_evaluation",
    evaluators: [
        AWSCDK::BedrockAgentCore::EvaluatorSelector.builtin(AWSCDK::BedrockAgentCore::BuiltinEvaluator.HELPFULNESS),
    ],
    data_source: AWSCDK::BedrockAgentCore::DataSourceConfig.from_agent_runtime_endpoint(runtime),
})

You can also specify a specific endpoint:

runtime = nil # AWSCDK::BedrockAgentCore::Runtime


# Using a specific endpoint construct
prod_endpoint = runtime.add_endpoint("PROD")
evaluation = AWSCDK::BedrockAgentCore::OnlineEvaluationConfig.new(self, "ProdEval", {
    online_evaluation_config_name: "prod_evaluation",
    evaluators: [
        AWSCDK::BedrockAgentCore::EvaluatorSelector.builtin(AWSCDK::BedrockAgentCore::BuiltinEvaluator.CORRECTNESS),
    ],
    data_source: AWSCDK::BedrockAgentCore::DataSourceConfig.from_agent_runtime_endpoint(runtime, prod_endpoint),
})

# Or using endpoint name as string
staging_eval = AWSCDK::BedrockAgentCore::OnlineEvaluationConfig.new(self, "StagingEval", {
    online_evaluation_config_name: "staging_evaluation",
    evaluators: [
        AWSCDK::BedrockAgentCore::EvaluatorSelector.builtin(AWSCDK::BedrockAgentCore::BuiltinEvaluator.CORRECTNESS),
    ],
    data_source: AWSCDK::BedrockAgentCore::DataSourceConfig.from_agent_runtime_endpoint_name(runtime, "STAGING"),
})

CloudWatch Logs Data Source:

For external agents or when you need to specify log groups directly:

evaluation = AWSCDK::BedrockAgentCore::OnlineEvaluationConfig.new(self, "CloudWatchEval", {
    online_evaluation_config_name: "cloudwatch_evaluation",
    evaluators: [
        AWSCDK::BedrockAgentCore::EvaluatorSelector.builtin(AWSCDK::BedrockAgentCore::BuiltinEvaluator.HELPFULNESS),
    ],
    data_source: AWSCDK::BedrockAgentCore::DataSourceConfig.from_cloud_watch_logs({
        log_group_names: [
            "/aws/bedrock-agentcore/agent1",
            "/aws/bedrock-agentcore/agent2",
        ],
        service_names: ["agent1.default"],
    }),
})

Sampling and Filtering

Configure sampling percentage and filters to control which traces are evaluated:

evaluation = AWSCDK::BedrockAgentCore::OnlineEvaluationConfig.new(self, "FilteredEval", {
    online_evaluation_config_name: "filtered_evaluation",
    evaluators: [
        AWSCDK::BedrockAgentCore::EvaluatorSelector.builtin(AWSCDK::BedrockAgentCore::BuiltinEvaluator.HELPFULNESS),
    ],
    data_source: AWSCDK::BedrockAgentCore::DataSourceConfig.from_cloud_watch_logs({
        log_group_names: ["/aws/bedrock-agentcore/my-agent"],
        service_names: ["my-agent.default"],
    }),
    # Sample 25% of traces
    sampling_percentage: 25,
    # Only evaluate traces matching these filters
    filters: [
        {
            key: "user.region",
            operator: AWSCDK::BedrockAgentCore::FilterOperator.EQUAL,
            value: AWSCDK::BedrockAgentCore::FilterValue.string("us-east-1"),
        },
        {
            key: "session.duration",
            operator: AWSCDK::BedrockAgentCore::FilterOperator.GREATER_THAN,
            value: AWSCDK::BedrockAgentCore::FilterValue.number(60),
        },
    ],
    # Consider sessions complete after 30 minutes of inactivity
    session_timeout: AWSCDK::Duration.minutes(30),
})

Online Evaluation with Custom Execution Role

Provide a custom IAM role for the evaluation execution:

execution_role = AWSCDK::IAM::Role.new(self, "EvaluationRole", {
    assumed_by: AWSCDK::IAM::ServicePrincipal.new("bedrock-agentcore.amazonaws.com"),
    description: "Custom role for online evaluation",
})

# Add required permissions
execution_role.add_to_policy(AWSCDK::IAM::PolicyStatement.new({
    actions: [
        "logs:DescribeLogGroups",
        "logs:GetQueryResults",
        "logs:StartQuery",
    ],
    resources: ["arn:aws:logs:*:*:log-group:/aws/bedrock-agentcore/*"],
}))

evaluation = AWSCDK::BedrockAgentCore::OnlineEvaluationConfig.new(self, "CustomRoleEval", {
    online_evaluation_config_name: "custom_role_evaluation",
    evaluators: [
        AWSCDK::BedrockAgentCore::EvaluatorSelector.builtin(AWSCDK::BedrockAgentCore::BuiltinEvaluator.HELPFULNESS),
    ],
    data_source: AWSCDK::BedrockAgentCore::DataSourceConfig.from_cloud_watch_logs({
        log_group_names: ["/aws/bedrock-agentcore/my-agent"],
        service_names: ["my-agent.default"],
    }),
    execution_role: execution_role,
})

Online Evaluation IAM Permissions

Grant IAM permissions to manage or read evaluation configurations:

evaluation = nil # AWSCDK::BedrockAgentCore::OnlineEvaluationConfig
role = nil # AWSCDK::IAM::IRole


# Grant specific permissions
evaluation.grant(role, "bedrock-agentcore:GetOnlineEvaluationConfig", "bedrock-agentcore:UpdateOnlineEvaluationConfig")

API Reference

Classes 100

AgentCoreRuntimeBedrock AgentCore runtime environment for code execution Allowed values: PYTHON_3_10 | PYT AgentRuntimeArtifactAbstract base class for agent runtime artifacts. APIGatewayHttpMethodHTTP methods supported by API Gateway. APIGatewayTargetConfigurationConfiguration for API Gateway-based MCP targets. APIKeyCredentialLocationAPI Key location within the request. APIKeyCredentialProviderL2 construct for `AWS::BedrockAgentCore::ApiKeyCredentialProvider`. APIKeyCredentialProviderIdentityPermsIAM actions for AgentCore API key credential providers (Token Vault). APISchemaRepresents the concept of an API Schema for a Gateway Target. AssetAPISchemaAPI Schema from a local asset. AssetToolSchemaTool Schema from a local asset. BrowserCustomBrowser resource for AWS Bedrock Agent Core. BrowserCustomBaseAbstract base class for a Browser. BrowserNetworkConfigurationNetwork configuration for the Browser tool. BuiltinEvaluatorBuilt-in evaluators provided by Amazon Bedrock AgentCore. CfnAPIKeyCredentialProviderResource Type definition for AWS::BedrockAgentCore::ApiKeyCredentialProvider. CfnBrowserDefinition of AWS::BedrockAgentCore::Browser Resource Type. CfnBrowserCustomAgentCore Browser tool provides a fast, secure, cloud-based browser runtime to enable AI a CfnBrowserProfileResource definition for AWS::BedrockAgentCore::BrowserProfile. CfnCodeInterpreterCustomThe AgentCore Code Interpreter tool enables agents to securely execute code in isolated sa CfnConfigurationBundleDefinition of AWS::BedrockAgentCore::ConfigurationBundle Resource Type. CfnDatasetDefinition of AWS::BedrockAgentCore::Dataset Resource Type. CfnEvaluatorResource Type definition for AWS::BedrockAgentCore::Evaluator - Creates a custom evaluator CfnGatewayAmazon Bedrock AgentCore Gateway provides a unified connectivity layer between agents and CfnGatewayTargetAfter creating a gateway, you can add targets, which define the tools that your gateway wi CfnHarnessResource Type definition for AWS::BedrockAgentCore::Harness - a managed agentic loop servi CfnMemoryMemory allows AI agents to maintain both immediate and long-term knowledge, enabling conte CfnOAuth2CredentialProviderResource Type definition for AWS::BedrockAgentCore::OAuth2CredentialProvider. CfnOnlineEvaluationConfigResource Type definition for AWS::BedrockAgentCore::OnlineEvaluationConfig - Creates an on CfnPaymentConnectorResource Type definition for AWS::BedrockAgentCore::PaymentConnector. CfnPaymentCredentialProviderResource Type definition for AWS::BedrockAgentCore::PaymentCredentialProvider. CfnPaymentManagerResource Type definition for AWS::BedrockAgentCore::PaymentManager. CfnPolicyResource Type definition for AWS::BedrockAgentCore::Policy. CfnPolicyEngineResource Type definition for AWS::BedrockAgentCore::PolicyEngine. CfnResourcePolicyResource Type definition for AWS::BedrockAgentCore::ResourcePolicy. CfnRuntimeContains information about an agent runtime. An agent runtime is the execution environment CfnRuntimeEndpointAgentCore Runtime is a secure, serverless runtime purpose-built for deploying and scaling CfnWorkloadIdentityCreates a workload identity for Amazon Bedrock AgentCore. CodeInterpreterCustomCustom code interpreter resource for AWS Bedrock Agent Core. CodeInterpreterCustomBaseAbstract base class for a Code Interpreter. CodeInterpreterNetworkConfigurationNetwork configuration for the Code Interpreter tool. CustomJwtAuthorizerCustom JWT authorizer configuration implementation. DataSourceConfigConfiguration for the data source used in online evaluation. EvaluationLevelThe level at which a custom evaluator assesses agent performance. EvaluatorA custom evaluator for Amazon Bedrock AgentCore. EvaluatorBaseAbstract base class for Evaluator. EvaluatorConfigConfiguration for a custom evaluator. EvaluatorRatingScaleRepresents a rating scale for custom LLM-as-a-Judge evaluators. EvaluatorSelectorRepresents a reference to an evaluator for online evaluation. ExecutionStatusThe execution status of an online evaluation configuration. FilterOperatorFilter operators for online evaluation filtering. FilterValueA typed filter value for online evaluation filtering. GatewayGateway resource for AWS Bedrock Agent Core. GatewayAuthorizerFactory class for creating Gateway Authorizers. GatewayBase**************************************************************************** GatewayCredentialProviderFactory class for creating different Gateway Credential Providers. GatewayCustomClaimRepresents a custom claim validation configuration for Gateway JWT authorizers. GatewayExceptionLevelException levels for gateway. GatewayProtocolFactory class for instantiating Gateway Protocols. GatewayTargetDefines tools that your gateway will host. GatewayTargetBaseBase class for gateway target implementations. IAMAuthorizerAWS IAM authorizer configuration implementation. InlineAPISchemaClass to define an API Schema from an inline string. InlineToolSchemaClass to define a Tool Schema from an inline string. LambdaInterceptorA Lambda-based interceptor for Gateway. LambdaTargetConfigurationConfiguration for Lambda-based MCP targets. LoggingDestinationRepresents a logging destination for AgentCore Runtime. LogTypeLog types for AgentCore Runtime observability. ManagedMemoryStrategyManaged memory strategy that handles both built-in and override configurations. McpGatewaySearchTypeSearch types supported by MCP gateway. McpProtocolConfigurationMCP (Model Context Protocol) configuration implementation. MCPProtocolVersionMCP protocol versions. McpServerTargetConfigurationConfiguration for MCP Server-based targets. McpTargetConfigurationAbstract base class for MCP target configurations Provides common functionality for all MC MemoryLong-term memory store for extracted insights like user preferences, semantic facts and su MemoryBaseAbstract base class for a Memory. MemoryStrategyFactory class for creating memory strategies If you need long-term memory for context reca NetworkConfigurationAbstract base class for network configuration. NoAuthAuthorizerNo authorization configuration implementation. OAuth2CredentialProviderL2 construct for `AWS::BedrockAgentCore::OAuth2CredentialProvider`. OAuth2CredentialProviderIdentityPermsIAM actions for AgentCore OAuth2 credential providers (Token Vault). OAuth2CredentialProviderVendorBuilt-in OAuth2 vendors supported by `AWS::BedrockAgentCore::OAuth2CredentialProvider`. OnlineEvaluationBaseAbstract base class for OnlineEvaluationConfig. OnlineEvaluationConfigOnline evaluation configuration for Amazon Bedrock AgentCore. OpenAPITargetConfigurationConfiguration for OpenAPI-based MCP targets. ProtocolTypeProtocol configuration for Agent Runtime. RuntimeBedrock Agent Core Runtime Enables running containerized agents with specific network conf RuntimeAuthorizerConfigurationAbstract base class for runtime authorizer configurations. RuntimeBaseBase class for Agent Runtime. RuntimeCustomClaimRepresents a custom claim validation configuration for Runtime JWT authorizers. RuntimeEndpointBedrock Agent Core Runtime Endpoint Provides a stable endpoint for invoking agent runtimes RuntimeEndpointBaseBase class for Runtime Endpoint. RuntimeNetworkConfigurationNetwork configuration for the Runtime. S3APISchemaClass to define an API Schema from an S3 object. S3ToolSchemaClass to define a Tool Schema from an S3 object. SchemaDefinitionTypeSchema definition types. SelfManagedMemoryStrategyUse AgentCore memory for event storage with custom triggers. SmithyTargetConfigurationConfiguration for Smithy-based MCP targets. ToolSchema**************************************************************************** WorkloadIdentityL2 construct for `AWS::BedrockAgentCore::WorkloadIdentity`. WorkloadIdentityPermsIAM actions for AgentCore workload identities.

Interfaces 146

AddAPIGatewayTargetOptionsOptions for adding an API Gateway target to a gateway. AddEndpointOptionsOptions for adding an endpoint to the runtime. AddLambdaTargetOptionsOptions for adding a Lambda target to a gateway. AddMcpServerTargetOptionsOptions for adding an MCP Server target to a gateway. AddOpenAPITargetOptionsOptions for adding an OpenAPI target to a gateway. AddSmithyTargetOptionsOptions for adding a Smithy target to a gateway. AgentRuntimeAttributesAttributes for importing an existing Agent Runtime. APIGatewayTargetConfigurationPropsProperties for creating an API Gateway target configuration. APIGatewayToolConfigurationConfiguration for API Gateway tools. APIGatewayToolFilterConfiguration for filtering API Gateway tools. APIGatewayToolOverrideConfiguration for overriding API Gateway tool metadata. APIKeyAdditionalConfigurationAPI Key additional configuration. APIKeyCredentialProviderAttributesAttributes for importing an existing API key credential provider. APIKeyCredentialProviderOptionsAPI key credential provider ARNs for gateway outbound auth (Token Vault identity). APIKeyCredentialProviderPropsProperties for a new {@link ApiKeyCredentialProvider} (Token Vault resource). AtlassianOAuth2CredentialProviderPropsProps for {@link OAuth2CredentialProvider.usingAtlassian}. BrowserCustomAttributesAttributes for specifying an imported Browser Custom. BrowserCustomPropsProperties for creating a Browser resource. CategoricalRatingOptionA categorical rating scale option for custom evaluators. CfnAPIKeyCredentialProviderPropsProperties for defining a `CfnApiKeyCredentialProvider`. CfnBrowserCustomPropsProperties for defining a `CfnBrowserCustom`. CfnBrowserProfilePropsProperties for defining a `CfnBrowserProfile`. CfnBrowserPropsProperties for defining a `CfnBrowser`. CfnCodeInterpreterCustomPropsProperties for defining a `CfnCodeInterpreterCustom`. CfnConfigurationBundlePropsProperties for defining a `CfnConfigurationBundle`. CfnDatasetPropsProperties for defining a `CfnDataset`. CfnEvaluatorPropsProperties for defining a `CfnEvaluator`. CfnGatewayPropsProperties for defining a `CfnGateway`. CfnGatewayTargetPropsProperties for defining a `CfnGatewayTarget`. CfnHarnessPropsProperties for defining a `CfnHarness`. CfnMemoryPropsProperties for defining a `CfnMemory`. CfnOAuth2CredentialProviderPropsProperties for defining a `CfnOAuth2CredentialProvider`. CfnOnlineEvaluationConfigPropsProperties for defining a `CfnOnlineEvaluationConfig`. CfnPaymentConnectorPropsProperties for defining a `CfnPaymentConnector`. CfnPaymentCredentialProviderPropsProperties for defining a `CfnPaymentCredentialProvider`. CfnPaymentManagerPropsProperties for defining a `CfnPaymentManager`. CfnPolicyEnginePropsProperties for defining a `CfnPolicyEngine`. CfnPolicyPropsProperties for defining a `CfnPolicy`. CfnResourcePolicyPropsProperties for defining a `CfnResourcePolicy`. CfnRuntimeEndpointPropsProperties for defining a `CfnRuntimeEndpoint`. CfnRuntimePropsProperties for defining a `CfnRuntime`. CfnWorkloadIdentityPropsProperties for defining a `CfnWorkloadIdentity`. CloudWatchLogsDataSourceConfigConfiguration for CloudWatch Logs data source. CodeAssetOptionsOptions for configuring an S3 code asset from local files for agent runtime artifact. CodeBasedOptionsOptions for configuring a code-based custom evaluator using a Lambda function. CodeInterpreterCustomAttributesAttributes for specifying an imported Code Interpreter Custom. CodeInterpreterCustomPropsProperties for creating a CodeInterpreter resource. CognitoAuthorizerProps**************************************************************************** CustomJwtConfigurationCustom JWT authorizer configuration. CustomOAuth2CredentialProviderPropsProps for {@link OAuth2CredentialProvider.usingCustom}. DataSourceConfigBindResultThe result of binding a DataSourceConfig. DropboxOAuth2CredentialProviderPropsProps for {@link OAuth2CredentialProvider.usingDropbox}. EpisodicReflectionConfigurationConfiguration for episodic memory reflection. EvaluatorAttributesAttributes for importing an existing Evaluator. EvaluatorInferenceConfigInference configuration for a custom LLM-as-a-Judge evaluator. EvaluatorPropsProperties for creating an Evaluator. EvaluatorSelectorBindResultThe result of binding an EvaluatorSelector. FacebookOAuth2CredentialProviderPropsProps for {@link OAuth2CredentialProvider.usingFacebook}. FilterConfigFilter configuration for online evaluation. FromAPIKeyIdentityOptionsOptional gateway settings when binding an {@link IApiKeyCredentialProvider} to a target. FromOauthIdentityOptionsOAuth scopes (and optional custom parameters) when binding an {@link IOAuth2CredentialProv GatewayAPIKeyIdentityBindingProvider and secret ARNs for wiring a Token Vault API key identity into a gateway target. GatewayAttributesAttributes for importing an existing Gateway. GatewayIAMRoleCredentialProviderPropsProperties for configuring the IAM role credential provider. GatewayOAuth2IdentityBindingProvider ARN, secret ARN, and OAuth scopes for wiring a Token Vault OAuth2 identity into a GatewayPropsProperties for defining a Gateway. GatewayTargetAPIGatewayPropsProperties for creating an API Gateway-based Gateway Target. GatewayTargetAttributesAttributes for importing an existing Gateway Target. GatewayTargetCommonPropsCommon properties for all Gateway Target types. GatewayTargetLambdaPropsProperties for creating a Lambda-based Gateway Target Convenience interface for the most c GatewayTargetMcpServerPropsProperties for creating an MCP Server-based Gateway Target. GatewayTargetOpenAPIPropsProperties for creating an OpenAPI-based Gateway Target. GatewayTargetPropsProperties for creating a Gateway Target resource. GatewayTargetSmithyPropsProperties for creating a Smithy-based Gateway Target. GithubOAuth2CredentialProviderPropsProps for {@link OAuth2CredentialProvider.usingGithub}. GoogleOAuth2CredentialProviderPropsProps for {@link OAuth2CredentialProvider.usingGoogle}. HubspotOAuth2CredentialProviderPropsProps for {@link OAuth2CredentialProvider.usingHubspot}. IAPIKeyCredentialProviderAn API key credential provider registered in AgentCore Token Vault. IBedrockAgentRuntimeInterface for Agent Runtime resources. IBrowserCustomInterface for Browser resources. ICodeInterpreterCustomInterface for CodeInterpreterCustom resources. ICredentialProviderConfigAbstract interface for gateway credential provider configuration. IEvaluatorInterface for Evaluator resources. IGatewayInterface for Gateway resources. IGatewayAuthorizerConfigAbstract interface for gateway authorizer configuration. IGatewayProtocolConfigAbstract interface for gateway protocol configuration. IGatewayTargetInterface for GatewayTarget resources. IInterceptorRepresents an interceptor that can be bound to a Gateway. IMcpGatewayTargetInterface for MCP gateway targets. IMemoryInterface for Memory resources. IMemoryStrategyInterface for Memory strategies. IncludedOauth2TenantCredentialProviderPropsProps for `IncludedOauth2ProviderConfig` IdPs whose [outbound documentation](https://docs. IncludedOauth2TenantEndpointsOptional tenant OAuth endpoints for IdPs that use CloudFormation `IncludedOauth2ProviderCo InterceptorBindConfigConfiguration returned from binding an interceptor to a Gateway. InterceptorOptionsOptions for configuring an interceptor. InvocationConfigurationInvocation configuration for self managed memory strategy. IOAuth2CredentialProviderAn OAuth2 credential provider registered in AgentCore Token Vault. IOnlineEvaluationConfigInterface for OnlineEvaluationConfig resources. IRuntimeEndpointInterface for Runtime Endpoint resources. ITargetConfigurationBase interface for target configurations. IWorkloadIdentityA workload identity for Amazon Bedrock AgentCore. LifecycleConfigurationLifecycleConfiguration lets you manage the lifecycle of runtime sessions and resources in LinkedinOAuth2CredentialProviderPropsProps for {@link OAuth2CredentialProvider.usingLinkedin}. LlmAsAJudgeOptionsOptions for configuring an LLM-as-a-Judge custom evaluator. LoggingConfigConfiguration for logging with log type and destination. ManagedStrategyPropsConfiguration parameters for a memory strategy that can override existing built-in default McpConfigurationMCP protocol configuration The configuration for the Model Context Protocol (MCP). MemoryAttributesAttributes for specifying an imported Memory. MemoryPropsProperties for creating a Memory resource. MemoryStrategyCommonPropsConfiguration parameters common for any memory strategy. MetadataConfigurationConfiguration for passing metadata (headers and query parameters) to the API Gateway targe MicrosoftOAuth2CredentialProviderPropsProps for {@link OAuth2CredentialProvider.usingMicrosoft}. NotionOAuth2CredentialProviderPropsProps for {@link OAuth2CredentialProvider.usingNotion}. NumericalRatingOptionA numerical rating scale option for custom evaluators. OAuth2AuthorizationServerMetadataStatic OAuth2 authorization server metadata for custom credential providers. OAuth2ClientCredentialsOAuth2 client identifier and secret registered with the identity provider (all vendors). OAuth2CredentialProviderAttributesAttributes for importing an existing OAuth2 credential provider. OAuth2CredentialProviderBasePropsShared properties for OAuth2 credential providers created via {@link OAuth2CredentialProvi OAuth2CredentialProviderFactoryBasePropsNaming, tags, and client credentials shared by every {@link OAuth2CredentialProvider} fact OAuth2CredentialProviderPropsLow-level properties when you need full control (prefer {@link OAuth2CredentialProvider.us OAuthConfigurationOAuth configuration. OnlineEvaluationBasePropsBase properties for creating an OnlineEvaluationConfig. OnlineEvaluationConfigAttributesAttributes for importing an existing OnlineEvaluationConfig. OnlineEvaluationConfigPropsProperties for creating an OnlineEvaluationConfig. OverrideConfigConfiguration for overriding model and prompt template. RecordingConfigRecording configuration for browser. RedditOAuth2CredentialProviderPropsProps for {@link OAuth2CredentialProvider.usingReddit}. RequestHeaderConfigurationConfiguration for HTTP request headers that will be passed through to the runtime. RuntimeEndpointAttributesAttributes for importing an existing Runtime Endpoint. RuntimeEndpointPropsProperties for creating a Bedrock Agent Core Runtime Endpoint resource. RuntimePropsProperties for creating a Bedrock Agent Core Runtime resource. SalesforceOAuth2CredentialProviderPropsProps for {@link OAuth2CredentialProvider.usingSalesforce}. SchemaDefinitionSchema definition for tool input/output. SelfManagedStrategyPropsConfiguration parameters for a self managed memory strategy existing built-in default prom SlackOAuth2CredentialProviderPropsProps for {@link OAuth2CredentialProvider.usingSlack}. SpotifyOAuth2CredentialProviderPropsProps for {@link OAuth2CredentialProvider.usingSpotify}. TargetConfigurationConfigConfiguration returned by binding a target configuration. ToolDefinitionTool definition for inline payload. TriggerConditionsTrigger conditions for self managed memory strategy When first condition is met, batched p TwitchOAuth2CredentialProviderPropsProps for {@link OAuth2CredentialProvider.usingTwitch}. VPCConfigPropsVPC configuration properties. WorkloadIdentityAttributesAttributes for importing an existing workload identity. WorkloadIdentityPropsProperties for a new {@link WorkloadIdentity}. XOAuth2CredentialProviderPropsProps for {@link OAuth2CredentialProvider.usingX}. YandexOAuth2CredentialProviderPropsProps for {@link OAuth2CredentialProvider.usingYandex}. ZoomOAuth2CredentialProviderPropsProps for {@link OAuth2CredentialProvider.usingZoom}.

Enums 8

BrowserSigningBrowser signing. CredentialProviderTypeCredential provider types supported by gateway target. CustomClaimOperatorCustom claim match operator. GatewayAuthorizerTypeGateway authorizer type. GatewayTargetProtocolTypeProtocol types supported by gateway targets. InterceptionPointThe interception point where the interceptor will be invoked. McpTargetTypeMCP target types. MemoryStrategyTypeLong-term memory extraction strategy types.