Amazon Bedrock AgentCore Construct Library
| Language | Package |
|---|---|
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:CreateServiceLinkedRolepermission for AgentCore service-linked roles.
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:
- Using Runtime.addEndpoint() - Convenient method when creating endpoints alongside the runtime.
- Using RuntimeEndpoint - Flexible approach for existing runtimes.
For example, you might keep a "production" endpoint on a stable version while testing newer versions through a "staging" endpoint. This separation allows you to test changes thoroughly before promoting them to production by simply updating the endpoint to point to the newer version.
AgentCore Runtime Properties
| Name | Type | Required | Description |
|---|---|---|---|
runtimeName | string | No | The name of the agent runtime. Valid characters are a-z, A-Z, 0-9, _ (underscore). Must start with a letter and can be up to 48 characters long. If not provided, a unique name will be auto-generated |
agentRuntimeArtifact | AgentRuntimeArtifact | Yes | The artifact configuration for the agent runtime containing the container configuration with ECR URI |
executionRole | iam.IRole | No | The IAM role that provides permissions for the agent runtime. If not provided, a role will be created automatically |
networkConfiguration | NetworkConfiguration | No | Network configuration for the agent runtime. Defaults to RuntimeNetworkConfiguration.usingPublicNetwork() |
description | string | No | Optional description for the agent runtime |
protocolConfiguration | ProtocolType | No | Protocol configuration for the agent runtime. Defaults to ProtocolType.HTTP |
platformVersion | PlatformVersion | No | The platform version of the runtime (for example PlatformVersion.V1 or PlatformVersion.V2). Defaults to the service default platform version |
authorizerConfiguration | RuntimeAuthorizerConfiguration | No | Authorizer configuration for the agent runtime. Use RuntimeAuthorizerConfiguration static methods to create configurations for IAM, Cognito, JWT, or OAuth authentication |
environmentVariables | { [key: string]: string } | No | Environment variables for the agent runtime. Maximum 50 environment variables |
tags | { [key: string]: string } | No | Tags for the agent runtime. A list of key:value pairs of tags to apply to this Runtime resource |
lifecycleConfiguration | LifecycleConfiguration | No | The life cycle configuration for the AgentCore Runtime. Defaults to 900 seconds (15 minutes) for idle, 28800 seconds (8 hours) for max life time |
requestHeaderConfiguration | RequestHeaderConfiguration | No | Configuration for HTTP request headers that will be passed through to the runtime. Defaults to no configuration |
tracingEnabled | boolean | No | Whether to enable X-Ray tracing for this runtime. When enabled, traces will be delivered to AWS X-Ray. Defaults to false |
loggingConfigs | LoggingConfig[] | No | Logging configuration for the runtime. Allows sending APPLICATION_LOGS and USAGE_LOGS to CloudWatch Logs, S3, or Kinesis Data Firehose. Defaults to no logging configured |
manageDeliveryResourcePolicy | boolean | No | Whether to create resource policies for log/trace delivery. When false, the AWS::Logs::ResourcePolicy and AWS::XRay::ResourcePolicy are not created. This is useful when deploying many runtimes per account/Region, as each resource policy consumes an account-level quota slot (CloudWatch Logs: 10, X-Ray: lower). For same-account /aws/vendedlogs/ delivery, the log-delivery service-linked role provides the necessary write access without an explicit policy. Defaults to true |
Runtime Endpoint Properties
| Name | Type | Required | Description |
|---|---|---|---|
endpointName | string | No | The name of the runtime endpoint. Valid characters are a-z, A-Z, 0-9, _ (underscore). Must start with a letter and can be up to 48 characters long. If not provided, a unique name will be auto-generated |
agentRuntimeId | string | Yes | The Agent Runtime ID for this endpoint |
agentRuntimeVersion | string | Yes | The Agent Runtime version for this endpoint. Must be between 1 and 5 characters long. |
description | string | No | Optional description for the runtime endpoint |
tags | { [key: string]: string } | No | Tags for the runtime endpoint |
Creating a Runtime
Option 1: Use an existing image in ECR
Reference an image available within ECR.
const repository = new ecr.Repository(this, "TestRepository", {
repositoryName: "test-agent-runtime",
});
// The runtime by default create ECR permission only for the repository available in the account the stack is being deployed
const agentRuntimeArtifact = agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
// Create runtime using the built image
const runtime = new agentcore.Runtime(this, "MyAgentRuntime", {
runtimeName: "myAgent",
agentRuntimeArtifact: agentRuntimeArtifact
});
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
# The runtime by default create ECR permission only for the repository available in the account the stack is being deployed
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
# Create runtime using the built image
runtime = agentcore.Runtime(self, "MyAgentRuntime",
runtime_name="myAgent",
agent_runtime_artifact=agent_runtime_artifact
)
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
// The runtime by default create ECR permission only for the repository available in the account the stack is being deployed
AgentRuntimeArtifact agentRuntimeArtifact = AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
// Create runtime using the built image
Runtime runtime = Runtime.Builder.create(this, "MyAgentRuntime")
.runtimeName("myAgent")
.agentRuntimeArtifact(agentRuntimeArtifact)
.build();
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
// The runtime by default create ECR permission only for the repository available in the account the stack is being deployed
var agentRuntimeArtifact = AgentRuntimeArtifact.FromEcrRepository(repository, "v1.0.0");
// Create runtime using the built image
var runtime = new Runtime(this, "MyAgentRuntime", new RuntimeProps {
RuntimeName = "myAgent",
AgentRuntimeArtifact = agentRuntimeArtifact
});
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
// The runtime by default create ECR permission only for the repository available in the account the stack is being deployed
agentRuntimeArtifact := agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v1.0.0"))
// Create runtime using the built image
runtime := agentcore.NewRuntime(this, jsii.String("MyAgentRuntime"), &RuntimeProps{
RuntimeName: jsii.String("myAgent"),
AgentRuntimeArtifact: agentRuntimeArtifact,
})
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.
const agentRuntimeArtifact = agentcore.AgentRuntimeArtifact.fromAsset(
path.join(__dirname, "path to agent dockerfile directory")
);
const runtime = new agentcore.Runtime(this, "MyAgentRuntime", {
runtimeName: "myAgent",
agentRuntimeArtifact: agentRuntimeArtifact,
});
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_asset(
path.join(__dirname, "path to agent dockerfile directory"))
runtime = agentcore.Runtime(self, "MyAgentRuntime",
runtime_name="myAgent",
agent_runtime_artifact=agent_runtime_artifact
)
AgentRuntimeArtifact agentRuntimeArtifact = AgentRuntimeArtifact.fromAsset(path.join(__dirname, "path to agent dockerfile directory"));
Runtime runtime = Runtime.Builder.create(this, "MyAgentRuntime")
.runtimeName("myAgent")
.agentRuntimeArtifact(agentRuntimeArtifact)
.build();
var agentRuntimeArtifact = AgentRuntimeArtifact.FromAsset(path.Join(__dirname, "path to agent dockerfile directory"));
var runtime = new Runtime(this, "MyAgentRuntime", new RuntimeProps {
RuntimeName = "myAgent",
AgentRuntimeArtifact = agentRuntimeArtifact
});
agentRuntimeArtifact := agentcore.AgentRuntimeArtifact_FromAsset(path.join(__dirname, jsii.String("path to agent dockerfile directory")))
runtime := agentcore.NewRuntime(this, jsii.String("MyAgentRuntime"), &RuntimeProps{
RuntimeName: jsii.String("myAgent"),
AgentRuntimeArtifact: agentRuntimeArtifact,
})
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
const codeBucket = new s3.Bucket(this, "AgentCode", {
bucketName: "my-code-bucket",
removalPolicy: RemovalPolicy.DESTROY, // For demo purposes
});
// the bucket above needs to contain the agent code
const agentRuntimeArtifact = agentcore.AgentRuntimeArtifact.fromS3(
{
bucketName: codeBucket.bucketName,
objectKey: 'deployment_package.zip',
},
agentcore.AgentCoreRuntime.PYTHON_3_12,
['opentelemetry-instrument', 'main.py']
);
const runtimeInstance = new agentcore.Runtime(this, "MyAgentRuntime", {
runtimeName: "myAgent",
agentRuntimeArtifact: agentRuntimeArtifact,
});
# S3 bucket containing the agent core
code_bucket = s3.Bucket(self, "AgentCode",
bucket_name="my-code-bucket",
removal_policy=RemovalPolicy.DESTROY
)
# the bucket above needs to contain the agent code
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_s3(s3.Location(
bucket_name=code_bucket.bucket_name,
object_key="deployment_package.zip"
), agentcore.AgentCoreRuntime.PYTHON_3_12, ["opentelemetry-instrument", "main.py"])
runtime_instance = agentcore.Runtime(self, "MyAgentRuntime",
runtime_name="myAgent",
agent_runtime_artifact=agent_runtime_artifact
)
// S3 bucket containing the agent core
Bucket codeBucket = Bucket.Builder.create(this, "AgentCode")
.bucketName("my-code-bucket")
.removalPolicy(RemovalPolicy.DESTROY)
.build();
// the bucket above needs to contain the agent code
AgentRuntimeArtifact agentRuntimeArtifact = AgentRuntimeArtifact.fromS3(Location.builder()
.bucketName(codeBucket.getBucketName())
.objectKey("deployment_package.zip")
.build(), AgentCoreRuntime.PYTHON_3_12, List.of("opentelemetry-instrument", "main.py"));
Runtime runtimeInstance = Runtime.Builder.create(this, "MyAgentRuntime")
.runtimeName("myAgent")
.agentRuntimeArtifact(agentRuntimeArtifact)
.build();
// S3 bucket containing the agent core
var codeBucket = new Bucket(this, "AgentCode", new BucketProps {
BucketName = "my-code-bucket",
RemovalPolicy = RemovalPolicy.DESTROY
});
// the bucket above needs to contain the agent code
var agentRuntimeArtifact = AgentRuntimeArtifact.FromS3(new Location {
BucketName = codeBucket.BucketName,
ObjectKey = "deployment_package.zip"
}, AgentCoreRuntime.PYTHON_3_12, new [] { "opentelemetry-instrument", "main.py" });
var runtimeInstance = new Runtime(this, "MyAgentRuntime", new RuntimeProps {
RuntimeName = "myAgent",
AgentRuntimeArtifact = agentRuntimeArtifact
});
// S3 bucket containing the agent core
codeBucket := s3.NewBucket(this, jsii.String("AgentCode"), &BucketProps{
BucketName: jsii.String("my-code-bucket"),
RemovalPolicy: awscdk.RemovalPolicy_DESTROY,
})
// the bucket above needs to contain the agent code
agentRuntimeArtifact := agentcore.AgentRuntimeArtifact_FromS3(&Location{
BucketName: codeBucket.bucketName,
ObjectKey: jsii.String("deployment_package.zip"),
}, agentcore.AgentCoreRuntime_PYTHON_3_12(), []*string{
jsii.String("opentelemetry-instrument"),
jsii.String("main.py"),
})
runtimeInstance := agentcore.NewRuntime(this, jsii.String("MyAgentRuntime"), &RuntimeProps{
RuntimeName: jsii.String("myAgent"),
AgentRuntimeArtifact: agentRuntimeArtifact,
})
Alternatively, you can use local code assets that will be automatically packaged and uploaded to a CDK-managed S3 bucket:
const agentRuntimeArtifact = agentcore.AgentRuntimeArtifact.fromCodeAsset({
path: path.join(__dirname, 'path/to/agent/code'),
runtime: agentcore.AgentCoreRuntime.PYTHON_3_12,
entrypoint: ['opentelemetry-instrument', 'main.py'],
});
const runtimeInstance = new agentcore.Runtime(this, "MyAgentRuntime", {
runtimeName: "myAgent",
agentRuntimeArtifact: agentRuntimeArtifact,
});
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_code_asset(
path=path.join(__dirname, "path/to/agent/code"),
runtime=agentcore.AgentCoreRuntime.PYTHON_3_12,
entrypoint=["opentelemetry-instrument", "main.py"]
)
runtime_instance = agentcore.Runtime(self, "MyAgentRuntime",
runtime_name="myAgent",
agent_runtime_artifact=agent_runtime_artifact
)
AgentRuntimeArtifact agentRuntimeArtifact = AgentRuntimeArtifact.fromCodeAsset(CodeAssetOptions.builder()
.path(path.join(__dirname, "path/to/agent/code"))
.runtime(AgentCoreRuntime.PYTHON_3_12)
.entrypoint(List.of("opentelemetry-instrument", "main.py"))
.build());
Runtime runtimeInstance = Runtime.Builder.create(this, "MyAgentRuntime")
.runtimeName("myAgent")
.agentRuntimeArtifact(agentRuntimeArtifact)
.build();
var agentRuntimeArtifact = AgentRuntimeArtifact.FromCodeAsset(new CodeAssetOptions {
Path = path.Join(__dirname, "path/to/agent/code"),
Runtime = AgentCoreRuntime.PYTHON_3_12,
Entrypoint = new [] { "opentelemetry-instrument", "main.py" }
});
var runtimeInstance = new Runtime(this, "MyAgentRuntime", new RuntimeProps {
RuntimeName = "myAgent",
AgentRuntimeArtifact = agentRuntimeArtifact
});
agentRuntimeArtifact := agentcore.AgentRuntimeArtifact_FromCodeAsset(&CodeAssetOptions{
Path: path.join(__dirname, jsii.String("path/to/agent/code")),
Runtime: agentcore.AgentCoreRuntime_PYTHON_3_12(),
Entrypoint: []*string{
jsii.String("opentelemetry-instrument"),
jsii.String("main.py"),
},
})
runtimeInstance := agentcore.NewRuntime(this, jsii.String("MyAgentRuntime"), &RuntimeProps{
RuntimeName: jsii.String("myAgent"),
AgentRuntimeArtifact: agentRuntimeArtifact,
})
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
const agentRuntimeArtifact = agentcore.AgentRuntimeArtifact.fromImageUri(
"123456789012.dkr.ecr.us-east-1.amazonaws.com/my-agent:v1.0.0"
);
const runtime = new agentcore.Runtime(this, "MyAgentRuntime", {
runtimeName: "myAgent",
agentRuntimeArtifact: agentRuntimeArtifact,
});
# Direct URI reference
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_image_uri("123456789012.dkr.ecr.us-east-1.amazonaws.com/my-agent:v1.0.0")
runtime = agentcore.Runtime(self, "MyAgentRuntime",
runtime_name="myAgent",
agent_runtime_artifact=agent_runtime_artifact
)
// Direct URI reference
AgentRuntimeArtifact agentRuntimeArtifact = AgentRuntimeArtifact.fromImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/my-agent:v1.0.0");
Runtime runtime = Runtime.Builder.create(this, "MyAgentRuntime")
.runtimeName("myAgent")
.agentRuntimeArtifact(agentRuntimeArtifact)
.build();
// Direct URI reference
var agentRuntimeArtifact = AgentRuntimeArtifact.FromImageUri("123456789012.dkr.ecr.us-east-1.amazonaws.com/my-agent:v1.0.0");
var runtime = new Runtime(this, "MyAgentRuntime", new RuntimeProps {
RuntimeName = "myAgent",
AgentRuntimeArtifact = agentRuntimeArtifact
});
// Direct URI reference
agentRuntimeArtifact := agentcore.AgentRuntimeArtifact_FromImageUri(jsii.String("123456789012.dkr.ecr.us-east-1.amazonaws.com/my-agent:v1.0.0"))
runtime := agentcore.NewRuntime(this, jsii.String("MyAgentRuntime"), &RuntimeProps{
RuntimeName: jsii.String("myAgent"),
AgentRuntimeArtifact: agentRuntimeArtifact,
})
You can also use CloudFormation parameters or references:
// Using a CloudFormation parameter
const imageUriParam = new cdk.CfnParameter(this, "ImageUri", {
type: "String",
description: "Container image URI for the agent runtime",
});
const agentRuntimeArtifact = agentcore.AgentRuntimeArtifact.fromImageUri(
imageUriParam.valueAsString
);
const runtime = new agentcore.Runtime(this, "MyAgentRuntime", {
runtimeName: "myAgent",
agentRuntimeArtifact: agentRuntimeArtifact,
});
# Using a CloudFormation parameter
image_uri_param = cdk.CfnParameter(self, "ImageUri",
type="String",
description="Container image URI for the agent runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_image_uri(image_uri_param.value_as_string)
runtime = agentcore.Runtime(self, "MyAgentRuntime",
runtime_name="myAgent",
agent_runtime_artifact=agent_runtime_artifact
)
// Using a CloudFormation parameter
CfnParameter imageUriParam = CfnParameter.Builder.create(this, "ImageUri")
.type("String")
.description("Container image URI for the agent runtime")
.build();
AgentRuntimeArtifact agentRuntimeArtifact = AgentRuntimeArtifact.fromImageUri(imageUriParam.getValueAsString());
Runtime runtime = Runtime.Builder.create(this, "MyAgentRuntime")
.runtimeName("myAgent")
.agentRuntimeArtifact(agentRuntimeArtifact)
.build();
// Using a CloudFormation parameter
var imageUriParam = new CfnParameter(this, "ImageUri", new CfnParameterProps {
Type = "String",
Description = "Container image URI for the agent runtime"
});
var agentRuntimeArtifact = AgentRuntimeArtifact.FromImageUri(imageUriParam.ValueAsString);
var runtime = new Runtime(this, "MyAgentRuntime", new RuntimeProps {
RuntimeName = "myAgent",
AgentRuntimeArtifact = agentRuntimeArtifact
});
// Using a CloudFormation parameter
imageUriParam := cdk.NewCfnParameter(this, jsii.String("ImageUri"), &CfnParameterProps{
Type: jsii.String("String"),
Description: jsii.String("Container image URI for the agent runtime"),
})
agentRuntimeArtifact := agentcore.AgentRuntimeArtifact_FromImageUri(imageUriParam.valueAsString)
runtime := agentcore.NewRuntime(this, jsii.String("MyAgentRuntime"), &RuntimeProps{
RuntimeName: jsii.String("myAgent"),
AgentRuntimeArtifact: agentRuntimeArtifact,
})
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
declare const runtime: agentcore.Runtime;
// Define the Bedrock Foundation Model
const model = bedrock.FoundationModel.fromFoundationModelId(this, 'Model',
bedrock.FoundationModelIdentifier.ANTHROPIC_CLAUDE_3_7_SONNET_20250219_V1_0,
);
// Grant the runtime permissions to invoke the model
runtime.role.addToPrincipalPolicy(new iam.PolicyStatement({
actions: ['bedrock:InvokeModel'],
resources: [model.modelArn],
}));
# Note: This example uses aws-cdk-lib/aws-bedrock for foundation model references
# runtime: agentcore.Runtime
# Define the Bedrock Foundation Model
model = bedrock.FoundationModel.from_foundation_model_id(self, "Model", bedrock.FoundationModelIdentifier.ANTHROPIC_CLAUDE_3_7_SONNET_20250219_V1_0)
# Grant the runtime permissions to invoke the model
runtime.role.add_to_principal_policy(iam.PolicyStatement(
actions=["bedrock:InvokeModel"],
resources=[model.model_arn]
))
// Note: This example uses aws-cdk-lib/aws-bedrock for foundation model references
Runtime runtime;
// Define the Bedrock Foundation Model
FoundationModel model = FoundationModel.fromFoundationModelId(this, "Model", FoundationModelIdentifier.ANTHROPIC_CLAUDE_3_7_SONNET_20250219_V1_0);
// Grant the runtime permissions to invoke the model
runtime.role.addToPrincipalPolicy(PolicyStatement.Builder.create()
.actions(List.of("bedrock:InvokeModel"))
.resources(List.of(model.getModelArn()))
.build());
// Note: This example uses aws-cdk-lib/aws-bedrock for foundation model references
Runtime runtime;
// Define the Bedrock Foundation Model
var model = FoundationModel.FromFoundationModelId(this, "Model", FoundationModelIdentifier.ANTHROPIC_CLAUDE_3_7_SONNET_20250219_V1_0);
// Grant the runtime permissions to invoke the model
runtime.Role.AddToPrincipalPolicy(new PolicyStatement(new PolicyStatementProps {
Actions = new [] { "bedrock:InvokeModel" },
Resources = new [] { model.ModelArn }
}));
// Note: This example uses aws-cdk-lib/aws-bedrock for foundation model references
var runtime Runtime
// Define the Bedrock Foundation Model
model := bedrock.FoundationModel_FromFoundationModelId(this, jsii.String("Model"), bedrock.FoundationModelIdentifier_ANTHROPIC_CLAUDE_3_7_SONNET_20250219_V1_0())
// Grant the runtime permissions to invoke the model
runtime.Role.AddToPrincipalPolicy(iam.NewPolicyStatement(&PolicyStatementProps{
Actions: []*string{
jsii.String("bedrock:InvokeModel"),
},
Resources: []*string{
model.ModelArn,
},
}))
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.
const repository = new ecr.Repository(this, "TestRepository", {
repositoryName: "test-agent-runtime",
});
const runtime = new agentcore.Runtime(this, "MyAgentRuntime", {
runtimeName: "myAgent",
agentRuntimeArtifact: agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0"),
});
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
runtime = agentcore.Runtime(self, "MyAgentRuntime",
runtime_name="myAgent",
agent_runtime_artifact=agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
)
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
Runtime runtime = Runtime.Builder.create(this, "MyAgentRuntime")
.runtimeName("myAgent")
.agentRuntimeArtifact(AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0"))
.build();
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
var runtime = new Runtime(this, "MyAgentRuntime", new RuntimeProps {
RuntimeName = "myAgent",
AgentRuntimeArtifact = AgentRuntimeArtifact.FromEcrRepository(repository, "v1.0.0")
});
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
runtime := agentcore.NewRuntime(this, jsii.String("MyAgentRuntime"), &RuntimeProps{
RuntimeName: jsii.String("myAgent"),
AgentRuntimeArtifact: agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("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.
const repository = new ecr.Repository(this, "TestRepository", {
repositoryName: "test-agent-runtime",
});
const runtime = new agentcore.Runtime(this, "MyAgentRuntime", {
runtimeName: "myAgent",
agentRuntimeArtifact: agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0"),
});
const prodEndpoint = runtime.addEndpoint("production", {
version: "1",
description: "Stable production endpoint - pinned to v1"
});
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
runtime = agentcore.Runtime(self, "MyAgentRuntime",
runtime_name="myAgent",
agent_runtime_artifact=agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
)
prod_endpoint = runtime.add_endpoint("production",
version="1",
description="Stable production endpoint - pinned to v1"
)
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
Runtime runtime = Runtime.Builder.create(this, "MyAgentRuntime")
.runtimeName("myAgent")
.agentRuntimeArtifact(AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0"))
.build();
RuntimeEndpoint prodEndpoint = runtime.addEndpoint("production", AddEndpointOptions.builder()
.version("1")
.description("Stable production endpoint - pinned to v1")
.build());
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
var runtime = new Runtime(this, "MyAgentRuntime", new RuntimeProps {
RuntimeName = "myAgent",
AgentRuntimeArtifact = AgentRuntimeArtifact.FromEcrRepository(repository, "v1.0.0")
});
var prodEndpoint = runtime.AddEndpoint("production", new AddEndpointOptions {
Version = "1",
Description = "Stable production endpoint - pinned to v1"
});
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
runtime := agentcore.NewRuntime(this, jsii.String("MyAgentRuntime"), &RuntimeProps{
RuntimeName: jsii.String("myAgent"),
AgentRuntimeArtifact: agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v1.0.0")),
})
prodEndpoint := runtime.AddEndpoint(jsii.String("production"), &AddEndpointOptions{
Version: jsii.String("1"),
Description: jsii.String("Stable production endpoint - pinned to v1"),
})
Step 3: Runtime Update Deployment
When you update the runtime configuration (such as updating the container image, modifying network settings, or changing protocol configurations), AgentCore automatically creates a new version (Version 2). Upon this update:
- Version 2 is created automatically with the new configuration
- The DEFAULT endpoint automatically updates to point to Version 2
- Any explicitly pinned endpoints (like the production endpoint) remain on their specified versions
const repository = new ecr.Repository(this, "TestRepository", {
repositoryName: "test-agent-runtime",
});
const agentRuntimeArtifactNew = agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, "v2.0.0");
const runtime = new agentcore.Runtime(this, "MyAgentRuntime", {
runtimeName: "myAgent",
agentRuntimeArtifact: agentRuntimeArtifactNew,
});
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
agent_runtime_artifact_new = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v2.0.0")
runtime = agentcore.Runtime(self, "MyAgentRuntime",
runtime_name="myAgent",
agent_runtime_artifact=agent_runtime_artifact_new
)
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
AgentRuntimeArtifact agentRuntimeArtifactNew = AgentRuntimeArtifact.fromEcrRepository(repository, "v2.0.0");
Runtime runtime = Runtime.Builder.create(this, "MyAgentRuntime")
.runtimeName("myAgent")
.agentRuntimeArtifact(agentRuntimeArtifactNew)
.build();
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
var agentRuntimeArtifactNew = AgentRuntimeArtifact.FromEcrRepository(repository, "v2.0.0");
var runtime = new Runtime(this, "MyAgentRuntime", new RuntimeProps {
RuntimeName = "myAgent",
AgentRuntimeArtifact = agentRuntimeArtifactNew
});
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
agentRuntimeArtifactNew := agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v2.0.0"))
runtime := agentcore.NewRuntime(this, jsii.String("MyAgentRuntime"), &RuntimeProps{
RuntimeName: jsii.String("myAgent"),
AgentRuntimeArtifact: agentRuntimeArtifactNew,
})
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.
const repository = new ecr.Repository(this, "TestRepository", {
repositoryName: "test-agent-runtime",
});
const agentRuntimeArtifactNew = agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, "v2.0.0");
const runtime = new agentcore.Runtime(this, "MyAgentRuntime", {
runtimeName: "myAgent",
agentRuntimeArtifact: agentRuntimeArtifactNew,
});
const stagingEndpoint = runtime.addEndpoint("staging", {
version: "2",
description: "Staging environment for testing new version"
});
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
agent_runtime_artifact_new = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v2.0.0")
runtime = agentcore.Runtime(self, "MyAgentRuntime",
runtime_name="myAgent",
agent_runtime_artifact=agent_runtime_artifact_new
)
staging_endpoint = runtime.add_endpoint("staging",
version="2",
description="Staging environment for testing new version"
)
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
AgentRuntimeArtifact agentRuntimeArtifactNew = AgentRuntimeArtifact.fromEcrRepository(repository, "v2.0.0");
Runtime runtime = Runtime.Builder.create(this, "MyAgentRuntime")
.runtimeName("myAgent")
.agentRuntimeArtifact(agentRuntimeArtifactNew)
.build();
RuntimeEndpoint stagingEndpoint = runtime.addEndpoint("staging", AddEndpointOptions.builder()
.version("2")
.description("Staging environment for testing new version")
.build());
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
var agentRuntimeArtifactNew = AgentRuntimeArtifact.FromEcrRepository(repository, "v2.0.0");
var runtime = new Runtime(this, "MyAgentRuntime", new RuntimeProps {
RuntimeName = "myAgent",
AgentRuntimeArtifact = agentRuntimeArtifactNew
});
var stagingEndpoint = runtime.AddEndpoint("staging", new AddEndpointOptions {
Version = "2",
Description = "Staging environment for testing new version"
});
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
agentRuntimeArtifactNew := agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v2.0.0"))
runtime := agentcore.NewRuntime(this, jsii.String("MyAgentRuntime"), &RuntimeProps{
RuntimeName: jsii.String("myAgent"),
AgentRuntimeArtifact: agentRuntimeArtifactNew,
})
stagingEndpoint := runtime.AddEndpoint(jsii.String("staging"), &AddEndpointOptions{
Version: jsii.String("2"),
Description: jsii.String("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.
const repository = new ecr.Repository(this, "TestRepository", {
repositoryName: "test-agent-runtime",
});
const agentRuntimeArtifactNew = agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, "v2.0.0");
const runtime = new agentcore.Runtime(this, "MyAgentRuntime", {
runtimeName: "myAgent",
agentRuntimeArtifact: agentRuntimeArtifactNew,
});
const prodEndpoint = runtime.addEndpoint("production", {
version: "2", // New version added here
description: "Stable production endpoint"
});
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
agent_runtime_artifact_new = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v2.0.0")
runtime = agentcore.Runtime(self, "MyAgentRuntime",
runtime_name="myAgent",
agent_runtime_artifact=agent_runtime_artifact_new
)
prod_endpoint = runtime.add_endpoint("production",
version="2", # New version added here
description="Stable production endpoint"
)
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
AgentRuntimeArtifact agentRuntimeArtifactNew = AgentRuntimeArtifact.fromEcrRepository(repository, "v2.0.0");
Runtime runtime = Runtime.Builder.create(this, "MyAgentRuntime")
.runtimeName("myAgent")
.agentRuntimeArtifact(agentRuntimeArtifactNew)
.build();
RuntimeEndpoint prodEndpoint = runtime.addEndpoint("production", AddEndpointOptions.builder()
.version("2") // New version added here
.description("Stable production endpoint")
.build());
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
var agentRuntimeArtifactNew = AgentRuntimeArtifact.FromEcrRepository(repository, "v2.0.0");
var runtime = new Runtime(this, "MyAgentRuntime", new RuntimeProps {
RuntimeName = "myAgent",
AgentRuntimeArtifact = agentRuntimeArtifactNew
});
var prodEndpoint = runtime.AddEndpoint("production", new AddEndpointOptions {
Version = "2", // New version added here
Description = "Stable production endpoint"
});
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
agentRuntimeArtifactNew := agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v2.0.0"))
runtime := agentcore.NewRuntime(this, jsii.String("MyAgentRuntime"), &RuntimeProps{
RuntimeName: jsii.String("myAgent"),
AgentRuntimeArtifact: agentRuntimeArtifactNew,
})
prodEndpoint := runtime.AddEndpoint(jsii.String("production"), &AddEndpointOptions{
Version: jsii.String("2"),
// New version added here
Description: jsii.String("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
const existingRuntimeId = "abc123-runtime-id"; // The ID of an existing runtime
// Create a standalone endpoint
const endpoint = new agentcore.RuntimeEndpoint(this, "MyEndpoint", {
endpointName: "production",
agentRuntimeId: existingRuntimeId,
agentRuntimeVersion: "1", // Specify which version to use
description: "Production endpoint for 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 = agentcore.RuntimeEndpoint(self, "MyEndpoint",
endpoint_name="production",
agent_runtime_id=existing_runtime_id,
agent_runtime_version="1", # Specify which version to use
description="Production endpoint for existing runtime"
)
// Reference an existing runtime by its ID
String existingRuntimeId = "abc123-runtime-id"; // The ID of an existing runtime
// Create a standalone endpoint
RuntimeEndpoint endpoint = RuntimeEndpoint.Builder.create(this, "MyEndpoint")
.endpointName("production")
.agentRuntimeId(existingRuntimeId)
.agentRuntimeVersion("1") // Specify which version to use
.description("Production endpoint for existing runtime")
.build();
// Reference an existing runtime by its ID
var existingRuntimeId = "abc123-runtime-id"; // The ID of an existing runtime
// Create a standalone endpoint
var endpoint = new RuntimeEndpoint(this, "MyEndpoint", new RuntimeEndpointProps {
EndpointName = "production",
AgentRuntimeId = existingRuntimeId,
AgentRuntimeVersion = "1", // Specify which version to use
Description = "Production endpoint for existing runtime"
});
// Reference an existing runtime by its ID
existingRuntimeId := "abc123-runtime-id" // The ID of an existing runtime
// Create a standalone endpoint
endpoint := agentcore.NewRuntimeEndpoint(this, jsii.String("MyEndpoint"), &RuntimeEndpointProps{
EndpointName: jsii.String("production"),
AgentRuntimeId: existingRuntimeId,
AgentRuntimeVersion: jsii.String("1"),
// Specify which version to use
Description: jsii.String("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:
declare const userPool: cognito.UserPool;
declare const userPoolClient: cognito.UserPoolClient;
declare const anotherUserPoolClient: cognito.UserPoolClient;
const repository = new ecr.Repository(this, "TestRepository", {
repositoryName: "test-agent-runtime",
});
const agentRuntimeArtifact = agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
// Optional: Create custom claims for additional validation
const customClaims = [
agentcore.RuntimeCustomClaim.withStringValue('department', 'engineering'),
agentcore.RuntimeCustomClaim.withStringArrayValue('roles', ['admin'], agentcore.CustomClaimOperator.CONTAINS),
agentcore.RuntimeCustomClaim.withStringArrayValue('permissions', ['read', 'write'], agentcore.CustomClaimOperator.CONTAINS_ANY),
];
const runtime = new agentcore.Runtime(this, "MyAgentRuntime", {
runtimeName: "myAgent",
agentRuntimeArtifact: agentRuntimeArtifact,
authorizerConfiguration: agentcore.RuntimeAuthorizerConfiguration.usingCognito(
userPool, // User Pool (required)
[userPoolClient, anotherUserPoolClient], // User Pool Clients
["audience1"], // Allowed Audiences (optional)
["read", "write"], // Allowed Scopes (optional)
customClaims, // Custom claims (optional) - see Custom Claims Validation section
),
});
# user_pool: cognito.UserPool
# user_pool_client: cognito.UserPoolClient
# another_user_pool_client: cognito.UserPoolClient
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
# Optional: Create custom claims for additional validation
custom_claims = [
agentcore.RuntimeCustomClaim.with_string_value("department", "engineering"),
agentcore.RuntimeCustomClaim.with_string_array_value("roles", ["admin"], agentcore.CustomClaimOperator.CONTAINS),
agentcore.RuntimeCustomClaim.with_string_array_value("permissions", ["read", "write"], agentcore.CustomClaimOperator.CONTAINS_ANY)
]
runtime = agentcore.Runtime(self, "MyAgentRuntime",
runtime_name="myAgent",
agent_runtime_artifact=agent_runtime_artifact,
authorizer_configuration=agentcore.RuntimeAuthorizerConfiguration.using_cognito(user_pool, [user_pool_client, another_user_pool_client], ["audience1"], ["read", "write"], custom_claims)
)
UserPool userPool;
UserPoolClient userPoolClient;
UserPoolClient anotherUserPoolClient;
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
AgentRuntimeArtifact agentRuntimeArtifact = AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
// Optional: Create custom claims for additional validation
RuntimeCustomClaim[] customClaims = List.of(RuntimeCustomClaim.withStringValue("department", "engineering"), RuntimeCustomClaim.withStringArrayValue("roles", List.of("admin"), CustomClaimOperator.CONTAINS), RuntimeCustomClaim.withStringArrayValue("permissions", List.of("read", "write"), CustomClaimOperator.CONTAINS_ANY));
Runtime runtime = Runtime.Builder.create(this, "MyAgentRuntime")
.runtimeName("myAgent")
.agentRuntimeArtifact(agentRuntimeArtifact)
.authorizerConfiguration(RuntimeAuthorizerConfiguration.usingCognito(userPool, List.of(userPoolClient, anotherUserPoolClient), List.of("audience1"), List.of("read", "write"), customClaims))
.build();
UserPool userPool;
UserPoolClient userPoolClient;
UserPoolClient anotherUserPoolClient;
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
var agentRuntimeArtifact = AgentRuntimeArtifact.FromEcrRepository(repository, "v1.0.0");
// Optional: Create custom claims for additional validation
var customClaims = new [] { RuntimeCustomClaim.WithStringValue("department", "engineering"), RuntimeCustomClaim.WithStringArrayValue("roles", new [] { "admin" }, CustomClaimOperator.CONTAINS), RuntimeCustomClaim.WithStringArrayValue("permissions", new [] { "read", "write" }, CustomClaimOperator.CONTAINS_ANY) };
var runtime = new Runtime(this, "MyAgentRuntime", new RuntimeProps {
RuntimeName = "myAgent",
AgentRuntimeArtifact = agentRuntimeArtifact,
AuthorizerConfiguration = RuntimeAuthorizerConfiguration.UsingCognito(userPool, new [] { userPoolClient, anotherUserPoolClient }, new [] { "audience1" }, new [] { "read", "write" }, customClaims)
});
var userPool UserPool
var userPoolClient UserPoolClient
var anotherUserPoolClient UserPoolClient
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
agentRuntimeArtifact := agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v1.0.0"))
// Optional: Create custom claims for additional validation
customClaims := []RuntimeCustomClaim{
agentcore.RuntimeCustomClaim_WithStringValue(jsii.String("department"), jsii.String("engineering")),
agentcore.RuntimeCustomClaim_WithStringArrayValue(jsii.String("roles"), []*string{
jsii.String("admin"),
}, agentcore.CustomClaimOperator_CONTAINS),
agentcore.RuntimeCustomClaim_WithStringArrayValue(jsii.String("permissions"), []*string{
jsii.String("read"),
jsii.String("write"),
}, agentcore.CustomClaimOperator_CONTAINS_ANY),
}
runtime := agentcore.NewRuntime(this, jsii.String("MyAgentRuntime"), &RuntimeProps{
RuntimeName: jsii.String("myAgent"),
AgentRuntimeArtifact: agentRuntimeArtifact,
AuthorizerConfiguration: agentcore.RuntimeAuthorizerConfiguration_UsingCognito(userPool, []IUserPoolClient{
userPoolClient,
anotherUserPoolClient,
}, []*string{
jsii.String("audience1"),
}, []*string{
jsii.String("read"),
jsii.String("write"),
}, customClaims),
})
You can configure:
- User Pool: The Cognito User Pool that issues JWT tokens
- User Pool Clients: One or more Cognito User Pool App Clients that are allowed to access the runtime
- Allowed audiences: Used to validate that the audiences specified in the Cognito token match or are a subset of the audiences specified in the AgentCore Runtime
- Allowed scopes: Allow access only if the token contains at least one of the required scopes configured here
- Custom claims: A set of rules to match specific claims in the incoming token against predefined values for validating JWT tokens
JWT Authentication
To configure custom JWT authentication with your own OpenID Connect (OIDC) provider:
const repository = new ecr.Repository(this, "TestRepository", {
repositoryName: "test-agent-runtime",
});
const agentRuntimeArtifact = agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
const runtime = new agentcore.Runtime(this, "MyAgentRuntime", {
runtimeName: "myAgent",
agentRuntimeArtifact: agentRuntimeArtifact,
authorizerConfiguration: agentcore.RuntimeAuthorizerConfiguration.usingJWT(
"https://example.com/.well-known/openid-configuration", // Discovery URL (required)
["client1", "client2"], // Allowed Client IDs (optional)
["audience1"], // Allowed Audiences (optional)
["read", "write"], // Allowed Scopes (optional)
// Custom claims (optional) - see Custom Claims Validation section below
),
});
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
runtime = agentcore.Runtime(self, "MyAgentRuntime",
runtime_name="myAgent",
agent_runtime_artifact=agent_runtime_artifact,
authorizer_configuration=agentcore.RuntimeAuthorizerConfiguration.using_jwt("https://example.com/.well-known/openid-configuration", ["client1", "client2"], ["audience1"], ["read", "write"])
)
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
AgentRuntimeArtifact agentRuntimeArtifact = AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
Runtime runtime = Runtime.Builder.create(this, "MyAgentRuntime")
.runtimeName("myAgent")
.agentRuntimeArtifact(agentRuntimeArtifact)
.authorizerConfiguration(RuntimeAuthorizerConfiguration.usingJWT("https://example.com/.well-known/openid-configuration", List.of("client1", "client2"), List.of("audience1"), List.of("read", "write")))
.build();
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
var agentRuntimeArtifact = AgentRuntimeArtifact.FromEcrRepository(repository, "v1.0.0");
var runtime = new Runtime(this, "MyAgentRuntime", new RuntimeProps {
RuntimeName = "myAgent",
AgentRuntimeArtifact = agentRuntimeArtifact,
AuthorizerConfiguration = RuntimeAuthorizerConfiguration.UsingJWT("https://example.com/.well-known/openid-configuration", new [] { "client1", "client2" }, new [] { "audience1" }, new [] { "read", "write" })
});
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
agentRuntimeArtifact := agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v1.0.0"))
runtime := agentcore.NewRuntime(this, jsii.String("MyAgentRuntime"), &RuntimeProps{
RuntimeName: jsii.String("myAgent"),
AgentRuntimeArtifact: agentRuntimeArtifact,
AuthorizerConfiguration: agentcore.RuntimeAuthorizerConfiguration_UsingJWT(jsii.String("https://example.com/.well-known/openid-configuration"), []*string{
jsii.String("client1"),
jsii.String("client2"),
}, []*string{
jsii.String("audience1"),
}, []*string{
jsii.String("read"),
jsii.String("write"),
}),
})
You can configure:
- Discovery URL: Enter the Discovery URL from your identity provider (e.g. Okta, Cognito, etc.), typically found in that provider's documentation. This allows your Agent or Tool to fetch login, downstream resource token, and verification settings.
- Allowed audiences: This is used to validate that the audiences specified for the OAuth token matches or are a subset of the audiences specified in the AgentCore Runtime.
- Allowed clients: This is used to validate that the public identifier of the client, as specified in the authorization token, is allowed to access the AgentCore Runtime.
- Allowed scopes: Allow access only if the token contains at least one of the required scopes configured here.
- Custom claims: A set of rules to match specific claims in the incoming token against predefined values for validating JWT tokens.
Note: The discovery URL must end with /.well-known/openid-configuration.
Custom Claims Validation
Custom claims allow you to validate additional fields in JWT tokens beyond the standard audience, client, and scope validations. You can create custom claims using the RuntimeCustomClaim class:
const repository = new ecr.Repository(this, "TestRepository", {
repositoryName: "test-agent-runtime",
});
const agentRuntimeArtifact = agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
// String claim - validates that the claim exactly equals the specified value
// Uses EQUALS operator automatically
const departmentClaim = agentcore.RuntimeCustomClaim.withStringValue('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
const rolesClaim = agentcore.RuntimeCustomClaim.withStringArrayValue('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
const permissionsClaim = agentcore.RuntimeCustomClaim.withStringArrayValue(
'permissions',
['read', 'write'],
agentcore.CustomClaimOperator.CONTAINS_ANY
);
// Use custom claims in authorizer configuration
const runtime = new agentcore.Runtime(this, "MyAgentRuntime", {
runtimeName: "myAgent",
agentRuntimeArtifact: agentRuntimeArtifact,
authorizerConfiguration: agentcore.RuntimeAuthorizerConfiguration.usingJWT(
"https://example.com/.well-known/openid-configuration",
["client1", "client2"],
["audience1"],
["read", "write"],
[departmentClaim, rolesClaim, permissionsClaim] // Custom claims
),
});
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
# String claim - validates that the claim exactly equals the specified value
# Uses EQUALS operator automatically
department_claim = agentcore.RuntimeCustomClaim.with_string_value("department", "engineering")
# String array claim with CONTAINS operator (default)
# Validates that the claim array contains a specific string value
# IMPORTANT: CONTAINS requires exactly one value in the array parameter
roles_claim = agentcore.RuntimeCustomClaim.with_string_array_value("roles", ["admin"])
# String array claim with CONTAINS_ANY operator
# Validates that the claim array contains at least one of the specified values
# Use this when you want to check for multiple possible values
permissions_claim = agentcore.RuntimeCustomClaim.with_string_array_value("permissions", ["read", "write"], agentcore.CustomClaimOperator.CONTAINS_ANY)
# Use custom claims in authorizer configuration
runtime = agentcore.Runtime(self, "MyAgentRuntime",
runtime_name="myAgent",
agent_runtime_artifact=agent_runtime_artifact,
authorizer_configuration=agentcore.RuntimeAuthorizerConfiguration.using_jwt("https://example.com/.well-known/openid-configuration", ["client1", "client2"], ["audience1"], ["read", "write"], [department_claim, roles_claim, permissions_claim])
)
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
AgentRuntimeArtifact agentRuntimeArtifact = AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
// String claim - validates that the claim exactly equals the specified value
// Uses EQUALS operator automatically
RuntimeCustomClaim departmentClaim = RuntimeCustomClaim.withStringValue("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
RuntimeCustomClaim rolesClaim = RuntimeCustomClaim.withStringArrayValue("roles", List.of("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
RuntimeCustomClaim permissionsClaim = RuntimeCustomClaim.withStringArrayValue("permissions", List.of("read", "write"), CustomClaimOperator.CONTAINS_ANY);
// Use custom claims in authorizer configuration
Runtime runtime = Runtime.Builder.create(this, "MyAgentRuntime")
.runtimeName("myAgent")
.agentRuntimeArtifact(agentRuntimeArtifact)
.authorizerConfiguration(RuntimeAuthorizerConfiguration.usingJWT("https://example.com/.well-known/openid-configuration", List.of("client1", "client2"), List.of("audience1"), List.of("read", "write"), List.of(departmentClaim, rolesClaim, permissionsClaim)))
.build();
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
var agentRuntimeArtifact = AgentRuntimeArtifact.FromEcrRepository(repository, "v1.0.0");
// String claim - validates that the claim exactly equals the specified value
// Uses EQUALS operator automatically
var departmentClaim = RuntimeCustomClaim.WithStringValue("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
var rolesClaim = RuntimeCustomClaim.WithStringArrayValue("roles", new [] { "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
var permissionsClaim = RuntimeCustomClaim.WithStringArrayValue("permissions", new [] { "read", "write" }, CustomClaimOperator.CONTAINS_ANY);
// Use custom claims in authorizer configuration
var runtime = new Runtime(this, "MyAgentRuntime", new RuntimeProps {
RuntimeName = "myAgent",
AgentRuntimeArtifact = agentRuntimeArtifact,
AuthorizerConfiguration = RuntimeAuthorizerConfiguration.UsingJWT("https://example.com/.well-known/openid-configuration", new [] { "client1", "client2" }, new [] { "audience1" }, new [] { "read", "write" }, new [] { departmentClaim, rolesClaim, permissionsClaim })
});
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
agentRuntimeArtifact := agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v1.0.0"))
// String claim - validates that the claim exactly equals the specified value
// Uses EQUALS operator automatically
departmentClaim := agentcore.RuntimeCustomClaim_WithStringValue(jsii.String("department"), jsii.String("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
rolesClaim := agentcore.RuntimeCustomClaim_WithStringArrayValue(jsii.String("roles"), []*string{
jsii.String("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
permissionsClaim := agentcore.RuntimeCustomClaim_WithStringArrayValue(jsii.String("permissions"), []*string{
jsii.String("read"),
jsii.String("write"),
}, agentcore.CustomClaimOperator_CONTAINS_ANY)
// Use custom claims in authorizer configuration
runtime := agentcore.NewRuntime(this, jsii.String("MyAgentRuntime"), &RuntimeProps{
RuntimeName: jsii.String("myAgent"),
AgentRuntimeArtifact: agentRuntimeArtifact,
AuthorizerConfiguration: agentcore.RuntimeAuthorizerConfiguration_UsingJWT(jsii.String("https://example.com/.well-known/openid-configuration"), []*string{
jsii.String("client1"),
jsii.String("client2"),
}, []*string{
jsii.String("audience1"),
}, []*string{
jsii.String("read"),
jsii.String("write"),
}, []RuntimeCustomClaim{
departmentClaim,
rolesClaim,
permissionsClaim,
}),
})
Custom Claim Rules:
- String claims: Must use the
EQUALSoperator (automatically set). The claim value must exactly match the specified string. - String array claims: Can use
CONTAINS(default) orCONTAINS_ANYoperators:CONTAINS: Checks if the claim array contains a specific string value. Requires exactly one value in the array parameter. For example,['admin']will check if the token's claim array contains the string'admin'.CONTAINS_ANY: Checks if the claim array contains at least one of the provided string values. Use this when you want to validate against multiple possible values. For example,['read', 'write']will check if the token's claim array contains either'read'or'write'.
Example Use Cases:
- Use
CONTAINSwhen you need to verify a user has a specific role:RuntimeCustomClaim.withStringArrayValue('roles', ['admin']) - Use
CONTAINS_ANYwhen you need to verify a user has any of several permissions:RuntimeCustomClaim.withStringArrayValue('permissions', ['read', 'write'], CustomClaimOperator.CONTAINS_ANY)
OAuth Authentication
To configure OAuth 2.0 authentication:
const repository = new ecr.Repository(this, "TestRepository", {
repositoryName: "test-agent-runtime",
});
const agentRuntimeArtifact = agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
const runtime = new agentcore.Runtime(this, "MyAgentRuntime", {
runtimeName: "myAgent",
agentRuntimeArtifact: agentRuntimeArtifact,
authorizerConfiguration: agentcore.RuntimeAuthorizerConfiguration.usingOAuth(
"https://github.com/.well-known/openid-configuration", // Discovery URL (required)
"oauth_client_123", // OAuth Client ID (required)
["audience1"], // Allowed Audiences (optional)
["openid", "profile"], // Allowed Scopes (optional)
// Custom claims (optional) - see Custom Claims Validation section
),
});
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
runtime = agentcore.Runtime(self, "MyAgentRuntime",
runtime_name="myAgent",
agent_runtime_artifact=agent_runtime_artifact,
authorizer_configuration=agentcore.RuntimeAuthorizerConfiguration.using_o_auth("https://github.com/.well-known/openid-configuration", "oauth_client_123", ["audience1"], ["openid", "profile"])
)
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
AgentRuntimeArtifact agentRuntimeArtifact = AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
Runtime runtime = Runtime.Builder.create(this, "MyAgentRuntime")
.runtimeName("myAgent")
.agentRuntimeArtifact(agentRuntimeArtifact)
.authorizerConfiguration(RuntimeAuthorizerConfiguration.usingOAuth("https://github.com/.well-known/openid-configuration", "oauth_client_123", List.of("audience1"), List.of("openid", "profile")))
.build();
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
var agentRuntimeArtifact = AgentRuntimeArtifact.FromEcrRepository(repository, "v1.0.0");
var runtime = new Runtime(this, "MyAgentRuntime", new RuntimeProps {
RuntimeName = "myAgent",
AgentRuntimeArtifact = agentRuntimeArtifact,
AuthorizerConfiguration = RuntimeAuthorizerConfiguration.UsingOAuth("https://github.com/.well-known/openid-configuration", "oauth_client_123", new [] { "audience1" }, new [] { "openid", "profile" })
});
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
agentRuntimeArtifact := agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v1.0.0"))
runtime := agentcore.NewRuntime(this, jsii.String("MyAgentRuntime"), &RuntimeProps{
RuntimeName: jsii.String("myAgent"),
AgentRuntimeArtifact: agentRuntimeArtifact,
AuthorizerConfiguration: agentcore.RuntimeAuthorizerConfiguration_UsingOAuth(jsii.String("https://github.com/.well-known/openid-configuration"), jsii.String("oauth_client_123"), []*string{
jsii.String("audience1"),
}, []*string{
jsii.String("openid"),
jsii.String("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:
const repository = new ecr.Repository(this, "TestRepository", {
repositoryName: "test-agent-runtime",
});
const agentRuntimeArtifact = agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
// Explicitly using public network (this is the default)
const runtime = new agentcore.Runtime(this, "MyAgentRuntime", {
runtimeName: "myAgent",
agentRuntimeArtifact: agentRuntimeArtifact,
networkConfiguration: agentcore.RuntimeNetworkConfiguration.usingPublicNetwork(),
});
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
# Explicitly using public network (this is the default)
runtime = agentcore.Runtime(self, "MyAgentRuntime",
runtime_name="myAgent",
agent_runtime_artifact=agent_runtime_artifact,
network_configuration=agentcore.RuntimeNetworkConfiguration.using_public_network()
)
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
AgentRuntimeArtifact agentRuntimeArtifact = AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
// Explicitly using public network (this is the default)
Runtime runtime = Runtime.Builder.create(this, "MyAgentRuntime")
.runtimeName("myAgent")
.agentRuntimeArtifact(agentRuntimeArtifact)
.networkConfiguration(RuntimeNetworkConfiguration.usingPublicNetwork())
.build();
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
var agentRuntimeArtifact = AgentRuntimeArtifact.FromEcrRepository(repository, "v1.0.0");
// Explicitly using public network (this is the default)
var runtime = new Runtime(this, "MyAgentRuntime", new RuntimeProps {
RuntimeName = "myAgent",
AgentRuntimeArtifact = agentRuntimeArtifact,
NetworkConfiguration = RuntimeNetworkConfiguration.UsingPublicNetwork()
});
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
agentRuntimeArtifact := agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v1.0.0"))
// Explicitly using public network (this is the default)
runtime := agentcore.NewRuntime(this, jsii.String("MyAgentRuntime"), &RuntimeProps{
RuntimeName: jsii.String("myAgent"),
AgentRuntimeArtifact: agentRuntimeArtifact,
NetworkConfiguration: agentcore.RuntimeNetworkConfiguration_UsingPublicNetwork(),
})
VPC Network Mode
For enhanced security and network isolation, you can deploy your runtime within a VPC:
const repository = new ecr.Repository(this, "TestRepository", {
repositoryName: "test-agent-runtime",
});
const agentRuntimeArtifact = agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
// Create or use an existing VPC
const vpc = new ec2.Vpc(this, 'MyVpc', {
maxAzs: 2,
});
// Configure runtime with VPC
const runtime = new agentcore.Runtime(this, "MyAgentRuntime", {
runtimeName: "myAgent",
agentRuntimeArtifact: agentRuntimeArtifact,
networkConfiguration: agentcore.RuntimeNetworkConfiguration.usingVpc(this, {
vpc: vpc,
vpcSubnets: { subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS },
// Optionally specify security groups, or one will be created automatically
// securityGroups: [mySecurityGroup],
}),
});
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
# Create or use an existing VPC
vpc = ec2.Vpc(self, "MyVpc",
max_azs=2
)
# Configure runtime with VPC
runtime = agentcore.Runtime(self, "MyAgentRuntime",
runtime_name="myAgent",
agent_runtime_artifact=agent_runtime_artifact,
network_configuration=agentcore.RuntimeNetworkConfiguration.using_vpc(self,
vpc=vpc,
vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS)
)
)
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
AgentRuntimeArtifact agentRuntimeArtifact = AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
// Create or use an existing VPC
Vpc vpc = Vpc.Builder.create(this, "MyVpc")
.maxAzs(2)
.build();
// Configure runtime with VPC
Runtime runtime = Runtime.Builder.create(this, "MyAgentRuntime")
.runtimeName("myAgent")
.agentRuntimeArtifact(agentRuntimeArtifact)
.networkConfiguration(RuntimeNetworkConfiguration.usingVpc(this, VpcConfigProps.builder()
.vpc(vpc)
.vpcSubnets(SubnetSelection.builder().subnetType(SubnetType.PRIVATE_WITH_EGRESS).build())
.build()))
.build();
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
var agentRuntimeArtifact = AgentRuntimeArtifact.FromEcrRepository(repository, "v1.0.0");
// Create or use an existing VPC
var vpc = new Vpc(this, "MyVpc", new VpcProps {
MaxAzs = 2
});
// Configure runtime with VPC
var runtime = new Runtime(this, "MyAgentRuntime", new RuntimeProps {
RuntimeName = "myAgent",
AgentRuntimeArtifact = agentRuntimeArtifact,
NetworkConfiguration = RuntimeNetworkConfiguration.UsingVpc(this, new VpcConfigProps {
Vpc = vpc,
VpcSubnets = new SubnetSelection { SubnetType = SubnetType.PRIVATE_WITH_EGRESS }
})
});
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
agentRuntimeArtifact := agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v1.0.0"))
// Create or use an existing VPC
vpc := ec2.NewVpc(this, jsii.String("MyVpc"), &VpcProps{
MaxAzs: jsii.Number(2),
})
// Configure runtime with VPC
runtime := agentcore.NewRuntime(this, jsii.String("MyAgentRuntime"), &RuntimeProps{
RuntimeName: jsii.String("myAgent"),
AgentRuntimeArtifact: agentRuntimeArtifact,
NetworkConfiguration: agentcore.RuntimeNetworkConfiguration_UsingVpc(this, &VpcConfigProps{
Vpc: vpc,
VpcSubnets: &SubnetSelection{
SubnetType: 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:
const vpc = new ec2.Vpc(this, 'MyVpc', {
maxAzs: 2,
});
const repository = new ecr.Repository(this, "TestRepository", {
repositoryName: "test-agent-runtime",
});
const agentRuntimeArtifact = agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
// Create runtime with VPC configuration
const runtime = new agentcore.Runtime(this, "MyAgentRuntime", {
runtimeName: "myAgent",
agentRuntimeArtifact: agentRuntimeArtifact,
networkConfiguration: agentcore.RuntimeNetworkConfiguration.usingVpc(this, {
vpc: vpc,
vpcSubnets: { subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS },
}),
});
// Now you can manage network access using the connections property
// Allow inbound HTTPS traffic from a specific security group
const webServerSecurityGroup = new ec2.SecurityGroup(this, 'WebServerSG', { vpc });
runtime.connections.allowFrom(webServerSecurityGroup, ec2.Port.tcp(443), 'Allow HTTPS from web servers');
// Allow outbound connections to a database
const databaseSecurityGroup = new ec2.SecurityGroup(this, 'DatabaseSG', { vpc });
runtime.connections.allowTo(databaseSecurityGroup, ec2.Port.tcp(5432), 'Allow PostgreSQL connection');
// Allow outbound HTTPS to anywhere (for external API calls)
runtime.connections.allowToAnyIpv4(ec2.Port.tcp(443), 'Allow HTTPS outbound');
vpc = ec2.Vpc(self, "MyVpc",
max_azs=2
)
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
# Create runtime with VPC configuration
runtime = agentcore.Runtime(self, "MyAgentRuntime",
runtime_name="myAgent",
agent_runtime_artifact=agent_runtime_artifact,
network_configuration=agentcore.RuntimeNetworkConfiguration.using_vpc(self,
vpc=vpc,
vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS)
)
)
# Now you can manage network access using the connections property
# Allow inbound HTTPS traffic from a specific security group
web_server_security_group = ec2.SecurityGroup(self, "WebServerSG", vpc=vpc)
runtime.connections.allow_from(web_server_security_group, ec2.Port.tcp(443), "Allow HTTPS from web servers")
# Allow outbound connections to a database
database_security_group = ec2.SecurityGroup(self, "DatabaseSG", vpc=vpc)
runtime.connections.allow_to(database_security_group, ec2.Port.tcp(5432), "Allow PostgreSQL connection")
# Allow outbound HTTPS to anywhere (for external API calls)
runtime.connections.allow_to_any_ipv4(ec2.Port.tcp(443), "Allow HTTPS outbound")
Vpc vpc = Vpc.Builder.create(this, "MyVpc")
.maxAzs(2)
.build();
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
AgentRuntimeArtifact agentRuntimeArtifact = AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
// Create runtime with VPC configuration
Runtime runtime = Runtime.Builder.create(this, "MyAgentRuntime")
.runtimeName("myAgent")
.agentRuntimeArtifact(agentRuntimeArtifact)
.networkConfiguration(RuntimeNetworkConfiguration.usingVpc(this, VpcConfigProps.builder()
.vpc(vpc)
.vpcSubnets(SubnetSelection.builder().subnetType(SubnetType.PRIVATE_WITH_EGRESS).build())
.build()))
.build();
// Now you can manage network access using the connections property
// Allow inbound HTTPS traffic from a specific security group
SecurityGroup webServerSecurityGroup = SecurityGroup.Builder.create(this, "WebServerSG").vpc(vpc).build();
runtime.connections.allowFrom(webServerSecurityGroup, Port.tcp(443), "Allow HTTPS from web servers");
// Allow outbound connections to a database
SecurityGroup databaseSecurityGroup = SecurityGroup.Builder.create(this, "DatabaseSG").vpc(vpc).build();
runtime.connections.allowTo(databaseSecurityGroup, Port.tcp(5432), "Allow PostgreSQL connection");
// Allow outbound HTTPS to anywhere (for external API calls)
runtime.connections.allowToAnyIpv4(Port.tcp(443), "Allow HTTPS outbound");
var vpc = new Vpc(this, "MyVpc", new VpcProps {
MaxAzs = 2
});
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
var agentRuntimeArtifact = AgentRuntimeArtifact.FromEcrRepository(repository, "v1.0.0");
// Create runtime with VPC configuration
var runtime = new Runtime(this, "MyAgentRuntime", new RuntimeProps {
RuntimeName = "myAgent",
AgentRuntimeArtifact = agentRuntimeArtifact,
NetworkConfiguration = RuntimeNetworkConfiguration.UsingVpc(this, new VpcConfigProps {
Vpc = vpc,
VpcSubnets = new SubnetSelection { SubnetType = SubnetType.PRIVATE_WITH_EGRESS }
})
});
// Now you can manage network access using the connections property
// Allow inbound HTTPS traffic from a specific security group
var webServerSecurityGroup = new SecurityGroup(this, "WebServerSG", new SecurityGroupProps { Vpc = vpc });
runtime.Connections.AllowFrom(webServerSecurityGroup, Port.Tcp(443), "Allow HTTPS from web servers");
// Allow outbound connections to a database
var databaseSecurityGroup = new SecurityGroup(this, "DatabaseSG", new SecurityGroupProps { Vpc = vpc });
runtime.Connections.AllowTo(databaseSecurityGroup, Port.Tcp(5432), "Allow PostgreSQL connection");
// Allow outbound HTTPS to anywhere (for external API calls)
runtime.Connections.AllowToAnyIpv4(Port.Tcp(443), "Allow HTTPS outbound");
vpc := ec2.NewVpc(this, jsii.String("MyVpc"), &VpcProps{
MaxAzs: jsii.Number(2),
})
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
agentRuntimeArtifact := agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v1.0.0"))
// Create runtime with VPC configuration
runtime := agentcore.NewRuntime(this, jsii.String("MyAgentRuntime"), &RuntimeProps{
RuntimeName: jsii.String("myAgent"),
AgentRuntimeArtifact: agentRuntimeArtifact,
NetworkConfiguration: agentcore.RuntimeNetworkConfiguration_UsingVpc(this, &VpcConfigProps{
Vpc: vpc,
VpcSubnets: &SubnetSelection{
SubnetType: ec2.SubnetType_PRIVATE_WITH_EGRESS,
},
}),
})
// Now you can manage network access using the connections property
// Allow inbound HTTPS traffic from a specific security group
webServerSecurityGroup := ec2.NewSecurityGroup(this, jsii.String("WebServerSG"), &SecurityGroupProps{
Vpc: Vpc,
})
runtime.connections.AllowFrom(webServerSecurityGroup, ec2.Port_Tcp(jsii.Number(443)), jsii.String("Allow HTTPS from web servers"))
// Allow outbound connections to a database
databaseSecurityGroup := ec2.NewSecurityGroup(this, jsii.String("DatabaseSG"), &SecurityGroupProps{
Vpc: Vpc,
})
runtime.connections.AllowTo(databaseSecurityGroup, ec2.Port_Tcp(jsii.Number(5432)), jsii.String("Allow PostgreSQL connection"))
// Allow outbound HTTPS to anywhere (for external API calls)
runtime.connections.AllowToAnyIpv4(ec2.Port_Tcp(jsii.Number(443)), jsii.String("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.
const repository = new ecr.Repository(this, "TestRepository", {
repositoryName: "test-agent-runtime",
});
const agentRuntimeArtifact = agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
// Create a runtime
const runtime = new agentcore.Runtime(this, "MyRuntime", {
runtimeName: "my_runtime",
agentRuntimeArtifact: agentRuntimeArtifact,
});
// Create a Lambda function that needs to invoke the runtime
const invokerFunction = new lambda.Function(this, "InvokerFunction", {
runtime: lambda.Runtime.PYTHON_3_12,
handler: "index.handler",
code: lambda.Code.fromInline(`
import boto3
def handler(event, context):
client = boto3.client('bedrock-agentcore')
# Invoke the runtime...
`),
});
// Grant permission to invoke the runtime directly
runtime.grantInvokeRuntime(invokerFunction);
// Grant permission to invoke the runtime on behalf of a user
// (requires X-Amzn-Bedrock-AgentCore-Runtime-User-Id header)
runtime.grantInvokeRuntimeForUser(invokerFunction);
// Grant both invoke permissions (most common use case)
runtime.grantInvoke(invokerFunction);
// 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.addToRolePolicy(new iam.PolicyStatement({
actions: ['s3:GetObject'],
resources: ['arn:aws:s3:::my-bucket/*'],
}));
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
# Create a runtime
runtime = agentcore.Runtime(self, "MyRuntime",
runtime_name="my_runtime",
agent_runtime_artifact=agent_runtime_artifact
)
# Create a Lambda function that needs to invoke the runtime
invoker_function = lambda_.Function(self, "InvokerFunction",
runtime=lambda_.Runtime.PYTHON_3_12,
handler="index.handler",
code=lambda_.Code.from_inline("""
import boto3
def handler(event, context):
client = boto3.client('bedrock-agentcore')
# Invoke the runtime...
""")
)
# Grant permission to invoke the runtime directly
runtime.grant_invoke_runtime(invoker_function)
# Grant permission to invoke the runtime on behalf of a user
# (requires X-Amzn-Bedrock-AgentCore-Runtime-User-Id header)
runtime.grant_invoke_runtime_for_user(invoker_function)
# Grant both invoke permissions (most common use case)
runtime.grant_invoke(invoker_function)
# Grant specific custom permissions to the runtime's execution role
runtime.grant(["bedrock:InvokeModel"], ["arn:aws:bedrock:*:*:*"])
# Add a policy statement to the runtime's execution role
runtime.add_to_role_policy(iam.PolicyStatement(
actions=["s3:GetObject"],
resources=["arn:aws:s3:::my-bucket/*"]
))
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
AgentRuntimeArtifact agentRuntimeArtifact = AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
// Create a runtime
Runtime runtime = Runtime.Builder.create(this, "MyRuntime")
.runtimeName("my_runtime")
.agentRuntimeArtifact(agentRuntimeArtifact)
.build();
// Create a Lambda function that needs to invoke the runtime
Function invokerFunction = Function.Builder.create(this, "InvokerFunction")
.runtime(Runtime.PYTHON_3_12)
.handler("index.handler")
.code(Code.fromInline("\nimport boto3\ndef handler(event, context):\n client = boto3.client('bedrock-agentcore')\n # Invoke the runtime...\n "))
.build();
// Grant permission to invoke the runtime directly
runtime.grantInvokeRuntime(invokerFunction);
// Grant permission to invoke the runtime on behalf of a user
// (requires X-Amzn-Bedrock-AgentCore-Runtime-User-Id header)
runtime.grantInvokeRuntimeForUser(invokerFunction);
// Grant both invoke permissions (most common use case)
runtime.grantInvoke(invokerFunction);
// Grant specific custom permissions to the runtime's execution role
runtime.grant(List.of("bedrock:InvokeModel"), List.of("arn:aws:bedrock:*:*:*"));
// Add a policy statement to the runtime's execution role
runtime.addToRolePolicy(PolicyStatement.Builder.create()
.actions(List.of("s3:GetObject"))
.resources(List.of("arn:aws:s3:::my-bucket/*"))
.build());
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
var agentRuntimeArtifact = AgentRuntimeArtifact.FromEcrRepository(repository, "v1.0.0");
// Create a runtime
var runtime = new Runtime(this, "MyRuntime", new RuntimeProps {
RuntimeName = "my_runtime",
AgentRuntimeArtifact = agentRuntimeArtifact
});
// Create a Lambda function that needs to invoke the runtime
var invokerFunction = new Function(this, "InvokerFunction", new FunctionProps {
Runtime = Runtime.PYTHON_3_12,
Handler = "index.handler",
Code = Code.FromInline(@"
import boto3
def handler(event, context):
client = boto3.client('bedrock-agentcore')
# Invoke the runtime...
")
});
// Grant permission to invoke the runtime directly
runtime.GrantInvokeRuntime(invokerFunction);
// Grant permission to invoke the runtime on behalf of a user
// (requires X-Amzn-Bedrock-AgentCore-Runtime-User-Id header)
runtime.GrantInvokeRuntimeForUser(invokerFunction);
// Grant both invoke permissions (most common use case)
runtime.GrantInvoke(invokerFunction);
// Grant specific custom permissions to the runtime's execution role
runtime.Grant(new [] { "bedrock:InvokeModel" }, new [] { "arn:aws:bedrock:*:*:*" });
// Add a policy statement to the runtime's execution role
runtime.AddToRolePolicy(new PolicyStatement(new PolicyStatementProps {
Actions = new [] { "s3:GetObject" },
Resources = new [] { "arn:aws:s3:::my-bucket/*" }
}));
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
agentRuntimeArtifact := agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v1.0.0"))
// Create a runtime
runtime := agentcore.NewRuntime(this, jsii.String("MyRuntime"), &RuntimeProps{
RuntimeName: jsii.String("my_runtime"),
AgentRuntimeArtifact: agentRuntimeArtifact,
})
// Create a Lambda function that needs to invoke the runtime
invokerFunction := lambda.NewFunction(this, jsii.String("InvokerFunction"), &FunctionProps{
Runtime: lambda.Runtime_PYTHON_3_12(),
Handler: jsii.String("index.handler"),
Code: lambda.Code_FromInline(jsii.String(`
import boto3
def handler(event, context):
client = boto3.client('bedrock-agentcore')
# Invoke the runtime...
`)),
})
// Grant permission to invoke the runtime directly
runtime.GrantInvokeRuntime(invokerFunction)
// Grant permission to invoke the runtime on behalf of a user
// (requires X-Amzn-Bedrock-AgentCore-Runtime-User-Id header)
runtime.GrantInvokeRuntimeForUser(invokerFunction)
// Grant both invoke permissions (most common use case)
runtime.GrantInvoke(invokerFunction)
// Grant specific custom permissions to the runtime's execution role
runtime.Grant([]*string{
jsii.String("bedrock:InvokeModel"),
}, []*string{
jsii.String("arn:aws:bedrock:*:*:*"),
})
// Add a policy statement to the runtime's execution role
runtime.AddToRolePolicy(iam.NewPolicyStatement(&PolicyStatementProps{
Actions: []*string{
jsii.String("s3:GetObject"),
},
Resources: []*string{
jsii.String("arn:aws:s3:::my-bucket/*"),
},
}))
Other configuration
Lifecycle configuration
The LifecycleConfiguration input parameter to CreateAgentRuntime lets you manage the lifecycle of runtime sessions and resources in Amazon Bedrock AgentCore Runtime. This configuration helps optimize resource utilization by automatically cleaning up idle sessions and preventing long-running instances from consuming resources indefinitely.
You can configure:
- idleRuntimeSessionTimeout: Timeout in seconds for idle runtime sessions. When a session remains idle for this duration, it will trigger termination. Termination can last up to 15 seconds due to logging and other process completion. Default: 900 seconds (15 minutes)
- maxLifetime: Maximum lifetime for the instance in seconds. Once reached, instances will initialize termination. Termination can last up to 15 seconds due to logging and other process completion. Default: 28800 seconds (8 hours)
For additional information, please refer to the documentation.
const repository = new ecr.Repository(this, "TestRepository", {
repositoryName: "test-agent-runtime",
});
const agentRuntimeArtifact = agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
new agentcore.Runtime(this, 'test-runtime', {
runtimeName: 'test_runtime',
agentRuntimeArtifact: agentRuntimeArtifact,
lifecycleConfiguration: {
idleRuntimeSessionTimeout: Duration.minutes(10),
maxLifetime: Duration.hours(4),
},
});
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
agentcore.Runtime(self, "test-runtime",
runtime_name="test_runtime",
agent_runtime_artifact=agent_runtime_artifact,
lifecycle_configuration=agentcore.LifecycleConfiguration(
idle_runtime_session_timeout=Duration.minutes(10),
max_lifetime=Duration.hours(4)
)
)
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
AgentRuntimeArtifact agentRuntimeArtifact = AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
Runtime.Builder.create(this, "test-runtime")
.runtimeName("test_runtime")
.agentRuntimeArtifact(agentRuntimeArtifact)
.lifecycleConfiguration(LifecycleConfiguration.builder()
.idleRuntimeSessionTimeout(Duration.minutes(10))
.maxLifetime(Duration.hours(4))
.build())
.build();
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
var agentRuntimeArtifact = AgentRuntimeArtifact.FromEcrRepository(repository, "v1.0.0");
new Runtime(this, "test-runtime", new RuntimeProps {
RuntimeName = "test_runtime",
AgentRuntimeArtifact = agentRuntimeArtifact,
LifecycleConfiguration = new LifecycleConfiguration {
IdleRuntimeSessionTimeout = Duration.Minutes(10),
MaxLifetime = Duration.Hours(4)
}
});
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
agentRuntimeArtifact := agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v1.0.0"))
agentcore.NewRuntime(this, jsii.String("test-runtime"), &RuntimeProps{
RuntimeName: jsii.String("test_runtime"),
AgentRuntimeArtifact: agentRuntimeArtifact,
LifecycleConfiguration: &LifecycleConfiguration{
IdleRuntimeSessionTimeout: awscdk.Duration_Minutes(jsii.Number(10)),
MaxLifetime: awscdk.Duration_Hours(jsii.Number(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.
const repository = new ecr.Repository(this, "TestRepository", {
repositoryName: "test-agent-runtime",
});
const agentRuntimeArtifact = agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
new agentcore.Runtime(this, 'test-runtime', {
runtimeName: 'test_runtime',
agentRuntimeArtifact: agentRuntimeArtifact,
requestHeaderConfiguration: {
allowlistedHeaders: ['X-Amzn-Bedrock-AgentCore-Runtime-Custom-H1'],
},
});
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
agentcore.Runtime(self, "test-runtime",
runtime_name="test_runtime",
agent_runtime_artifact=agent_runtime_artifact,
request_header_configuration=agentcore.RequestHeaderConfiguration(
allowlisted_headers=["X-Amzn-Bedrock-AgentCore-Runtime-Custom-H1"]
)
)
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
AgentRuntimeArtifact agentRuntimeArtifact = AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
Runtime.Builder.create(this, "test-runtime")
.runtimeName("test_runtime")
.agentRuntimeArtifact(agentRuntimeArtifact)
.requestHeaderConfiguration(RequestHeaderConfiguration.builder()
.allowlistedHeaders(List.of("X-Amzn-Bedrock-AgentCore-Runtime-Custom-H1"))
.build())
.build();
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
var agentRuntimeArtifact = AgentRuntimeArtifact.FromEcrRepository(repository, "v1.0.0");
new Runtime(this, "test-runtime", new RuntimeProps {
RuntimeName = "test_runtime",
AgentRuntimeArtifact = agentRuntimeArtifact,
RequestHeaderConfiguration = new RequestHeaderConfiguration {
AllowlistedHeaders = new [] { "X-Amzn-Bedrock-AgentCore-Runtime-Custom-H1" }
}
});
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
agentRuntimeArtifact := agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v1.0.0"))
agentcore.NewRuntime(this, jsii.String("test-runtime"), &RuntimeProps{
RuntimeName: jsii.String("test_runtime"),
AgentRuntimeArtifact: agentRuntimeArtifact,
RequestHeaderConfiguration: &RequestHeaderConfiguration{
AllowlistedHeaders: []*string{
jsii.String("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:
- tracingEnabled: Enable X-Ray tracing for the runtime
- loggingConfigs: Send APPLICATION_LOGS (agent runtime invocations) and USAGE_LOGS (session-level resource consumption) to CloudWatch Logs, S3, or Kinesis Data Firehose
- manageDeliveryResourcePolicy: Control whether resource policies are created for log/trace delivery. Defaults to
true
For additional information, please refer to the Set up logging and tracing for AgentCore.
Opting out of resource policy management
When deploying many AgentCore Runtime constructs per account/Region, the per-stack AWS::Logs::ResourcePolicy and AWS::XRay::ResourcePolicy created by the observability delivery consume account-level quota slots (CloudWatch Logs: 10, X-Ray: lower). Set manageDeliveryResourcePolicy: false to skip resource policy creation while still provisioning delivery sources, destinations, and deliveries.
Important: Setting false means you own the delivery permission. There are two safe ways to use it:
- Same-account delivery to a
/aws/vendedlogs/log group, where the log-delivery service-linked role grants write access implicitly. - Attaching the delivery resource policy yourself.
Otherwise delivery silently fails: synthesis and deploy succeed, but nothing is delivered. Per the vended-logs delivery docs, a resource policy is required for CloudWatch Logs delivery outside the /aws/vendedlogs/ same-account case.
const repository = new ecr.Repository(this, 'TestRepository', {
repositoryName: 'test-agent-runtime',
});
const agentRuntimeArtifact = agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, 'v1.0.0');
// Use a /aws/vendedlogs/ log group for same-account delivery without explicit resource policy
const logGroup = new logs.LogGroup(this, 'RuntimeLogGroup', {
logGroupName: '/aws/vendedlogs/bedrock-agentcore/my-runtime',
});
new agentcore.Runtime(this, 'test-runtime', {
runtimeName: 'test_runtime',
agentRuntimeArtifact: agentRuntimeArtifact,
tracingEnabled: true,
loggingConfigs: [
{
logType: agentcore.LogType.APPLICATION_LOGS,
destination: agentcore.LoggingDestination.cloudWatchLogs(logGroup),
},
],
manageDeliveryResourcePolicy: false,
});
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
# Use a /aws/vendedlogs/ log group for same-account delivery without explicit resource policy
log_group = logs.LogGroup(self, "RuntimeLogGroup",
log_group_name="/aws/vendedlogs/bedrock-agentcore/my-runtime"
)
agentcore.Runtime(self, "test-runtime",
runtime_name="test_runtime",
agent_runtime_artifact=agent_runtime_artifact,
tracing_enabled=True,
logging_configs=[agentcore.LoggingConfig(
log_type=agentcore.LogType.APPLICATION_LOGS,
destination=agentcore.LoggingDestination.cloud_watch_logs(log_group)
)
],
manage_delivery_resource_policy=False
)
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
AgentRuntimeArtifact agentRuntimeArtifact = AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
// Use a /aws/vendedlogs/ log group for same-account delivery without explicit resource policy
LogGroup logGroup = LogGroup.Builder.create(this, "RuntimeLogGroup")
.logGroupName("/aws/vendedlogs/bedrock-agentcore/my-runtime")
.build();
Runtime.Builder.create(this, "test-runtime")
.runtimeName("test_runtime")
.agentRuntimeArtifact(agentRuntimeArtifact)
.tracingEnabled(true)
.loggingConfigs(List.of(LoggingConfig.builder()
.logType(LogType.APPLICATION_LOGS)
.destination(LoggingDestination.cloudWatchLogs(logGroup))
.build()))
.manageDeliveryResourcePolicy(false)
.build();
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
var agentRuntimeArtifact = AgentRuntimeArtifact.FromEcrRepository(repository, "v1.0.0");
// Use a /aws/vendedlogs/ log group for same-account delivery without explicit resource policy
var logGroup = new LogGroup(this, "RuntimeLogGroup", new LogGroupProps {
LogGroupName = "/aws/vendedlogs/bedrock-agentcore/my-runtime"
});
new Runtime(this, "test-runtime", new RuntimeProps {
RuntimeName = "test_runtime",
AgentRuntimeArtifact = agentRuntimeArtifact,
TracingEnabled = true,
LoggingConfigs = new [] { new LoggingConfig {
LogType = LogType.APPLICATION_LOGS,
Destination = LoggingDestination.CloudWatchLogs(logGroup)
} },
ManageDeliveryResourcePolicy = false
});
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
agentRuntimeArtifact := agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v1.0.0"))
// Use a /aws/vendedlogs/ log group for same-account delivery without explicit resource policy
logGroup := logs.NewLogGroup(this, jsii.String("RuntimeLogGroup"), &LogGroupProps{
LogGroupName: jsii.String("/aws/vendedlogs/bedrock-agentcore/my-runtime"),
})
agentcore.NewRuntime(this, jsii.String("test-runtime"), &RuntimeProps{
RuntimeName: jsii.String("test_runtime"),
AgentRuntimeArtifact: agentRuntimeArtifact,
TracingEnabled: jsii.Boolean(true),
LoggingConfigs: []LoggingConfig{
&LoggingConfig{
LogType: agentcore.LogType_APPLICATION_LOGS(),
Destination: agentcore.LoggingDestination_CloudWatchLogs(logGroup),
},
},
ManageDeliveryResourcePolicy: jsii.Boolean(false),
})
const repository = new ecr.Repository(this, 'TestRepository', {
repositoryName: 'test-agent-runtime',
});
const agentRuntimeArtifact = agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, 'v1.0.0');
// Create logging destinations
const logGroup = new logs.LogGroup(this, 'RuntimeLogGroup');
const logBucket = new s3.Bucket(this, 'RuntimeLogBucket');
const firehoseStream = new firehose.DeliveryStream(this, 'RuntimeLogStream', {
destination: new firehose.S3Bucket(logBucket),
});
new agentcore.Runtime(this, 'test-runtime', {
runtimeName: 'test_runtime',
agentRuntimeArtifact: agentRuntimeArtifact,
tracingEnabled: true,
loggingConfigs: [
{
logType: agentcore.LogType.APPLICATION_LOGS,
destination: agentcore.LoggingDestination.cloudWatchLogs(logGroup),
},
{
logType: agentcore.LogType.APPLICATION_LOGS,
destination: agentcore.LoggingDestination.s3(logBucket),
},
{
logType: agentcore.LogType.APPLICATION_LOGS,
destination: agentcore.LoggingDestination.firehose(firehoseStream),
},
],
});
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
# Create logging destinations
log_group = logs.LogGroup(self, "RuntimeLogGroup")
log_bucket = s3.Bucket(self, "RuntimeLogBucket")
firehose_stream = firehose.DeliveryStream(self, "RuntimeLogStream",
destination=firehose.S3Bucket(log_bucket)
)
agentcore.Runtime(self, "test-runtime",
runtime_name="test_runtime",
agent_runtime_artifact=agent_runtime_artifact,
tracing_enabled=True,
logging_configs=[agentcore.LoggingConfig(
log_type=agentcore.LogType.APPLICATION_LOGS,
destination=agentcore.LoggingDestination.cloud_watch_logs(log_group)
), agentcore.LoggingConfig(
log_type=agentcore.LogType.APPLICATION_LOGS,
destination=agentcore.LoggingDestination.s3(log_bucket)
), agentcore.LoggingConfig(
log_type=agentcore.LogType.APPLICATION_LOGS,
destination=agentcore.LoggingDestination.firehose(firehose_stream)
)
]
)
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
AgentRuntimeArtifact agentRuntimeArtifact = AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
// Create logging destinations
LogGroup logGroup = new LogGroup(this, "RuntimeLogGroup");
Bucket logBucket = new Bucket(this, "RuntimeLogBucket");
DeliveryStream firehoseStream = DeliveryStream.Builder.create(this, "RuntimeLogStream")
.destination(new S3Bucket(logBucket))
.build();
Runtime.Builder.create(this, "test-runtime")
.runtimeName("test_runtime")
.agentRuntimeArtifact(agentRuntimeArtifact)
.tracingEnabled(true)
.loggingConfigs(List.of(LoggingConfig.builder()
.logType(LogType.APPLICATION_LOGS)
.destination(LoggingDestination.cloudWatchLogs(logGroup))
.build(), LoggingConfig.builder()
.logType(LogType.APPLICATION_LOGS)
.destination(LoggingDestination.s3(logBucket))
.build(), LoggingConfig.builder()
.logType(LogType.APPLICATION_LOGS)
.destination(LoggingDestination.firehose(firehoseStream))
.build()))
.build();
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
var agentRuntimeArtifact = AgentRuntimeArtifact.FromEcrRepository(repository, "v1.0.0");
// Create logging destinations
var logGroup = new LogGroup(this, "RuntimeLogGroup");
var logBucket = new Bucket(this, "RuntimeLogBucket");
var firehoseStream = new DeliveryStream(this, "RuntimeLogStream", new DeliveryStreamProps {
Destination = new S3Bucket(logBucket)
});
new Runtime(this, "test-runtime", new RuntimeProps {
RuntimeName = "test_runtime",
AgentRuntimeArtifact = agentRuntimeArtifact,
TracingEnabled = true,
LoggingConfigs = new [] { new LoggingConfig {
LogType = LogType.APPLICATION_LOGS,
Destination = LoggingDestination.CloudWatchLogs(logGroup)
}, new LoggingConfig {
LogType = LogType.APPLICATION_LOGS,
Destination = LoggingDestination.S3(logBucket)
}, new LoggingConfig {
LogType = LogType.APPLICATION_LOGS,
Destination = LoggingDestination.Firehose(firehoseStream)
} }
});
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
agentRuntimeArtifact := agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v1.0.0"))
// Create logging destinations
logGroup := logs.NewLogGroup(this, jsii.String("RuntimeLogGroup"))
logBucket := s3.NewBucket(this, jsii.String("RuntimeLogBucket"))
firehoseStream := firehose.NewDeliveryStream(this, jsii.String("RuntimeLogStream"), &DeliveryStreamProps{
Destination: firehose.NewS3Bucket(logBucket),
})
agentcore.NewRuntime(this, jsii.String("test-runtime"), &RuntimeProps{
RuntimeName: jsii.String("test_runtime"),
AgentRuntimeArtifact: agentRuntimeArtifact,
TracingEnabled: jsii.Boolean(true),
LoggingConfigs: []LoggingConfig{
&LoggingConfig{
LogType: agentcore.LogType_APPLICATION_LOGS(),
Destination: agentcore.LoggingDestination_CloudWatchLogs(logGroup),
},
&LoggingConfig{
LogType: agentcore.LogType_APPLICATION_LOGS(),
Destination: agentcore.LoggingDestination_S3(logBucket),
},
&LoggingConfig{
LogType: agentcore.LogType_APPLICATION_LOGS(),
Destination: agentcore.LoggingDestination_Firehose(firehoseStream),
},
},
})
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 applicationLogGroup so you can attach metric filters, subscription filters, or alarms without hardcoding the path:
const repository = new ecr.Repository(this, 'TestRepository');
const runtime = new agentcore.Runtime(this, 'Runtime', {
agentRuntimeArtifact: agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, 'v1.0.0'),
});
new logs.MetricFilter(this, 'ToolErrors', {
logGroup: runtime.applicationLogGroup,
filterPattern: logs.FilterPattern.stringValue('$.tool_status', '=', 'error'),
metricNamespace: 'MyApp',
metricName: 'ToolExecutionErrors',
});
repository = ecr.Repository(self, "TestRepository")
runtime = agentcore.Runtime(self, "Runtime",
agent_runtime_artifact=agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
)
logs.MetricFilter(self, "ToolErrors",
log_group=runtime.application_log_group,
filter_pattern=logs.FilterPattern.string_value("$.tool_status", "=", "error"),
metric_namespace="MyApp",
metric_name="ToolExecutionErrors"
)
Repository repository = new Repository(this, "TestRepository");
Runtime runtime = Runtime.Builder.create(this, "Runtime")
.agentRuntimeArtifact(AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0"))
.build();
MetricFilter.Builder.create(this, "ToolErrors")
.logGroup(runtime.getApplicationLogGroup())
.filterPattern(FilterPattern.stringValue("$.tool_status", "=", "error"))
.metricNamespace("MyApp")
.metricName("ToolExecutionErrors")
.build();
var repository = new Repository(this, "TestRepository");
var runtime = new Runtime(this, "Runtime", new RuntimeProps {
AgentRuntimeArtifact = AgentRuntimeArtifact.FromEcrRepository(repository, "v1.0.0")
});
new MetricFilter(this, "ToolErrors", new MetricFilterProps {
LogGroup = runtime.ApplicationLogGroup,
FilterPattern = FilterPattern.StringValue("$.tool_status", "=", "error"),
MetricNamespace = "MyApp",
MetricName = "ToolExecutionErrors"
});
repository := ecr.NewRepository(this, jsii.String("TestRepository"))
runtime := agentcore.NewRuntime(this, jsii.String("Runtime"), &RuntimeProps{
AgentRuntimeArtifact: agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v1.0.0")),
})
logs.NewMetricFilter(this, jsii.String("ToolErrors"), &MetricFilterProps{
LogGroup: runtime.applicationLogGroup,
FilterPattern: logs.FilterPattern_StringValue(jsii.String("$.tool_status"), jsii.String("="), jsii.String("error")),
MetricNamespace: jsii.String("MyApp"),
MetricName: jsii.String("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.
Platform version
Set platformVersion to choose the runtime platform (V1 or V2). If omitted when creating a runtime, the service applies its default platform version; if omitted when updating an existing runtime, the runtime keeps its current platform version.
Switching an existing runtime between platform versions updates it in place rather than replacing it. AgentCore creates a new runtime version, points the DEFAULT endpoint at it, leaves pinned endpoints on their versions, and drains in-flight sessions on the old one. Because V2 snapshots your agent, a V2 create or update takes a few minutes to reach READY (versus seconds on V1). See Platform versions for V2 specifics.
const repository = new ecr.Repository(this, 'TestRepository', {
repositoryName: 'test-agent-runtime',
});
const agentRuntimeArtifact = agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, 'v1.0.0');
new agentcore.Runtime(this, 'test-runtime', {
runtimeName: 'test_runtime',
agentRuntimeArtifact: agentRuntimeArtifact,
platformVersion: agentcore.PlatformVersion.V2,
});
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
agent_runtime_artifact = agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
agentcore.Runtime(self, "test-runtime",
runtime_name="test_runtime",
agent_runtime_artifact=agent_runtime_artifact,
platform_version=agentcore.PlatformVersion.V2
)
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
AgentRuntimeArtifact agentRuntimeArtifact = AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0");
Runtime.Builder.create(this, "test-runtime")
.runtimeName("test_runtime")
.agentRuntimeArtifact(agentRuntimeArtifact)
.platformVersion(PlatformVersion.V2)
.build();
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
var agentRuntimeArtifact = AgentRuntimeArtifact.FromEcrRepository(repository, "v1.0.0");
new Runtime(this, "test-runtime", new RuntimeProps {
RuntimeName = "test_runtime",
AgentRuntimeArtifact = agentRuntimeArtifact,
PlatformVersion = PlatformVersion.V2
});
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
agentRuntimeArtifact := agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v1.0.0"))
agentcore.NewRuntime(this, jsii.String("test-runtime"), &RuntimeProps{
RuntimeName: jsii.String("test_runtime"),
AgentRuntimeArtifact: agentRuntimeArtifact,
PlatformVersion: agentcore.PlatformVersion_V2(),
})
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:
Public Network Mode (
BrowserNetworkMode.usingPublicNetwork()) - Default- Allows internet access for web browsing and external API calls
- Suitable for scenarios where agents need to interact with publicly available websites
- Enables full web browsing capabilities
- VPC mode is not supported with this option
VPC (Virtual Private Cloud) (
BrowserNetworkMode.usingVpc())- Select whether to run the browser in a virtual private cloud (VPC).
- By configuring VPC connectivity, you enable secure access to private resources such as databases, internal APIs, and services within your VPC.
While the VPC itself is mandatory, these are optional:
- Subnets - if not provided, CDK will select appropriate subnets from the VPC
- Security Groups - if not provided, CDK will create a default security group
- Specific subnet selection criteria - you can let CDK choose automatically
For more information on VPC connectivity for Amazon Bedrock AgentCore Browser, please refer to the official documentation.
Browser Properties
| Name | Type | Required | Description |
|---|---|---|---|
browserCustomName | string | No | The name of the browser. Must start with a letter and can be up to 48 characters long. Pattern: [a-zA-Z][a-zA-Z0-9_]{0,47}. If not provided, a unique name will be auto-generated |
description | string | No | Optional description for the browser. Can have up to 200 characters |
networkConfiguration | BrowserNetworkConfiguration | No | Network configuration for browser. Defaults to PUBLIC network mode |
recordingConfig | RecordingConfig | No | Recording configuration for browser. Defaults to no recording |
executionRole | 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 |
browserSigning | BrowserSigning | No | Browser signing configuration. Defaults to DISABLED |
Basic Browser Creation
// Create a basic browser with public network access
const browser = new agentcore.BrowserCustom(this, "MyBrowser", {
browserCustomName: "my_browser",
description: "A browser for web automation",
});
# Create a basic browser with public network access
browser = agentcore.BrowserCustom(self, "MyBrowser",
browser_custom_name="my_browser",
description="A browser for web automation"
)
// Create a basic browser with public network access
BrowserCustom browser = BrowserCustom.Builder.create(this, "MyBrowser")
.browserCustomName("my_browser")
.description("A browser for web automation")
.build();
// Create a basic browser with public network access
var browser = new BrowserCustom(this, "MyBrowser", new BrowserCustomProps {
BrowserCustomName = "my_browser",
Description = "A browser for web automation"
});
// Create a basic browser with public network access
browser := agentcore.NewBrowserCustom(this, jsii.String("MyBrowser"), &BrowserCustomProps{
BrowserCustomName: jsii.String("my_browser"),
Description: jsii.String("A browser for web automation"),
})
Browser with Tags
// Create a browser with custom tags
const browser = new agentcore.BrowserCustom(this, "MyBrowser", {
browserCustomName: "my_browser",
description: "A browser for web automation with tags",
networkConfiguration: agentcore.BrowserNetworkConfiguration.usingPublicNetwork(),
tags: {
Environment: "Production",
Team: "AI/ML",
Project: "AgentCore",
},
});
# Create a browser with custom tags
browser = agentcore.BrowserCustom(self, "MyBrowser",
browser_custom_name="my_browser",
description="A browser for web automation with tags",
network_configuration=agentcore.BrowserNetworkConfiguration.using_public_network(),
tags={
"Environment": "Production",
"Team": "AI/ML",
"Project": "AgentCore"
}
)
// Create a browser with custom tags
BrowserCustom browser = BrowserCustom.Builder.create(this, "MyBrowser")
.browserCustomName("my_browser")
.description("A browser for web automation with tags")
.networkConfiguration(BrowserNetworkConfiguration.usingPublicNetwork())
.tags(Map.of(
"Environment", "Production",
"Team", "AI/ML",
"Project", "AgentCore"))
.build();
// Create a browser with custom tags
var browser = new BrowserCustom(this, "MyBrowser", new BrowserCustomProps {
BrowserCustomName = "my_browser",
Description = "A browser for web automation with tags",
NetworkConfiguration = BrowserNetworkConfiguration.UsingPublicNetwork(),
Tags = new Dictionary<string, string> {
{ "Environment", "Production" },
{ "Team", "AI/ML" },
{ "Project", "AgentCore" }
}
});
// Create a browser with custom tags
browser := agentcore.NewBrowserCustom(this, jsii.String("MyBrowser"), &BrowserCustomProps{
BrowserCustomName: jsii.String("my_browser"),
Description: jsii.String("A browser for web automation with tags"),
NetworkConfiguration: agentcore.BrowserNetworkConfiguration_UsingPublicNetwork(),
Tags: map[string]*string{
"Environment": jsii.String("Production"),
"Team": jsii.String("AI/ML"),
"Project": jsii.String("AgentCore"),
},
})
Browser with VPC
const browser = new agentcore.BrowserCustom(this, 'BrowserVpcWithRecording', {
browserCustomName: 'browser_recording',
networkConfiguration: agentcore.BrowserNetworkConfiguration.usingVpc(this, {
vpc: new ec2.Vpc(this, 'VPC', { restrictDefaultSecurityGroup: false }),
}),
});
browser = agentcore.BrowserCustom(self, "BrowserVpcWithRecording",
browser_custom_name="browser_recording",
network_configuration=agentcore.BrowserNetworkConfiguration.using_vpc(self,
vpc=ec2.Vpc(self, "VPC", restrict_default_security_group=False)
)
)
BrowserCustom browser = BrowserCustom.Builder.create(this, "BrowserVpcWithRecording")
.browserCustomName("browser_recording")
.networkConfiguration(BrowserNetworkConfiguration.usingVpc(this, VpcConfigProps.builder()
.vpc(Vpc.Builder.create(this, "VPC").restrictDefaultSecurityGroup(false).build())
.build()))
.build();
var browser = new BrowserCustom(this, "BrowserVpcWithRecording", new BrowserCustomProps {
BrowserCustomName = "browser_recording",
NetworkConfiguration = BrowserNetworkConfiguration.UsingVpc(this, new VpcConfigProps {
Vpc = new Vpc(this, "VPC", new VpcProps { RestrictDefaultSecurityGroup = false })
})
});
browser := agentcore.NewBrowserCustom(this, jsii.String("BrowserVpcWithRecording"), &BrowserCustomProps{
BrowserCustomName: jsii.String("browser_recording"),
NetworkConfiguration: agentcore.BrowserNetworkConfiguration_UsingVpc(this, &VpcConfigProps{
Vpc: ec2.NewVpc(this, jsii.String("VPC"), &VpcProps{
RestrictDefaultSecurityGroup: jsii.Boolean(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:
const vpc = new ec2.Vpc(this, 'testVPC');
const browser = new agentcore.BrowserCustom(this, 'test-browser', {
browserCustomName: 'test_browser',
networkConfiguration: agentcore.BrowserNetworkConfiguration.usingVpc(this, {
vpc: vpc,
}),
});
browser.connections.addSecurityGroup(new ec2.SecurityGroup(this, 'AdditionalGroup', { vpc }));
vpc = ec2.Vpc(self, "testVPC")
browser = agentcore.BrowserCustom(self, "test-browser",
browser_custom_name="test_browser",
network_configuration=agentcore.BrowserNetworkConfiguration.using_vpc(self,
vpc=vpc
)
)
browser.connections.add_security_group(ec2.SecurityGroup(self, "AdditionalGroup", vpc=vpc))
Vpc vpc = new Vpc(this, "testVPC");
BrowserCustom browser = BrowserCustom.Builder.create(this, "test-browser")
.browserCustomName("test_browser")
.networkConfiguration(BrowserNetworkConfiguration.usingVpc(this, VpcConfigProps.builder()
.vpc(vpc)
.build()))
.build();
browser.connections.addSecurityGroup(SecurityGroup.Builder.create(this, "AdditionalGroup").vpc(vpc).build());
var vpc = new Vpc(this, "testVPC");
var browser = new BrowserCustom(this, "test-browser", new BrowserCustomProps {
BrowserCustomName = "test_browser",
NetworkConfiguration = BrowserNetworkConfiguration.UsingVpc(this, new VpcConfigProps {
Vpc = vpc
})
});
browser.Connections.AddSecurityGroup(new SecurityGroup(this, "AdditionalGroup", new SecurityGroupProps { Vpc = vpc }));
vpc := ec2.NewVpc(this, jsii.String("testVPC"))
browser := agentcore.NewBrowserCustom(this, jsii.String("test-browser"), &BrowserCustomProps{
BrowserCustomName: jsii.String("test_browser"),
NetworkConfiguration: agentcore.BrowserNetworkConfiguration_UsingVpc(this, &VpcConfigProps{
Vpc: vpc,
}),
})
browser.connections.AddSecurityGroup(ec2.NewSecurityGroup(this, jsii.String("AdditionalGroup"), &SecurityGroupProps{
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
const recordingBucket = new s3.Bucket(this, "RecordingBucket", {
bucketName: "my-browser-recordings",
removalPolicy: RemovalPolicy.DESTROY, // For demo purposes
});
// Create browser with recording enabled
const browser = new agentcore.BrowserCustom(this, "MyBrowser", {
browserCustomName: "my_browser",
description: "Browser with recording enabled",
networkConfiguration: agentcore.BrowserNetworkConfiguration.usingPublicNetwork(),
recordingConfig: {
enabled: true,
s3Location: {
bucketName: recordingBucket.bucketName,
objectKey: "browser-recordings/",
},
},
});
# Create an S3 bucket for recordings
recording_bucket = s3.Bucket(self, "RecordingBucket",
bucket_name="my-browser-recordings",
removal_policy=RemovalPolicy.DESTROY
)
# Create browser with recording enabled
browser = agentcore.BrowserCustom(self, "MyBrowser",
browser_custom_name="my_browser",
description="Browser with recording enabled",
network_configuration=agentcore.BrowserNetworkConfiguration.using_public_network(),
recording_config=agentcore.RecordingConfig(
enabled=True,
s3_location=s3.Location(
bucket_name=recording_bucket.bucket_name,
object_key="browser-recordings/"
)
)
)
// Create an S3 bucket for recordings
Bucket recordingBucket = Bucket.Builder.create(this, "RecordingBucket")
.bucketName("my-browser-recordings")
.removalPolicy(RemovalPolicy.DESTROY)
.build();
// Create browser with recording enabled
BrowserCustom browser = BrowserCustom.Builder.create(this, "MyBrowser")
.browserCustomName("my_browser")
.description("Browser with recording enabled")
.networkConfiguration(BrowserNetworkConfiguration.usingPublicNetwork())
.recordingConfig(RecordingConfig.builder()
.enabled(true)
.s3Location(Location.builder()
.bucketName(recordingBucket.getBucketName())
.objectKey("browser-recordings/")
.build())
.build())
.build();
// Create an S3 bucket for recordings
var recordingBucket = new Bucket(this, "RecordingBucket", new BucketProps {
BucketName = "my-browser-recordings",
RemovalPolicy = RemovalPolicy.DESTROY
});
// Create browser with recording enabled
var browser = new BrowserCustom(this, "MyBrowser", new BrowserCustomProps {
BrowserCustomName = "my_browser",
Description = "Browser with recording enabled",
NetworkConfiguration = BrowserNetworkConfiguration.UsingPublicNetwork(),
RecordingConfig = new RecordingConfig {
Enabled = true,
S3Location = new Location {
BucketName = recordingBucket.BucketName,
ObjectKey = "browser-recordings/"
}
}
});
// Create an S3 bucket for recordings
recordingBucket := s3.NewBucket(this, jsii.String("RecordingBucket"), &BucketProps{
BucketName: jsii.String("my-browser-recordings"),
RemovalPolicy: awscdk.RemovalPolicy_DESTROY,
})
// Create browser with recording enabled
browser := agentcore.NewBrowserCustom(this, jsii.String("MyBrowser"), &BrowserCustomProps{
BrowserCustomName: jsii.String("my_browser"),
Description: jsii.String("Browser with recording enabled"),
NetworkConfiguration: agentcore.BrowserNetworkConfiguration_UsingPublicNetwork(),
RecordingConfig: &RecordingConfig{
Enabled: jsii.Boolean(true),
S3Location: &Location{
BucketName: recordingBucket.bucketName,
ObjectKey: jsii.String("browser-recordings/"),
},
},
})
Browser with Custom Execution Role
// Create a custom execution role
const executionRole = new iam.Role(this, "BrowserExecutionRole", {
assumedBy: new iam.ServicePrincipal("bedrock-agentcore.amazonaws.com"),
managedPolicies: [
iam.ManagedPolicy.fromAwsManagedPolicyName("AmazonBedrockAgentCoreBrowserExecutionRolePolicy"),
],
});
// Create browser with custom execution role
const browser = new agentcore.BrowserCustom(this, "MyBrowser", {
browserCustomName: "my_browser",
description: "Browser with custom execution role",
networkConfiguration: agentcore.BrowserNetworkConfiguration.usingPublicNetwork(),
executionRole: executionRole,
});
# Create a custom execution role
execution_role = iam.Role(self, "BrowserExecutionRole",
assumed_by=iam.ServicePrincipal("bedrock-agentcore.amazonaws.com"),
managed_policies=[
iam.ManagedPolicy.from_aws_managed_policy_name("AmazonBedrockAgentCoreBrowserExecutionRolePolicy")
]
)
# Create browser with custom execution role
browser = agentcore.BrowserCustom(self, "MyBrowser",
browser_custom_name="my_browser",
description="Browser with custom execution role",
network_configuration=agentcore.BrowserNetworkConfiguration.using_public_network(),
execution_role=execution_role
)
// Create a custom execution role
Role executionRole = Role.Builder.create(this, "BrowserExecutionRole")
.assumedBy(new ServicePrincipal("bedrock-agentcore.amazonaws.com"))
.managedPolicies(List.of(ManagedPolicy.fromAwsManagedPolicyName("AmazonBedrockAgentCoreBrowserExecutionRolePolicy")))
.build();
// Create browser with custom execution role
BrowserCustom browser = BrowserCustom.Builder.create(this, "MyBrowser")
.browserCustomName("my_browser")
.description("Browser with custom execution role")
.networkConfiguration(BrowserNetworkConfiguration.usingPublicNetwork())
.executionRole(executionRole)
.build();
// Create a custom execution role
var executionRole = new Role(this, "BrowserExecutionRole", new RoleProps {
AssumedBy = new ServicePrincipal("bedrock-agentcore.amazonaws.com"),
ManagedPolicies = new [] { ManagedPolicy.FromAwsManagedPolicyName("AmazonBedrockAgentCoreBrowserExecutionRolePolicy") }
});
// Create browser with custom execution role
var browser = new BrowserCustom(this, "MyBrowser", new BrowserCustomProps {
BrowserCustomName = "my_browser",
Description = "Browser with custom execution role",
NetworkConfiguration = BrowserNetworkConfiguration.UsingPublicNetwork(),
ExecutionRole = executionRole
});
// Create a custom execution role
executionRole := iam.NewRole(this, jsii.String("BrowserExecutionRole"), &RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("bedrock-agentcore.amazonaws.com")),
ManagedPolicies: []IManagedPolicy{
iam.ManagedPolicy_FromAwsManagedPolicyName(jsii.String("AmazonBedrockAgentCoreBrowserExecutionRolePolicy")),
},
})
// Create browser with custom execution role
browser := agentcore.NewBrowserCustom(this, jsii.String("MyBrowser"), &BrowserCustomProps{
BrowserCustomName: jsii.String("my_browser"),
Description: jsii.String("Browser with custom execution role"),
NetworkConfiguration: agentcore.BrowserNetworkConfiguration_UsingPublicNetwork(),
ExecutionRole: executionRole,
})
Browser with S3 Recording and Permissions
// Create an S3 bucket for recordings
const recordingBucket = new s3.Bucket(this, "RecordingBucket", {
bucketName: "my-browser-recordings",
removalPolicy: RemovalPolicy.DESTROY, // For demo purposes
});
// Create browser with recording enabled
const browser = new agentcore.BrowserCustom(this, "MyBrowser", {
browserCustomName: "my_browser",
description: "Browser with recording enabled",
networkConfiguration: agentcore.BrowserNetworkConfiguration.usingPublicNetwork(),
recordingConfig: {
enabled: true,
s3Location: {
bucketName: recordingBucket.bucketName,
objectKey: "browser-recordings/",
},
},
});
// When recording is enabled with an S3 location, the browser construct grants the
// execution role least-privilege access to write recordings: s3:PutObject,
// s3:ListMultipartUploadParts, and s3:AbortMultipartUpload, scoped to the recording
// prefix objects (bucket/prefix/*). No additional IAM configuration is needed. If the
// recording bucket is encrypted with a customer managed KMS key, grant the execution
// role kms:GenerateDataKey and kms:Decrypt on that key separately, since the bucket is
// imported by name.
# Create an S3 bucket for recordings
recording_bucket = s3.Bucket(self, "RecordingBucket",
bucket_name="my-browser-recordings",
removal_policy=RemovalPolicy.DESTROY
)
# Create browser with recording enabled
browser = agentcore.BrowserCustom(self, "MyBrowser",
browser_custom_name="my_browser",
description="Browser with recording enabled",
network_configuration=agentcore.BrowserNetworkConfiguration.using_public_network(),
recording_config=agentcore.RecordingConfig(
enabled=True,
s3_location=s3.Location(
bucket_name=recording_bucket.bucket_name,
object_key="browser-recordings/"
)
)
)
// Create an S3 bucket for recordings
Bucket recordingBucket = Bucket.Builder.create(this, "RecordingBucket")
.bucketName("my-browser-recordings")
.removalPolicy(RemovalPolicy.DESTROY)
.build();
// Create browser with recording enabled
BrowserCustom browser = BrowserCustom.Builder.create(this, "MyBrowser")
.browserCustomName("my_browser")
.description("Browser with recording enabled")
.networkConfiguration(BrowserNetworkConfiguration.usingPublicNetwork())
.recordingConfig(RecordingConfig.builder()
.enabled(true)
.s3Location(Location.builder()
.bucketName(recordingBucket.getBucketName())
.objectKey("browser-recordings/")
.build())
.build())
.build();
// Create an S3 bucket for recordings
var recordingBucket = new Bucket(this, "RecordingBucket", new BucketProps {
BucketName = "my-browser-recordings",
RemovalPolicy = RemovalPolicy.DESTROY
});
// Create browser with recording enabled
var browser = new BrowserCustom(this, "MyBrowser", new BrowserCustomProps {
BrowserCustomName = "my_browser",
Description = "Browser with recording enabled",
NetworkConfiguration = BrowserNetworkConfiguration.UsingPublicNetwork(),
RecordingConfig = new RecordingConfig {
Enabled = true,
S3Location = new Location {
BucketName = recordingBucket.BucketName,
ObjectKey = "browser-recordings/"
}
}
});
// Create an S3 bucket for recordings
recordingBucket := s3.NewBucket(this, jsii.String("RecordingBucket"), &BucketProps{
BucketName: jsii.String("my-browser-recordings"),
RemovalPolicy: awscdk.RemovalPolicy_DESTROY,
})
// Create browser with recording enabled
browser := agentcore.NewBrowserCustom(this, jsii.String("MyBrowser"), &BrowserCustomProps{
BrowserCustomName: jsii.String("my_browser"),
Description: jsii.String("Browser with recording enabled"),
NetworkConfiguration: agentcore.BrowserNetworkConfiguration_UsingPublicNetwork(),
RecordingConfig: &RecordingConfig{
Enabled: jsii.Boolean(true),
S3Location: &Location{
BucketName: recordingBucket.bucketName,
ObjectKey: jsii.String("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:
const browser = new agentcore.BrowserCustom(this, 'test-browser', {
browserCustomName: 'test_browser',
browserSigning: agentcore.BrowserSigning.ENABLED
});
browser = agentcore.BrowserCustom(self, "test-browser",
browser_custom_name="test_browser",
browser_signing=agentcore.BrowserSigning.ENABLED
)
BrowserCustom browser = BrowserCustom.Builder.create(this, "test-browser")
.browserCustomName("test_browser")
.browserSigning(BrowserSigning.ENABLED)
.build();
var browser = new BrowserCustom(this, "test-browser", new BrowserCustomProps {
BrowserCustomName = "test_browser",
BrowserSigning = BrowserSigning.ENABLED
});
browser := agentcore.NewBrowserCustom(this, jsii.String("test-browser"), &BrowserCustomProps{
BrowserCustomName: jsii.String("test_browser"),
BrowserSigning: agentcore.BrowserSigning_ENABLED,
})
Browser IAM Permissions
The Browser construct provides convenient methods for granting IAM permissions:
// Create a browser
const browser = new agentcore.BrowserCustom(this, "MyBrowser", {
browserCustomName: "my_browser",
description: "Browser for web automation",
networkConfiguration: agentcore.BrowserNetworkConfiguration.usingPublicNetwork(),
});
// Create a role that needs access to the browser
const userRole = new iam.Role(this, "UserRole", {
assumedBy: new iam.ServicePrincipal("lambda.amazonaws.com"),
});
// Grant read permissions (Get and List actions)
browser.grantRead(userRole);
// Grant use permissions (Start, Update, Connect to the automation stream, and Stop actions)
browser.grantUse(userRole);
// Grant specific custom permissions
browser.grant(userRole, "bedrock-agentcore:GetBrowserSession");
# Create a browser
browser = agentcore.BrowserCustom(self, "MyBrowser",
browser_custom_name="my_browser",
description="Browser for web automation",
network_configuration=agentcore.BrowserNetworkConfiguration.using_public_network()
)
# Create a role that needs access to the browser
user_role = iam.Role(self, "UserRole",
assumed_by=iam.ServicePrincipal("lambda.amazonaws.com")
)
# Grant read permissions (Get and List actions)
browser.grant_read(user_role)
# Grant use permissions (Start, Update, Connect to the automation stream, and Stop actions)
browser.grant_use(user_role)
# Grant specific custom permissions
browser.grant(user_role, "bedrock-agentcore:GetBrowserSession")
// Create a browser
BrowserCustom browser = BrowserCustom.Builder.create(this, "MyBrowser")
.browserCustomName("my_browser")
.description("Browser for web automation")
.networkConfiguration(BrowserNetworkConfiguration.usingPublicNetwork())
.build();
// Create a role that needs access to the browser
Role userRole = Role.Builder.create(this, "UserRole")
.assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
.build();
// Grant read permissions (Get and List actions)
browser.grantRead(userRole);
// Grant use permissions (Start, Update, Connect to the automation stream, and Stop actions)
browser.grantUse(userRole);
// Grant specific custom permissions
browser.grant(userRole, "bedrock-agentcore:GetBrowserSession");
// Create a browser
var browser = new BrowserCustom(this, "MyBrowser", new BrowserCustomProps {
BrowserCustomName = "my_browser",
Description = "Browser for web automation",
NetworkConfiguration = BrowserNetworkConfiguration.UsingPublicNetwork()
});
// Create a role that needs access to the browser
var userRole = new Role(this, "UserRole", new RoleProps {
AssumedBy = new ServicePrincipal("lambda.amazonaws.com")
});
// Grant read permissions (Get and List actions)
browser.GrantRead(userRole);
// Grant use permissions (Start, Update, Connect to the automation stream, and Stop actions)
browser.GrantUse(userRole);
// Grant specific custom permissions
browser.Grant(userRole, "bedrock-agentcore:GetBrowserSession");
// Create a browser
browser := agentcore.NewBrowserCustom(this, jsii.String("MyBrowser"), &BrowserCustomProps{
BrowserCustomName: jsii.String("my_browser"),
Description: jsii.String("Browser for web automation"),
NetworkConfiguration: agentcore.BrowserNetworkConfiguration_UsingPublicNetwork(),
})
// Create a role that needs access to the browser
userRole := iam.NewRole(this, jsii.String("UserRole"), &RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("lambda.amazonaws.com")),
})
// Grant read permissions (Get and List actions)
browser.GrantRead(userRole)
// Grant use permissions (Start, Update, Connect to the automation stream, and Stop actions)
browser.GrantUse(userRole)
// Grant specific custom permissions
browser.Grant(userRole, jsii.String("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:
Public Network Mode (
CodeInterpreterNetworkMode.usingPublicNetwork()) - Default- Allows internet access for package installation and external API calls
- Suitable for development and testing environments
- Enables downloading Python packages from PyPI
Sandbox Network Mode (
CodeInterpreterNetworkMode.usingSandboxNetwork())- Isolated network environment with no internet access
- Suitable for production environments with strict security requirements
- Only allows access to pre-installed packages and local resources
VPC (Virtual Private Cloud) (
CodeInterpreterNetworkMode.usingVpc())- Select whether to run the browser in a virtual private cloud (VPC).
- By configuring VPC connectivity, you enable secure access to private resources such as databases, internal APIs, and services within your VPC.
While the VPC itself is mandatory, these are optional:
- Subnets - if not provided, CDK will select appropriate subnets from the VPC
- Security Groups - if not provided, CDK will create a default security group
- Specific subnet selection criteria - you can let CDK choose automatically
For more information on VPC connectivity for Amazon Bedrock AgentCore Browser, please refer to the official documentation.
Code Interpreter Properties
| Name | Type | Required | Description |
|---|---|---|---|
codeInterpreterCustomName | 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 |
executionRole | 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 |
networkConfiguration | 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
const codeInterpreter = new agentcore.CodeInterpreterCustom(this, "MyCodeInterpreter", {
codeInterpreterCustomName: "my_code_interpreter",
description: "A code interpreter for Python execution",
});
# Create a basic code interpreter with public network access
code_interpreter = agentcore.CodeInterpreterCustom(self, "MyCodeInterpreter",
code_interpreter_custom_name="my_code_interpreter",
description="A code interpreter for Python execution"
)
// Create a basic code interpreter with public network access
CodeInterpreterCustom codeInterpreter = CodeInterpreterCustom.Builder.create(this, "MyCodeInterpreter")
.codeInterpreterCustomName("my_code_interpreter")
.description("A code interpreter for Python execution")
.build();
// Create a basic code interpreter with public network access
var codeInterpreter = new CodeInterpreterCustom(this, "MyCodeInterpreter", new CodeInterpreterCustomProps {
CodeInterpreterCustomName = "my_code_interpreter",
Description = "A code interpreter for Python execution"
});
// Create a basic code interpreter with public network access
codeInterpreter := agentcore.NewCodeInterpreterCustom(this, jsii.String("MyCodeInterpreter"), &CodeInterpreterCustomProps{
CodeInterpreterCustomName: jsii.String("my_code_interpreter"),
Description: jsii.String("A code interpreter for Python execution"),
})
Code Interpreter with VPC
const codeInterpreter = new agentcore.CodeInterpreterCustom(this, "MyCodeInterpreter", {
codeInterpreterCustomName: "my_sandbox_interpreter",
description: "Code interpreter with isolated network access",
networkConfiguration: agentcore.BrowserNetworkConfiguration.usingVpc(this, {
vpc: new ec2.Vpc(this, 'VPC', { restrictDefaultSecurityGroup: false }),
}),
});
code_interpreter = agentcore.CodeInterpreterCustom(self, "MyCodeInterpreter",
code_interpreter_custom_name="my_sandbox_interpreter",
description="Code interpreter with isolated network access",
network_configuration=agentcore.BrowserNetworkConfiguration.using_vpc(self,
vpc=ec2.Vpc(self, "VPC", restrict_default_security_group=False)
)
)
CodeInterpreterCustom codeInterpreter = CodeInterpreterCustom.Builder.create(this, "MyCodeInterpreter")
.codeInterpreterCustomName("my_sandbox_interpreter")
.description("Code interpreter with isolated network access")
.networkConfiguration(BrowserNetworkConfiguration.usingVpc(this, VpcConfigProps.builder()
.vpc(Vpc.Builder.create(this, "VPC").restrictDefaultSecurityGroup(false).build())
.build()))
.build();
var codeInterpreter = new CodeInterpreterCustom(this, "MyCodeInterpreter", new CodeInterpreterCustomProps {
CodeInterpreterCustomName = "my_sandbox_interpreter",
Description = "Code interpreter with isolated network access",
NetworkConfiguration = BrowserNetworkConfiguration.UsingVpc(this, new VpcConfigProps {
Vpc = new Vpc(this, "VPC", new VpcProps { RestrictDefaultSecurityGroup = false })
})
});
codeInterpreter := agentcore.NewCodeInterpreterCustom(this, jsii.String("MyCodeInterpreter"), &CodeInterpreterCustomProps{
CodeInterpreterCustomName: jsii.String("my_sandbox_interpreter"),
Description: jsii.String("Code interpreter with isolated network access"),
NetworkConfiguration: agentcore.BrowserNetworkConfiguration_UsingVpc(this, &VpcConfigProps{
Vpc: ec2.NewVpc(this, jsii.String("VPC"), &VpcProps{
RestrictDefaultSecurityGroup: jsii.Boolean(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:
const vpc = new ec2.Vpc(this, 'testVPC');
const codeInterpreter = new agentcore.CodeInterpreterCustom(this, "MyCodeInterpreter", {
codeInterpreterCustomName: "my_sandbox_interpreter",
description: "Code interpreter with isolated network access",
networkConfiguration: agentcore.BrowserNetworkConfiguration.usingVpc(this, {
vpc: vpc,
}),
});
codeInterpreter.connections.addSecurityGroup(new ec2.SecurityGroup(this, 'AdditionalGroup', { vpc }));
vpc = ec2.Vpc(self, "testVPC")
code_interpreter = agentcore.CodeInterpreterCustom(self, "MyCodeInterpreter",
code_interpreter_custom_name="my_sandbox_interpreter",
description="Code interpreter with isolated network access",
network_configuration=agentcore.BrowserNetworkConfiguration.using_vpc(self,
vpc=vpc
)
)
code_interpreter.connections.add_security_group(ec2.SecurityGroup(self, "AdditionalGroup", vpc=vpc))
Vpc vpc = new Vpc(this, "testVPC");
CodeInterpreterCustom codeInterpreter = CodeInterpreterCustom.Builder.create(this, "MyCodeInterpreter")
.codeInterpreterCustomName("my_sandbox_interpreter")
.description("Code interpreter with isolated network access")
.networkConfiguration(BrowserNetworkConfiguration.usingVpc(this, VpcConfigProps.builder()
.vpc(vpc)
.build()))
.build();
codeInterpreter.connections.addSecurityGroup(SecurityGroup.Builder.create(this, "AdditionalGroup").vpc(vpc).build());
var vpc = new Vpc(this, "testVPC");
var codeInterpreter = new CodeInterpreterCustom(this, "MyCodeInterpreter", new CodeInterpreterCustomProps {
CodeInterpreterCustomName = "my_sandbox_interpreter",
Description = "Code interpreter with isolated network access",
NetworkConfiguration = BrowserNetworkConfiguration.UsingVpc(this, new VpcConfigProps {
Vpc = vpc
})
});
codeInterpreter.Connections.AddSecurityGroup(new SecurityGroup(this, "AdditionalGroup", new SecurityGroupProps { Vpc = vpc }));
vpc := ec2.NewVpc(this, jsii.String("testVPC"))
codeInterpreter := agentcore.NewCodeInterpreterCustom(this, jsii.String("MyCodeInterpreter"), &CodeInterpreterCustomProps{
CodeInterpreterCustomName: jsii.String("my_sandbox_interpreter"),
Description: jsii.String("Code interpreter with isolated network access"),
NetworkConfiguration: agentcore.BrowserNetworkConfiguration_UsingVpc(this, &VpcConfigProps{
Vpc: vpc,
}),
})
codeInterpreter.connections.AddSecurityGroup(ec2.NewSecurityGroup(this, jsii.String("AdditionalGroup"), &SecurityGroupProps{
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)
const codeInterpreter = new agentcore.CodeInterpreterCustom(this, "MyCodeInterpreter", {
codeInterpreterCustomName: "my_sandbox_interpreter",
description: "Code interpreter with isolated network access",
networkConfiguration: agentcore.CodeInterpreterNetworkConfiguration.usingSandboxNetwork(),
});
# Create code interpreter with sandbox network mode (isolated)
code_interpreter = agentcore.CodeInterpreterCustom(self, "MyCodeInterpreter",
code_interpreter_custom_name="my_sandbox_interpreter",
description="Code interpreter with isolated network access",
network_configuration=agentcore.CodeInterpreterNetworkConfiguration.using_sandbox_network()
)
// Create code interpreter with sandbox network mode (isolated)
CodeInterpreterCustom codeInterpreter = CodeInterpreterCustom.Builder.create(this, "MyCodeInterpreter")
.codeInterpreterCustomName("my_sandbox_interpreter")
.description("Code interpreter with isolated network access")
.networkConfiguration(CodeInterpreterNetworkConfiguration.usingSandboxNetwork())
.build();
// Create code interpreter with sandbox network mode (isolated)
var codeInterpreter = new CodeInterpreterCustom(this, "MyCodeInterpreter", new CodeInterpreterCustomProps {
CodeInterpreterCustomName = "my_sandbox_interpreter",
Description = "Code interpreter with isolated network access",
NetworkConfiguration = CodeInterpreterNetworkConfiguration.UsingSandboxNetwork()
});
// Create code interpreter with sandbox network mode (isolated)
codeInterpreter := agentcore.NewCodeInterpreterCustom(this, jsii.String("MyCodeInterpreter"), &CodeInterpreterCustomProps{
CodeInterpreterCustomName: jsii.String("my_sandbox_interpreter"),
Description: jsii.String("Code interpreter with isolated network access"),
NetworkConfiguration: agentcore.CodeInterpreterNetworkConfiguration_UsingSandboxNetwork(),
})
Code Interpreter with Custom Execution Role
// Create a custom execution role
const executionRole = new iam.Role(this, "CodeInterpreterExecutionRole", {
assumedBy: new iam.ServicePrincipal("bedrock-agentcore.amazonaws.com"),
});
// Create code interpreter with custom execution role
const codeInterpreter = new agentcore.CodeInterpreterCustom(this, "MyCodeInterpreter", {
codeInterpreterCustomName: "my_code_interpreter",
description: "Code interpreter with custom execution role",
networkConfiguration: agentcore.CodeInterpreterNetworkConfiguration.usingPublicNetwork(),
executionRole: executionRole,
});
# Create a custom execution role
execution_role = iam.Role(self, "CodeInterpreterExecutionRole",
assumed_by=iam.ServicePrincipal("bedrock-agentcore.amazonaws.com")
)
# Create code interpreter with custom execution role
code_interpreter = agentcore.CodeInterpreterCustom(self, "MyCodeInterpreter",
code_interpreter_custom_name="my_code_interpreter",
description="Code interpreter with custom execution role",
network_configuration=agentcore.CodeInterpreterNetworkConfiguration.using_public_network(),
execution_role=execution_role
)
// Create a custom execution role
Role executionRole = Role.Builder.create(this, "CodeInterpreterExecutionRole")
.assumedBy(new ServicePrincipal("bedrock-agentcore.amazonaws.com"))
.build();
// Create code interpreter with custom execution role
CodeInterpreterCustom codeInterpreter = CodeInterpreterCustom.Builder.create(this, "MyCodeInterpreter")
.codeInterpreterCustomName("my_code_interpreter")
.description("Code interpreter with custom execution role")
.networkConfiguration(CodeInterpreterNetworkConfiguration.usingPublicNetwork())
.executionRole(executionRole)
.build();
// Create a custom execution role
var executionRole = new Role(this, "CodeInterpreterExecutionRole", new RoleProps {
AssumedBy = new ServicePrincipal("bedrock-agentcore.amazonaws.com")
});
// Create code interpreter with custom execution role
var codeInterpreter = new CodeInterpreterCustom(this, "MyCodeInterpreter", new CodeInterpreterCustomProps {
CodeInterpreterCustomName = "my_code_interpreter",
Description = "Code interpreter with custom execution role",
NetworkConfiguration = CodeInterpreterNetworkConfiguration.UsingPublicNetwork(),
ExecutionRole = executionRole
});
// Create a custom execution role
executionRole := iam.NewRole(this, jsii.String("CodeInterpreterExecutionRole"), &RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("bedrock-agentcore.amazonaws.com")),
})
// Create code interpreter with custom execution role
codeInterpreter := agentcore.NewCodeInterpreterCustom(this, jsii.String("MyCodeInterpreter"), &CodeInterpreterCustomProps{
CodeInterpreterCustomName: jsii.String("my_code_interpreter"),
Description: jsii.String("Code interpreter with custom execution role"),
NetworkConfiguration: agentcore.CodeInterpreterNetworkConfiguration_UsingPublicNetwork(),
ExecutionRole: executionRole,
})
Code Interpreter IAM Permissions
The Code Interpreter construct provides convenient methods for granting IAM permissions:
// Create a code interpreter
const codeInterpreter = new agentcore.CodeInterpreterCustom(this, "MyCodeInterpreter", {
codeInterpreterCustomName: "my_code_interpreter",
description: "Code interpreter for Python execution",
networkConfiguration: agentcore.CodeInterpreterNetworkConfiguration.usingPublicNetwork(),
});
// Create a role that needs access to the code interpreter
const userRole = new iam.Role(this, "UserRole", {
assumedBy: new iam.ServicePrincipal("lambda.amazonaws.com"),
});
// Grant read permissions (Get and List actions)
codeInterpreter.grantRead(userRole);
// Grant use permissions (Start, Invoke, Stop actions)
codeInterpreter.grantUse(userRole);
// Grant specific custom permissions
codeInterpreter.grant(userRole, "bedrock-agentcore:GetCodeInterpreterSession");
# Create a code interpreter
code_interpreter = agentcore.CodeInterpreterCustom(self, "MyCodeInterpreter",
code_interpreter_custom_name="my_code_interpreter",
description="Code interpreter for Python execution",
network_configuration=agentcore.CodeInterpreterNetworkConfiguration.using_public_network()
)
# Create a role that needs access to the code interpreter
user_role = iam.Role(self, "UserRole",
assumed_by=iam.ServicePrincipal("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")
// Create a code interpreter
CodeInterpreterCustom codeInterpreter = CodeInterpreterCustom.Builder.create(this, "MyCodeInterpreter")
.codeInterpreterCustomName("my_code_interpreter")
.description("Code interpreter for Python execution")
.networkConfiguration(CodeInterpreterNetworkConfiguration.usingPublicNetwork())
.build();
// Create a role that needs access to the code interpreter
Role userRole = Role.Builder.create(this, "UserRole")
.assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
.build();
// Grant read permissions (Get and List actions)
codeInterpreter.grantRead(userRole);
// Grant use permissions (Start, Invoke, Stop actions)
codeInterpreter.grantUse(userRole);
// Grant specific custom permissions
codeInterpreter.grant(userRole, "bedrock-agentcore:GetCodeInterpreterSession");
// Create a code interpreter
var codeInterpreter = new CodeInterpreterCustom(this, "MyCodeInterpreter", new CodeInterpreterCustomProps {
CodeInterpreterCustomName = "my_code_interpreter",
Description = "Code interpreter for Python execution",
NetworkConfiguration = CodeInterpreterNetworkConfiguration.UsingPublicNetwork()
});
// Create a role that needs access to the code interpreter
var userRole = new Role(this, "UserRole", new RoleProps {
AssumedBy = new ServicePrincipal("lambda.amazonaws.com")
});
// Grant read permissions (Get and List actions)
codeInterpreter.GrantRead(userRole);
// Grant use permissions (Start, Invoke, Stop actions)
codeInterpreter.GrantUse(userRole);
// Grant specific custom permissions
codeInterpreter.Grant(userRole, "bedrock-agentcore:GetCodeInterpreterSession");
// Create a code interpreter
codeInterpreter := agentcore.NewCodeInterpreterCustom(this, jsii.String("MyCodeInterpreter"), &CodeInterpreterCustomProps{
CodeInterpreterCustomName: jsii.String("my_code_interpreter"),
Description: jsii.String("Code interpreter for Python execution"),
NetworkConfiguration: agentcore.CodeInterpreterNetworkConfiguration_UsingPublicNetwork(),
})
// Create a role that needs access to the code interpreter
userRole := iam.NewRole(this, jsii.String("UserRole"), &RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("lambda.amazonaws.com")),
})
// Grant read permissions (Get and List actions)
codeInterpreter.GrantRead(userRole)
// Grant use permissions (Start, Invoke, Stop actions)
codeInterpreter.GrantUse(userRole)
// Grant specific custom permissions
codeInterpreter.Grant(userRole, jsii.String("bedrock-agentcore:GetCodeInterpreterSession"))
Code interpreter with tags
// Create code interpreter with sandbox network mode (isolated)
const codeInterpreter = new agentcore.CodeInterpreterCustom(this, "MyCodeInterpreter", {
codeInterpreterCustomName: "my_sandbox_interpreter",
description: "Code interpreter with isolated network access",
networkConfiguration: agentcore.CodeInterpreterNetworkConfiguration.usingPublicNetwork(),
tags: {
Environment: "Production",
Team: "AI/ML",
Project: "AgentCore",
},
});
# Create code interpreter with sandbox network mode (isolated)
code_interpreter = agentcore.CodeInterpreterCustom(self, "MyCodeInterpreter",
code_interpreter_custom_name="my_sandbox_interpreter",
description="Code interpreter with isolated network access",
network_configuration=agentcore.CodeInterpreterNetworkConfiguration.using_public_network(),
tags={
"Environment": "Production",
"Team": "AI/ML",
"Project": "AgentCore"
}
)
// Create code interpreter with sandbox network mode (isolated)
CodeInterpreterCustom codeInterpreter = CodeInterpreterCustom.Builder.create(this, "MyCodeInterpreter")
.codeInterpreterCustomName("my_sandbox_interpreter")
.description("Code interpreter with isolated network access")
.networkConfiguration(CodeInterpreterNetworkConfiguration.usingPublicNetwork())
.tags(Map.of(
"Environment", "Production",
"Team", "AI/ML",
"Project", "AgentCore"))
.build();
// Create code interpreter with sandbox network mode (isolated)
var codeInterpreter = new CodeInterpreterCustom(this, "MyCodeInterpreter", new CodeInterpreterCustomProps {
CodeInterpreterCustomName = "my_sandbox_interpreter",
Description = "Code interpreter with isolated network access",
NetworkConfiguration = CodeInterpreterNetworkConfiguration.UsingPublicNetwork(),
Tags = new Dictionary<string, string> {
{ "Environment", "Production" },
{ "Team", "AI/ML" },
{ "Project", "AgentCore" }
}
});
// Create code interpreter with sandbox network mode (isolated)
codeInterpreter := agentcore.NewCodeInterpreterCustom(this, jsii.String("MyCodeInterpreter"), &CodeInterpreterCustomProps{
CodeInterpreterCustomName: jsii.String("my_sandbox_interpreter"),
Description: jsii.String("Code interpreter with isolated network access"),
NetworkConfiguration: agentcore.CodeInterpreterNetworkConfiguration_UsingPublicNetwork(),
Tags: map[string]*string{
"Environment": jsii.String("Production"),
"Team": jsii.String("AI/ML"),
"Project": jsii.String("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 |
|---|---|---|---|
gatewayName | 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 |
protocolConfiguration | IGatewayProtocolConfig | No | The protocol configuration for the gateway. Defaults to MCP protocol |
authorizerConfiguration | IGatewayAuthorizerConfig | No | The authorizer configuration for the gateway. Defaults to Cognito |
exceptionLevel | GatewayExceptionLevel | No | The verbosity of exception messages. Use DEBUG mode to see granular exception messages |
kmsKey | 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 |
policyEngineConfiguration | GatewayPolicyEngineConfig | No | Associates a policy engine with this gateway. All agent requests are evaluated against the Cedar policies in the engine. The gateway role is automatically granted evaluate permissions. Default: no policy engine |
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
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
});
# Create a basic gateway with default MCP protocol and Cognito authorizer
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway"
)
// Create a basic gateway with default MCP protocol and Cognito authorizer
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.build();
// Create a basic gateway with default MCP protocol and Cognito authorizer
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway"
});
// Create a basic gateway with default MCP protocol and Cognito authorizer
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
})
Protocol configuration
Currently MCP is the only protocol available. To configure it, use the protocol property with McpProtocolConfiguration:
- Instructions: Guidance for how to use the gateway with your tools
- Semantic search: Smart tool discovery that finds the right tools without typical limits. It improves accuracy by finding relevant tools based on context
- Supported versions: Which MCP protocol versions the gateway can use
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
protocolConfiguration: new agentcore.McpProtocolConfiguration({
instructions: "Use this gateway to connect to external MCP tools",
searchType: agentcore.McpGatewaySearchType.SEMANTIC,
supportedVersions: [agentcore.MCPProtocolVersion.MCP_2025_03_26],
}),
});
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway",
protocol_configuration=agentcore.McpProtocolConfiguration(
instructions="Use this gateway to connect to external MCP tools",
search_type=agentcore.McpGatewaySearchType.SEMANTIC,
supported_versions=[agentcore.MCPProtocolVersion.MCP_2025_03_26]
)
)
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.protocolConfiguration(McpProtocolConfiguration.Builder.create()
.instructions("Use this gateway to connect to external MCP tools")
.searchType(McpGatewaySearchType.SEMANTIC)
.supportedVersions(List.of(MCPProtocolVersion.MCP_2025_03_26))
.build())
.build();
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway",
ProtocolConfiguration = new McpProtocolConfiguration(new McpConfiguration {
Instructions = "Use this gateway to connect to external MCP tools",
SearchType = McpGatewaySearchType.SEMANTIC,
SupportedVersions = new [] { MCPProtocolVersion.MCP_2025_03_26 }
})
});
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
ProtocolConfiguration: agentcore.NewMcpProtocolConfiguration(&McpConfiguration{
Instructions: jsii.String("Use this gateway to connect to external MCP tools"),
SearchType: agentcore.McpGatewaySearchType_SEMANTIC(),
SupportedVersions: []MCPProtocolVersion{
agentcore.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 authorizerConfiguration 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:
- Discovery Url — String that must match the pattern ^.+/.well-known/openid-configuration$ for OpenID Connect discovery URLs
- At least one of the below options depending on the chosen identity provider.
- Allowed audiences — List of allowed audiences for JWT tokens
- Allowed clients — List of allowed client identifiers
- Allowed scopes — List of allowed scopes for JWT tokens
- Custom claims — Optional custom claim validations (see Custom Claims Validation section below)
// Optional: Create custom claims (CustomClaimOperator and GatewayCustomClaim from agentcore)
const customClaims = [
agentcore.GatewayCustomClaim.withStringValue('department', 'engineering'),
agentcore.GatewayCustomClaim.withStringArrayValue('roles', ['admin'], agentcore.CustomClaimOperator.CONTAINS),
agentcore.GatewayCustomClaim.withStringArrayValue('permissions', ['read', 'write'], agentcore.CustomClaimOperator.CONTAINS_ANY),
];
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
authorizerConfiguration: agentcore.GatewayAuthorizer.usingCustomJwt({
discoveryUrl: "https://auth.example.com/.well-known/openid-configuration",
allowedAudience: ["my-app"],
allowedClients: ["my-client-id"],
allowedScopes: ["read", "write"],
customClaims: customClaims, // Optional custom claims
}),
});
# Optional: Create custom claims (CustomClaimOperator and GatewayCustomClaim from agentcore)
custom_claims = [
agentcore.GatewayCustomClaim.with_string_value("department", "engineering"),
agentcore.GatewayCustomClaim.with_string_array_value("roles", ["admin"], agentcore.CustomClaimOperator.CONTAINS),
agentcore.GatewayCustomClaim.with_string_array_value("permissions", ["read", "write"], agentcore.CustomClaimOperator.CONTAINS_ANY)
]
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway",
authorizer_configuration=agentcore.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
)
)
// Optional: Create custom claims (CustomClaimOperator and GatewayCustomClaim from agentcore)
GatewayCustomClaim[] customClaims = List.of(GatewayCustomClaim.withStringValue("department", "engineering"), GatewayCustomClaim.withStringArrayValue("roles", List.of("admin"), CustomClaimOperator.CONTAINS), GatewayCustomClaim.withStringArrayValue("permissions", List.of("read", "write"), CustomClaimOperator.CONTAINS_ANY));
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.authorizerConfiguration(GatewayAuthorizer.usingCustomJwt(CustomJwtConfiguration.builder()
.discoveryUrl("https://auth.example.com/.well-known/openid-configuration")
.allowedAudience(List.of("my-app"))
.allowedClients(List.of("my-client-id"))
.allowedScopes(List.of("read", "write"))
.customClaims(customClaims)
.build()))
.build();
// Optional: Create custom claims (CustomClaimOperator and GatewayCustomClaim from agentcore)
var customClaims = new [] { GatewayCustomClaim.WithStringValue("department", "engineering"), GatewayCustomClaim.WithStringArrayValue("roles", new [] { "admin" }, CustomClaimOperator.CONTAINS), GatewayCustomClaim.WithStringArrayValue("permissions", new [] { "read", "write" }, CustomClaimOperator.CONTAINS_ANY) };
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway",
AuthorizerConfiguration = GatewayAuthorizer.UsingCustomJwt(new CustomJwtConfiguration {
DiscoveryUrl = "https://auth.example.com/.well-known/openid-configuration",
AllowedAudience = new [] { "my-app" },
AllowedClients = new [] { "my-client-id" },
AllowedScopes = new [] { "read", "write" },
CustomClaims = customClaims
})
});
// Optional: Create custom claims (CustomClaimOperator and GatewayCustomClaim from agentcore)
customClaims := []GatewayCustomClaim{
agentcore.GatewayCustomClaim_WithStringValue(jsii.String("department"), jsii.String("engineering")),
agentcore.GatewayCustomClaim_WithStringArrayValue(jsii.String("roles"), []*string{
jsii.String("admin"),
}, agentcore.CustomClaimOperator_CONTAINS),
agentcore.GatewayCustomClaim_WithStringArrayValue(jsii.String("permissions"), []*string{
jsii.String("read"),
jsii.String("write"),
}, agentcore.CustomClaimOperator_CONTAINS_ANY),
}
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
AuthorizerConfiguration: agentcore.GatewayAuthorizer_UsingCustomJwt(&CustomJwtConfiguration{
DiscoveryUrl: jsii.String("https://auth.example.com/.well-known/openid-configuration"),
AllowedAudience: []*string{
jsii.String("my-app"),
},
AllowedClients: []*string{
jsii.String("my-client-id"),
},
AllowedScopes: []*string{
jsii.String("read"),
jsii.String("write"),
},
CustomClaims: customClaims,
}),
})
IAM – Authorizes through the credentials of the AWS IAM identity trying to access the gateway.
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
authorizerConfiguration: agentcore.GatewayAuthorizer.usingAwsIam(),
});
// Grant access to a Lambda function's role
const lambdaRole = new iam.Role(this, "LambdaRole", {
assumedBy: new iam.ServicePrincipal("lambda.amazonaws.com"),
});
// The Lambda needs permission to invoke the gateway
gateway.grantInvoke(lambdaRole);
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway",
authorizer_configuration=agentcore.GatewayAuthorizer.using_aws_iam()
)
# Grant access to a Lambda function's role
lambda_role = iam.Role(self, "LambdaRole",
assumed_by=iam.ServicePrincipal("lambda.amazonaws.com")
)
# The Lambda needs permission to invoke the gateway
gateway.grant_invoke(lambda_role)
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.authorizerConfiguration(GatewayAuthorizer.usingAwsIam())
.build();
// Grant access to a Lambda function's role
Role lambdaRole = Role.Builder.create(this, "LambdaRole")
.assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
.build();
// The Lambda needs permission to invoke the gateway
gateway.grantInvoke(lambdaRole);
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway",
AuthorizerConfiguration = GatewayAuthorizer.UsingAwsIam()
});
// Grant access to a Lambda function's role
var lambdaRole = new Role(this, "LambdaRole", new RoleProps {
AssumedBy = new ServicePrincipal("lambda.amazonaws.com")
});
// The Lambda needs permission to invoke the gateway
gateway.GrantInvoke(lambdaRole);
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
AuthorizerConfiguration: agentcore.GatewayAuthorizer_UsingAwsIam(),
})
// Grant access to a Lambda function's role
lambdaRole := iam.NewRole(this, jsii.String("LambdaRole"), &RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("lambda.amazonaws.com")),
})
// The Lambda needs permission to invoke the gateway
gateway.GrantInvoke(lambdaRole)
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.
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
authorizerConfiguration: agentcore.GatewayAuthorizer.withNoAuth(),
});
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway",
authorizer_configuration=agentcore.GatewayAuthorizer.with_no_auth()
)
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.authorizerConfiguration(GatewayAuthorizer.withNoAuth())
.build();
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway",
AuthorizerConfiguration = GatewayAuthorizer.WithNoAuth()
});
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
AuthorizerConfiguration: agentcore.GatewayAuthorizer_WithNoAuth(),
})
⚠️ 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
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
});
// Access the Cognito resources for authentication setup
const userPool = gateway.userPool;
const userPoolClient = gateway.userPoolClient;
// Get the token endpoint URL and OAuth scopes for client credentials flow
const tokenEndpointUrl = gateway.tokenEndpointUrl;
const oauthScopes = gateway.oauthScopes;
// oauthScopes are in the format: ['{resourceServerId}/read', '{resourceServerId}/write']
# Create a gateway with default Cognito M2M authorizer
gateway = agentcore.Gateway(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
// Create a gateway with default Cognito M2M authorizer
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.build();
// Access the Cognito resources for authentication setup
IUserPool userPool = gateway.getUserPool();
IUserPoolClient userPoolClient = gateway.getUserPoolClient();
// Get the token endpoint URL and OAuth scopes for client credentials flow
String tokenEndpointUrl = gateway.getTokenEndpointUrl();
String[] oauthScopes = gateway.getOauthScopes();
// Create a gateway with default Cognito M2M authorizer
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway"
});
// Access the Cognito resources for authentication setup
var userPool = gateway.UserPool;
var userPoolClient = gateway.UserPoolClient;
// Get the token endpoint URL and OAuth scopes for client credentials flow
var tokenEndpointUrl = gateway.TokenEndpointUrl;
var oauthScopes = gateway.OauthScopes;
// Create a gateway with default Cognito M2M authorizer
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
})
// Access the Cognito resources for authentication setup
userPool := gateway.UserPool
userPoolClient := gateway.UserPoolClient
// Get the token endpoint URL and OAuth scopes for client credentials flow
tokenEndpointUrl := gateway.TokenEndpointUrl
oauthScopes := gateway.OauthScopes
Using Cognito User Pool Explicitly with Custom Claims – You can also use an existing Cognito User Pool with custom claims:
declare const userPool: cognito.UserPool;
declare const userPoolClient: cognito.UserPoolClient;
// Optional: Create custom claims (CustomClaimOperator and GatewayCustomClaim from agentcore)
const customClaims = [
agentcore.GatewayCustomClaim.withStringValue('department', 'engineering'),
agentcore.GatewayCustomClaim.withStringArrayValue('roles', ['admin'], agentcore.CustomClaimOperator.CONTAINS),
agentcore.GatewayCustomClaim.withStringArrayValue('permissions', ['read', 'write'], agentcore.CustomClaimOperator.CONTAINS_ANY),
];
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
authorizerConfiguration: agentcore.GatewayAuthorizer.usingCognito({
userPool: userPool,
allowedClients: [userPoolClient],
allowedAudiences: ["audience1"],
allowedScopes: ["read", "write"],
customClaims: customClaims, // Optional custom claims
}),
});
# user_pool: cognito.UserPool
# user_pool_client: cognito.UserPoolClient
# Optional: Create custom claims (CustomClaimOperator and GatewayCustomClaim from agentcore)
custom_claims = [
agentcore.GatewayCustomClaim.with_string_value("department", "engineering"),
agentcore.GatewayCustomClaim.with_string_array_value("roles", ["admin"], agentcore.CustomClaimOperator.CONTAINS),
agentcore.GatewayCustomClaim.with_string_array_value("permissions", ["read", "write"], agentcore.CustomClaimOperator.CONTAINS_ANY)
]
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway",
authorizer_configuration=agentcore.GatewayAuthorizer.using_cognito(
user_pool=user_pool,
allowed_clients=[user_pool_client],
allowed_audiences=["audience1"],
allowed_scopes=["read", "write"],
custom_claims=custom_claims
)
)
UserPool userPool;
UserPoolClient userPoolClient;
// Optional: Create custom claims (CustomClaimOperator and GatewayCustomClaim from agentcore)
GatewayCustomClaim[] customClaims = List.of(GatewayCustomClaim.withStringValue("department", "engineering"), GatewayCustomClaim.withStringArrayValue("roles", List.of("admin"), CustomClaimOperator.CONTAINS), GatewayCustomClaim.withStringArrayValue("permissions", List.of("read", "write"), CustomClaimOperator.CONTAINS_ANY));
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.authorizerConfiguration(GatewayAuthorizer.usingCognito(CognitoAuthorizerProps.builder()
.userPool(userPool)
.allowedClients(List.of(userPoolClient))
.allowedAudiences(List.of("audience1"))
.allowedScopes(List.of("read", "write"))
.customClaims(customClaims)
.build()))
.build();
UserPool userPool;
UserPoolClient userPoolClient;
// Optional: Create custom claims (CustomClaimOperator and GatewayCustomClaim from agentcore)
var customClaims = new [] { GatewayCustomClaim.WithStringValue("department", "engineering"), GatewayCustomClaim.WithStringArrayValue("roles", new [] { "admin" }, CustomClaimOperator.CONTAINS), GatewayCustomClaim.WithStringArrayValue("permissions", new [] { "read", "write" }, CustomClaimOperator.CONTAINS_ANY) };
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway",
AuthorizerConfiguration = GatewayAuthorizer.UsingCognito(new CognitoAuthorizerProps {
UserPool = userPool,
AllowedClients = new [] { userPoolClient },
AllowedAudiences = new [] { "audience1" },
AllowedScopes = new [] { "read", "write" },
CustomClaims = customClaims
})
});
var userPool UserPool
var userPoolClient UserPoolClient
// Optional: Create custom claims (CustomClaimOperator and GatewayCustomClaim from agentcore)
customClaims := []GatewayCustomClaim{
agentcore.GatewayCustomClaim_WithStringValue(jsii.String("department"), jsii.String("engineering")),
agentcore.GatewayCustomClaim_WithStringArrayValue(jsii.String("roles"), []*string{
jsii.String("admin"),
}, agentcore.CustomClaimOperator_CONTAINS),
agentcore.GatewayCustomClaim_WithStringArrayValue(jsii.String("permissions"), []*string{
jsii.String("read"),
jsii.String("write"),
}, agentcore.CustomClaimOperator_CONTAINS_ANY),
}
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
AuthorizerConfiguration: agentcore.GatewayAuthorizer_UsingCognito(&CognitoAuthorizerProps{
UserPool: userPool,
AllowedClients: []IUserPoolClient{
userPoolClient,
},
AllowedAudiences: []*string{
jsii.String("audience1"),
},
AllowedScopes: []*string{
jsii.String("read"),
jsii.String("write"),
},
CustomClaims: customClaims,
}),
})
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
const encryptionKey = new kms.Key(this, "GatewayEncryptionKey", {
enableKeyRotation: true,
description: "KMS key for gateway encryption",
});
// Create gateway with KMS encryption
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-encrypted-gateway",
description: "Gateway with KMS encryption",
protocolConfiguration: new agentcore.McpProtocolConfiguration({
instructions: "Use this gateway to connect to external MCP tools",
searchType: agentcore.McpGatewaySearchType.SEMANTIC,
supportedVersions: [agentcore.MCPProtocolVersion.MCP_2025_03_26],
}),
authorizerConfiguration: agentcore.GatewayAuthorizer.usingCustomJwt({
discoveryUrl: "https://auth.example.com/.well-known/openid-configuration",
allowedAudience: ["my-app"],
allowedClients: ["my-client-id"],
allowedScopes: ["read", "write"],
}),
kmsKey: encryptionKey,
exceptionLevel: agentcore.GatewayExceptionLevel.DEBUG,
});
# Create a KMS key for encryption
encryption_key = kms.Key(self, "GatewayEncryptionKey",
enable_key_rotation=True,
description="KMS key for gateway encryption"
)
# Create gateway with KMS encryption
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-encrypted-gateway",
description="Gateway with KMS encryption",
protocol_configuration=agentcore.McpProtocolConfiguration(
instructions="Use this gateway to connect to external MCP tools",
search_type=agentcore.McpGatewaySearchType.SEMANTIC,
supported_versions=[agentcore.MCPProtocolVersion.MCP_2025_03_26]
),
authorizer_configuration=agentcore.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=agentcore.GatewayExceptionLevel.DEBUG
)
// Create a KMS key for encryption
Key encryptionKey = Key.Builder.create(this, "GatewayEncryptionKey")
.enableKeyRotation(true)
.description("KMS key for gateway encryption")
.build();
// Create gateway with KMS encryption
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-encrypted-gateway")
.description("Gateway with KMS encryption")
.protocolConfiguration(McpProtocolConfiguration.Builder.create()
.instructions("Use this gateway to connect to external MCP tools")
.searchType(McpGatewaySearchType.SEMANTIC)
.supportedVersions(List.of(MCPProtocolVersion.MCP_2025_03_26))
.build())
.authorizerConfiguration(GatewayAuthorizer.usingCustomJwt(CustomJwtConfiguration.builder()
.discoveryUrl("https://auth.example.com/.well-known/openid-configuration")
.allowedAudience(List.of("my-app"))
.allowedClients(List.of("my-client-id"))
.allowedScopes(List.of("read", "write"))
.build()))
.kmsKey(encryptionKey)
.exceptionLevel(GatewayExceptionLevel.DEBUG)
.build();
// Create a KMS key for encryption
var encryptionKey = new Key(this, "GatewayEncryptionKey", new KeyProps {
EnableKeyRotation = true,
Description = "KMS key for gateway encryption"
});
// Create gateway with KMS encryption
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-encrypted-gateway",
Description = "Gateway with KMS encryption",
ProtocolConfiguration = new McpProtocolConfiguration(new McpConfiguration {
Instructions = "Use this gateway to connect to external MCP tools",
SearchType = McpGatewaySearchType.SEMANTIC,
SupportedVersions = new [] { MCPProtocolVersion.MCP_2025_03_26 }
}),
AuthorizerConfiguration = GatewayAuthorizer.UsingCustomJwt(new CustomJwtConfiguration {
DiscoveryUrl = "https://auth.example.com/.well-known/openid-configuration",
AllowedAudience = new [] { "my-app" },
AllowedClients = new [] { "my-client-id" },
AllowedScopes = new [] { "read", "write" }
}),
KmsKey = encryptionKey,
ExceptionLevel = GatewayExceptionLevel.DEBUG
});
// Create a KMS key for encryption
encryptionKey := kms.NewKey(this, jsii.String("GatewayEncryptionKey"), &KeyProps{
EnableKeyRotation: jsii.Boolean(true),
Description: jsii.String("KMS key for gateway encryption"),
})
// Create gateway with KMS encryption
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-encrypted-gateway"),
Description: jsii.String("Gateway with KMS encryption"),
ProtocolConfiguration: agentcore.NewMcpProtocolConfiguration(&McpConfiguration{
Instructions: jsii.String("Use this gateway to connect to external MCP tools"),
SearchType: agentcore.McpGatewaySearchType_SEMANTIC(),
SupportedVersions: []MCPProtocolVersion{
agentcore.MCPProtocolVersion_MCP_2025_03_26(),
},
}),
AuthorizerConfiguration: agentcore.GatewayAuthorizer_UsingCustomJwt(&CustomJwtConfiguration{
DiscoveryUrl: jsii.String("https://auth.example.com/.well-known/openid-configuration"),
AllowedAudience: []*string{
jsii.String("my-app"),
},
AllowedClients: []*string{
jsii.String("my-client-id"),
},
AllowedScopes: []*string{
jsii.String("read"),
jsii.String("write"),
},
}),
KmsKey: encryptionKey,
ExceptionLevel: agentcore.GatewayExceptionLevel_DEBUG(),
})
Gateway with Custom Execution Role
// Create a custom execution role
const executionRole = new iam.Role(this, "GatewayExecutionRole", {
assumedBy: new iam.ServicePrincipal("bedrock-agentcore.amazonaws.com"),
managedPolicies: [
iam.ManagedPolicy.fromAwsManagedPolicyName("AmazonBedrockAgentCoreGatewayExecutionRolePolicy"),
],
});
// Create gateway with custom execution role
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
description: "Gateway with custom execution role",
protocolConfiguration: new agentcore.McpProtocolConfiguration({
instructions: "Use this gateway to connect to external MCP tools",
searchType: agentcore.McpGatewaySearchType.SEMANTIC,
supportedVersions: [agentcore.MCPProtocolVersion.MCP_2025_03_26],
}),
authorizerConfiguration: agentcore.GatewayAuthorizer.usingCustomJwt({
discoveryUrl: "https://auth.example.com/.well-known/openid-configuration",
allowedAudience: ["my-app"],
allowedClients: ["my-client-id"],
allowedScopes: ["read", "write"],
}),
role: executionRole,
});
# Create a custom execution role
execution_role = iam.Role(self, "GatewayExecutionRole",
assumed_by=iam.ServicePrincipal("bedrock-agentcore.amazonaws.com"),
managed_policies=[
iam.ManagedPolicy.from_aws_managed_policy_name("AmazonBedrockAgentCoreGatewayExecutionRolePolicy")
]
)
# Create gateway with custom execution role
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway",
description="Gateway with custom execution role",
protocol_configuration=agentcore.McpProtocolConfiguration(
instructions="Use this gateway to connect to external MCP tools",
search_type=agentcore.McpGatewaySearchType.SEMANTIC,
supported_versions=[agentcore.MCPProtocolVersion.MCP_2025_03_26]
),
authorizer_configuration=agentcore.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
)
// Create a custom execution role
Role executionRole = Role.Builder.create(this, "GatewayExecutionRole")
.assumedBy(new ServicePrincipal("bedrock-agentcore.amazonaws.com"))
.managedPolicies(List.of(ManagedPolicy.fromAwsManagedPolicyName("AmazonBedrockAgentCoreGatewayExecutionRolePolicy")))
.build();
// Create gateway with custom execution role
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.description("Gateway with custom execution role")
.protocolConfiguration(McpProtocolConfiguration.Builder.create()
.instructions("Use this gateway to connect to external MCP tools")
.searchType(McpGatewaySearchType.SEMANTIC)
.supportedVersions(List.of(MCPProtocolVersion.MCP_2025_03_26))
.build())
.authorizerConfiguration(GatewayAuthorizer.usingCustomJwt(CustomJwtConfiguration.builder()
.discoveryUrl("https://auth.example.com/.well-known/openid-configuration")
.allowedAudience(List.of("my-app"))
.allowedClients(List.of("my-client-id"))
.allowedScopes(List.of("read", "write"))
.build()))
.role(executionRole)
.build();
// Create a custom execution role
var executionRole = new Role(this, "GatewayExecutionRole", new RoleProps {
AssumedBy = new ServicePrincipal("bedrock-agentcore.amazonaws.com"),
ManagedPolicies = new [] { ManagedPolicy.FromAwsManagedPolicyName("AmazonBedrockAgentCoreGatewayExecutionRolePolicy") }
});
// Create gateway with custom execution role
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway",
Description = "Gateway with custom execution role",
ProtocolConfiguration = new McpProtocolConfiguration(new McpConfiguration {
Instructions = "Use this gateway to connect to external MCP tools",
SearchType = McpGatewaySearchType.SEMANTIC,
SupportedVersions = new [] { MCPProtocolVersion.MCP_2025_03_26 }
}),
AuthorizerConfiguration = GatewayAuthorizer.UsingCustomJwt(new CustomJwtConfiguration {
DiscoveryUrl = "https://auth.example.com/.well-known/openid-configuration",
AllowedAudience = new [] { "my-app" },
AllowedClients = new [] { "my-client-id" },
AllowedScopes = new [] { "read", "write" }
}),
Role = executionRole
});
// Create a custom execution role
executionRole := iam.NewRole(this, jsii.String("GatewayExecutionRole"), &RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("bedrock-agentcore.amazonaws.com")),
ManagedPolicies: []IManagedPolicy{
iam.ManagedPolicy_FromAwsManagedPolicyName(jsii.String("AmazonBedrockAgentCoreGatewayExecutionRolePolicy")),
},
})
// Create gateway with custom execution role
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
Description: jsii.String("Gateway with custom execution role"),
ProtocolConfiguration: agentcore.NewMcpProtocolConfiguration(&McpConfiguration{
Instructions: jsii.String("Use this gateway to connect to external MCP tools"),
SearchType: agentcore.McpGatewaySearchType_SEMANTIC(),
SupportedVersions: []MCPProtocolVersion{
agentcore.MCPProtocolVersion_MCP_2025_03_26(),
},
}),
AuthorizerConfiguration: agentcore.GatewayAuthorizer_UsingCustomJwt(&CustomJwtConfiguration{
DiscoveryUrl: jsii.String("https://auth.example.com/.well-known/openid-configuration"),
AllowedAudience: []*string{
jsii.String("my-app"),
},
AllowedClients: []*string{
jsii.String("my-client-id"),
},
AllowedScopes: []*string{
jsii.String("read"),
jsii.String("write"),
},
}),
Role: executionRole,
})
Gateway IAM Permissions
The Gateway construct provides convenient methods for granting IAM permissions:
// Create a gateway
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
description: "Gateway for external service integration",
protocolConfiguration: new agentcore.McpProtocolConfiguration({
instructions: "Use this gateway to connect to external MCP tools",
searchType: agentcore.McpGatewaySearchType.SEMANTIC,
supportedVersions: [agentcore.MCPProtocolVersion.MCP_2025_03_26],
}),
authorizerConfiguration: agentcore.GatewayAuthorizer.usingCustomJwt({
discoveryUrl: "https://auth.example.com/.well-known/openid-configuration",
allowedAudience: ["my-app"],
allowedClients: ["my-client-id"],
allowedScopes: ["read", "write"],
}),
});
// Create a role that needs access to the gateway
const userRole = new iam.Role(this, "UserRole", {
assumedBy: new iam.ServicePrincipal("lambda.amazonaws.com"),
});
// Grant read permissions (Get and List actions)
gateway.grantRead(userRole);
// Grant manage permissions (Create, Update, Delete actions)
gateway.grantManage(userRole);
// Grant specific custom permissions
gateway.grant(userRole, "bedrock-agentcore:GetGateway");
# Create a gateway
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway",
description="Gateway for external service integration",
protocol_configuration=agentcore.McpProtocolConfiguration(
instructions="Use this gateway to connect to external MCP tools",
search_type=agentcore.McpGatewaySearchType.SEMANTIC,
supported_versions=[agentcore.MCPProtocolVersion.MCP_2025_03_26]
),
authorizer_configuration=agentcore.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 = iam.Role(self, "UserRole",
assumed_by=iam.ServicePrincipal("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")
// Create a gateway
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.description("Gateway for external service integration")
.protocolConfiguration(McpProtocolConfiguration.Builder.create()
.instructions("Use this gateway to connect to external MCP tools")
.searchType(McpGatewaySearchType.SEMANTIC)
.supportedVersions(List.of(MCPProtocolVersion.MCP_2025_03_26))
.build())
.authorizerConfiguration(GatewayAuthorizer.usingCustomJwt(CustomJwtConfiguration.builder()
.discoveryUrl("https://auth.example.com/.well-known/openid-configuration")
.allowedAudience(List.of("my-app"))
.allowedClients(List.of("my-client-id"))
.allowedScopes(List.of("read", "write"))
.build()))
.build();
// Create a role that needs access to the gateway
Role userRole = Role.Builder.create(this, "UserRole")
.assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
.build();
// Grant read permissions (Get and List actions)
gateway.grantRead(userRole);
// Grant manage permissions (Create, Update, Delete actions)
gateway.grantManage(userRole);
// Grant specific custom permissions
gateway.grant(userRole, "bedrock-agentcore:GetGateway");
// Create a gateway
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway",
Description = "Gateway for external service integration",
ProtocolConfiguration = new McpProtocolConfiguration(new McpConfiguration {
Instructions = "Use this gateway to connect to external MCP tools",
SearchType = McpGatewaySearchType.SEMANTIC,
SupportedVersions = new [] { MCPProtocolVersion.MCP_2025_03_26 }
}),
AuthorizerConfiguration = GatewayAuthorizer.UsingCustomJwt(new CustomJwtConfiguration {
DiscoveryUrl = "https://auth.example.com/.well-known/openid-configuration",
AllowedAudience = new [] { "my-app" },
AllowedClients = new [] { "my-client-id" },
AllowedScopes = new [] { "read", "write" }
})
});
// Create a role that needs access to the gateway
var userRole = new Role(this, "UserRole", new RoleProps {
AssumedBy = new ServicePrincipal("lambda.amazonaws.com")
});
// Grant read permissions (Get and List actions)
gateway.GrantRead(userRole);
// Grant manage permissions (Create, Update, Delete actions)
gateway.GrantManage(userRole);
// Grant specific custom permissions
gateway.Grant(userRole, "bedrock-agentcore:GetGateway");
// Create a gateway
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
Description: jsii.String("Gateway for external service integration"),
ProtocolConfiguration: agentcore.NewMcpProtocolConfiguration(&McpConfiguration{
Instructions: jsii.String("Use this gateway to connect to external MCP tools"),
SearchType: agentcore.McpGatewaySearchType_SEMANTIC(),
SupportedVersions: []MCPProtocolVersion{
agentcore.MCPProtocolVersion_MCP_2025_03_26(),
},
}),
AuthorizerConfiguration: agentcore.GatewayAuthorizer_UsingCustomJwt(&CustomJwtConfiguration{
DiscoveryUrl: jsii.String("https://auth.example.com/.well-known/openid-configuration"),
AllowedAudience: []*string{
jsii.String("my-app"),
},
AllowedClients: []*string{
jsii.String("my-client-id"),
},
AllowedScopes: []*string{
jsii.String("read"),
jsii.String("write"),
},
}),
})
// Create a role that needs access to the gateway
userRole := iam.NewRole(this, jsii.String("UserRole"), &RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("lambda.amazonaws.com")),
})
// Grant read permissions (Get and List actions)
gateway.GrantRead(userRole)
// Grant manage permissions (Create, Update, Delete actions)
gateway.GrantManage(userRole)
// Grant specific custom permissions
gateway.Grant(userRole, jsii.String("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 |
|---|---|---|---|
gatewayTargetName | 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 |
targetConfiguration | 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 addLambdaTarget(), addOpenApiTarget(), addSmithyTarget(), addApiGatewayTarget(), addMcpServerTarget() methods, this configuration is created internally for you. Only needed when using the GatewayTarget constructor directly for advanced scenarios. |
credentialProviderConfigurations | IGatewayCredentialProvider[] | No | Credential providers for authentication. Defaults to [GatewayCredentialProvider.fromIamRole()]. With Token Vault L2 constructs, prefer GatewayCredentialProvider.fromApiKeyIdentity() / fromOauthIdentity(); otherwise use fromApiKeyIdentityArn() / fromOauthIdentityArn(), or fromIamRole() |
validateOpenApiSchema | 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.
- Supports GATEWAY_IAM_ROLE credential provider only
- Ideal for custom serverless function integration
- Need tool schema (tool schema is a blueprint that describes the functions your Lambda provides to AI agents). The construct provide 3 ways to upload a tool schema to Lambda target
- When using the default IAM authentication (no
credentialProviderConfigurationsspecified), the construct automatocally grants the gateway role permission to invoke your Lambda function (lambda:InvokeFunction).
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
- Supports OAUTH and API_KEY credential providers (Do not support IAM, you must provide
credentialProviderConfigurations) - Ideal for integrating with external REST services
- Need API schema. The construct provide 3 ways to upload a API schema to OpenAPI target
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
- Supports OAUTH and API_KEY credential providers
- Ideal for AWS service integrations
- Need API schema. The construct provide 3 ways to upload a API schema to Smity target
- When using the default IAM authentication (no
credentialProviderConfigurationsspecified), The construct only grants permission to read the Smithy schema file from S3. You MUST manually grant permissions for the gateway role to invoke the actual Smithy API endpoints
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:
- Requires explicit authentication configuration (OAuth2 recommended, empty array for NoAuth)
- Ideal for connecting to external MCP-compliant servers
- The endpoint must use HTTPS protocol
- Supported MCP protocol versions: 2025-06-18, 2025-03-26
- Automatic tool discovery through synchronization
Synchronization Behavior:
MCP Server targets require synchronization to discover and index available tools:
Implicit Synchronization (Automatic): Tool discovery happens automatically during:
- Target creation (
CreateGatewayTarget) - Target updates (
UpdateGatewayTarget) - The Gateway calls the MCP server's
tools/listendpoint and indexes tools without user intervention
- Target creation (
Explicit Synchronization (Manual): When the MCP server's tools change independently (new tools added, schemas modified, tools removed):
- The Gateway's tool catalog becomes stale
- Call the
SynchronizeGatewayTargetsAPI to refresh the catalog - Use the
grantSync()method to grant permissions to Lambda functions, CI/CD pipelines, or scheduled tasks that will trigger synchronization
Authentication & Permissions:
When using OAuth2, the Gateway service role automatically receives:
bedrock-agentcore:GetWorkloadAccessTokenbedrock-agentcore:GetResourceOauth2Tokensecretsmanager:GetSecretValue- KMS decrypt (if secrets are encrypted)
For explicit synchronization, use grantSync() 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:
- For Lambda Targets: Your Lambda handler must strip the target name prefix before processing the tool request. The full tool name (with prefix) is sent in the event.
- For MCP Server Targets: The MCP server receives tool calls with the prefixed name from the gateway.
- For OpenAPI/Smithy Targets: The gateway handles the prefix automatically when mapping to API operations based on the
operationId.
This naming convention ensures that:
- Tools from different targets don't collide even if they have the same name
- Agents can access tools from multiple targets through a single gateway
- Tool names remain unique in the unified tool catalog
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:
- From a local asset file
const toolSchema = agentcore.ToolSchema.fromLocalAsset(
path.join(__dirname, "schemas", "my-tool-schema.json")
);
tool_schema = agentcore.ToolSchema.from_local_asset(
path.join(__dirname, "schemas", "my-tool-schema.json"))
ToolSchema toolSchema = ToolSchema.fromLocalAsset(path.join(__dirname, "schemas", "my-tool-schema.json"));
var toolSchema = ToolSchema.FromLocalAsset(path.Join(__dirname, "schemas", "my-tool-schema.json"));
toolSchema := agentcore.ToolSchema_FromLocalAsset(path.join(__dirname, jsii.String("schemas"), jsii.String("my-tool-schema.json")))
- From an existing S3 file:
const toolSchema = agentcore.ToolSchema.fromS3File(
s3.Bucket.fromBucketName(this, "SchemasBucket", "my-schemas-bucket"),
"tools/complex-tool-schema.json",
"123456789012"
);
tool_schema = agentcore.ToolSchema.from_s3_file(
s3.Bucket.from_bucket_name(self, "SchemasBucket", "my-schemas-bucket"), "tools/complex-tool-schema.json", "123456789012")
S3ToolSchema toolSchema = ToolSchema.fromS3File(Bucket.fromBucketName(this, "SchemasBucket", "my-schemas-bucket"), "tools/complex-tool-schema.json", "123456789012");
var toolSchema = ToolSchema.FromS3File(Bucket.FromBucketName(this, "SchemasBucket", "my-schemas-bucket"), "tools/complex-tool-schema.json", "123456789012");
toolSchema := agentcore.ToolSchema_FromS3File(s3.Bucket_FromBucketName(this, jsii.String("SchemasBucket"), jsii.String("my-schemas-bucket")), jsii.String("tools/complex-tool-schema.json"), jsii.String("123456789012"))
- From Inline:
const toolSchema = agentcore.ToolSchema.fromInline([{
name: "hello_world",
description: "A simple hello world tool",
inputSchema: {
type: agentcore.SchemaDefinitionType.OBJECT,
properties: {
name: {
type: agentcore.SchemaDefinitionType.STRING,
description: "The name to greet",
},
},
required: ["name"],
},
}]);
tool_schema = agentcore.ToolSchema.from_inline([
name="hello_world",
description="A simple hello world tool",
input_schema=agentcore.SchemaDefinition(
type=agentcore.SchemaDefinitionType.OBJECT,
properties={
"name": agentcore.SchemaDefinition(
type=agentcore.SchemaDefinitionType.STRING,
description="The name to greet"
)
},
required=["name"]
)
])
InlineToolSchema toolSchema = ToolSchema.fromInline(List.of(ToolDefinition.builder()
.name("hello_world")
.description("A simple hello world tool")
.inputSchema(SchemaDefinition.builder()
.type(SchemaDefinitionType.OBJECT)
.properties(Map.of(
"name", SchemaDefinition.builder()
.type(SchemaDefinitionType.STRING)
.description("The name to greet")
.build()))
.required(List.of("name"))
.build())
.build()));
var toolSchema = ToolSchema.FromInline(new [] { new ToolDefinition {
Name = "hello_world",
Description = "A simple hello world tool",
InputSchema = new SchemaDefinition {
Type = SchemaDefinitionType.OBJECT,
Properties = new Dictionary<string, SchemaDefinition> {
{ "name", new SchemaDefinition {
Type = SchemaDefinitionType.STRING,
Description = "The name to greet"
} }
},
Required = new [] { "name" }
}
} });
toolSchema := agentcore.ToolSchema_FromInline([]ToolDefinition{
&ToolDefinition{
Name: jsii.String("hello_world"),
Description: jsii.String("A simple hello world tool"),
InputSchema: &SchemaDefinition{
Type: agentcore.SchemaDefinitionType_OBJECT(),
Properties: map[string]SchemaDefinition{
"name": &SchemaDefinition{
"type": agentcore.SchemaDefinitionType_STRING(),
"description": jsii.String("The name to greet"),
},
},
Required: []*string{
jsii.String("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:
- From a local asset file (requires binding to scope):
// When using ApiSchema.fromLocalAsset, you must bind the schema to a scope
const schema = agentcore.ApiSchema.fromLocalAsset(path.join(__dirname, "mySchema.yml"));
schema.bind(this);
# When using ApiSchema.fromLocalAsset, you must bind the schema to a scope
schema = agentcore.ApiSchema.from_local_asset(path.join(__dirname, "mySchema.yml"))
schema.bind(self)
// When using ApiSchema.fromLocalAsset, you must bind the schema to a scope
AssetApiSchema schema = ApiSchema.fromLocalAsset(path.join(__dirname, "mySchema.yml"));
schema.bind(this);
// When using ApiSchema.fromLocalAsset, you must bind the schema to a scope
var schema = ApiSchema.FromLocalAsset(path.Join(__dirname, "mySchema.yml"));
schema.Bind(this);
// When using ApiSchema.fromLocalAsset, you must bind the schema to a scope
schema := agentcore.ApiSchema_FromLocalAsset(path.join(__dirname, jsii.String("mySchema.yml")))
schema.Bind(this)
- From an inline schema:
const inlineSchema = agentcore.ApiSchema.fromInline(`
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
`);
inline_schema = agentcore.ApiSchema.from_inline("""
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
""")
InlineApiSchema inlineSchema = ApiSchema.fromInline("\nopenapi: 3.0.3\ninfo:\n title: Library API\n version: 1.0.0\npaths:\n /search:\n get:\n summary: Search for books\n operationId: searchBooks\n parameters:\n - name: query\n in: query\n required: true\n schema:\n type: string\n");
var inlineSchema = ApiSchema.FromInline(@"
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
");
inlineSchema := agentcore.ApiSchema_FromInline(jsii.String(`
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
`))
- From an existing S3 file:
const bucket = s3.Bucket.fromBucketName(this, "ExistingBucket", "my-schema-bucket");
const s3Schema = agentcore.ApiSchema.fromS3File(bucket, "schemas/action-group.yaml");
bucket = s3.Bucket.from_bucket_name(self, "ExistingBucket", "my-schema-bucket")
s3_schema = agentcore.ApiSchema.from_s3_file(bucket, "schemas/action-group.yaml")
IBucket bucket = Bucket.fromBucketName(this, "ExistingBucket", "my-schema-bucket");
S3ApiSchema s3Schema = ApiSchema.fromS3File(bucket, "schemas/action-group.yaml");
var bucket = Bucket.FromBucketName(this, "ExistingBucket", "my-schema-bucket");
var s3Schema = ApiSchema.FromS3File(bucket, "schemas/action-group.yaml");
bucket := s3.Bucket_FromBucketName(this, jsii.String("ExistingBucket"), jsii.String("my-schema-bucket"))
s3Schema := agentcore.ApiSchema_FromS3File(bucket, jsii.String("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:
agentcore.GatewayCredentialProvider.fromIamRole({
service: 'bedrock-runtime', // SigV4 signing name (typically the endpoint prefix); see the AWS service authorization reference
region: 'us-east-1', // defaults to the gateway's region
});
agentcore.GatewayCredentialProvider.from_iam_role(
service="bedrock-runtime", # SigV4 signing name (typically the endpoint prefix); see the AWS service authorization reference
region="us-east-1"
)
GatewayCredentialProvider.fromIamRole(GatewayIamRoleCredentialProviderProps.builder()
.service("bedrock-runtime") // SigV4 signing name (typically the endpoint prefix); see the AWS service authorization reference
.region("us-east-1")
.build());
GatewayCredentialProvider.FromIamRole(new GatewayIamRoleCredentialProviderProps {
Service = "bedrock-runtime", // SigV4 signing name (typically the endpoint prefix); see the AWS service authorization reference
Region = "us-east-1"
});
agentcore.GatewayCredentialProvider_FromIamRole(&GatewayIamRoleCredentialProviderProps{
Service: jsii.String("bedrock-runtime"),
// SigV4 signing name (typically the endpoint prefix); see the AWS service authorization reference
Region: jsii.String("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 clientId and clientSecret, plus optional oAuth2CredentialProviderName and tags. Extra properties appear only when an IdP needs them (for example tenantId 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 (usingCustom) — Supply exactly one of:
discoveryUrl— OIDC/OAuth2 discovery document URL (for examplehttps://idp.example.com/.well-known/openid-configuration), orauthorizationServerMetadata— Manual authorization server metadata (issuer,authorizationEndpoint,tokenEndpoint, and other fields supported by theAWS::BedrockAgentCore::OAuth2CredentialProviderresource).
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 fromApiKeyIdentity() (optional API key header/query settings go in the second argument for API keys). Alternatively, call bindForGatewayOAuthTarget / bindForGatewayApiKeyTarget on the provider and pass that object to fromOauthIdentityArn / fromApiKeyIdentityArn. You can still pass raw ARNs from the console or API when the provider already exists.
Example: GitHub OAuth2 and an MCP target
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
});
const oauth = agentcore.OAuth2CredentialProvider.usingGithub(this, "GhOAuth", {
oAuth2CredentialProviderName: "github-oauth",
clientId: "your-client-id",
clientSecret: cdk.SecretValue.unsafePlainText("your-client-secret"),
});
gateway.addMcpServerTarget("Mcp", {
gatewayTargetName: "mcp-server",
description: "MCP with GitHub OAuth",
endpoint: "https://my-mcp-server.example.com",
credentialProviderConfigurations: [
agentcore.GatewayCredentialProvider.fromOauthIdentity(oauth, {
scopes: ["read:user"],
}),
],
});
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway"
)
oauth = agentcore.OAuth2CredentialProvider.using_github(self, "GhOAuth",
o_auth2_credential_provider_name="github-oauth",
client_id="your-client-id",
client_secret=cdk.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=[
agentcore.GatewayCredentialProvider.from_oauth_identity(oauth,
scopes=["read:user"]
)
]
)
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.build();
OAuth2CredentialProvider oauth = OAuth2CredentialProvider.usingGithub(this, "GhOAuth", GithubOAuth2CredentialProviderProps.builder()
.oAuth2CredentialProviderName("github-oauth")
.clientId("your-client-id")
.clientSecret(SecretValue.unsafePlainText("your-client-secret"))
.build());
gateway.addMcpServerTarget("Mcp", AddMcpServerTargetOptions.builder()
.gatewayTargetName("mcp-server")
.description("MCP with GitHub OAuth")
.endpoint("https://my-mcp-server.example.com")
.credentialProviderConfigurations(List.of(GatewayCredentialProvider.fromOauthIdentity(oauth, FromOauthIdentityOptions.builder()
.scopes(List.of("read:user"))
.build())))
.build());
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway"
});
var oauth = OAuth2CredentialProvider.UsingGithub(this, "GhOAuth", new GithubOAuth2CredentialProviderProps {
OAuth2CredentialProviderName = "github-oauth",
ClientId = "your-client-id",
ClientSecret = SecretValue.UnsafePlainText("your-client-secret")
});
gateway.AddMcpServerTarget("Mcp", new AddMcpServerTargetOptions {
GatewayTargetName = "mcp-server",
Description = "MCP with GitHub OAuth",
Endpoint = "https://my-mcp-server.example.com",
CredentialProviderConfigurations = new [] { GatewayCredentialProvider.FromOauthIdentity(oauth, new FromOauthIdentityOptions {
Scopes = new [] { "read:user" }
}) }
});
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
})
oauth := agentcore.OAuth2CredentialProvider_UsingGithub(this, jsii.String("GhOAuth"), &GithubOAuth2CredentialProviderProps{
OAuth2CredentialProviderName: jsii.String("github-oauth"),
ClientId: jsii.String("your-client-id"),
ClientSecret: cdk.SecretValue_UnsafePlainText(jsii.String("your-client-secret")),
})
gateway.AddMcpServerTarget(jsii.String("Mcp"), &AddMcpServerTargetOptions{
GatewayTargetName: jsii.String("mcp-server"),
Description: jsii.String("MCP with GitHub OAuth"),
Endpoint: jsii.String("https://my-mcp-server.example.com"),
CredentialProviderConfigurations: []ICredentialProviderConfig{
agentcore.GatewayCredentialProvider_FromOauthIdentity(oauth, &FromOauthIdentityOptions{
Scopes: []*string{
jsii.String("read:user"),
},
}),
},
})
Example: custom IdP with a discovery URL
agentcore.OAuth2CredentialProvider.usingCustom(this, "CustomOAuth", {
oAuth2CredentialProviderName: "custom-idp",
clientId: "your-client-id",
clientSecret: cdk.SecretValue.unsafePlainText("your-client-secret"),
discoveryUrl: "https://idp.example.com/.well-known/openid-configuration",
});
agentcore.OAuth2CredentialProvider.using_custom(self, "CustomOAuth",
o_auth2_credential_provider_name="custom-idp",
client_id="your-client-id",
client_secret=cdk.SecretValue.unsafe_plain_text("your-client-secret"),
discovery_url="https://idp.example.com/.well-known/openid-configuration"
)
OAuth2CredentialProvider.usingCustom(this, "CustomOAuth", CustomOAuth2CredentialProviderProps.builder()
.oAuth2CredentialProviderName("custom-idp")
.clientId("your-client-id")
.clientSecret(SecretValue.unsafePlainText("your-client-secret"))
.discoveryUrl("https://idp.example.com/.well-known/openid-configuration")
.build());
OAuth2CredentialProvider.UsingCustom(this, "CustomOAuth", new CustomOAuth2CredentialProviderProps {
OAuth2CredentialProviderName = "custom-idp",
ClientId = "your-client-id",
ClientSecret = SecretValue.UnsafePlainText("your-client-secret"),
DiscoveryUrl = "https://idp.example.com/.well-known/openid-configuration"
});
agentcore.OAuth2CredentialProvider_UsingCustom(this, jsii.String("CustomOAuth"), &CustomOAuth2CredentialProviderProps{
OAuth2CredentialProviderName: jsii.String("custom-idp"),
ClientId: jsii.String("your-client-id"),
ClientSecret: cdk.SecretValue_UnsafePlainText(jsii.String("your-client-secret")),
DiscoveryUrl: jsii.String("https://idp.example.com/.well-known/openid-configuration"),
})
Example: custom IdP with explicit authorization server metadata
agentcore.OAuth2CredentialProvider.usingCustom(this, "CustomOAuthMeta", {
clientId: "your-client-id",
clientSecret: cdk.SecretValue.unsafePlainText("your-client-secret"),
authorizationServerMetadata: {
issuer: "https://idp.example.com",
authorizationEndpoint: "https://idp.example.com/oauth2/authorize",
tokenEndpoint: "https://idp.example.com/oauth2/token",
},
});
agentcore.OAuth2CredentialProvider.using_custom(self, "CustomOAuthMeta",
client_id="your-client-id",
client_secret=cdk.SecretValue.unsafe_plain_text("your-client-secret"),
authorization_server_metadata=agentcore.OAuth2AuthorizationServerMetadata(
issuer="https://idp.example.com",
authorization_endpoint="https://idp.example.com/oauth2/authorize",
token_endpoint="https://idp.example.com/oauth2/token"
)
)
OAuth2CredentialProvider.usingCustom(this, "CustomOAuthMeta", CustomOAuth2CredentialProviderProps.builder()
.clientId("your-client-id")
.clientSecret(SecretValue.unsafePlainText("your-client-secret"))
.authorizationServerMetadata(OAuth2AuthorizationServerMetadata.builder()
.issuer("https://idp.example.com")
.authorizationEndpoint("https://idp.example.com/oauth2/authorize")
.tokenEndpoint("https://idp.example.com/oauth2/token")
.build())
.build());
OAuth2CredentialProvider.UsingCustom(this, "CustomOAuthMeta", new CustomOAuth2CredentialProviderProps {
ClientId = "your-client-id",
ClientSecret = SecretValue.UnsafePlainText("your-client-secret"),
AuthorizationServerMetadata = new OAuth2AuthorizationServerMetadata {
Issuer = "https://idp.example.com",
AuthorizationEndpoint = "https://idp.example.com/oauth2/authorize",
TokenEndpoint = "https://idp.example.com/oauth2/token"
}
});
agentcore.OAuth2CredentialProvider_UsingCustom(this, jsii.String("CustomOAuthMeta"), &CustomOAuth2CredentialProviderProps{
ClientId: jsii.String("your-client-id"),
ClientSecret: cdk.SecretValue_UnsafePlainText(jsii.String("your-client-secret")),
AuthorizationServerMetadata: &OAuth2AuthorizationServerMetadata{
Issuer: jsii.String("https://idp.example.com"),
AuthorizationEndpoint: jsii.String("https://idp.example.com/oauth2/authorize"),
TokenEndpoint: jsii.String("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.
Construct — WorkloadIdentity maps to AWS::BedrockAgentCore::WorkloadIdentity. It exposes workloadIdentityArn, workloadIdentityName, and workloadIdentityRef for wiring into IAM or other AgentCore resources. Import an existing identity with WorkloadIdentity.fromWorkloadIdentityAttributes. Grant helpers (grantRead, grantAdmin, grantFullAccess) align with directory-level IAM patterns such as listing identities on the directory resource and scoping mutations to specific identity ARNs.
Example
new agentcore.WorkloadIdentity(this, "MyWorkloadIdentity", {
workloadIdentityName: "customer-support-agent-prod",
allowedResourceOauth2ReturnUrls: ["https://app.example.com/oauth/callback"],
tags: { team: "agents", env: "prod" },
});
agentcore.WorkloadIdentity(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"}
)
WorkloadIdentity.Builder.create(this, "MyWorkloadIdentity")
.workloadIdentityName("customer-support-agent-prod")
.allowedResourceOauth2ReturnUrls(List.of("https://app.example.com/oauth/callback"))
.tags(Map.of("team", "agents", "env", "prod"))
.build();
new WorkloadIdentity(this, "MyWorkloadIdentity", new WorkloadIdentityProps {
WorkloadIdentityName = "customer-support-agent-prod",
AllowedResourceOauth2ReturnUrls = new [] { "https://app.example.com/oauth/callback" },
Tags = new Dictionary<string, string> { { "team", "agents" }, { "env", "prod" } }
});
agentcore.NewWorkloadIdentity(this, jsii.String("MyWorkloadIdentity"), &WorkloadIdentityProps{
WorkloadIdentityName: jsii.String("customer-support-agent-prod"),
AllowedResourceOauth2ReturnUrls: []*string{
jsii.String("https://app.example.com/oauth/callback"),
},
Tags: map[string]*string{
"team": jsii.String("agents"),
"env": jsii.String("prod"),
},
})
Basic Gateway Target Creation
You can create targets in two ways: using the static factory methods on GatewayTarget or using the convenient addTarget methods on the gateway instance.
Using addTarget methods (Recommended)
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 addTarget methods.
// Create a gateway first
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
});
const lambdaFunction = new lambda.Function(this, "MyFunction", {
runtime: lambda.Runtime.NODEJS_22_X,
handler: "index.handler",
code: lambda.Code.fromInline(`
exports.handler = async (event) => {
return {
statusCode: 200,
body: JSON.stringify({ message: 'Hello from Lambda!' })
};
};
`),
});
const lambdaTarget = gateway.addLambdaTarget("MyLambdaTarget", {
gatewayTargetName: "my-lambda-target",
description: "Lambda function target",
lambdaFunction: lambdaFunction,
toolSchema: agentcore.ToolSchema.fromInline([
{
name: "hello_world",
description: "A simple hello world tool",
inputSchema: {
type: agentcore.SchemaDefinitionType.OBJECT,
properties: {
name: {
type: agentcore.SchemaDefinitionType.STRING,
description: "The name to greet",
},
},
required: ["name"],
},
},
]),
});
# Create a gateway first
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway"
)
lambda_function = lambda_.Function(self, "MyFunction",
runtime=lambda_.Runtime.NODEJS_22_X,
handler="index.handler",
code=lambda_.Code.from_inline("""
exports.handler = async (event) => {
return {
statusCode: 200,
body: JSON.stringify({ message: 'Hello from Lambda!' })
};
};
""")
)
lambda_target = gateway.add_lambda_target("MyLambdaTarget",
gateway_target_name="my-lambda-target",
description="Lambda function target",
lambda_function=lambda_function,
tool_schema=agentcore.ToolSchema.from_inline([
name="hello_world",
description="A simple hello world tool",
input_schema=agentcore.SchemaDefinition(
type=agentcore.SchemaDefinitionType.OBJECT,
properties={
"name": agentcore.SchemaDefinition(
type=agentcore.SchemaDefinitionType.STRING,
description="The name to greet"
)
},
required=["name"]
)
])
)
// Create a gateway first
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.build();
Function lambdaFunction = Function.Builder.create(this, "MyFunction")
.runtime(Runtime.NODEJS_22_X)
.handler("index.handler")
.code(Code.fromInline("\n exports.handler = async (event) => {\n return {\n statusCode: 200,\n body: JSON.stringify({ message: 'Hello from Lambda!' })\n };\n };\n "))
.build();
GatewayTarget lambdaTarget = gateway.addLambdaTarget("MyLambdaTarget", AddLambdaTargetOptions.builder()
.gatewayTargetName("my-lambda-target")
.description("Lambda function target")
.lambdaFunction(lambdaFunction)
.toolSchema(ToolSchema.fromInline(List.of(ToolDefinition.builder()
.name("hello_world")
.description("A simple hello world tool")
.inputSchema(SchemaDefinition.builder()
.type(SchemaDefinitionType.OBJECT)
.properties(Map.of(
"name", SchemaDefinition.builder()
.type(SchemaDefinitionType.STRING)
.description("The name to greet")
.build()))
.required(List.of("name"))
.build())
.build())))
.build());
// Create a gateway first
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway"
});
var lambdaFunction = new Function(this, "MyFunction", new FunctionProps {
Runtime = Runtime.NODEJS_22_X,
Handler = "index.handler",
Code = Code.FromInline(@"
exports.handler = async (event) => {
return {
statusCode: 200,
body: JSON.stringify({ message: 'Hello from Lambda!' })
};
};
")
});
var lambdaTarget = gateway.AddLambdaTarget("MyLambdaTarget", new AddLambdaTargetOptions {
GatewayTargetName = "my-lambda-target",
Description = "Lambda function target",
LambdaFunction = lambdaFunction,
ToolSchema = ToolSchema.FromInline(new [] { new ToolDefinition {
Name = "hello_world",
Description = "A simple hello world tool",
InputSchema = new SchemaDefinition {
Type = SchemaDefinitionType.OBJECT,
Properties = new Dictionary<string, SchemaDefinition> {
{ "name", new SchemaDefinition {
Type = SchemaDefinitionType.STRING,
Description = "The name to greet"
} }
},
Required = new [] { "name" }
}
} })
});
// Create a gateway first
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
})
lambdaFunction := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
Runtime: lambda.Runtime_NODEJS_22_X(),
Handler: jsii.String("index.handler"),
Code: lambda.Code_FromInline(jsii.String(`
exports.handler = async (event) => {
return {
statusCode: 200,
body: JSON.stringify({ message: 'Hello from Lambda!' })
};
};
`)),
})
lambdaTarget := gateway.AddLambdaTarget(jsii.String("MyLambdaTarget"), &AddLambdaTargetOptions{
GatewayTargetName: jsii.String("my-lambda-target"),
Description: jsii.String("Lambda function target"),
LambdaFunction: lambdaFunction,
ToolSchema: agentcore.ToolSchema_FromInline([]ToolDefinition{
&ToolDefinition{
Name: jsii.String("hello_world"),
Description: jsii.String("A simple hello world tool"),
InputSchema: &SchemaDefinition{
Type: agentcore.SchemaDefinitionType_OBJECT(),
Properties: map[string]SchemaDefinition{
"name": &SchemaDefinition{
"type": agentcore.SchemaDefinitionType_STRING(),
"description": jsii.String("The name to greet"),
},
},
Required: []*string{
jsii.String("name"),
},
},
},
}),
})
- OpenAPI Target (using Token Vault L2 construct — preferred)
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
});
// Create an API key credential provider in Token Vault
const apiKeyProvider = new agentcore.ApiKeyCredentialProvider(this, "MyApiKeyProvider", {
apiKeyCredentialProviderName: "my-apikey",
});
const bucket = s3.Bucket.fromBucketName(this, "ExistingBucket", "my-schema-bucket");
const s3mySchema = agentcore.ApiSchema.fromS3File(bucket, "schemas/myschema.yaml");
// Add an OpenAPI target using the L2 construct directly
const target = gateway.addOpenApiTarget("MyTarget", {
gatewayTargetName: "my-api-target",
description: "Target for external API integration",
apiSchema: s3mySchema,
credentialProviderConfigurations: [
agentcore.GatewayCredentialProvider.fromApiKeyIdentity(apiKeyProvider, {
credentialLocation: agentcore.ApiKeyCredentialLocation.header({
credentialParameterName: "X-API-Key",
}),
}),
],
});
// This makes sure your s3 bucket is available before target
target.node.addDependency(bucket);
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway"
)
# Create an API key credential provider in Token Vault
api_key_provider = agentcore.ApiKeyCredentialProvider(self, "MyApiKeyProvider",
api_key_credential_provider_name="my-apikey"
)
bucket = s3.Bucket.from_bucket_name(self, "ExistingBucket", "my-schema-bucket")
s3my_schema = agentcore.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=[
agentcore.GatewayCredentialProvider.from_api_key_identity(api_key_provider,
credential_location=agentcore.ApiKeyCredentialLocation.header(
credential_parameter_name="X-API-Key"
)
)
]
)
# This makes sure your s3 bucket is available before target
target.node.add_dependency(bucket)
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.build();
// Create an API key credential provider in Token Vault
ApiKeyCredentialProvider apiKeyProvider = ApiKeyCredentialProvider.Builder.create(this, "MyApiKeyProvider")
.apiKeyCredentialProviderName("my-apikey")
.build();
IBucket bucket = Bucket.fromBucketName(this, "ExistingBucket", "my-schema-bucket");
S3ApiSchema s3mySchema = ApiSchema.fromS3File(bucket, "schemas/myschema.yaml");
// Add an OpenAPI target using the L2 construct directly
GatewayTarget target = gateway.addOpenApiTarget("MyTarget", AddOpenApiTargetOptions.builder()
.gatewayTargetName("my-api-target")
.description("Target for external API integration")
.apiSchema(s3mySchema)
.credentialProviderConfigurations(List.of(GatewayCredentialProvider.fromApiKeyIdentity(apiKeyProvider, FromApiKeyIdentityOptions.builder()
.credentialLocation(ApiKeyCredentialLocation.header(ApiKeyAdditionalConfiguration.builder()
.credentialParameterName("X-API-Key")
.build()))
.build())))
.build());
// This makes sure your s3 bucket is available before target
target.node.addDependency(bucket);
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway"
});
// Create an API key credential provider in Token Vault
var apiKeyProvider = new ApiKeyCredentialProvider(this, "MyApiKeyProvider", new ApiKeyCredentialProviderProps {
ApiKeyCredentialProviderName = "my-apikey"
});
var bucket = Bucket.FromBucketName(this, "ExistingBucket", "my-schema-bucket");
var s3mySchema = ApiSchema.FromS3File(bucket, "schemas/myschema.yaml");
// Add an OpenAPI target using the L2 construct directly
var target = gateway.AddOpenApiTarget("MyTarget", new AddOpenApiTargetOptions {
GatewayTargetName = "my-api-target",
Description = "Target for external API integration",
ApiSchema = s3mySchema,
CredentialProviderConfigurations = new [] { GatewayCredentialProvider.FromApiKeyIdentity(apiKeyProvider, new FromApiKeyIdentityOptions {
CredentialLocation = ApiKeyCredentialLocation.Header(new ApiKeyAdditionalConfiguration {
CredentialParameterName = "X-API-Key"
})
}) }
});
// This makes sure your s3 bucket is available before target
target.Node.AddDependency(bucket);
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
})
// Create an API key credential provider in Token Vault
apiKeyProvider := agentcore.NewApiKeyCredentialProvider(this, jsii.String("MyApiKeyProvider"), &ApiKeyCredentialProviderProps{
ApiKeyCredentialProviderName: jsii.String("my-apikey"),
})
bucket := s3.Bucket_FromBucketName(this, jsii.String("ExistingBucket"), jsii.String("my-schema-bucket"))
s3mySchema := agentcore.ApiSchema_FromS3File(bucket, jsii.String("schemas/myschema.yaml"))
// Add an OpenAPI target using the L2 construct directly
target := gateway.AddOpenApiTarget(jsii.String("MyTarget"), &AddOpenApiTargetOptions{
GatewayTargetName: jsii.String("my-api-target"),
Description: jsii.String("Target for external API integration"),
ApiSchema: s3mySchema,
CredentialProviderConfigurations: []ICredentialProviderConfig{
agentcore.GatewayCredentialProvider_FromApiKeyIdentity(apiKeyProvider, &FromApiKeyIdentityOptions{
CredentialLocation: agentcore.ApiKeyCredentialLocation_Header(&ApiKeyAdditionalConfiguration{
CredentialParameterName: jsii.String("X-API-Key"),
}),
}),
},
})
// This makes sure your s3 bucket is available before target
target.Node.AddDependency(bucket)
- OpenAPI Target (using ARNs — for providers created outside of CDK)
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
});
// ARNs from the console/API, or from ApiKeyCredentialProvider + bindForGatewayApiKeyTarget
const apiKeyProviderArn = "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/apikeycredentialprovider/my-apikey"
const apiKeySecretArn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-apikey-secret-abc123"
const bucket = s3.Bucket.fromBucketName(this, "ExistingBucket", "my-schema-bucket");
const s3mySchema = agentcore.ApiSchema.fromS3File(bucket, "schemas/myschema.yaml");
// Add an OpenAPI target using ARNs directly
const target = gateway.addOpenApiTarget("MyTarget", {
gatewayTargetName: "my-api-target",
description: "Target for external API integration",
apiSchema: s3mySchema,
credentialProviderConfigurations: [
agentcore.GatewayCredentialProvider.fromApiKeyIdentityArn({
providerArn: apiKeyProviderArn,
secretArn: apiKeySecretArn,
credentialLocation: agentcore.ApiKeyCredentialLocation.header({
credentialParameterName: "X-API-Key",
}),
}),
],
});
// This makes sure your s3 bucket is available before target
target.node.addDependency(bucket);
gateway = agentcore.Gateway(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 = s3.Bucket.from_bucket_name(self, "ExistingBucket", "my-schema-bucket")
s3my_schema = agentcore.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=[
agentcore.GatewayCredentialProvider.from_api_key_identity_arn(
provider_arn=api_key_provider_arn,
secret_arn=api_key_secret_arn,
credential_location=agentcore.ApiKeyCredentialLocation.header(
credential_parameter_name="X-API-Key"
)
)
]
)
# This makes sure your s3 bucket is available before target
target.node.add_dependency(bucket)
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.build();
// ARNs from the console/API, or from ApiKeyCredentialProvider + bindForGatewayApiKeyTarget
String apiKeyProviderArn = "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/apikeycredentialprovider/my-apikey";
String apiKeySecretArn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-apikey-secret-abc123";
IBucket bucket = Bucket.fromBucketName(this, "ExistingBucket", "my-schema-bucket");
S3ApiSchema s3mySchema = ApiSchema.fromS3File(bucket, "schemas/myschema.yaml");
// Add an OpenAPI target using ARNs directly
GatewayTarget target = gateway.addOpenApiTarget("MyTarget", AddOpenApiTargetOptions.builder()
.gatewayTargetName("my-api-target")
.description("Target for external API integration")
.apiSchema(s3mySchema)
.credentialProviderConfigurations(List.of(GatewayCredentialProvider.fromApiKeyIdentityArn(ApiKeyCredentialProviderOptions.builder()
.providerArn(apiKeyProviderArn)
.secretArn(apiKeySecretArn)
.credentialLocation(ApiKeyCredentialLocation.header(ApiKeyAdditionalConfiguration.builder()
.credentialParameterName("X-API-Key")
.build()))
.build())))
.build());
// This makes sure your s3 bucket is available before target
target.node.addDependency(bucket);
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway"
});
// ARNs from the console/API, or from ApiKeyCredentialProvider + bindForGatewayApiKeyTarget
var apiKeyProviderArn = "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/apikeycredentialprovider/my-apikey";
var apiKeySecretArn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-apikey-secret-abc123";
var bucket = Bucket.FromBucketName(this, "ExistingBucket", "my-schema-bucket");
var s3mySchema = ApiSchema.FromS3File(bucket, "schemas/myschema.yaml");
// Add an OpenAPI target using ARNs directly
var target = gateway.AddOpenApiTarget("MyTarget", new AddOpenApiTargetOptions {
GatewayTargetName = "my-api-target",
Description = "Target for external API integration",
ApiSchema = s3mySchema,
CredentialProviderConfigurations = new [] { GatewayCredentialProvider.FromApiKeyIdentityArn(new ApiKeyCredentialProviderOptions {
ProviderArn = apiKeyProviderArn,
SecretArn = apiKeySecretArn,
CredentialLocation = ApiKeyCredentialLocation.Header(new ApiKeyAdditionalConfiguration {
CredentialParameterName = "X-API-Key"
})
}) }
});
// This makes sure your s3 bucket is available before target
target.Node.AddDependency(bucket);
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
})
// ARNs from the console/API, or from ApiKeyCredentialProvider + bindForGatewayApiKeyTarget
apiKeyProviderArn := "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/apikeycredentialprovider/my-apikey"
apiKeySecretArn := "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-apikey-secret-abc123"
bucket := s3.Bucket_FromBucketName(this, jsii.String("ExistingBucket"), jsii.String("my-schema-bucket"))
s3mySchema := agentcore.ApiSchema_FromS3File(bucket, jsii.String("schemas/myschema.yaml"))
// Add an OpenAPI target using ARNs directly
target := gateway.AddOpenApiTarget(jsii.String("MyTarget"), &AddOpenApiTargetOptions{
GatewayTargetName: jsii.String("my-api-target"),
Description: jsii.String("Target for external API integration"),
ApiSchema: s3mySchema,
CredentialProviderConfigurations: []ICredentialProviderConfig{
agentcore.GatewayCredentialProvider_FromApiKeyIdentityArn(&ApiKeyCredentialProviderOptions{
ProviderArn: apiKeyProviderArn,
SecretArn: apiKeySecretArn,
CredentialLocation: agentcore.ApiKeyCredentialLocation_Header(&ApiKeyAdditionalConfiguration{
CredentialParameterName: jsii.String("X-API-Key"),
}),
}),
},
})
// This makes sure your s3 bucket is available before target
target.Node.AddDependency(bucket)
- Smithy Target
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
});
const smithySchema = agentcore.ApiSchema.fromLocalAsset(
path.join(__dirname, "models", "smithy-model.json")
);
smithySchema.bind(this);
const smithyTarget = gateway.addSmithyTarget("MySmithyTarget", {
gatewayTargetName: "my-smithy-target",
description: "Smithy model target",
smithyModel: smithySchema,
});
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway"
)
smithy_schema = agentcore.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 gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.build();
AssetApiSchema smithySchema = ApiSchema.fromLocalAsset(path.join(__dirname, "models", "smithy-model.json"));
smithySchema.bind(this);
GatewayTarget smithyTarget = gateway.addSmithyTarget("MySmithyTarget", AddSmithyTargetOptions.builder()
.gatewayTargetName("my-smithy-target")
.description("Smithy model target")
.smithyModel(smithySchema)
.build());
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway"
});
var smithySchema = ApiSchema.FromLocalAsset(path.Join(__dirname, "models", "smithy-model.json"));
smithySchema.Bind(this);
var smithyTarget = gateway.AddSmithyTarget("MySmithyTarget", new AddSmithyTargetOptions {
GatewayTargetName = "my-smithy-target",
Description = "Smithy model target",
SmithyModel = smithySchema
});
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
})
smithySchema := agentcore.ApiSchema_FromLocalAsset(path.join(__dirname, jsii.String("models"), jsii.String("smithy-model.json")))
smithySchema.Bind(this)
smithyTarget := gateway.AddSmithyTarget(jsii.String("MySmithyTarget"), &AddSmithyTargetOptions{
GatewayTargetName: jsii.String("my-smithy-target"),
Description: jsii.String("Smithy model target"),
SmithyModel: smithySchema,
})
- MCP Server Target
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
});
// OAuth2 (recommended): use OAuth2CredentialProvider + bindForGatewayOAuthTarget, or ARNs from console/API
const oauthProviderArn = "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/oauth2credentialprovider/my-oauth";
const oauthSecretArn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-oauth-secret-abc123";
// Add an MCP server target directly to the gateway
const mcpTarget = gateway.addMcpServerTarget("MyMcpServer", {
gatewayTargetName: "my-mcp-server",
description: "External MCP server integration",
endpoint: "https://my-mcp-server.example.com",
credentialProviderConfigurations: [
agentcore.GatewayCredentialProvider.fromOauthIdentityArn({
providerArn: oauthProviderArn,
secretArn: oauthSecretArn,
scopes:['mcp-runtime-server/invoke']
}),
],
});
// Grant sync permission to a Lambda function that will trigger synchronization
const syncFunction = new lambda.Function(this, "SyncFunction", {
runtime: lambda.Runtime.PYTHON_3_12,
handler: "index.handler",
code: lambda.Code.fromInline(`
import boto3
def handler(event, context):
client = boto3.client('bedrock-agentcore')
response = client.synchronize_gateway_targets(
gatewayIdentifier=event['gatewayId'],
targetIds=[event['targetId']]
)
return response
`),
});
mcpTarget.grantSync(syncFunction);
gateway = agentcore.Gateway(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=[
agentcore.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 = lambda_.Function(self, "SyncFunction",
runtime=lambda_.Runtime.PYTHON_3_12,
handler="index.handler",
code=lambda_.Code.from_inline("""
import boto3
def handler(event, context):
client = boto3.client('bedrock-agentcore')
response = client.synchronize_gateway_targets(
gatewayIdentifier=event['gatewayId'],
targetIds=[event['targetId']]
)
return response
""")
)
mcp_target.grant_sync(sync_function)
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.build();
// OAuth2 (recommended): use OAuth2CredentialProvider + bindForGatewayOAuthTarget, or ARNs from console/API
String oauthProviderArn = "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/oauth2credentialprovider/my-oauth";
String oauthSecretArn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-oauth-secret-abc123";
// Add an MCP server target directly to the gateway
GatewayTarget mcpTarget = gateway.addMcpServerTarget("MyMcpServer", AddMcpServerTargetOptions.builder()
.gatewayTargetName("my-mcp-server")
.description("External MCP server integration")
.endpoint("https://my-mcp-server.example.com")
.credentialProviderConfigurations(List.of(GatewayCredentialProvider.fromOauthIdentityArn(OAuthConfiguration.builder()
.providerArn(oauthProviderArn)
.secretArn(oauthSecretArn)
.scopes(List.of("mcp-runtime-server/invoke"))
.build())))
.build());
// Grant sync permission to a Lambda function that will trigger synchronization
Function syncFunction = Function.Builder.create(this, "SyncFunction")
.runtime(Runtime.PYTHON_3_12)
.handler("index.handler")
.code(Code.fromInline("\nimport boto3\n\ndef handler(event, context):\n client = boto3.client('bedrock-agentcore')\n response = client.synchronize_gateway_targets(\n gatewayIdentifier=event['gatewayId'],\n targetIds=[event['targetId']]\n )\n return response\n "))
.build();
mcpTarget.grantSync(syncFunction);
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway"
});
// OAuth2 (recommended): use OAuth2CredentialProvider + bindForGatewayOAuthTarget, or ARNs from console/API
var oauthProviderArn = "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/oauth2credentialprovider/my-oauth";
var oauthSecretArn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-oauth-secret-abc123";
// Add an MCP server target directly to the gateway
var mcpTarget = gateway.AddMcpServerTarget("MyMcpServer", new AddMcpServerTargetOptions {
GatewayTargetName = "my-mcp-server",
Description = "External MCP server integration",
Endpoint = "https://my-mcp-server.example.com",
CredentialProviderConfigurations = new [] { GatewayCredentialProvider.FromOauthIdentityArn(new OAuthConfiguration {
ProviderArn = oauthProviderArn,
SecretArn = oauthSecretArn,
Scopes = new [] { "mcp-runtime-server/invoke" }
}) }
});
// Grant sync permission to a Lambda function that will trigger synchronization
var syncFunction = new Function(this, "SyncFunction", new FunctionProps {
Runtime = Runtime.PYTHON_3_12,
Handler = "index.handler",
Code = Code.FromInline(@"
import boto3
def handler(event, context):
client = boto3.client('bedrock-agentcore')
response = client.synchronize_gateway_targets(
gatewayIdentifier=event['gatewayId'],
targetIds=[event['targetId']]
)
return response
")
});
mcpTarget.GrantSync(syncFunction);
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
})
// OAuth2 (recommended): use OAuth2CredentialProvider + bindForGatewayOAuthTarget, or ARNs from console/API
oauthProviderArn := "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/oauth2credentialprovider/my-oauth"
oauthSecretArn := "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-oauth-secret-abc123"
// Add an MCP server target directly to the gateway
mcpTarget := gateway.AddMcpServerTarget(jsii.String("MyMcpServer"), &AddMcpServerTargetOptions{
GatewayTargetName: jsii.String("my-mcp-server"),
Description: jsii.String("External MCP server integration"),
Endpoint: jsii.String("https://my-mcp-server.example.com"),
CredentialProviderConfigurations: []ICredentialProviderConfig{
agentcore.GatewayCredentialProvider_FromOauthIdentityArn(&OAuthConfiguration{
ProviderArn: oauthProviderArn,
SecretArn: oauthSecretArn,
Scopes: []*string{
jsii.String("mcp-runtime-server/invoke"),
},
}),
},
})
// Grant sync permission to a Lambda function that will trigger synchronization
syncFunction := lambda.NewFunction(this, jsii.String("SyncFunction"), &FunctionProps{
Runtime: lambda.Runtime_PYTHON_3_12(),
Handler: jsii.String("index.handler"),
Code: lambda.Code_FromInline(jsii.String(`
import boto3
def handler(event, context):
client = boto3.client('bedrock-agentcore')
response = client.synchronize_gateway_targets(
gatewayIdentifier=event['gatewayId'],
targetIds=[event['targetId']]
)
return response
`)),
})
mcpTarget.GrantSync(syncFunction)
- API Gateway Target
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
});
const api = new apigateway.RestApi(this, 'MyApi', {
restApiName: 'my-api',
});
// Uses IAM authorization for outbound auth by default
const apiGatewayTarget = gateway.addApiGatewayTarget("MyApiGatewayTarget", {
restApi: api,
apiGatewayToolConfiguration: {
toolFilters: [
{
filterPath: "/pets/*",
methods: [agentcore.ApiGatewayHttpMethod.GET],
},
],
},
});
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway"
)
api = apigateway.RestApi(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=agentcore.ApiGatewayToolConfiguration(
tool_filters=[agentcore.ApiGatewayToolFilter(
filter_path="/pets/*",
methods=[agentcore.ApiGatewayHttpMethod.GET]
)
]
)
)
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.build();
RestApi api = RestApi.Builder.create(this, "MyApi")
.restApiName("my-api")
.build();
// Uses IAM authorization for outbound auth by default
GatewayTarget apiGatewayTarget = gateway.addApiGatewayTarget("MyApiGatewayTarget", AddApiGatewayTargetOptions.builder()
.restApi(api)
.apiGatewayToolConfiguration(ApiGatewayToolConfiguration.builder()
.toolFilters(List.of(ApiGatewayToolFilter.builder()
.filterPath("/pets/*")
.methods(List.of(ApiGatewayHttpMethod.GET))
.build()))
.build())
.build());
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway"
});
var api = new RestApi(this, "MyApi", new RestApiProps {
RestApiName = "my-api"
});
// Uses IAM authorization for outbound auth by default
var apiGatewayTarget = gateway.AddApiGatewayTarget("MyApiGatewayTarget", new AddApiGatewayTargetOptions {
RestApi = api,
ApiGatewayToolConfiguration = new ApiGatewayToolConfiguration {
ToolFilters = new [] { new ApiGatewayToolFilter {
FilterPath = "/pets/*",
Methods = new [] { ApiGatewayHttpMethod.GET }
} }
}
});
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
})
api := apigateway.NewRestApi(this, jsii.String("MyApi"), &RestApiProps{
RestApiName: jsii.String("my-api"),
})
// Uses IAM authorization for outbound auth by default
apiGatewayTarget := gateway.AddApiGatewayTarget(jsii.String("MyApiGatewayTarget"), &AddApiGatewayTargetOptions{
RestApi: api,
ApiGatewayToolConfiguration: &ApiGatewayToolConfiguration{
ToolFilters: []ApiGatewayToolFilter{
&ApiGatewayToolFilter{
FilterPath: jsii.String("/pets/*"),
Methods: []ApiGatewayHttpMethod{
agentcore.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.
- Lambda Target
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
});
const lambdaFunction = new lambda.Function(this, "MyFunction", {
runtime: lambda.Runtime.NODEJS_22_X,
handler: "index.handler",
code: lambda.Code.fromInline(`
exports.handler = async (event) => {
return {
statusCode: 200,
body: JSON.stringify({ message: 'Hello from Lambda!' })
};
};
`),
});
// Create a gateway target with Lambda and tool schema
const target = agentcore.GatewayTarget.forLambda(this, "MyLambdaTarget", {
gatewayTargetName: "my-lambda-target",
description: "Target for Lambda function integration",
gateway: gateway,
lambdaFunction: lambdaFunction,
toolSchema: agentcore.ToolSchema.fromLocalAsset(
path.join(__dirname, "schemas", "my-tool-schema.json")
),
});
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway"
)
lambda_function = lambda_.Function(self, "MyFunction",
runtime=lambda_.Runtime.NODEJS_22_X,
handler="index.handler",
code=lambda_.Code.from_inline("""
exports.handler = async (event) => {
return {
statusCode: 200,
body: JSON.stringify({ message: 'Hello from Lambda!' })
};
};
""")
)
# Create a gateway target with Lambda and tool schema
target = agentcore.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=agentcore.ToolSchema.from_local_asset(
path.join(__dirname, "schemas", "my-tool-schema.json"))
)
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.build();
Function lambdaFunction = Function.Builder.create(this, "MyFunction")
.runtime(Runtime.NODEJS_22_X)
.handler("index.handler")
.code(Code.fromInline("\n exports.handler = async (event) => {\n return {\n statusCode: 200,\n body: JSON.stringify({ message: 'Hello from Lambda!' })\n };\n };\n "))
.build();
// Create a gateway target with Lambda and tool schema
GatewayTarget target = GatewayTarget.forLambda(this, "MyLambdaTarget", GatewayTargetLambdaProps.builder()
.gatewayTargetName("my-lambda-target")
.description("Target for Lambda function integration")
.gateway(gateway)
.lambdaFunction(lambdaFunction)
.toolSchema(ToolSchema.fromLocalAsset(path.join(__dirname, "schemas", "my-tool-schema.json")))
.build());
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway"
});
var lambdaFunction = new Function(this, "MyFunction", new FunctionProps {
Runtime = Runtime.NODEJS_22_X,
Handler = "index.handler",
Code = Code.FromInline(@"
exports.handler = async (event) => {
return {
statusCode: 200,
body: JSON.stringify({ message: 'Hello from Lambda!' })
};
};
")
});
// Create a gateway target with Lambda and tool schema
var target = GatewayTarget.ForLambda(this, "MyLambdaTarget", new GatewayTargetLambdaProps {
GatewayTargetName = "my-lambda-target",
Description = "Target for Lambda function integration",
Gateway = gateway,
LambdaFunction = lambdaFunction,
ToolSchema = ToolSchema.FromLocalAsset(path.Join(__dirname, "schemas", "my-tool-schema.json"))
});
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
})
lambdaFunction := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
Runtime: lambda.Runtime_NODEJS_22_X(),
Handler: jsii.String("index.handler"),
Code: lambda.Code_FromInline(jsii.String(`
exports.handler = async (event) => {
return {
statusCode: 200,
body: JSON.stringify({ message: 'Hello from Lambda!' })
};
};
`)),
})
// Create a gateway target with Lambda and tool schema
target := agentcore.GatewayTarget_ForLambda(this, jsii.String("MyLambdaTarget"), &GatewayTargetLambdaProps{
GatewayTargetName: jsii.String("my-lambda-target"),
Description: jsii.String("Target for Lambda function integration"),
Gateway: gateway,
LambdaFunction: lambdaFunction,
ToolSchema: agentcore.ToolSchema_FromLocalAsset(path.join(__dirname, jsii.String("schemas"), jsii.String("my-tool-schema.json"))),
})
- OpenAPI Target
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
});
// Outbound auth: ApiKeyCredentialProvider + bindForGatewayApiKeyTarget, or ARNs from console/API
const apiKeyIdentityArn = "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/apikeycredentialprovider/my-apikey"
const apiKeySecretArn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-apikey-secret-abc123"
const opneapiSchema = agentcore.ApiSchema.fromLocalAsset(path.join(__dirname, "mySchema.yml"));
opneapiSchema.bind(this);
// Create a gateway target with OpenAPI Schema
const target = agentcore.GatewayTarget.forOpenApi(this, "MyTarget", {
gatewayTargetName: "my-api-target",
description: "Target for external API integration",
gateway: gateway, // Note: you need to pass the gateway reference
apiSchema: opneapiSchema,
credentialProviderConfigurations: [
agentcore.GatewayCredentialProvider.fromApiKeyIdentityArn({
providerArn: apiKeyIdentityArn,
secretArn: apiKeySecretArn
}),
],
});
gateway = agentcore.Gateway(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 = agentcore.ApiSchema.from_local_asset(path.join(__dirname, "mySchema.yml"))
opneapi_schema.bind(self)
# Create a gateway target with OpenAPI Schema
target = agentcore.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=[
agentcore.GatewayCredentialProvider.from_api_key_identity_arn(
provider_arn=api_key_identity_arn,
secret_arn=api_key_secret_arn
)
]
)
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.build();
// Outbound auth: ApiKeyCredentialProvider + bindForGatewayApiKeyTarget, or ARNs from console/API
String apiKeyIdentityArn = "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/apikeycredentialprovider/my-apikey";
String apiKeySecretArn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-apikey-secret-abc123";
AssetApiSchema opneapiSchema = ApiSchema.fromLocalAsset(path.join(__dirname, "mySchema.yml"));
opneapiSchema.bind(this);
// Create a gateway target with OpenAPI Schema
GatewayTarget target = GatewayTarget.forOpenApi(this, "MyTarget", GatewayTargetOpenApiProps.builder()
.gatewayTargetName("my-api-target")
.description("Target for external API integration")
.gateway(gateway) // Note: you need to pass the gateway reference
.apiSchema(opneapiSchema)
.credentialProviderConfigurations(List.of(GatewayCredentialProvider.fromApiKeyIdentityArn(ApiKeyCredentialProviderOptions.builder()
.providerArn(apiKeyIdentityArn)
.secretArn(apiKeySecretArn)
.build())))
.build());
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway"
});
// Outbound auth: ApiKeyCredentialProvider + bindForGatewayApiKeyTarget, or ARNs from console/API
var apiKeyIdentityArn = "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/apikeycredentialprovider/my-apikey";
var apiKeySecretArn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-apikey-secret-abc123";
var opneapiSchema = ApiSchema.FromLocalAsset(path.Join(__dirname, "mySchema.yml"));
opneapiSchema.Bind(this);
// Create a gateway target with OpenAPI Schema
var target = GatewayTarget.ForOpenApi(this, "MyTarget", new GatewayTargetOpenApiProps {
GatewayTargetName = "my-api-target",
Description = "Target for external API integration",
Gateway = gateway, // Note: you need to pass the gateway reference
ApiSchema = opneapiSchema,
CredentialProviderConfigurations = new [] { GatewayCredentialProvider.FromApiKeyIdentityArn(new ApiKeyCredentialProviderOptions {
ProviderArn = apiKeyIdentityArn,
SecretArn = apiKeySecretArn
}) }
});
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
})
// Outbound auth: ApiKeyCredentialProvider + bindForGatewayApiKeyTarget, or ARNs from console/API
apiKeyIdentityArn := "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/apikeycredentialprovider/my-apikey"
apiKeySecretArn := "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-apikey-secret-abc123"
opneapiSchema := agentcore.ApiSchema_FromLocalAsset(path.join(__dirname, jsii.String("mySchema.yml")))
opneapiSchema.Bind(this)
// Create a gateway target with OpenAPI Schema
target := agentcore.GatewayTarget_ForOpenApi(this, jsii.String("MyTarget"), &GatewayTargetOpenApiProps{
GatewayTargetName: jsii.String("my-api-target"),
Description: jsii.String("Target for external API integration"),
Gateway: gateway,
// Note: you need to pass the gateway reference
ApiSchema: opneapiSchema,
CredentialProviderConfigurations: []ICredentialProviderConfig{
agentcore.GatewayCredentialProvider_FromApiKeyIdentityArn(&ApiKeyCredentialProviderOptions{
ProviderArn: apiKeyIdentityArn,
SecretArn: apiKeySecretArn,
}),
},
})
- Smithy Target
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
});
const smithySchema = agentcore.ApiSchema.fromLocalAsset(
path.join(__dirname, "models", "smithy-model.json")
);
smithySchema.bind(this);
// Create a gateway target with Smithy Model and OAuth
const target = agentcore.GatewayTarget.forSmithy(this, "MySmithyTarget", {
gatewayTargetName: "my-smithy-target",
description: "Target for Smithy model integration",
gateway: gateway,
smithyModel: smithySchema,
});
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway"
)
smithy_schema = agentcore.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 = agentcore.GatewayTarget.for_smithy(self, "MySmithyTarget",
gateway_target_name="my-smithy-target",
description="Target for Smithy model integration",
gateway=gateway,
smithy_model=smithy_schema
)
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.build();
AssetApiSchema smithySchema = ApiSchema.fromLocalAsset(path.join(__dirname, "models", "smithy-model.json"));
smithySchema.bind(this);
// Create a gateway target with Smithy Model and OAuth
GatewayTarget target = GatewayTarget.forSmithy(this, "MySmithyTarget", GatewayTargetSmithyProps.builder()
.gatewayTargetName("my-smithy-target")
.description("Target for Smithy model integration")
.gateway(gateway)
.smithyModel(smithySchema)
.build());
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway"
});
var smithySchema = ApiSchema.FromLocalAsset(path.Join(__dirname, "models", "smithy-model.json"));
smithySchema.Bind(this);
// Create a gateway target with Smithy Model and OAuth
var target = GatewayTarget.ForSmithy(this, "MySmithyTarget", new GatewayTargetSmithyProps {
GatewayTargetName = "my-smithy-target",
Description = "Target for Smithy model integration",
Gateway = gateway,
SmithyModel = smithySchema
});
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
})
smithySchema := agentcore.ApiSchema_FromLocalAsset(path.join(__dirname, jsii.String("models"), jsii.String("smithy-model.json")))
smithySchema.Bind(this)
// Create a gateway target with Smithy Model and OAuth
target := agentcore.GatewayTarget_ForSmithy(this, jsii.String("MySmithyTarget"), &GatewayTargetSmithyProps{
GatewayTargetName: jsii.String("my-smithy-target"),
Description: jsii.String("Target for Smithy model integration"),
Gateway: gateway,
SmithyModel: smithySchema,
})
- MCP Server Target
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
});
// OAuth2 (recommended): use OAuth2CredentialProvider + bindForGatewayOAuthTarget, or ARNs from console/API
const oauthProviderArn = "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/oauth2credentialprovider/my-oauth";
const oauthSecretArn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-oauth-secret-abc123";
// Create a gateway target with MCP Server
const mcpTarget = agentcore.GatewayTarget.forMcpServer(this, "MyMcpServer", {
gatewayTargetName: "my-mcp-server",
description: "External MCP server integration",
gateway: gateway,
endpoint: "https://my-mcp-server.example.com",
credentialProviderConfigurations: [
agentcore.GatewayCredentialProvider.fromOauthIdentityArn({
providerArn: oauthProviderArn,
secretArn: oauthSecretArn,
scopes:['mcp-runtime-server/invoke']
}),
],
});
gateway = agentcore.Gateway(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 = agentcore.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=[
agentcore.GatewayCredentialProvider.from_oauth_identity_arn(
provider_arn=oauth_provider_arn,
secret_arn=oauth_secret_arn,
scopes=["mcp-runtime-server/invoke"]
)
]
)
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.build();
// OAuth2 (recommended): use OAuth2CredentialProvider + bindForGatewayOAuthTarget, or ARNs from console/API
String oauthProviderArn = "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/oauth2credentialprovider/my-oauth";
String oauthSecretArn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-oauth-secret-abc123";
// Create a gateway target with MCP Server
GatewayTarget mcpTarget = GatewayTarget.forMcpServer(this, "MyMcpServer", GatewayTargetMcpServerProps.builder()
.gatewayTargetName("my-mcp-server")
.description("External MCP server integration")
.gateway(gateway)
.endpoint("https://my-mcp-server.example.com")
.credentialProviderConfigurations(List.of(GatewayCredentialProvider.fromOauthIdentityArn(OAuthConfiguration.builder()
.providerArn(oauthProviderArn)
.secretArn(oauthSecretArn)
.scopes(List.of("mcp-runtime-server/invoke"))
.build())))
.build());
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway"
});
// OAuth2 (recommended): use OAuth2CredentialProvider + bindForGatewayOAuthTarget, or ARNs from console/API
var oauthProviderArn = "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/oauth2credentialprovider/my-oauth";
var oauthSecretArn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-oauth-secret-abc123";
// Create a gateway target with MCP Server
var mcpTarget = GatewayTarget.ForMcpServer(this, "MyMcpServer", new GatewayTargetMcpServerProps {
GatewayTargetName = "my-mcp-server",
Description = "External MCP server integration",
Gateway = gateway,
Endpoint = "https://my-mcp-server.example.com",
CredentialProviderConfigurations = new [] { GatewayCredentialProvider.FromOauthIdentityArn(new OAuthConfiguration {
ProviderArn = oauthProviderArn,
SecretArn = oauthSecretArn,
Scopes = new [] { "mcp-runtime-server/invoke" }
}) }
});
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
})
// OAuth2 (recommended): use OAuth2CredentialProvider + bindForGatewayOAuthTarget, or ARNs from console/API
oauthProviderArn := "arn:aws:bedrock-agentcore:us-east-1:123456789012:token-vault/abc123/oauth2credentialprovider/my-oauth"
oauthSecretArn := "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-oauth-secret-abc123"
// Create a gateway target with MCP Server
mcpTarget := agentcore.GatewayTarget_ForMcpServer(this, jsii.String("MyMcpServer"), &GatewayTargetMcpServerProps{
GatewayTargetName: jsii.String("my-mcp-server"),
Description: jsii.String("External MCP server integration"),
Gateway: gateway,
Endpoint: jsii.String("https://my-mcp-server.example.com"),
CredentialProviderConfigurations: []ICredentialProviderConfig{
agentcore.GatewayCredentialProvider_FromOauthIdentityArn(&OAuthConfiguration{
ProviderArn: oauthProviderArn,
SecretArn: oauthSecretArn,
Scopes: []*string{
jsii.String("mcp-runtime-server/invoke"),
},
}),
},
})
- API Gateway Target
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
});
const api = new apigateway.RestApi(this, 'MyApi', {
restApiName: 'my-api',
});
// Create a gateway target using the static factory method
const apiGatewayTarget = agentcore.GatewayTarget.forApiGateway(this, "MyApiGatewayTarget", {
gatewayTargetName: "my-api-gateway-target",
description: "Target for API Gateway REST API integration",
gateway: gateway,
restApi: api,
apiGatewayToolConfiguration: {
toolFilters: [
{
filterPath: "/pets/*",
methods: [agentcore.ApiGatewayHttpMethod.GET, agentcore.ApiGatewayHttpMethod.POST],
},
],
},
metadataConfiguration: {
allowedRequestHeaders: ["X-User-Id"],
allowedQueryParameters: ["limit"],
},
});
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway"
)
api = apigateway.RestApi(self, "MyApi",
rest_api_name="my-api"
)
# Create a gateway target using the static factory method
api_gateway_target = agentcore.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=agentcore.ApiGatewayToolConfiguration(
tool_filters=[agentcore.ApiGatewayToolFilter(
filter_path="/pets/*",
methods=[agentcore.ApiGatewayHttpMethod.GET, agentcore.ApiGatewayHttpMethod.POST]
)
]
),
metadata_configuration=agentcore.MetadataConfiguration(
allowed_request_headers=["X-User-Id"],
allowed_query_parameters=["limit"]
)
)
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.build();
RestApi api = RestApi.Builder.create(this, "MyApi")
.restApiName("my-api")
.build();
// Create a gateway target using the static factory method
GatewayTarget apiGatewayTarget = GatewayTarget.forApiGateway(this, "MyApiGatewayTarget", GatewayTargetApiGatewayProps.builder()
.gatewayTargetName("my-api-gateway-target")
.description("Target for API Gateway REST API integration")
.gateway(gateway)
.restApi(api)
.apiGatewayToolConfiguration(ApiGatewayToolConfiguration.builder()
.toolFilters(List.of(ApiGatewayToolFilter.builder()
.filterPath("/pets/*")
.methods(List.of(ApiGatewayHttpMethod.GET, ApiGatewayHttpMethod.POST))
.build()))
.build())
.metadataConfiguration(MetadataConfiguration.builder()
.allowedRequestHeaders(List.of("X-User-Id"))
.allowedQueryParameters(List.of("limit"))
.build())
.build());
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway"
});
var api = new RestApi(this, "MyApi", new RestApiProps {
RestApiName = "my-api"
});
// Create a gateway target using the static factory method
var apiGatewayTarget = GatewayTarget.ForApiGateway(this, "MyApiGatewayTarget", new GatewayTargetApiGatewayProps {
GatewayTargetName = "my-api-gateway-target",
Description = "Target for API Gateway REST API integration",
Gateway = gateway,
RestApi = api,
ApiGatewayToolConfiguration = new ApiGatewayToolConfiguration {
ToolFilters = new [] { new ApiGatewayToolFilter {
FilterPath = "/pets/*",
Methods = new [] { ApiGatewayHttpMethod.GET, ApiGatewayHttpMethod.POST }
} }
},
MetadataConfiguration = new MetadataConfiguration {
AllowedRequestHeaders = new [] { "X-User-Id" },
AllowedQueryParameters = new [] { "limit" }
}
});
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
})
api := apigateway.NewRestApi(this, jsii.String("MyApi"), &RestApiProps{
RestApiName: jsii.String("my-api"),
})
// Create a gateway target using the static factory method
apiGatewayTarget := agentcore.GatewayTarget_ForApiGateway(this, jsii.String("MyApiGatewayTarget"), &GatewayTargetApiGatewayProps{
GatewayTargetName: jsii.String("my-api-gateway-target"),
Description: jsii.String("Target for API Gateway REST API integration"),
Gateway: gateway,
RestApi: api,
ApiGatewayToolConfiguration: &ApiGatewayToolConfiguration{
ToolFilters: []ApiGatewayToolFilter{
&ApiGatewayToolFilter{
FilterPath: jsii.String("/pets/*"),
Methods: []ApiGatewayHttpMethod{
agentcore.ApiGatewayHttpMethod_GET(),
agentcore.ApiGatewayHttpMethod_POST(),
},
},
},
},
MetadataConfiguration: &MetadataConfiguration{
AllowedRequestHeaders: []*string{
jsii.String("X-User-Id"),
},
AllowedQueryParameters: []*string{
jsii.String("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:
- Lambda:
LambdaTargetConfiguration.create(lambdaFunction, toolSchema) - OpenAPI:
OpenApiTargetConfiguration.create(apiSchema, validateSchema?) - Smithy:
SmithyTargetConfiguration.create(smithyModel) - API Gateway:
ApiGatewayTargetConfiguration.create(props)
Example: Lambda Target with Custom Configuration
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
});
const myLambdaFunction = new lambda.Function(this, "MyFunction", {
runtime: lambda.Runtime.NODEJS_22_X,
handler: "index.handler",
code: lambda.Code.fromInline(`
exports.handler = async (event) => ({ statusCode: 200 });
`),
});
const myToolSchema = agentcore.ToolSchema.fromInline([{
name: "my_tool",
description: "My custom tool",
inputSchema: {
type: agentcore.SchemaDefinitionType.OBJECT,
properties: {},
},
}]);
// Create a custom Lambda configuration
const customConfig = agentcore.LambdaTargetConfiguration.create(
myLambdaFunction,
myToolSchema
);
// Use the GatewayTarget constructor directly
const target = new agentcore.GatewayTarget(this, "AdvancedTarget", {
gateway: gateway,
gatewayTargetName: "advanced-target",
targetConfiguration: customConfig, // Manually created configuration
credentialProviderConfigurations: [
agentcore.GatewayCredentialProvider.fromIamRole()
]
});
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway"
)
my_lambda_function = lambda_.Function(self, "MyFunction",
runtime=lambda_.Runtime.NODEJS_22_X,
handler="index.handler",
code=lambda_.Code.from_inline("""
exports.handler = async (event) => ({ statusCode: 200 });
""")
)
my_tool_schema = agentcore.ToolSchema.from_inline([
name="my_tool",
description="My custom tool",
input_schema=agentcore.SchemaDefinition(
type=agentcore.SchemaDefinitionType.OBJECT,
properties={}
)
])
# Create a custom Lambda configuration
custom_config = agentcore.LambdaTargetConfiguration.create(my_lambda_function, my_tool_schema)
# Use the GatewayTarget constructor directly
target = agentcore.GatewayTarget(self, "AdvancedTarget",
gateway=gateway,
gateway_target_name="advanced-target",
target_configuration=custom_config, # Manually created configuration
credential_provider_configurations=[
agentcore.GatewayCredentialProvider.from_iam_role()
]
)
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.build();
Function myLambdaFunction = Function.Builder.create(this, "MyFunction")
.runtime(Runtime.NODEJS_22_X)
.handler("index.handler")
.code(Code.fromInline("\n exports.handler = async (event) => ({ statusCode: 200 });\n "))
.build();
InlineToolSchema myToolSchema = ToolSchema.fromInline(List.of(ToolDefinition.builder()
.name("my_tool")
.description("My custom tool")
.inputSchema(SchemaDefinition.builder()
.type(SchemaDefinitionType.OBJECT)
.properties(Map.of())
.build())
.build()));
// Create a custom Lambda configuration
LambdaTargetConfiguration customConfig = LambdaTargetConfiguration.create(myLambdaFunction, myToolSchema);
// Use the GatewayTarget constructor directly
GatewayTarget target = GatewayTarget.Builder.create(this, "AdvancedTarget")
.gateway(gateway)
.gatewayTargetName("advanced-target")
.targetConfiguration(customConfig) // Manually created configuration
.credentialProviderConfigurations(List.of(GatewayCredentialProvider.fromIamRole()))
.build();
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway"
});
var myLambdaFunction = new Function(this, "MyFunction", new FunctionProps {
Runtime = Runtime.NODEJS_22_X,
Handler = "index.handler",
Code = Code.FromInline(@"
exports.handler = async (event) => ({ statusCode: 200 });
")
});
var myToolSchema = ToolSchema.FromInline(new [] { new ToolDefinition {
Name = "my_tool",
Description = "My custom tool",
InputSchema = new SchemaDefinition {
Type = SchemaDefinitionType.OBJECT,
Properties = new Dictionary<string, object> { }
}
} });
// Create a custom Lambda configuration
var customConfig = LambdaTargetConfiguration.Create(myLambdaFunction, myToolSchema);
// Use the GatewayTarget constructor directly
var target = new GatewayTarget(this, "AdvancedTarget", new GatewayTargetProps {
Gateway = gateway,
GatewayTargetName = "advanced-target",
TargetConfiguration = customConfig, // Manually created configuration
CredentialProviderConfigurations = new [] { GatewayCredentialProvider.FromIamRole() }
});
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
})
myLambdaFunction := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
Runtime: lambda.Runtime_NODEJS_22_X(),
Handler: jsii.String("index.handler"),
Code: lambda.Code_FromInline(jsii.String(`
exports.handler = async (event) => ({ statusCode: 200 });
`)),
})
myToolSchema := agentcore.ToolSchema_FromInline([]ToolDefinition{
&ToolDefinition{
Name: jsii.String("my_tool"),
Description: jsii.String("My custom tool"),
InputSchema: &SchemaDefinition{
Type: agentcore.SchemaDefinitionType_OBJECT(),
Properties: map[string]interface{}{
},
},
},
})
// Create a custom Lambda configuration
customConfig := agentcore.LambdaTargetConfiguration_Create(myLambdaFunction, myToolSchema)
// Use the GatewayTarget constructor directly
target := agentcore.NewGatewayTarget(this, jsii.String("AdvancedTarget"), &GatewayTargetProps{
Gateway: gateway,
GatewayTargetName: jsii.String("advanced-target"),
TargetConfiguration: customConfig,
// Manually created configuration
CredentialProviderConfigurations: []ICredentialProviderConfig{
agentcore.GatewayCredentialProvider_FromIamRole(),
},
})
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:
- REQUEST interceptors: Execute before the gateway calls the target. Useful for request validation, transformation, or custom authorization
- RESPONSE interceptors: Execute after the target responds but before the gateway sends the response back. Useful for response transformation, filtering, or adding custom headers
Security Best Practices:
- Keep
passRequestHeadersdisabled unless absolutely necessary (default: false) - Implement idempotent Lambda functions (gateway may retry on failures)
- Restrict gateway execution role to specific Lambda functions
- Avoid logging sensitive information in your interceptor
For more information, see the Gateway Interceptors documentation.
Adding Interceptors via Constructor
// Create Lambda functions for interceptors
const requestInterceptorFn = new lambda.Function(this, "RequestInterceptor", {
runtime: lambda.Runtime.PYTHON_3_12,
handler: "index.handler",
code: lambda.Code.fromInline(`
def handler(event, context):
# Validate and transform request
return {
"interceptorOutputVersion": "1.0",
"mcp": {
"transformedGatewayRequest": event["mcp"]["gatewayRequest"]
}
}
`),
});
const responseInterceptorFn = new lambda.Function(this, "ResponseInterceptor", {
runtime: lambda.Runtime.PYTHON_3_12,
handler: "index.handler",
code: lambda.Code.fromInline(`
def handler(event, context):
# Filter or transform response
return {
"interceptorOutputVersion": "1.0",
"mcp": {
"transformedGatewayResponse": event["mcp"]["gatewayResponse"]
}
}
`),
});
// Create gateway with interceptors
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
interceptorConfigurations: [
agentcore.LambdaInterceptor.forRequest(requestInterceptorFn, {
passRequestHeaders: true // Only if you need to inspect headers
}),
agentcore.LambdaInterceptor.forResponse(responseInterceptorFn)
]
});
# Create Lambda functions for interceptors
request_interceptor_fn = lambda_.Function(self, "RequestInterceptor",
runtime=lambda_.Runtime.PYTHON_3_12,
handler="index.handler",
code=lambda_.Code.from_inline("""
def handler(event, context):
# Validate and transform request
return {
"interceptorOutputVersion": "1.0",
"mcp": {
"transformedGatewayRequest": event["mcp"]["gatewayRequest"]
}
}
""")
)
response_interceptor_fn = lambda_.Function(self, "ResponseInterceptor",
runtime=lambda_.Runtime.PYTHON_3_12,
handler="index.handler",
code=lambda_.Code.from_inline("""
def handler(event, context):
# Filter or transform response
return {
"interceptorOutputVersion": "1.0",
"mcp": {
"transformedGatewayResponse": event["mcp"]["gatewayResponse"]
}
}
""")
)
# Create gateway with interceptors
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway",
interceptor_configurations=[
agentcore.LambdaInterceptor.for_request(request_interceptor_fn,
pass_request_headers=True
),
agentcore.LambdaInterceptor.for_response(response_interceptor_fn)
]
)
// Create Lambda functions for interceptors
Function requestInterceptorFn = Function.Builder.create(this, "RequestInterceptor")
.runtime(Runtime.PYTHON_3_12)
.handler("index.handler")
.code(Code.fromInline("\ndef handler(event, context):\n # Validate and transform request\n return {\n \"interceptorOutputVersion\": \"1.0\",\n \"mcp\": {\n \"transformedGatewayRequest\": event[\"mcp\"][\"gatewayRequest\"]\n }\n }\n "))
.build();
Function responseInterceptorFn = Function.Builder.create(this, "ResponseInterceptor")
.runtime(Runtime.PYTHON_3_12)
.handler("index.handler")
.code(Code.fromInline("\ndef handler(event, context):\n # Filter or transform response\n return {\n \"interceptorOutputVersion\": \"1.0\",\n \"mcp\": {\n \"transformedGatewayResponse\": event[\"mcp\"][\"gatewayResponse\"]\n }\n }\n "))
.build();
// Create gateway with interceptors
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.interceptorConfigurations(List.of(LambdaInterceptor.forRequest(requestInterceptorFn, InterceptorOptions.builder()
.passRequestHeaders(true)
.build()), LambdaInterceptor.forResponse(responseInterceptorFn)))
.build();
// Create Lambda functions for interceptors
var requestInterceptorFn = new Function(this, "RequestInterceptor", new FunctionProps {
Runtime = Runtime.PYTHON_3_12,
Handler = "index.handler",
Code = Code.FromInline(@"
def handler(event, context):
# Validate and transform request
return {
""interceptorOutputVersion"": ""1.0"",
""mcp"": {
""transformedGatewayRequest"": event[""mcp""][""gatewayRequest""]
}
}
")
});
var responseInterceptorFn = new Function(this, "ResponseInterceptor", new FunctionProps {
Runtime = Runtime.PYTHON_3_12,
Handler = "index.handler",
Code = Code.FromInline(@"
def handler(event, context):
# Filter or transform response
return {
""interceptorOutputVersion"": ""1.0"",
""mcp"": {
""transformedGatewayResponse"": event[""mcp""][""gatewayResponse""]
}
}
")
});
// Create gateway with interceptors
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway",
InterceptorConfigurations = new [] { LambdaInterceptor.ForRequest(requestInterceptorFn, new InterceptorOptions {
PassRequestHeaders = true
}), LambdaInterceptor.ForResponse(responseInterceptorFn) }
});
// Create Lambda functions for interceptors
requestInterceptorFn := lambda.NewFunction(this, jsii.String("RequestInterceptor"), &FunctionProps{
Runtime: lambda.Runtime_PYTHON_3_12(),
Handler: jsii.String("index.handler"),
Code: lambda.Code_FromInline(jsii.String(`
def handler(event, context):
# Validate and transform request
return {
"interceptorOutputVersion": "1.0",
"mcp": {
"transformedGatewayRequest": event["mcp"]["gatewayRequest"]
}
}
`)),
})
responseInterceptorFn := lambda.NewFunction(this, jsii.String("ResponseInterceptor"), &FunctionProps{
Runtime: lambda.Runtime_PYTHON_3_12(),
Handler: jsii.String("index.handler"),
Code: lambda.Code_*FromInline(jsii.String(`
def handler(event, context):
# Filter or transform response
return {
"interceptorOutputVersion": "1.0",
"mcp": {
"transformedGatewayResponse": event["mcp"]["gatewayResponse"]
}
}
`)),
})
// Create gateway with interceptors
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
InterceptorConfigurations: []IInterceptor{
agentcore.LambdaInterceptor_ForRequest(requestInterceptorFn, &InterceptorOptions{
PassRequestHeaders: jsii.Boolean(true),
}),
agentcore.LambdaInterceptor_ForResponse(responseInterceptorFn),
},
})
Automatic Permission Granting:
When you add a Lambda interceptor to a gateway (either via constructor or addInterceptor()), 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
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
});
// Create Lambda functions for interceptors
const requestInterceptorFn = new lambda.Function(this, "RequestInterceptor", {
runtime: lambda.Runtime.PYTHON_3_12,
handler: "index.handler",
code: lambda.Code.fromInline(`
def handler(event, context):
# Custom request validation logic
return {
"interceptorOutputVersion": "1.0",
"mcp": {
"transformedGatewayRequest": event["mcp"]["gatewayRequest"]
}
}
`),
});
const responseInterceptorFn = new lambda.Function(this, "ResponseInterceptor", {
runtime: lambda.Runtime.PYTHON_3_12,
handler: "index.handler",
code: lambda.Code.fromInline(`
def handler(event, context):
# Filter sensitive data from response
return {
"interceptorOutputVersion": "1.0",
"mcp": {
"transformedGatewayResponse": event["mcp"]["gatewayResponse"]
}
}
`),
});
gateway.addInterceptor(
agentcore.LambdaInterceptor.forRequest(requestInterceptorFn, {
passRequestHeaders: false // Default, headers not passed for security
})
);
gateway.addInterceptor(
agentcore.LambdaInterceptor.forResponse(responseInterceptorFn)
);
# Create a gateway first
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway"
)
# Create Lambda functions for interceptors
request_interceptor_fn = lambda_.Function(self, "RequestInterceptor",
runtime=lambda_.Runtime.PYTHON_3_12,
handler="index.handler",
code=lambda_.Code.from_inline("""
def handler(event, context):
# Custom request validation logic
return {
"interceptorOutputVersion": "1.0",
"mcp": {
"transformedGatewayRequest": event["mcp"]["gatewayRequest"]
}
}
""")
)
response_interceptor_fn = lambda_.Function(self, "ResponseInterceptor",
runtime=lambda_.Runtime.PYTHON_3_12,
handler="index.handler",
code=lambda_.Code.from_inline("""
def handler(event, context):
# Filter sensitive data from response
return {
"interceptorOutputVersion": "1.0",
"mcp": {
"transformedGatewayResponse": event["mcp"]["gatewayResponse"]
}
}
""")
)
gateway.add_interceptor(
agentcore.LambdaInterceptor.for_request(request_interceptor_fn,
pass_request_headers=False
))
gateway.add_interceptor(
agentcore.LambdaInterceptor.for_response(response_interceptor_fn))
// Create a gateway first
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.build();
// Create Lambda functions for interceptors
Function requestInterceptorFn = Function.Builder.create(this, "RequestInterceptor")
.runtime(Runtime.PYTHON_3_12)
.handler("index.handler")
.code(Code.fromInline("\ndef handler(event, context):\n # Custom request validation logic\n return {\n \"interceptorOutputVersion\": \"1.0\",\n \"mcp\": {\n \"transformedGatewayRequest\": event[\"mcp\"][\"gatewayRequest\"]\n }\n }\n "))
.build();
Function responseInterceptorFn = Function.Builder.create(this, "ResponseInterceptor")
.runtime(Runtime.PYTHON_3_12)
.handler("index.handler")
.code(Code.fromInline("\ndef handler(event, context):\n # Filter sensitive data from response\n return {\n \"interceptorOutputVersion\": \"1.0\",\n \"mcp\": {\n \"transformedGatewayResponse\": event[\"mcp\"][\"gatewayResponse\"]\n }\n }\n "))
.build();
gateway.addInterceptor(LambdaInterceptor.forRequest(requestInterceptorFn, InterceptorOptions.builder()
.passRequestHeaders(false)
.build()));
gateway.addInterceptor(LambdaInterceptor.forResponse(responseInterceptorFn));
// Create a gateway first
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway"
});
// Create Lambda functions for interceptors
var requestInterceptorFn = new Function(this, "RequestInterceptor", new FunctionProps {
Runtime = Runtime.PYTHON_3_12,
Handler = "index.handler",
Code = Code.FromInline(@"
def handler(event, context):
# Custom request validation logic
return {
""interceptorOutputVersion"": ""1.0"",
""mcp"": {
""transformedGatewayRequest"": event[""mcp""][""gatewayRequest""]
}
}
")
});
var responseInterceptorFn = new Function(this, "ResponseInterceptor", new FunctionProps {
Runtime = Runtime.PYTHON_3_12,
Handler = "index.handler",
Code = Code.FromInline(@"
def handler(event, context):
# Filter sensitive data from response
return {
""interceptorOutputVersion"": ""1.0"",
""mcp"": {
""transformedGatewayResponse"": event[""mcp""][""gatewayResponse""]
}
}
")
});
gateway.AddInterceptor(LambdaInterceptor.ForRequest(requestInterceptorFn, new InterceptorOptions {
PassRequestHeaders = false
}));
gateway.AddInterceptor(LambdaInterceptor.ForResponse(responseInterceptorFn));
// Create a gateway first
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
})
// Create Lambda functions for interceptors
requestInterceptorFn := lambda.NewFunction(this, jsii.String("RequestInterceptor"), &FunctionProps{
Runtime: lambda.Runtime_PYTHON_3_12(),
Handler: jsii.String("index.handler"),
Code: lambda.Code_FromInline(jsii.String(`
def handler(event, context):
# Custom request validation logic
return {
"interceptorOutputVersion": "1.0",
"mcp": {
"transformedGatewayRequest": event["mcp"]["gatewayRequest"]
}
}
`)),
})
responseInterceptorFn := lambda.NewFunction(this, jsii.String("ResponseInterceptor"), &FunctionProps{
Runtime: lambda.Runtime_PYTHON_3_12(),
Handler: jsii.String("index.handler"),
Code: lambda.Code_*FromInline(jsii.String(`
def handler(event, context):
# Filter sensitive data from response
return {
"interceptorOutputVersion": "1.0",
"mcp": {
"transformedGatewayResponse": event["mcp"]["gatewayResponse"]
}
}
`)),
})
gateway.AddInterceptor(agentcore.LambdaInterceptor_ForRequest(requestInterceptorFn, &InterceptorOptions{
PassRequestHeaders: jsii.Boolean(false),
}))
gateway.AddInterceptor(agentcore.LambdaInterceptor_ForResponse(responseInterceptorFn))
Gateway Target IAM Permissions
The Gateway Target construct provides convenient methods for granting IAM permissions:
// Create a gateway and target
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
});
const smithySchema = agentcore.ApiSchema.fromLocalAsset(
path.join(__dirname, "models", "smithy-model.json")
);
smithySchema.bind(this);
// Create a gateway target with Smithy Model and OAuth
const target = agentcore.GatewayTarget.forSmithy(this, "MySmithyTarget", {
gatewayTargetName: "my-smithy-target",
description: "Target for Smithy model integration",
gateway: gateway,
smithyModel: smithySchema,
});
// Create a role that needs access to the gateway target
const userRole = new iam.Role(this, "UserRole", {
assumedBy: new iam.ServicePrincipal("lambda.amazonaws.com"),
});
// Grant read permissions (Get and List actions)
target.grantRead(userRole);
// Grant manage permissions (Create, Update, Delete actions)
target.grantManage(userRole);
// Grant specific custom permissions
target.grant(userRole, "bedrock-agentcore:GetGatewayTarget");
// Grants permission to invoke this Gateway
gateway.grantInvoke(userRole);
# Create a gateway and target
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway"
)
smithy_schema = agentcore.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 = agentcore.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 = iam.Role(self, "UserRole",
assumed_by=iam.ServicePrincipal("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)
// Create a gateway and target
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.build();
AssetApiSchema smithySchema = ApiSchema.fromLocalAsset(path.join(__dirname, "models", "smithy-model.json"));
smithySchema.bind(this);
// Create a gateway target with Smithy Model and OAuth
GatewayTarget target = GatewayTarget.forSmithy(this, "MySmithyTarget", GatewayTargetSmithyProps.builder()
.gatewayTargetName("my-smithy-target")
.description("Target for Smithy model integration")
.gateway(gateway)
.smithyModel(smithySchema)
.build());
// Create a role that needs access to the gateway target
Role userRole = Role.Builder.create(this, "UserRole")
.assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
.build();
// Grant read permissions (Get and List actions)
target.grantRead(userRole);
// Grant manage permissions (Create, Update, Delete actions)
target.grantManage(userRole);
// Grant specific custom permissions
target.grant(userRole, "bedrock-agentcore:GetGatewayTarget");
// Grants permission to invoke this Gateway
gateway.grantInvoke(userRole);
// Create a gateway and target
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway"
});
var smithySchema = ApiSchema.FromLocalAsset(path.Join(__dirname, "models", "smithy-model.json"));
smithySchema.Bind(this);
// Create a gateway target with Smithy Model and OAuth
var target = GatewayTarget.ForSmithy(this, "MySmithyTarget", new GatewayTargetSmithyProps {
GatewayTargetName = "my-smithy-target",
Description = "Target for Smithy model integration",
Gateway = gateway,
SmithyModel = smithySchema
});
// Create a role that needs access to the gateway target
var userRole = new Role(this, "UserRole", new RoleProps {
AssumedBy = new ServicePrincipal("lambda.amazonaws.com")
});
// Grant read permissions (Get and List actions)
target.GrantRead(userRole);
// Grant manage permissions (Create, Update, Delete actions)
target.GrantManage(userRole);
// Grant specific custom permissions
target.Grant(userRole, "bedrock-agentcore:GetGatewayTarget");
// Grants permission to invoke this Gateway
gateway.GrantInvoke(userRole);
// Create a gateway and target
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
})
smithySchema := agentcore.ApiSchema_FromLocalAsset(path.join(__dirname, jsii.String("models"), jsii.String("smithy-model.json")))
smithySchema.Bind(this)
// Create a gateway target with Smithy Model and OAuth
target := agentcore.GatewayTarget_ForSmithy(this, jsii.String("MySmithyTarget"), &GatewayTargetSmithyProps{
GatewayTargetName: jsii.String("my-smithy-target"),
Description: jsii.String("Target for Smithy model integration"),
Gateway: gateway,
SmithyModel: smithySchema,
})
// Create a role that needs access to the gateway target
userRole := iam.NewRole(this, jsii.String("UserRole"), &RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("lambda.amazonaws.com")),
})
// Grant read permissions (Get and List actions)
target.GrantRead(userRole)
// Grant manage permissions (Create, Update, Delete actions)
target.GrantManage(userRole)
// Grant specific custom permissions
target.Grant(userRole, jsii.String("bedrock-agentcore:GetGatewayTarget"))
// Grants permission to invoke this Gateway
gateway.GrantInvoke(userRole)
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:
- Short-Term Memory: Immediate conversation context and session-based information that provides continuity within a single interaction or closely related sessions.
- Long-Term Memory: Persistent information extracted and stored across multiple conversations, including facts, preferences, and summaries that enable personalized experiences over time.
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 |
|---|---|---|---|
memoryName | string | No | The name of the memory. If not provided, a unique name will be auto-generated |
expirationDuration | 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. |
kmsKey | IKey | No | Custom KMS key to use for encryption. Default: Your data is encrypted with a key that AWS owns and manages for you |
memoryStrategies | MemoryStrategyBase[] | No | Built-in extraction strategies to use for this memory. Default: No extraction strategies (short term memory only) |
executionRole | 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 expirationDuration, 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
const memory = new agentcore.Memory(this, "MyMemory", {
memoryName: "my_memory",
description: "A memory for storing user interactions for a period of 90 days",
expirationDuration: cdk.Duration.days(90),
});
# Create a basic memory with default settings, no LTM strategies
memory = agentcore.Memory(self, "MyMemory",
memory_name="my_memory",
description="A memory for storing user interactions for a period of 90 days",
expiration_duration=cdk.Duration.days(90)
)
// Create a basic memory with default settings, no LTM strategies
Memory memory = Memory.Builder.create(this, "MyMemory")
.memoryName("my_memory")
.description("A memory for storing user interactions for a period of 90 days")
.expirationDuration(Duration.days(90))
.build();
// Create a basic memory with default settings, no LTM strategies
var memory = new Memory(this, "MyMemory", new MemoryProps {
MemoryName = "my_memory",
Description = "A memory for storing user interactions for a period of 90 days",
ExpirationDuration = Duration.Days(90)
});
// Create a basic memory with default settings, no LTM strategies
memory := agentcore.NewMemory(this, jsii.String("MyMemory"), &MemoryProps{
MemoryName: jsii.String("my_memory"),
Description: jsii.String("A memory for storing user interactions for a period of 90 days"),
ExpirationDuration: cdk.Duration_Days(jsii.Number(90)),
})
Basic Memory with Custom KMS Encryption
// Create a custom KMS key for encryption
const encryptionKey = new kms.Key(this, "MemoryEncryptionKey", {
enableKeyRotation: true,
description: "KMS key for memory encryption",
});
// Create memory with custom encryption
const memory = new agentcore.Memory(this, "MyMemory", {
memoryName: "my_encrypted_memory",
description: "Memory with custom KMS encryption",
expirationDuration: cdk.Duration.days(90),
kmsKey: encryptionKey,
});
# Create a custom KMS key for encryption
encryption_key = kms.Key(self, "MemoryEncryptionKey",
enable_key_rotation=True,
description="KMS key for memory encryption"
)
# Create memory with custom encryption
memory = agentcore.Memory(self, "MyMemory",
memory_name="my_encrypted_memory",
description="Memory with custom KMS encryption",
expiration_duration=cdk.Duration.days(90),
kms_key=encryption_key
)
// Create a custom KMS key for encryption
Key encryptionKey = Key.Builder.create(this, "MemoryEncryptionKey")
.enableKeyRotation(true)
.description("KMS key for memory encryption")
.build();
// Create memory with custom encryption
Memory memory = Memory.Builder.create(this, "MyMemory")
.memoryName("my_encrypted_memory")
.description("Memory with custom KMS encryption")
.expirationDuration(Duration.days(90))
.kmsKey(encryptionKey)
.build();
// Create a custom KMS key for encryption
var encryptionKey = new Key(this, "MemoryEncryptionKey", new KeyProps {
EnableKeyRotation = true,
Description = "KMS key for memory encryption"
});
// Create memory with custom encryption
var memory = new Memory(this, "MyMemory", new MemoryProps {
MemoryName = "my_encrypted_memory",
Description = "Memory with custom KMS encryption",
ExpirationDuration = Duration.Days(90),
KmsKey = encryptionKey
});
// Create a custom KMS key for encryption
encryptionKey := kms.NewKey(this, jsii.String("MemoryEncryptionKey"), &KeyProps{
EnableKeyRotation: jsii.Boolean(true),
Description: jsii.String("KMS key for memory encryption"),
})
// Create memory with custom encryption
memory := agentcore.NewMemory(this, jsii.String("MyMemory"), &MemoryProps{
MemoryName: jsii.String("my_encrypted_memory"),
Description: jsii.String("Memory with custom KMS encryption"),
ExpirationDuration: cdk.Duration_Days(jsii.Number(90)),
KmsKey: encryptionKey,
})
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:
- Summarization: to summarize interactions to preserve critical context and key insights.
- Semantic Memory: to extract general factual knowledge, concepts and meanings from raw conversations using vector embeddings. This enables similarity-based retrieval of relevant facts and context.
- User Preferences: to extract user behavior patterns from raw conversations.
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:
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.- Extracts concise summaries to preserve critical context and key insights
- Namespace:
/strategies/{memoryStrategyId}/actors/{actorId}/sessions/{sessionId}
Semantic Memory Strategy (
MemoryStrategy.usingBuiltInSemantic()) Distills general facts, concepts, and underlying meanings from raw conversational data, presenting the information in a context-independent format. Extracted memory example: In-context learning = task-solving via examples, no training needed.- Extracts general factual knowledge, concepts and meanings from raw conversations
- Namespace:
/strategies/{memoryStrategyId}/actors/{actorId}
User Preference Strategy (
MemoryStrategy.usingBuiltInUserPreference()) Captures individual preferences, interaction patterns, and personalized settings to enhance future experiences. Extracted memory example: User needs clear guidance on cloud storage account connection during onboarding.- Extracts user behavior patterns from raw conversations
- Namespace:
/strategies/{memoryStrategyId}/actors/{actorId}
Episodic Memory Strategy (
MemoryStrategy.usingBuiltInEpisodic()) Captures meaningful slices of user and system interactions, preserve them into compact records after summarizing. Extracted memory example: User first asked about pricing on Monday, then requested feature comparison on Tuesday, finally made purchase decision on Wednesday.- Captures event sequences and temporal relationships
- Namespace:
/strategy/{memoryStrategyId}/actor/{actorId}/session/{sessionId} - Reflections:
/strategy/{memoryStrategyId}/actor/{actorId}
// Create memory with built-in strategies
const memory = new agentcore.Memory(this, "MyMemory", {
memoryName: "my_memory",
description: "Memory with built-in strategies",
expirationDuration: cdk.Duration.days(90),
memoryStrategies: [
agentcore.MemoryStrategy.usingBuiltInSummarization(),
agentcore.MemoryStrategy.usingBuiltInSemantic(),
agentcore.MemoryStrategy.usingBuiltInUserPreference(),
agentcore.MemoryStrategy.usingBuiltInEpisodic(),
],
});
# Create memory with built-in strategies
memory = agentcore.Memory(self, "MyMemory",
memory_name="my_memory",
description="Memory with built-in strategies",
expiration_duration=cdk.Duration.days(90),
memory_strategies=[
agentcore.MemoryStrategy.using_built_in_summarization(),
agentcore.MemoryStrategy.using_built_in_semantic(),
agentcore.MemoryStrategy.using_built_in_user_preference(),
agentcore.MemoryStrategy.using_built_in_episodic()
]
)
// Create memory with built-in strategies
Memory memory = Memory.Builder.create(this, "MyMemory")
.memoryName("my_memory")
.description("Memory with built-in strategies")
.expirationDuration(Duration.days(90))
.memoryStrategies(List.of(MemoryStrategy.usingBuiltInSummarization(), MemoryStrategy.usingBuiltInSemantic(), MemoryStrategy.usingBuiltInUserPreference(), MemoryStrategy.usingBuiltInEpisodic()))
.build();
// Create memory with built-in strategies
var memory = new Memory(this, "MyMemory", new MemoryProps {
MemoryName = "my_memory",
Description = "Memory with built-in strategies",
ExpirationDuration = Duration.Days(90),
MemoryStrategies = new [] { MemoryStrategy.UsingBuiltInSummarization(), MemoryStrategy.UsingBuiltInSemantic(), MemoryStrategy.UsingBuiltInUserPreference(), MemoryStrategy.UsingBuiltInEpisodic() }
});
// Create memory with built-in strategies
memory := agentcore.NewMemory(this, jsii.String("MyMemory"), &MemoryProps{
MemoryName: jsii.String("my_memory"),
Description: jsii.String("Memory with built-in strategies"),
ExpirationDuration: cdk.Duration_Days(jsii.Number(90)),
MemoryStrategies: []IMemoryStrategy{
agentcore.MemoryStrategy_UsingBuiltInSummarization(),
agentcore.MemoryStrategy_UsingBuiltInSemantic(),
agentcore.MemoryStrategy_UsingBuiltInUserPreference(),
agentcore.MemoryStrategy_UsingBuiltInEpisodic(),
},
})
The name generated for each built in memory strategy is as follows:
- For Summarization:
summary_builtin_cdk001 - For Semantic:
semantic_builtin_cdk001> - For User Preferences:
preference_builtin_cdk001 - For Episodic :
episodic_builtin_cdkGen0001
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:
actorId– Identifies who the long-term memory belongs to, such as a usermemoryStrategyId– Shows which memory strategy is being used. This strategy identifier is auto-generated when you create a memory using CreateMemory operation.sessionId– Identifies which session or conversation the memory is from.
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:
- Summarization Strategy (
MemoryStrategy.usingSummarization(props)) - Semantic Memory Strategy (
MemoryStrategy.usingSemantic(props)) - User Preference Strategy (
MemoryStrategy.usingUserPreference(props)) - Episodic Memory Strategy (
MemoryStrategy.usingEpisodic(props))
// Create memory with custom strategies
const memory = new agentcore.Memory(this, "MyMemory", {
memoryName: "my_memory",
description: "Memory with custom strategies",
expirationDuration: cdk.Duration.days(90),
memoryStrategies: [
agentcore.MemoryStrategy.usingUserPreference({
strategyName: "CustomerPreferences",
namespaces: ["support/customer/{actorId}/preferences"]
}),
agentcore.MemoryStrategy.usingSemantic({
strategyName: "CustomerSupportSemantic",
namespaces: ["support/customer/{actorId}/semantic"]
}),
agentcore.MemoryStrategy.usingEpisodic({
strategyName: "customerJourneyEpisodic",
namespaces: ["/journey/customer/{actorId}/episodes"],
reflectionConfiguration: {
namespaces: ["/journey/customer/{actorId}/reflections"]
}
}),
],
});
# Create memory with custom strategies
memory = agentcore.Memory(self, "MyMemory",
memory_name="my_memory",
description="Memory with custom strategies",
expiration_duration=cdk.Duration.days(90),
memory_strategies=[
agentcore.MemoryStrategy.using_user_preference(
strategy_name="CustomerPreferences",
namespaces=["support/customer/{actorId}/preferences"]
),
agentcore.MemoryStrategy.using_semantic(
strategy_name="CustomerSupportSemantic",
namespaces=["support/customer/{actorId}/semantic"]
),
agentcore.MemoryStrategy.using_episodic(
strategy_name="customerJourneyEpisodic",
namespaces=["/journey/customer/{actorId}/episodes"],
reflection_configuration=agentcore.EpisodicReflectionConfiguration(
namespaces=["/journey/customer/{actorId}/reflections"]
)
)
]
)
// Create memory with custom strategies
Memory memory = Memory.Builder.create(this, "MyMemory")
.memoryName("my_memory")
.description("Memory with custom strategies")
.expirationDuration(Duration.days(90))
.memoryStrategies(List.of(MemoryStrategy.usingUserPreference(ManagedStrategyProps.builder()
.strategyName("CustomerPreferences")
.namespaces(List.of("support/customer/{actorId}/preferences"))
.build()), MemoryStrategy.usingSemantic(ManagedStrategyProps.builder()
.strategyName("CustomerSupportSemantic")
.namespaces(List.of("support/customer/{actorId}/semantic"))
.build()), MemoryStrategy.usingEpisodic(ManagedStrategyProps.builder()
.strategyName("customerJourneyEpisodic")
.namespaces(List.of("/journey/customer/{actorId}/episodes"))
.reflectionConfiguration(EpisodicReflectionConfiguration.builder()
.namespaces(List.of("/journey/customer/{actorId}/reflections"))
.build())
.build())))
.build();
// Create memory with custom strategies
var memory = new Memory(this, "MyMemory", new MemoryProps {
MemoryName = "my_memory",
Description = "Memory with custom strategies",
ExpirationDuration = Duration.Days(90),
MemoryStrategies = new [] { MemoryStrategy.UsingUserPreference(new ManagedStrategyProps {
StrategyName = "CustomerPreferences",
Namespaces = new [] { "support/customer/{actorId}/preferences" }
}), MemoryStrategy.UsingSemantic(new ManagedStrategyProps {
StrategyName = "CustomerSupportSemantic",
Namespaces = new [] { "support/customer/{actorId}/semantic" }
}), MemoryStrategy.UsingEpisodic(new ManagedStrategyProps {
StrategyName = "customerJourneyEpisodic",
Namespaces = new [] { "/journey/customer/{actorId}/episodes" },
ReflectionConfiguration = new EpisodicReflectionConfiguration {
Namespaces = new [] { "/journey/customer/{actorId}/reflections" }
}
}) }
});
// Create memory with custom strategies
memory := agentcore.NewMemory(this, jsii.String("MyMemory"), &MemoryProps{
MemoryName: jsii.String("my_memory"),
Description: jsii.String("Memory with custom strategies"),
ExpirationDuration: cdk.Duration_Days(jsii.Number(90)),
MemoryStrategies: []IMemoryStrategy{
agentcore.MemoryStrategy_UsingUserPreference(&ManagedStrategyProps{
StrategyName: jsii.String("CustomerPreferences"),
Namespaces: []*string{
jsii.String("support/customer/{actorId}/preferences"),
},
}),
agentcore.MemoryStrategy_UsingSemantic(&ManagedStrategyProps{
StrategyName: jsii.String("CustomerSupportSemantic"),
Namespaces: []*string{
jsii.String("support/customer/{actorId}/semantic"),
},
}),
agentcore.MemoryStrategy_UsingEpisodic(&ManagedStrategyProps{
StrategyName: jsii.String("customerJourneyEpisodic"),
Namespaces: []*string{
jsii.String("/journey/customer/{actorId}/episodes"),
},
ReflectionConfiguration: &EpisodicReflectionConfiguration{
Namespaces: []*string{
jsii.String("/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:
- Let the L2 construct create a minimum permission role for you when use L2 Bedrock Foundation Models.
- Use a custom role with the overly permissive
AmazonBedrockAgentCoreMemoryBedrockModelInferenceExecutionRolePolicymanaged policy. - Use a custom role with your own custom policies.
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
const executionRole = new iam.Role(this, "MemoryExecutionRole", {
assumedBy: new iam.ServicePrincipal("bedrock-agentcore.amazonaws.com"),
managedPolicies: [
iam.ManagedPolicy.fromAwsManagedPolicyName(
"AmazonBedrockAgentCoreMemoryBedrockModelInferenceExecutionRolePolicy"
),
],
});
// Create memory with custom execution role
const memory = new agentcore.Memory(this, "MyMemory", {
memoryName: "my_memory",
description: "Memory with custom execution role",
expirationDuration: cdk.Duration.days(90),
executionRole: executionRole,
});
# Create a custom execution role
execution_role = iam.Role(self, "MemoryExecutionRole",
assumed_by=iam.ServicePrincipal("bedrock-agentcore.amazonaws.com"),
managed_policies=[
iam.ManagedPolicy.from_aws_managed_policy_name("AmazonBedrockAgentCoreMemoryBedrockModelInferenceExecutionRolePolicy")
]
)
# Create memory with custom execution role
memory = agentcore.Memory(self, "MyMemory",
memory_name="my_memory",
description="Memory with custom execution role",
expiration_duration=cdk.Duration.days(90),
execution_role=execution_role
)
// Create a custom execution role
Role executionRole = Role.Builder.create(this, "MemoryExecutionRole")
.assumedBy(new ServicePrincipal("bedrock-agentcore.amazonaws.com"))
.managedPolicies(List.of(ManagedPolicy.fromAwsManagedPolicyName("AmazonBedrockAgentCoreMemoryBedrockModelInferenceExecutionRolePolicy")))
.build();
// Create memory with custom execution role
Memory memory = Memory.Builder.create(this, "MyMemory")
.memoryName("my_memory")
.description("Memory with custom execution role")
.expirationDuration(Duration.days(90))
.executionRole(executionRole)
.build();
// Create a custom execution role
var executionRole = new Role(this, "MemoryExecutionRole", new RoleProps {
AssumedBy = new ServicePrincipal("bedrock-agentcore.amazonaws.com"),
ManagedPolicies = new [] { ManagedPolicy.FromAwsManagedPolicyName("AmazonBedrockAgentCoreMemoryBedrockModelInferenceExecutionRolePolicy") }
});
// Create memory with custom execution role
var memory = new Memory(this, "MyMemory", new MemoryProps {
MemoryName = "my_memory",
Description = "Memory with custom execution role",
ExpirationDuration = Duration.Days(90),
ExecutionRole = executionRole
});
// Create a custom execution role
executionRole := iam.NewRole(this, jsii.String("MemoryExecutionRole"), &RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("bedrock-agentcore.amazonaws.com")),
ManagedPolicies: []IManagedPolicy{
iam.ManagedPolicy_FromAwsManagedPolicyName(jsii.String("AmazonBedrockAgentCoreMemoryBedrockModelInferenceExecutionRolePolicy")),
},
})
// Create memory with custom execution role
memory := agentcore.NewMemory(this, jsii.String("MyMemory"), &MemoryProps{
MemoryName: jsii.String("my_memory"),
Description: jsii.String("Memory with custom execution role"),
ExpirationDuration: cdk.Duration_Days(jsii.Number(90)),
ExecutionRole: executionRole,
})
In customConsolidation and customExtraction, the model property uses IModel from aws-cdk-lib/aws-bedrock.
// Create a custom semantic memory strategy
const customSemanticStrategy = agentcore.MemoryStrategy.usingSemantic({
strategyName: "customSemanticStrategy",
description: "Custom semantic memory strategy",
namespaces: ["/custom/strategies/{memoryStrategyId}/actors/{actorId}"],
customConsolidation: {
model: bedrock.FoundationModel.fromFoundationModelId(this, 'ConsolidationModel',
bedrock.FoundationModelIdentifier.ANTHROPIC_CLAUDE_3_5_SONNET_20241022_V2_0,
),
appendToPrompt: "Custom consolidation prompt for semantic memory",
},
customExtraction: {
model: bedrock.FoundationModel.fromFoundationModelId(this, 'ExtractionModel',
bedrock.FoundationModelIdentifier.ANTHROPIC_CLAUDE_3_5_SONNET_20241022_V2_0,
),
appendToPrompt: "Custom extraction prompt for semantic memory",
},
});
// Create memory with custom strategy
const memory = new agentcore.Memory(this, "MyMemory", {
memoryName: "my-custom-memory",
description: "Memory with custom strategy",
expirationDuration: cdk.Duration.days(90),
memoryStrategies: [customSemanticStrategy],
});
# Create a custom semantic memory strategy
custom_semantic_strategy = agentcore.MemoryStrategy.using_semantic(
strategy_name="customSemanticStrategy",
description="Custom semantic memory strategy",
namespaces=["/custom/strategies/{memoryStrategyId}/actors/{actorId}"],
custom_consolidation=agentcore.OverrideConfig(
model=bedrock.FoundationModel.from_foundation_model_id(self, "ConsolidationModel", bedrock.FoundationModelIdentifier.ANTHROPIC_CLAUDE_3_5_SONNET_20241022_V2_0),
append_to_prompt="Custom consolidation prompt for semantic memory"
),
custom_extraction=agentcore.OverrideConfig(
model=bedrock.FoundationModel.from_foundation_model_id(self, "ExtractionModel", 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 = agentcore.Memory(self, "MyMemory",
memory_name="my-custom-memory",
description="Memory with custom strategy",
expiration_duration=cdk.Duration.days(90),
memory_strategies=[custom_semantic_strategy]
)
// Create a custom semantic memory strategy
ManagedMemoryStrategy customSemanticStrategy = MemoryStrategy.usingSemantic(ManagedStrategyProps.builder()
.strategyName("customSemanticStrategy")
.description("Custom semantic memory strategy")
.namespaces(List.of("/custom/strategies/{memoryStrategyId}/actors/{actorId}"))
.customConsolidation(OverrideConfig.builder()
.model(FoundationModel.fromFoundationModelId(this, "ConsolidationModel", FoundationModelIdentifier.ANTHROPIC_CLAUDE_3_5_SONNET_20241022_V2_0))
.appendToPrompt("Custom consolidation prompt for semantic memory")
.build())
.customExtraction(OverrideConfig.builder()
.model(FoundationModel.fromFoundationModelId(this, "ExtractionModel", FoundationModelIdentifier.ANTHROPIC_CLAUDE_3_5_SONNET_20241022_V2_0))
.appendToPrompt("Custom extraction prompt for semantic memory")
.build())
.build());
// Create memory with custom strategy
Memory memory = Memory.Builder.create(this, "MyMemory")
.memoryName("my-custom-memory")
.description("Memory with custom strategy")
.expirationDuration(Duration.days(90))
.memoryStrategies(List.of(customSemanticStrategy))
.build();
// Create a custom semantic memory strategy
var customSemanticStrategy = MemoryStrategy.UsingSemantic(new ManagedStrategyProps {
StrategyName = "customSemanticStrategy",
Description = "Custom semantic memory strategy",
Namespaces = new [] { "/custom/strategies/{memoryStrategyId}/actors/{actorId}" },
CustomConsolidation = new OverrideConfig {
Model = FoundationModel.FromFoundationModelId(this, "ConsolidationModel", FoundationModelIdentifier.ANTHROPIC_CLAUDE_3_5_SONNET_20241022_V2_0),
AppendToPrompt = "Custom consolidation prompt for semantic memory"
},
CustomExtraction = new OverrideConfig {
Model = FoundationModel.FromFoundationModelId(this, "ExtractionModel", FoundationModelIdentifier.ANTHROPIC_CLAUDE_3_5_SONNET_20241022_V2_0),
AppendToPrompt = "Custom extraction prompt for semantic memory"
}
});
// Create memory with custom strategy
var memory = new Memory(this, "MyMemory", new MemoryProps {
MemoryName = "my-custom-memory",
Description = "Memory with custom strategy",
ExpirationDuration = Duration.Days(90),
MemoryStrategies = new [] { customSemanticStrategy }
});
// Create a custom semantic memory strategy
customSemanticStrategy := agentcore.MemoryStrategy_UsingSemantic(&ManagedStrategyProps{
StrategyName: jsii.String("customSemanticStrategy"),
Description: jsii.String("Custom semantic memory strategy"),
Namespaces: []*string{
jsii.String("/custom/strategies/{memoryStrategyId}/actors/{actorId}"),
},
CustomConsolidation: &OverrideConfig{
Model: bedrock.FoundationModel_FromFoundationModelId(this, jsii.String("ConsolidationModel"), bedrock.FoundationModelIdentifier_ANTHROPIC_CLAUDE_3_5_SONNET_20241022_V2_0()),
AppendToPrompt: jsii.String("Custom consolidation prompt for semantic memory"),
},
CustomExtraction: &OverrideConfig{
Model: bedrock.FoundationModel_*FromFoundationModelId(this, jsii.String("ExtractionModel"), bedrock.FoundationModelIdentifier_ANTHROPIC_CLAUDE_3_5_SONNET_20241022_V2_0()),
AppendToPrompt: jsii.String("Custom extraction prompt for semantic memory"),
},
})
// Create memory with custom strategy
memory := agentcore.NewMemory(this, jsii.String("MyMemory"), &MemoryProps{
MemoryName: jsii.String("my-custom-memory"),
Description: jsii.String("Memory with custom strategy"),
ExpirationDuration: cdk.Duration_Days(jsii.Number(90)),
MemoryStrategies: []IMemoryStrategy{
customSemanticStrategy,
},
})
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:
- an S3 bucket in your account where Amazon Bedrock AgentCore will deliver batched event payloads.
- an SNS topic for job notifications. Use FIFO topics if processing order within sessions is important for your use case.
The construct will apply the correct permissions to the memory execution role to access these resources.
const bucket = new s3.Bucket(this, 'memoryBucket', {
bucketName: 'test-memory',
removalPolicy: cdk.RemovalPolicy.DESTROY,
autoDeleteObjects: true,
});
const topic = new sns.Topic(this, 'topic');
// Create a custom semantic memory strategy
const selfManagedStrategy = agentcore.MemoryStrategy.usingSelfManaged({
strategyName: "selfManagedStrategy",
description: "self managed memory strategy",
historicalContextWindowSize: 5,
invocationConfiguration: {
topic: topic,
s3Location: {
bucketName: bucket.bucketName,
objectKey: 'memory/',
}
},
triggerConditions: {
messageBasedTrigger: 1,
timeBasedTrigger: cdk.Duration.seconds(10),
tokenBasedTrigger: 100
}
});
// Create memory with custom strategy
const memory = new agentcore.Memory(this, "MyMemory", {
memoryName: "my-custom-memory",
description: "Memory with custom strategy",
expirationDuration: cdk.Duration.days(90),
memoryStrategies: [selfManagedStrategy],
});
bucket = s3.Bucket(self, "memoryBucket",
bucket_name="test-memory",
removal_policy=cdk.RemovalPolicy.DESTROY,
auto_delete_objects=True
)
topic = sns.Topic(self, "topic")
# Create a custom semantic memory strategy
self_managed_strategy = agentcore.MemoryStrategy.using_self_managed(
strategy_name="selfManagedStrategy",
description="self managed memory strategy",
historical_context_window_size=5,
invocation_configuration=agentcore.InvocationConfiguration(
topic=topic,
s3_location=s3.Location(
bucket_name=bucket.bucket_name,
object_key="memory/"
)
),
trigger_conditions=agentcore.TriggerConditions(
message_based_trigger=1,
time_based_trigger=cdk.Duration.seconds(10),
token_based_trigger=100
)
)
# Create memory with custom strategy
memory = agentcore.Memory(self, "MyMemory",
memory_name="my-custom-memory",
description="Memory with custom strategy",
expiration_duration=cdk.Duration.days(90),
memory_strategies=[self_managed_strategy]
)
Bucket bucket = Bucket.Builder.create(this, "memoryBucket")
.bucketName("test-memory")
.removalPolicy(RemovalPolicy.DESTROY)
.autoDeleteObjects(true)
.build();
Topic topic = new Topic(this, "topic");
// Create a custom semantic memory strategy
SelfManagedMemoryStrategy selfManagedStrategy = MemoryStrategy.usingSelfManaged(SelfManagedStrategyProps.builder()
.strategyName("selfManagedStrategy")
.description("self managed memory strategy")
.historicalContextWindowSize(5)
.invocationConfiguration(InvocationConfiguration.builder()
.topic(topic)
.s3Location(Location.builder()
.bucketName(bucket.getBucketName())
.objectKey("memory/")
.build())
.build())
.triggerConditions(TriggerConditions.builder()
.messageBasedTrigger(1)
.timeBasedTrigger(Duration.seconds(10))
.tokenBasedTrigger(100)
.build())
.build());
// Create memory with custom strategy
Memory memory = Memory.Builder.create(this, "MyMemory")
.memoryName("my-custom-memory")
.description("Memory with custom strategy")
.expirationDuration(Duration.days(90))
.memoryStrategies(List.of(selfManagedStrategy))
.build();
var bucket = new Bucket(this, "memoryBucket", new BucketProps {
BucketName = "test-memory",
RemovalPolicy = RemovalPolicy.DESTROY,
AutoDeleteObjects = true
});
var topic = new Topic(this, "topic");
// Create a custom semantic memory strategy
var selfManagedStrategy = MemoryStrategy.UsingSelfManaged(new SelfManagedStrategyProps {
StrategyName = "selfManagedStrategy",
Description = "self managed memory strategy",
HistoricalContextWindowSize = 5,
InvocationConfiguration = new InvocationConfiguration {
Topic = topic,
S3Location = new Location {
BucketName = bucket.BucketName,
ObjectKey = "memory/"
}
},
TriggerConditions = new TriggerConditions {
MessageBasedTrigger = 1,
TimeBasedTrigger = Duration.Seconds(10),
TokenBasedTrigger = 100
}
});
// Create memory with custom strategy
var memory = new Memory(this, "MyMemory", new MemoryProps {
MemoryName = "my-custom-memory",
Description = "Memory with custom strategy",
ExpirationDuration = Duration.Days(90),
MemoryStrategies = new [] { selfManagedStrategy }
});
bucket := s3.NewBucket(this, jsii.String("memoryBucket"), &BucketProps{
BucketName: jsii.String("test-memory"),
RemovalPolicy: cdk.RemovalPolicy_DESTROY,
AutoDeleteObjects: jsii.Boolean(true),
})
topic := sns.NewTopic(this, jsii.String("topic"))
// Create a custom semantic memory strategy
selfManagedStrategy := agentcore.MemoryStrategy_UsingSelfManaged(&SelfManagedStrategyProps{
StrategyName: jsii.String("selfManagedStrategy"),
Description: jsii.String("self managed memory strategy"),
HistoricalContextWindowSize: jsii.Number(5),
InvocationConfiguration: &InvocationConfiguration{
Topic: topic,
S3Location: &Location{
BucketName: bucket.bucketName,
ObjectKey: jsii.String("memory/"),
},
},
TriggerConditions: &TriggerConditions{
MessageBasedTrigger: jsii.Number(1),
TimeBasedTrigger: cdk.Duration_Seconds(jsii.Number(10)),
TokenBasedTrigger: jsii.Number(100),
},
})
// Create memory with custom strategy
memory := agentcore.NewMemory(this, jsii.String("MyMemory"), &MemoryProps{
MemoryName: jsii.String("my-custom-memory"),
Description: jsii.String("Memory with custom strategy"),
ExpirationDuration: cdk.Duration_Days(jsii.Number(90)),
MemoryStrategies: []IMemoryStrategy{
selfManagedStrategy,
},
})
Memory Strategy Methods
You can add new memory strategies to the memory construct using the addMemoryStrategy() method, for instance:
// Create memory without initial strategies
const memory = new agentcore.Memory(this, "test-memory", {
memoryName: "test_memory_add_strategy",
description: "A test memory for testing addMemoryStrategy method",
expirationDuration: cdk.Duration.days(90),
});
// Add strategies after instantiation
memory.addMemoryStrategy(agentcore.MemoryStrategy.usingBuiltInSummarization());
memory.addMemoryStrategy(agentcore.MemoryStrategy.usingBuiltInSemantic());
# Create memory without initial strategies
memory = agentcore.Memory(self, "test-memory",
memory_name="test_memory_add_strategy",
description="A test memory for testing addMemoryStrategy method",
expiration_duration=cdk.Duration.days(90)
)
# Add strategies after instantiation
memory.add_memory_strategy(agentcore.MemoryStrategy.using_built_in_summarization())
memory.add_memory_strategy(agentcore.MemoryStrategy.using_built_in_semantic())
// Create memory without initial strategies
Memory memory = Memory.Builder.create(this, "test-memory")
.memoryName("test_memory_add_strategy")
.description("A test memory for testing addMemoryStrategy method")
.expirationDuration(Duration.days(90))
.build();
// Add strategies after instantiation
memory.addMemoryStrategy(MemoryStrategy.usingBuiltInSummarization());
memory.addMemoryStrategy(MemoryStrategy.usingBuiltInSemantic());
// Create memory without initial strategies
var memory = new Memory(this, "test-memory", new MemoryProps {
MemoryName = "test_memory_add_strategy",
Description = "A test memory for testing addMemoryStrategy method",
ExpirationDuration = Duration.Days(90)
});
// Add strategies after instantiation
memory.AddMemoryStrategy(MemoryStrategy.UsingBuiltInSummarization());
memory.AddMemoryStrategy(MemoryStrategy.UsingBuiltInSemantic());
// Create memory without initial strategies
memory := agentcore.NewMemory(this, jsii.String("test-memory"), &MemoryProps{
MemoryName: jsii.String("test_memory_add_strategy"),
Description: jsii.String("A test memory for testing addMemoryStrategy method"),
ExpirationDuration: cdk.Duration_Days(jsii.Number(90)),
})
// Add strategies after instantiation
memory.AddMemoryStrategy(agentcore.MemoryStrategy_UsingBuiltInSummarization())
memory.AddMemoryStrategy(agentcore.MemoryStrategy_UsingBuiltInSemantic())
Memory with Stream Delivery
You can configure stream delivery resources to enable real-time push-based streaming of memory record lifecycle events (created, updated, deleted) to Amazon Kinesis Data Streams. This allows you to react to memory changes in real-time, build event-driven architectures, or feed memory events into downstream analytics pipelines.
Delivery targets are created with the static factory methods on StreamDeliveryResource, one per target type. Kinesis Data Streams is currently the only supported target:
// Create a Kinesis Data Stream
const stream = new kinesis.Stream(this, 'MemoryEventStream', {
streamName: 'memory-events',
});
const memory = new agentcore.Memory(this, 'MemoryWithStreamDelivery', {
memoryName: 'memory_with_stream',
description: 'Memory with Kinesis stream delivery',
expirationDuration: cdk.Duration.days(90),
streamDeliveryResources: [
agentcore.StreamDeliveryResource.kinesis(stream, {
contentConfigurations: [
{
type: agentcore.StreamDeliveryContentType.MEMORY_RECORDS,
level: agentcore.StreamDeliveryContentLevel.METADATA_ONLY,
},
],
}),
],
});
# Create a Kinesis Data Stream
stream = kinesis.Stream(self, "MemoryEventStream",
stream_name="memory-events"
)
memory = agentcore.Memory(self, "MemoryWithStreamDelivery",
memory_name="memory_with_stream",
description="Memory with Kinesis stream delivery",
expiration_duration=cdk.Duration.days(90),
stream_delivery_resources=[
agentcore.StreamDeliveryResource.kinesis(stream,
content_configurations=[agentcore.StreamDeliveryContentConfiguration(
type=agentcore.StreamDeliveryContentType.MEMORY_RECORDS,
level=agentcore.StreamDeliveryContentLevel.METADATA_ONLY
)
]
)
]
)
// Create a Kinesis Data Stream
Stream stream = Stream.Builder.create(this, "MemoryEventStream")
.streamName("memory-events")
.build();
Memory memory = Memory.Builder.create(this, "MemoryWithStreamDelivery")
.memoryName("memory_with_stream")
.description("Memory with Kinesis stream delivery")
.expirationDuration(Duration.days(90))
.streamDeliveryResources(List.of(StreamDeliveryResource.kinesis(stream, KinesisStreamDeliveryOptions.builder()
.contentConfigurations(List.of(StreamDeliveryContentConfiguration.builder()
.type(StreamDeliveryContentType.MEMORY_RECORDS)
.level(StreamDeliveryContentLevel.METADATA_ONLY)
.build()))
.build())))
.build();
// Create a Kinesis Data Stream
var stream = new Stream(this, "MemoryEventStream", new StreamProps {
StreamName = "memory-events"
});
var memory = new Memory(this, "MemoryWithStreamDelivery", new MemoryProps {
MemoryName = "memory_with_stream",
Description = "Memory with Kinesis stream delivery",
ExpirationDuration = Duration.Days(90),
StreamDeliveryResources = new [] { StreamDeliveryResource.Kinesis(stream, new KinesisStreamDeliveryOptions {
ContentConfigurations = new [] { new StreamDeliveryContentConfiguration {
Type = StreamDeliveryContentType.MEMORY_RECORDS,
Level = StreamDeliveryContentLevel.METADATA_ONLY
} }
}) }
});
// Create a Kinesis Data Stream
stream := kinesis.NewStream(this, jsii.String("MemoryEventStream"), &StreamProps{
StreamName: jsii.String("memory-events"),
})
memory := agentcore.NewMemory(this, jsii.String("MemoryWithStreamDelivery"), &MemoryProps{
MemoryName: jsii.String("memory_with_stream"),
Description: jsii.String("Memory with Kinesis stream delivery"),
ExpirationDuration: cdk.Duration_Days(jsii.Number(90)),
StreamDeliveryResources: []StreamDeliveryResource{
agentcore.StreamDeliveryResource_Kinesis(stream, &KinesisStreamDeliveryOptions{
ContentConfigurations: []StreamDeliveryContentConfiguration{
&StreamDeliveryContentConfiguration{
Type: agentcore.StreamDeliveryContentType_MEMORY_RECORDS,
Level: agentcore.StreamDeliveryContentLevel_METADATA_ONLY,
},
},
}),
},
})
There is no default content level — you must choose one explicitly. METADATA_ONLY delivers only the record ID, timestamps, and event type. FULL_CONTENT delivers the complete memory record body, which can contain personally identifiable information and other sensitive conversation content, so make sure the destination stream and its consumers are an appropriate place for that data:
const stream = new kinesis.Stream(this, 'MemoryEventStream');
const memory = new agentcore.Memory(this, 'MemoryWithStreamDelivery', {
memoryName: 'memory_with_stream',
streamDeliveryResources: [
agentcore.StreamDeliveryResource.kinesis(stream, {
contentConfigurations: [
{
type: agentcore.StreamDeliveryContentType.MEMORY_RECORDS,
// Streams complete memory record bodies, which may include sensitive data
level: agentcore.StreamDeliveryContentLevel.FULL_CONTENT,
},
],
}),
],
});
stream = kinesis.Stream(self, "MemoryEventStream")
memory = agentcore.Memory(self, "MemoryWithStreamDelivery",
memory_name="memory_with_stream",
stream_delivery_resources=[
agentcore.StreamDeliveryResource.kinesis(stream,
content_configurations=[agentcore.StreamDeliveryContentConfiguration(
type=agentcore.StreamDeliveryContentType.MEMORY_RECORDS,
# Streams complete memory record bodies, which may include sensitive data
level=agentcore.StreamDeliveryContentLevel.FULL_CONTENT
)
]
)
]
)
Stream stream = new Stream(this, "MemoryEventStream");
Memory memory = Memory.Builder.create(this, "MemoryWithStreamDelivery")
.memoryName("memory_with_stream")
.streamDeliveryResources(List.of(StreamDeliveryResource.kinesis(stream, KinesisStreamDeliveryOptions.builder()
.contentConfigurations(List.of(StreamDeliveryContentConfiguration.builder()
.type(StreamDeliveryContentType.MEMORY_RECORDS)
// Streams complete memory record bodies, which may include sensitive data
.level(StreamDeliveryContentLevel.FULL_CONTENT)
.build()))
.build())))
.build();
var stream = new Stream(this, "MemoryEventStream");
var memory = new Memory(this, "MemoryWithStreamDelivery", new MemoryProps {
MemoryName = "memory_with_stream",
StreamDeliveryResources = new [] { StreamDeliveryResource.Kinesis(stream, new KinesisStreamDeliveryOptions {
ContentConfigurations = new [] { new StreamDeliveryContentConfiguration {
Type = StreamDeliveryContentType.MEMORY_RECORDS,
// Streams complete memory record bodies, which may include sensitive data
Level = StreamDeliveryContentLevel.FULL_CONTENT
} }
}) }
});
stream := kinesis.NewStream(this, jsii.String("MemoryEventStream"))
memory := agentcore.NewMemory(this, jsii.String("MemoryWithStreamDelivery"), &MemoryProps{
MemoryName: jsii.String("memory_with_stream"),
StreamDeliveryResources: []StreamDeliveryResource{
agentcore.StreamDeliveryResource_Kinesis(stream, &KinesisStreamDeliveryOptions{
ContentConfigurations: []StreamDeliveryContentConfiguration{
&StreamDeliveryContentConfiguration{
Type: agentcore.StreamDeliveryContentType_MEMORY_RECORDS,
// Streams complete memory record bodies, which may include sensitive data
Level: agentcore.StreamDeliveryContentLevel_FULL_CONTENT,
},
},
}),
},
})
You can also add stream delivery resources after instantiation using the addStreamDeliveryResource() method:
const memory = new agentcore.Memory(this, 'MyMemory', {
memoryName: 'my_memory',
});
const stream = new kinesis.Stream(this, 'EventStream');
memory.addStreamDeliveryResource(agentcore.StreamDeliveryResource.kinesis(stream, {
contentConfigurations: [
{
type: agentcore.StreamDeliveryContentType.MEMORY_RECORDS,
level: agentcore.StreamDeliveryContentLevel.METADATA_ONLY,
},
],
}));
memory = agentcore.Memory(self, "MyMemory",
memory_name="my_memory"
)
stream = kinesis.Stream(self, "EventStream")
memory.add_stream_delivery_resource(agentcore.StreamDeliveryResource.kinesis(stream,
content_configurations=[agentcore.StreamDeliveryContentConfiguration(
type=agentcore.StreamDeliveryContentType.MEMORY_RECORDS,
level=agentcore.StreamDeliveryContentLevel.METADATA_ONLY
)
]
))
Memory memory = Memory.Builder.create(this, "MyMemory")
.memoryName("my_memory")
.build();
Stream stream = new Stream(this, "EventStream");
memory.addStreamDeliveryResource(StreamDeliveryResource.kinesis(stream, KinesisStreamDeliveryOptions.builder()
.contentConfigurations(List.of(StreamDeliveryContentConfiguration.builder()
.type(StreamDeliveryContentType.MEMORY_RECORDS)
.level(StreamDeliveryContentLevel.METADATA_ONLY)
.build()))
.build()));
var memory = new Memory(this, "MyMemory", new MemoryProps {
MemoryName = "my_memory"
});
var stream = new Stream(this, "EventStream");
memory.AddStreamDeliveryResource(StreamDeliveryResource.Kinesis(stream, new KinesisStreamDeliveryOptions {
ContentConfigurations = new [] { new StreamDeliveryContentConfiguration {
Type = StreamDeliveryContentType.MEMORY_RECORDS,
Level = StreamDeliveryContentLevel.METADATA_ONLY
} }
}));
memory := agentcore.NewMemory(this, jsii.String("MyMemory"), &MemoryProps{
MemoryName: jsii.String("my_memory"),
})
stream := kinesis.NewStream(this, jsii.String("EventStream"))
memory.AddStreamDeliveryResource(agentcore.StreamDeliveryResource_Kinesis(stream, &KinesisStreamDeliveryOptions{
ContentConfigurations: []StreamDeliveryContentConfiguration{
&StreamDeliveryContentConfiguration{
Type: agentcore.StreamDeliveryContentType_MEMORY_RECORDS,
Level: agentcore.StreamDeliveryContentLevel_METADATA_ONLY,
},
},
}))
Only one stream delivery resource is currently supported (a CloudFormation maximum); providing more than one fails at synth with TooManyStreamDeliveryResources.
The memory execution role is automatically granted write permissions (kinesis:PutRecord, kinesis:PutRecords, kinesis:ListShards, kinesis:DescribeStream) to each configured Kinesis stream. If the stream uses a customer-managed KMS key, encryption permissions are also granted automatically.
Encryption permissions can only be granted when the stream's key is known to CDK — that is, for streams you create and for streams imported with Stream.fromStreamAttributes({ encryptionKey }). A stream imported with Stream.fromStreamArn() carries no key reference, so grant the key permissions yourself in that case.
Policy Engine
A policy engine is a collection of policies that evaluates and authorizes agent tool calls. When associated with a gateway, the policy engine intercepts all agent requests and determines whether to allow or deny each action based on the defined policies.
For more information, see the Policy in Amazon Bedrock AgentCore documentation.
PolicyEngine Properties
| Name | Type | Required | Description |
|---|---|---|---|
policyEngineName | string | No | The name of the policy engine. Valid characters: a-z, A-Z, 0-9, _ (underscore). Must start with a letter, 1-48 characters. If not provided, a unique name will be auto-generated |
description | string | No | Optional description for the policy engine (max 4,096 characters). Default: no description |
kmsKey | IKey | No | Custom KMS key for encryption. IMPORTANT: Once set, cannot be changed (requires replacement). Must be symmetric ENCRYPT_DECRYPT key. If key becomes inaccessible, all authorization decisions will be DENIED. Default: AWS owned key |
tags | { [key: string]: string } | No | Tags for the policy engine (max 50 tags). Default: no tags |
Understanding Cedar Policies in AgentCore
Policies are constructed using Cedar language, an open source language for writing and enforcing authorization policies. Cedar policies in AgentCore follow a specific structure with three main components: Principal, Action, and Resource. Understanding how these components work together is critical for writing effective policies.
Policy Structure
Every Cedar policy has this basic structure:
permit( // or forbid
principal, // Who is making the request
action, // What operation they want to perform
resource // What Gateway/tool they want to access
)
when { // Optional conditions
// Additional constraints
};
Example Policy
permit(
principal,
action == AgentCore::Action::"ApplicationToolTarget___create_application",
resource == AgentCore::Gateway::"<gateway-arn>"
) when {
context.input.coverage_amount <= 1000000
};
Basic PolicyEngine and Policy Creation
Create a policy engine and add policies to it.
Policy Engine Mode
When associating a policy engine with a gateway, you can control the enforcement behavior using PolicyEngineMode:
PolicyEngineMode.ENFORCE(default) — actively allows or denies agent operations based on Cedar policy evaluation.PolicyEngineMode.LOG_ONLY— evaluates actions and adds traces but does not enforce decisions. Every tool call succeeds regardless of anyforbidpolicy, so use this mode to validate policies against real traffic before enforcing them. It is not recommended for production.
// Create a Policy engine
const policyEngine = new agentcore.PolicyEngine(this, "MyPolicyEngine", {
policyEngineName: "my_policy_engine",
description: "Policy engine for access control",
});
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
policyEngineConfiguration: {
policyEngine: policyEngine,
mode: agentcore.PolicyEngineMode.ENFORCE, // This is the default
},
});
// Add policy to policy engine
policyEngine.addPolicy("AllowAllActions", {
statement: agentcore.PolicyStatement.fromCedar(`
permit(
principal,
action,
resource == AgentCore::Gateway::"${gateway.gatewayArn}"
);
`),
description: "Allow all actions on specific gateway (development)",
validationMode: agentcore.PolicyValidationMode.IGNORE_ALL_FINDINGS, // This will ignore all cedar warnings
});
// you can add multiple policies to the policy engine
policyEngine.addPolicy("SpecificToolPolicy", {
statement: agentcore.PolicyStatement.fromCedar(`
permit(
principal is AgentCore::OAuthUser,
action == AgentCore::Action::"WeatherTool__get_forecast",
resource == AgentCore::Gateway::"${gateway.gatewayArn}"
);
`),
description: "Allow specific weather tool access",
validationMode: agentcore.PolicyValidationMode.FAIL_ON_ANY_FINDINGS, // This will fail policy creation for any cedar warning
});
# Create a Policy engine
policy_engine = agentcore.PolicyEngine(self, "MyPolicyEngine",
policy_engine_name="my_policy_engine",
description="Policy engine for access control"
)
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway",
policy_engine_configuration=agentcore.GatewayPolicyEngineConfig(
policy_engine=policy_engine,
mode=agentcore.PolicyEngineMode.ENFORCE
)
)
# Add policy to policy engine
policy_engine.add_policy("AllowAllActions",
statement=agentcore.PolicyStatement.from_cedar(f"""
permit(
principal,
action,
resource == AgentCore::Gateway::\"{gateway.gatewayArn}\"
);
"""),
description="Allow all actions on specific gateway (development)",
validation_mode=agentcore.PolicyValidationMode.IGNORE_ALL_FINDINGS
)
# you can add multiple policies to the policy engine
policy_engine.add_policy("SpecificToolPolicy",
statement=agentcore.PolicyStatement.from_cedar(f"""
permit(
principal is AgentCore::OAuthUser,
action == AgentCore::Action::\"WeatherTool__get_forecast\",
resource == AgentCore::Gateway::\"{gateway.gatewayArn}\"
);
"""),
description="Allow specific weather tool access",
validation_mode=agentcore.PolicyValidationMode.FAIL_ON_ANY_FINDINGS
)
// Create a Policy engine
PolicyEngine policyEngine = PolicyEngine.Builder.create(this, "MyPolicyEngine")
.policyEngineName("my_policy_engine")
.description("Policy engine for access control")
.build();
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.policyEngineConfiguration(GatewayPolicyEngineConfig.builder()
.policyEngine(policyEngine)
.mode(PolicyEngineMode.ENFORCE)
.build())
.build();
// Add policy to policy engine
policyEngine.addPolicy("AllowAllActions", AddPolicyOptions.builder()
.statement(PolicyStatement.fromCedar(String.format("%n permit(%n principal,%n action,%n resource == AgentCore::Gateway::\"%s\"%n );%n ", gateway.getGatewayArn())))
.description("Allow all actions on specific gateway (development)")
.validationMode(PolicyValidationMode.IGNORE_ALL_FINDINGS)
.build());
// you can add multiple policies to the policy engine
policyEngine.addPolicy("SpecificToolPolicy", AddPolicyOptions.builder()
.statement(PolicyStatement.fromCedar(String.format("%n permit(%n principal is AgentCore::OAuthUser,%n action == AgentCore::Action::\"WeatherTool__get_forecast\",%n resource == AgentCore::Gateway::\"%s\"%n );%n ", gateway.getGatewayArn())))
.description("Allow specific weather tool access")
.validationMode(PolicyValidationMode.FAIL_ON_ANY_FINDINGS)
.build());
// Create a Policy engine
var policyEngine = new PolicyEngine(this, "MyPolicyEngine", new PolicyEngineProps {
PolicyEngineName = "my_policy_engine",
Description = "Policy engine for access control"
});
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway",
PolicyEngineConfiguration = new GatewayPolicyEngineConfig {
PolicyEngine = policyEngine,
Mode = PolicyEngineMode.ENFORCE
}
});
// Add policy to policy engine
policyEngine.AddPolicy("AllowAllActions", new AddPolicyOptions {
Statement = PolicyStatement.FromCedar($@"
permit(
principal,
action,
resource == AgentCore::Gateway::""{gateway.gatewayArn}""
);
"),
Description = "Allow all actions on specific gateway (development)",
ValidationMode = PolicyValidationMode.IGNORE_ALL_FINDINGS
});
// you can add multiple policies to the policy engine
policyEngine.AddPolicy("SpecificToolPolicy", new AddPolicyOptions {
Statement = PolicyStatement.FromCedar($@"
permit(
principal is AgentCore::OAuthUser,
action == AgentCore::Action::""WeatherTool__get_forecast"",
resource == AgentCore::Gateway::""{gateway.gatewayArn}""
);
"),
Description = "Allow specific weather tool access",
ValidationMode = PolicyValidationMode.FAIL_ON_ANY_FINDINGS
});
// Create a Policy engine
policyEngine := agentcore.NewPolicyEngine(this, jsii.String("MyPolicyEngine"), &PolicyEngineProps{
PolicyEngineName: jsii.String("my_policy_engine"),
Description: jsii.String("Policy engine for access control"),
})
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
PolicyEngineConfiguration: &GatewayPolicyEngineConfig{
PolicyEngine: policyEngine,
Mode: agentcore.PolicyEngineMode_ENFORCE(),
},
})
// Add policy to policy engine
policyEngine.AddPolicy(jsii.String("AllowAllActions"), &AddPolicyOptions{
Statement: agentcore.PolicyStatement_FromCedar(fmt.Sprintf("\n permit(\n principal,\n action,\n resource == AgentCore::Gateway::\"%v\"\n );\n ", gateway.GatewayArn)),
Description: jsii.String("Allow all actions on specific gateway (development)"),
ValidationMode: agentcore.PolicyValidationMode_IGNORE_ALL_FINDINGS(),
})
// you can add multiple policies to the policy engine
policyEngine.AddPolicy(jsii.String("SpecificToolPolicy"), &AddPolicyOptions{
Statement: agentcore.PolicyStatement_*FromCedar(fmt.Sprintf("\n permit(\n principal is AgentCore::OAuthUser,\n action == AgentCore::Action::\"WeatherTool__get_forecast\",\n resource == AgentCore::Gateway::\"%v\"\n );\n ", gateway.*GatewayArn)),
Description: jsii.String("Allow specific weather tool access"),
ValidationMode: agentcore.PolicyValidationMode_FAIL_ON_ANY_FINDINGS(),
})
Type-Safe Policy Statements
For a more type-safe approach, construct a PolicyStatement instead of writing raw Cedar syntax. A statement names the effect, principal, action and resource it applies to, and all four are required, so a statement is complete as soon as it is constructed.
const gateway = new agentcore.Gateway(this, "MyGateway", {
gatewayName: "my-gateway",
});
const policyEngine = new agentcore.PolicyEngine(this, "MyPolicyEngine", {
policyEngineName: "my_policy_engine",
});
const allowAllPolicy = new agentcore.Policy(this, "AllowAllPolicy", {
policyEngine: policyEngine,
policyName: "allow_all",
statement: new agentcore.PolicyStatement({
effect: agentcore.PolicyEffect.PERMIT,
// ** This will give overly broad permission to all principals
principal: agentcore.PolicyPrincipal.any(),
action: agentcore.PolicyAction.any(),
resource: agentcore.PolicyResource.instance('AgentCore::Gateway', gateway.gatewayArn),
}),
description: "Allow all actions on specific gateway (development only)",
validationMode: agentcore.PolicyValidationMode.IGNORE_ALL_FINDINGS,
});
// Generated Cedar:
// permit(
// principal,
// action,
// resource == AgentCore::Gateway::"arn:aws:bedrock-agentcore:region:account:gateway/gateway-id"
// );
gateway = agentcore.Gateway(self, "MyGateway",
gateway_name="my-gateway"
)
policy_engine = agentcore.PolicyEngine(self, "MyPolicyEngine",
policy_engine_name="my_policy_engine"
)
allow_all_policy = agentcore.Policy(self, "AllowAllPolicy",
policy_engine=policy_engine,
policy_name="allow_all",
statement=agentcore.PolicyStatement(
effect=agentcore.PolicyEffect.PERMIT,
# ** This will give overly broad permission to all principals
principal=agentcore.PolicyPrincipal.any(),
action=agentcore.PolicyAction.any(),
resource=agentcore.PolicyResource.instance("AgentCore::Gateway", gateway.gateway_arn)
),
description="Allow all actions on specific gateway (development only)",
validation_mode=agentcore.PolicyValidationMode.IGNORE_ALL_FINDINGS
)
Gateway gateway = Gateway.Builder.create(this, "MyGateway")
.gatewayName("my-gateway")
.build();
PolicyEngine policyEngine = PolicyEngine.Builder.create(this, "MyPolicyEngine")
.policyEngineName("my_policy_engine")
.build();
Policy allowAllPolicy = Policy.Builder.create(this, "AllowAllPolicy")
.policyEngine(policyEngine)
.policyName("allow_all")
.statement(PolicyStatement.Builder.create()
.effect(PolicyEffect.PERMIT)
// ** This will give overly broad permission to all principals
.principal(PolicyPrincipal.any())
.action(PolicyAction.any())
.resource(PolicyResource.instance("AgentCore::Gateway", gateway.getGatewayArn()))
.build())
.description("Allow all actions on specific gateway (development only)")
.validationMode(PolicyValidationMode.IGNORE_ALL_FINDINGS)
.build();
var gateway = new Gateway(this, "MyGateway", new GatewayProps {
GatewayName = "my-gateway"
});
var policyEngine = new PolicyEngine(this, "MyPolicyEngine", new PolicyEngineProps {
PolicyEngineName = "my_policy_engine"
});
var allowAllPolicy = new Policy(this, "AllowAllPolicy", new PolicyProps {
PolicyEngine = policyEngine,
PolicyName = "allow_all",
Statement = new PolicyStatement(new PolicyStatementProps {
Effect = PolicyEffect.PERMIT,
// ** This will give overly broad permission to all principals
Principal = PolicyPrincipal.Any(),
Action = PolicyAction.Any(),
Resource = PolicyResource.Instance("AgentCore::Gateway", gateway.GatewayArn)
}),
Description = "Allow all actions on specific gateway (development only)",
ValidationMode = PolicyValidationMode.IGNORE_ALL_FINDINGS
});
gateway := agentcore.NewGateway(this, jsii.String("MyGateway"), &GatewayProps{
GatewayName: jsii.String("my-gateway"),
})
policyEngine := agentcore.NewPolicyEngine(this, jsii.String("MyPolicyEngine"), &PolicyEngineProps{
PolicyEngineName: jsii.String("my_policy_engine"),
})
allowAllPolicy := agentcore.NewPolicy(this, jsii.String("AllowAllPolicy"), &PolicyProps{
PolicyEngine: policyEngine,
PolicyName: jsii.String("allow_all"),
Statement: agentcore.NewPolicyStatement(&PolicyStatementProps{
Effect: agentcore.PolicyEffect_PERMIT,
// ** This will give overly broad permission to all principals
Principal: agentcore.PolicyPrincipal_Any(),
Action: agentcore.PolicyAction_Any(),
Resource: agentcore.PolicyResource_Instance(jsii.String("AgentCore::Gateway"), gateway.GatewayArn),
}),
Description: jsii.String("Allow all actions on specific gateway (development only)"),
ValidationMode: agentcore.PolicyValidationMode_IGNORE_ALL_FINDINGS(),
})
Policy with Specific Actions
declare const policyEngine: agentcore.PolicyEngine;
declare const gateway: agentcore.Gateway;
// Allow specific tool actions on specific gateway
// Action names follow pattern: "ToolName__operation"
policyEngine.addPolicy("SpecificToolPolicy", {
statement: new agentcore.PolicyStatement({
effect: agentcore.PolicyEffect.PERMIT,
principal: agentcore.PolicyPrincipal.entityType('AgentCore::OAuthUser'),
action: agentcore.PolicyAction.anyOf([
'AgentCore::Action::WeatherTool__get_forecast',
'AgentCore::Action::WeatherTool__get_current',
]),
resource: agentcore.PolicyResource.instance('AgentCore::Gateway', gateway.gatewayArn),
}),
description: "Allow specific weather tool operations",
validationMode: agentcore.PolicyValidationMode.FAIL_ON_ANY_FINDINGS,
});
// Generated Cedar:
// permit(
// principal is AgentCore::OAuthUser,
// action in [
// AgentCore::Action::"WeatherTool__get_forecast",
// AgentCore::Action::"WeatherTool__get_current"
// ],
// resource == AgentCore::Gateway::"arn:aws:bedrock-agentcore:us-east-1:123:gateway/gw-123"
// );
# policy_engine: agentcore.PolicyEngine
# gateway: agentcore.Gateway
# Allow specific tool actions on specific gateway
# Action names follow pattern: "ToolName__operation"
policy_engine.add_policy("SpecificToolPolicy",
statement=agentcore.PolicyStatement(
effect=agentcore.PolicyEffect.PERMIT,
principal=agentcore.PolicyPrincipal.entity_type("AgentCore::OAuthUser"),
action=agentcore.PolicyAction.any_of(["AgentCore::Action::WeatherTool__get_forecast", "AgentCore::Action::WeatherTool__get_current"
]),
resource=agentcore.PolicyResource.instance("AgentCore::Gateway", gateway.gateway_arn)
),
description="Allow specific weather tool operations",
validation_mode=agentcore.PolicyValidationMode.FAIL_ON_ANY_FINDINGS
)
PolicyEngine policyEngine;
Gateway gateway;
// Allow specific tool actions on specific gateway
// Action names follow pattern: "ToolName__operation"
policyEngine.addPolicy("SpecificToolPolicy", AddPolicyOptions.builder()
.statement(PolicyStatement.Builder.create()
.effect(PolicyEffect.PERMIT)
.principal(PolicyPrincipal.entityType("AgentCore::OAuthUser"))
.action(PolicyAction.anyOf(List.of("AgentCore::Action::WeatherTool__get_forecast", "AgentCore::Action::WeatherTool__get_current")))
.resource(PolicyResource.instance("AgentCore::Gateway", gateway.getGatewayArn()))
.build())
.description("Allow specific weather tool operations")
.validationMode(PolicyValidationMode.FAIL_ON_ANY_FINDINGS)
.build());
PolicyEngine policyEngine;
Gateway gateway;
// Allow specific tool actions on specific gateway
// Action names follow pattern: "ToolName__operation"
policyEngine.AddPolicy("SpecificToolPolicy", new AddPolicyOptions {
Statement = new PolicyStatement(new PolicyStatementProps {
Effect = PolicyEffect.PERMIT,
Principal = PolicyPrincipal.EntityType("AgentCore::OAuthUser"),
Action = PolicyAction.AnyOf(new [] { "AgentCore::Action::WeatherTool__get_forecast", "AgentCore::Action::WeatherTool__get_current" }),
Resource = PolicyResource.Instance("AgentCore::Gateway", gateway.GatewayArn)
}),
Description = "Allow specific weather tool operations",
ValidationMode = PolicyValidationMode.FAIL_ON_ANY_FINDINGS
});
var policyEngine PolicyEngine
var gateway Gateway
// Allow specific tool actions on specific gateway
// Action names follow pattern: "ToolName__operation"
policyEngine.AddPolicy(jsii.String("SpecificToolPolicy"), &AddPolicyOptions{
Statement: agentcore.NewPolicyStatement(&PolicyStatementProps{
Effect: agentcore.PolicyEffect_PERMIT,
Principal: agentcore.PolicyPrincipal_EntityType(jsii.String("AgentCore::OAuthUser")),
Action: agentcore.PolicyAction_AnyOf([]*string{
jsii.String("AgentCore::Action::WeatherTool__get_forecast"),
jsii.String("AgentCore::Action::WeatherTool__get_current"),
}),
Resource: agentcore.PolicyResource_Instance(jsii.String("AgentCore::Gateway"), gateway.GatewayArn),
}),
Description: jsii.String("Allow specific weather tool operations"),
ValidationMode: agentcore.PolicyValidationMode_FAIL_ON_ANY_FINDINGS(),
})
Policy with Conditions
Use when clauses to add advanced conditions based on principal tags (from OAuth token) or context:
declare const policyEngine: agentcore.PolicyEngine;
declare const gateway: agentcore.Gateway;
// Policy with when conditions using principal tags
const conditionalPolicy = new agentcore.Policy(this, "ConditionalPolicy", {
policyEngine: policyEngine,
policyName: "conditional_access",
statement: new agentcore.PolicyStatement({
effect: agentcore.PolicyEffect.PERMIT,
principal: agentcore.PolicyPrincipal.entityType('AgentCore::OAuthUser'), // Type constraint
action: agentcore.PolicyAction.any(),
resource: agentcore.PolicyResource.instance('AgentCore::Gateway', gateway.gatewayArn), // Specific ARN
when: [
agentcore.PolicyCondition.stringEquals(
agentcore.PolicyAttribute.principal('department'), 'Engineering'),
agentcore.PolicyCondition.stringEquals(
agentcore.PolicyAttribute.context('input.priority'), 'high'),
],
}),
description: "Allow engineers for high-priority requests",
validationMode: agentcore.PolicyValidationMode.FAIL_ON_ANY_FINDINGS,
});
// Generated Cedar:
// permit(
// principal is AgentCore::OAuthUser,
// action,
// resource == AgentCore::Gateway::"arn:..."
// )
// when {
// principal.department == "Engineering" && context.input.priority == "high"
// };
# policy_engine: agentcore.PolicyEngine
# gateway: agentcore.Gateway
# Policy with when conditions using principal tags
conditional_policy = agentcore.Policy(self, "ConditionalPolicy",
policy_engine=policy_engine,
policy_name="conditional_access",
statement=agentcore.PolicyStatement(
effect=agentcore.PolicyEffect.PERMIT,
principal=agentcore.PolicyPrincipal.entity_type("AgentCore::OAuthUser"), # Type constraint
action=agentcore.PolicyAction.any(),
resource=agentcore.PolicyResource.instance("AgentCore::Gateway", gateway.gateway_arn), # Specific ARN
when=[
agentcore.PolicyCondition.string_equals(
agentcore.PolicyAttribute.principal("department"), "Engineering"),
agentcore.PolicyCondition.string_equals(
agentcore.PolicyAttribute.context("input.priority"), "high")
]
),
description="Allow engineers for high-priority requests",
validation_mode=agentcore.PolicyValidationMode.FAIL_ON_ANY_FINDINGS
)
PolicyEngine policyEngine;
Gateway gateway;
// Policy with when conditions using principal tags
Policy conditionalPolicy = Policy.Builder.create(this, "ConditionalPolicy")
.policyEngine(policyEngine)
.policyName("conditional_access")
.statement(PolicyStatement.Builder.create()
.effect(PolicyEffect.PERMIT)
.principal(PolicyPrincipal.entityType("AgentCore::OAuthUser")) // Type constraint
.action(PolicyAction.any())
.resource(PolicyResource.instance("AgentCore::Gateway", gateway.getGatewayArn())) // Specific ARN
.when(List.of(PolicyCondition.stringEquals(PolicyAttribute.principal("department"), "Engineering"), PolicyCondition.stringEquals(PolicyAttribute.context("input.priority"), "high")))
.build())
.description("Allow engineers for high-priority requests")
.validationMode(PolicyValidationMode.FAIL_ON_ANY_FINDINGS)
.build();
PolicyEngine policyEngine;
Gateway gateway;
// Policy with when conditions using principal tags
var conditionalPolicy = new Policy(this, "ConditionalPolicy", new PolicyProps {
PolicyEngine = policyEngine,
PolicyName = "conditional_access",
Statement = new PolicyStatement(new PolicyStatementProps {
Effect = PolicyEffect.PERMIT,
Principal = PolicyPrincipal.EntityType("AgentCore::OAuthUser"), // Type constraint
Action = PolicyAction.Any(),
Resource = PolicyResource.Instance("AgentCore::Gateway", gateway.GatewayArn), // Specific ARN
When = new [] { PolicyCondition.StringEquals(PolicyAttribute.Principal("department"), "Engineering"), PolicyCondition.StringEquals(PolicyAttribute.Context("input.priority"), "high") }
}),
Description = "Allow engineers for high-priority requests",
ValidationMode = PolicyValidationMode.FAIL_ON_ANY_FINDINGS
});
var policyEngine PolicyEngine
var gateway Gateway
// Policy with when conditions using principal tags
conditionalPolicy := agentcore.NewPolicy(this, jsii.String("ConditionalPolicy"), &PolicyProps{
PolicyEngine: policyEngine,
PolicyName: jsii.String("conditional_access"),
Statement: agentcore.NewPolicyStatement(&PolicyStatementProps{
Effect: agentcore.PolicyEffect_PERMIT,
Principal: agentcore.PolicyPrincipal_EntityType(jsii.String("AgentCore::OAuthUser")),
// Type constraint
Action: agentcore.PolicyAction_Any(),
Resource: agentcore.PolicyResource_Instance(jsii.String("AgentCore::Gateway"), gateway.GatewayArn),
// Specific ARN
When: []PolicyCondition{
agentcore.PolicyCondition_StringEquals(agentcore.PolicyAttribute_Principal(jsii.String("department")), jsii.String("Engineering")),
agentcore.PolicyCondition_*StringEquals(agentcore.PolicyAttribute_Context(jsii.String("input.priority")), jsii.String("high")),
},
}),
Description: jsii.String("Allow engineers for high-priority requests"),
ValidationMode: agentcore.PolicyValidationMode_FAIL_ON_ANY_FINDINGS(),
})
Policy with Exclusions (unless)
Use unless clauses to exclude specific conditions from a policy. The policy applies when the unless conditions are NOT met:
declare const policyEngine: agentcore.PolicyEngine;
declare const gateway: agentcore.Gateway;
// Allow access unless the user is suspended
const policyWithUnless = new agentcore.Policy(this, "UnlessPolicy", {
policyEngine: policyEngine,
policyName: "unless_suspended",
statement: new agentcore.PolicyStatement({
effect: agentcore.PolicyEffect.PERMIT,
principal: agentcore.PolicyPrincipal.entityType('AgentCore::OAuthUser'),
action: agentcore.PolicyAction.any(),
resource: agentcore.PolicyResource.instance('AgentCore::Gateway', gateway.gatewayArn),
unless: [
agentcore.PolicyCondition.booleanEquals(
agentcore.PolicyAttribute.principal('suspended'), true),
],
}),
description: "Allow all actions unless user is suspended",
validationMode: agentcore.PolicyValidationMode.FAIL_ON_ANY_FINDINGS,
});
// Generated Cedar:
// permit(
// principal is AgentCore::OAuthUser,
// action,
// resource == AgentCore::Gateway::"arn:..."
// )
// unless {
// principal.suspended == true
// };
# policy_engine: agentcore.PolicyEngine
# gateway: agentcore.Gateway
# Allow access unless the user is suspended
policy_with_unless = agentcore.Policy(self, "UnlessPolicy",
policy_engine=policy_engine,
policy_name="unless_suspended",
statement=agentcore.PolicyStatement(
effect=agentcore.PolicyEffect.PERMIT,
principal=agentcore.PolicyPrincipal.entity_type("AgentCore::OAuthUser"),
action=agentcore.PolicyAction.any(),
resource=agentcore.PolicyResource.instance("AgentCore::Gateway", gateway.gateway_arn),
unless=[
agentcore.PolicyCondition.boolean_equals(
agentcore.PolicyAttribute.principal("suspended"), True)
]
),
description="Allow all actions unless user is suspended",
validation_mode=agentcore.PolicyValidationMode.FAIL_ON_ANY_FINDINGS
)
PolicyEngine policyEngine;
Gateway gateway;
// Allow access unless the user is suspended
Policy policyWithUnless = Policy.Builder.create(this, "UnlessPolicy")
.policyEngine(policyEngine)
.policyName("unless_suspended")
.statement(PolicyStatement.Builder.create()
.effect(PolicyEffect.PERMIT)
.principal(PolicyPrincipal.entityType("AgentCore::OAuthUser"))
.action(PolicyAction.any())
.resource(PolicyResource.instance("AgentCore::Gateway", gateway.getGatewayArn()))
.unless(List.of(PolicyCondition.booleanEquals(PolicyAttribute.principal("suspended"), true)))
.build())
.description("Allow all actions unless user is suspended")
.validationMode(PolicyValidationMode.FAIL_ON_ANY_FINDINGS)
.build();
PolicyEngine policyEngine;
Gateway gateway;
// Allow access unless the user is suspended
var policyWithUnless = new Policy(this, "UnlessPolicy", new PolicyProps {
PolicyEngine = policyEngine,
PolicyName = "unless_suspended",
Statement = new PolicyStatement(new PolicyStatementProps {
Effect = PolicyEffect.PERMIT,
Principal = PolicyPrincipal.EntityType("AgentCore::OAuthUser"),
Action = PolicyAction.Any(),
Resource = PolicyResource.Instance("AgentCore::Gateway", gateway.GatewayArn),
Unless = new [] { PolicyCondition.BooleanEquals(PolicyAttribute.Principal("suspended"), true) }
}),
Description = "Allow all actions unless user is suspended",
ValidationMode = PolicyValidationMode.FAIL_ON_ANY_FINDINGS
});
var policyEngine PolicyEngine
var gateway Gateway
// Allow access unless the user is suspended
policyWithUnless := agentcore.NewPolicy(this, jsii.String("UnlessPolicy"), &PolicyProps{
PolicyEngine: policyEngine,
PolicyName: jsii.String("unless_suspended"),
Statement: agentcore.NewPolicyStatement(&PolicyStatementProps{
Effect: agentcore.PolicyEffect_PERMIT,
Principal: agentcore.PolicyPrincipal_EntityType(jsii.String("AgentCore::OAuthUser")),
Action: agentcore.PolicyAction_Any(),
Resource: agentcore.PolicyResource_Instance(jsii.String("AgentCore::Gateway"), gateway.GatewayArn),
Unless: []PolicyCondition{
agentcore.PolicyCondition_BooleanEquals(agentcore.PolicyAttribute_Principal(jsii.String("suspended")), jsii.Boolean(true)),
},
}),
Description: jsii.String("Allow all actions unless user is suspended"),
ValidationMode: agentcore.PolicyValidationMode_FAIL_ON_ANY_FINDINGS(),
})
You can combine when and unless clauses in the same policy:
declare const policyEngine: agentcore.PolicyEngine;
declare const gateway: agentcore.Gateway;
// Allow engineers unless they are on probation
policyEngine.addPolicy("CombinedConditions", {
statement: new agentcore.PolicyStatement({
effect: agentcore.PolicyEffect.PERMIT,
principal: agentcore.PolicyPrincipal.entityType('AgentCore::OAuthUser'),
action: agentcore.PolicyAction.any(),
resource: agentcore.PolicyResource.instance('AgentCore::Gateway', gateway.gatewayArn),
when: [
agentcore.PolicyCondition.stringEquals(
agentcore.PolicyAttribute.principal('department'), 'Engineering'),
],
unless: [
agentcore.PolicyCondition.stringEquals(
agentcore.PolicyAttribute.principal('status'), 'probation'),
],
}),
description: "Allow engineers unless on probation",
validationMode: agentcore.PolicyValidationMode.FAIL_ON_ANY_FINDINGS,
});
# policy_engine: agentcore.PolicyEngine
# gateway: agentcore.Gateway
# Allow engineers unless they are on probation
policy_engine.add_policy("CombinedConditions",
statement=agentcore.PolicyStatement(
effect=agentcore.PolicyEffect.PERMIT,
principal=agentcore.PolicyPrincipal.entity_type("AgentCore::OAuthUser"),
action=agentcore.PolicyAction.any(),
resource=agentcore.PolicyResource.instance("AgentCore::Gateway", gateway.gateway_arn),
when=[
agentcore.PolicyCondition.string_equals(
agentcore.PolicyAttribute.principal("department"), "Engineering")
],
unless=[
agentcore.PolicyCondition.string_equals(
agentcore.PolicyAttribute.principal("status"), "probation")
]
),
description="Allow engineers unless on probation",
validation_mode=agentcore.PolicyValidationMode.FAIL_ON_ANY_FINDINGS
)
PolicyEngine policyEngine;
Gateway gateway;
// Allow engineers unless they are on probation
policyEngine.addPolicy("CombinedConditions", AddPolicyOptions.builder()
.statement(PolicyStatement.Builder.create()
.effect(PolicyEffect.PERMIT)
.principal(PolicyPrincipal.entityType("AgentCore::OAuthUser"))
.action(PolicyAction.any())
.resource(PolicyResource.instance("AgentCore::Gateway", gateway.getGatewayArn()))
.when(List.of(PolicyCondition.stringEquals(PolicyAttribute.principal("department"), "Engineering")))
.unless(List.of(PolicyCondition.stringEquals(PolicyAttribute.principal("status"), "probation")))
.build())
.description("Allow engineers unless on probation")
.validationMode(PolicyValidationMode.FAIL_ON_ANY_FINDINGS)
.build());
PolicyEngine policyEngine;
Gateway gateway;
// Allow engineers unless they are on probation
policyEngine.AddPolicy("CombinedConditions", new AddPolicyOptions {
Statement = new PolicyStatement(new PolicyStatementProps {
Effect = PolicyEffect.PERMIT,
Principal = PolicyPrincipal.EntityType("AgentCore::OAuthUser"),
Action = PolicyAction.Any(),
Resource = PolicyResource.Instance("AgentCore::Gateway", gateway.GatewayArn),
When = new [] { PolicyCondition.StringEquals(PolicyAttribute.Principal("department"), "Engineering") },
Unless = new [] { PolicyCondition.StringEquals(PolicyAttribute.Principal("status"), "probation") }
}),
Description = "Allow engineers unless on probation",
ValidationMode = PolicyValidationMode.FAIL_ON_ANY_FINDINGS
});
var policyEngine PolicyEngine
var gateway Gateway
// Allow engineers unless they are on probation
policyEngine.AddPolicy(jsii.String("CombinedConditions"), &AddPolicyOptions{
Statement: agentcore.NewPolicyStatement(&PolicyStatementProps{
Effect: agentcore.PolicyEffect_PERMIT,
Principal: agentcore.PolicyPrincipal_EntityType(jsii.String("AgentCore::OAuthUser")),
Action: agentcore.PolicyAction_Any(),
Resource: agentcore.PolicyResource_Instance(jsii.String("AgentCore::Gateway"), gateway.GatewayArn),
When: []PolicyCondition{
agentcore.PolicyCondition_StringEquals(agentcore.PolicyAttribute_Principal(jsii.String("department")), jsii.String("Engineering")),
},
Unless: []PolicyCondition{
agentcore.PolicyCondition_*StringEquals(agentcore.PolicyAttribute_*Principal(jsii.String("status")), jsii.String("probation")),
},
}),
Description: jsii.String("Allow engineers unless on probation"),
ValidationMode: agentcore.PolicyValidationMode_FAIL_ON_ANY_FINDINGS(),
})
Forbid (Deny) Policy
Use forbid to explicitly deny access. Forbid policies override permit policies.
declare const policyEngine: agentcore.PolicyEngine;
declare const gateway: agentcore.Gateway;
// Explicitly deny dangerous tool operations
policyEngine.addPolicy("DenyDangerous", {
statement: new agentcore.PolicyStatement({
effect: agentcore.PolicyEffect.FORBID,
principal: agentcore.PolicyPrincipal.any(),
action: agentcore.PolicyAction.one('AgentCore::Action::DeleteTool__delete_all'),
resource: agentcore.PolicyResource.instance('AgentCore::Gateway', gateway.gatewayArn),
}),
description: "Forbid delete_all operation for all users",
validationMode: agentcore.PolicyValidationMode.FAIL_ON_ANY_FINDINGS,
});
// Generated Cedar:
// forbid(
// principal,
// action == AgentCore::Action::"DeleteTool__delete_all",
// resource == AgentCore::Gateway::"arn:..."
// );
# policy_engine: agentcore.PolicyEngine
# gateway: agentcore.Gateway
# Explicitly deny dangerous tool operations
policy_engine.add_policy("DenyDangerous",
statement=agentcore.PolicyStatement(
effect=agentcore.PolicyEffect.FORBID,
principal=agentcore.PolicyPrincipal.any(),
action=agentcore.PolicyAction.one("AgentCore::Action::DeleteTool__delete_all"),
resource=agentcore.PolicyResource.instance("AgentCore::Gateway", gateway.gateway_arn)
),
description="Forbid delete_all operation for all users",
validation_mode=agentcore.PolicyValidationMode.FAIL_ON_ANY_FINDINGS
)
PolicyEngine policyEngine;
Gateway gateway;
// Explicitly deny dangerous tool operations
policyEngine.addPolicy("DenyDangerous", AddPolicyOptions.builder()
.statement(PolicyStatement.Builder.create()
.effect(PolicyEffect.FORBID)
.principal(PolicyPrincipal.any())
.action(PolicyAction.one("AgentCore::Action::DeleteTool__delete_all"))
.resource(PolicyResource.instance("AgentCore::Gateway", gateway.getGatewayArn()))
.build())
.description("Forbid delete_all operation for all users")
.validationMode(PolicyValidationMode.FAIL_ON_ANY_FINDINGS)
.build());
PolicyEngine policyEngine;
Gateway gateway;
// Explicitly deny dangerous tool operations
policyEngine.AddPolicy("DenyDangerous", new AddPolicyOptions {
Statement = new PolicyStatement(new PolicyStatementProps {
Effect = PolicyEffect.FORBID,
Principal = PolicyPrincipal.Any(),
Action = PolicyAction.One("AgentCore::Action::DeleteTool__delete_all"),
Resource = PolicyResource.Instance("AgentCore::Gateway", gateway.GatewayArn)
}),
Description = "Forbid delete_all operation for all users",
ValidationMode = PolicyValidationMode.FAIL_ON_ANY_FINDINGS
});
var policyEngine PolicyEngine
var gateway Gateway
// Explicitly deny dangerous tool operations
policyEngine.AddPolicy(jsii.String("DenyDangerous"), &AddPolicyOptions{
Statement: agentcore.NewPolicyStatement(&PolicyStatementProps{
Effect: agentcore.PolicyEffect_FORBID,
Principal: agentcore.PolicyPrincipal_Any(),
Action: agentcore.PolicyAction_One(jsii.String("AgentCore::Action::DeleteTool__delete_all")),
Resource: agentcore.PolicyResource_Instance(jsii.String("AgentCore::Gateway"), gateway.GatewayArn),
}),
Description: jsii.String("Forbid delete_all operation for all users"),
ValidationMode: agentcore.PolicyValidationMode_FAIL_ON_ANY_FINDINGS(),
})
Raw Cedar for Advanced Cases
For advanced Cedar features that PolicyStatement does not model, pass a raw Cedar string through PolicyStatement.fromCedar():
declare const policyEngine: agentcore.PolicyEngine;
const advancedPolicy = new agentcore.Policy(this, "AdvancedPolicy", {
policyEngine: policyEngine,
statement: agentcore.PolicyStatement.fromCedar(
'permit(principal, action, resource) when { context.custom > 10 };'
),
description: "Advanced policy with custom Cedar logic",
});
policyEngine.addPolicy("CustomPolicy", {
statement: agentcore.PolicyStatement.fromCedar(
'forbid(principal, action, resource) when { resource.confidential == true };'
),
description: "Custom policy from Cedar string",
});
# policy_engine: agentcore.PolicyEngine
advanced_policy = agentcore.Policy(self, "AdvancedPolicy",
policy_engine=policy_engine,
statement=agentcore.PolicyStatement.from_cedar("permit(principal, action, resource) when { context.custom > 10 };"),
description="Advanced policy with custom Cedar logic"
)
policy_engine.add_policy("CustomPolicy",
statement=agentcore.PolicyStatement.from_cedar("forbid(principal, action, resource) when { resource.confidential == true };"),
description="Custom policy from Cedar string"
)
PolicyEngine policyEngine;
Policy advancedPolicy = Policy.Builder.create(this, "AdvancedPolicy")
.policyEngine(policyEngine)
.statement(PolicyStatement.fromCedar("permit(principal, action, resource) when { context.custom > 10 };"))
.description("Advanced policy with custom Cedar logic")
.build();
policyEngine.addPolicy("CustomPolicy", AddPolicyOptions.builder()
.statement(PolicyStatement.fromCedar("forbid(principal, action, resource) when { resource.confidential == true };"))
.description("Custom policy from Cedar string")
.build());
PolicyEngine policyEngine;
var advancedPolicy = new Policy(this, "AdvancedPolicy", new PolicyProps {
PolicyEngine = policyEngine,
Statement = PolicyStatement.FromCedar("permit(principal, action, resource) when { context.custom > 10 };"),
Description = "Advanced policy with custom Cedar logic"
});
policyEngine.AddPolicy("CustomPolicy", new AddPolicyOptions {
Statement = PolicyStatement.FromCedar("forbid(principal, action, resource) when { resource.confidential == true };"),
Description = "Custom policy from Cedar string"
});
var policyEngine PolicyEngine
advancedPolicy := agentcore.NewPolicy(this, jsii.String("AdvancedPolicy"), &PolicyProps{
PolicyEngine: policyEngine,
Statement: agentcore.PolicyStatement_FromCedar(jsii.String("permit(principal, action, resource) when { context.custom > 10 };")),
Description: jsii.String("Advanced policy with custom Cedar logic"),
})
policyEngine.AddPolicy(jsii.String("CustomPolicy"), &AddPolicyOptions{
Statement: agentcore.PolicyStatement_*FromCedar(jsii.String("forbid(principal, action, resource) when { resource.confidential == true };")),
Description: jsii.String("Custom policy from Cedar string"),
})
Raw Cedar is trusted input
A PolicyStatement built from the factories is the safe tier: every value you pass to it is written as a single Cedar string literal, and synthesis fails if a value cannot be represented that way.
PolicyStatement.fromCedar() is the direct tier. The module passes the string through unchanged, applying no escaping, no quoting, and no syntax checking. Keep these four points in mind:
- The string is used exactly as given. The module does not escape it, quote it, or check its syntax.
- Treat the string as trusted input. Supply Cedar you control.
- Do not assemble the string by joining values that come from outside your application, such as a request body, a user profile field, or a database record. A value containing a double quote can end a string literal early and add policy statements you did not write. Pass those values through
PolicyConditionand the principal, action and resource factories instead, because they reject exactly that case. - Service-side validation is not a safety net here. It checks the policy against your schema, and an injected policy is still valid Cedar, so it passes.
When you write raw Cedar, you are responsible for Cedar's own escaping: write two backslashes for each literal backslash, and \" for each double quote. In TypeScript two layers of escaping stack, the language's and then Cedar's:
| Value you want | The Cedar source must read | TypeScript string literal | With String.raw |
|---|---|---|---|
C:\reports\newdata | "C:\\reports\\newdata" | 'C:\\\\reports\\\\newdata' | String.raw`C:\\reports\\newdata` |
my "quoted" gateway | "my \"quoted\" gateway" | 'my \\"quoted\\" gateway' | String.raw`my \"quoted\" gateway` |
If the Cedar source ends up with one backslash instead of two, the policy still parses and still deploys, and Cedar stores a different value. That failure is silent, so prefer String.raw in TypeScript to leave only the Cedar-level rule to think about:
declare const policyEngine: agentcore.PolicyEngine;
policyEngine.addPolicy("RawCedarPolicy", {
statement: agentcore.PolicyStatement.fromCedar(
String.raw`permit(principal, action, resource == AgentCore::Gateway::"my \"quoted\" gateway");`,
),
});
# policy_engine: agentcore.PolicyEngine
policy_engine.add_policy("RawCedarPolicy",
statement=agentcore.PolicyStatement.from_cedar(String.raw`permit(principal, action, resource == AgentCore::Gateway::"my \"quoted\" gateway");`)
)
PolicyEngine policyEngine;
policyEngine.addPolicy("RawCedarPolicy", AddPolicyOptions.builder()
.statement(PolicyStatement.fromCedar(String.raw`permit(principal, action, resource == AgentCore::Gateway::"my \"quoted\" gateway");`))
.build());
PolicyEngine policyEngine;
policyEngine.AddPolicy("RawCedarPolicy", new AddPolicyOptions {
Statement = PolicyStatement.FromCedar(String.raw`permit(principal, action, resource == AgentCore::Gateway::"my \"quoted\" gateway");`)
});
var policyEngine PolicyEngine
policyEngine.AddPolicy(jsii.String("RawCedarPolicy"), &AddPolicyOptions{
Statement: agentcore.PolicyStatement_FromCedar(String.raw`permit(principal, action, resource == AgentCore::Gateway::"my \"quoted\" gateway");`),
})
String.raw is a TypeScript and JavaScript convenience, not the rule. Other jsii languages have their own raw-string forms (Python r"...", C# @"...", Java text blocks, Go backticks). The Cedar-level rule is the part that holds in every language.
There is no way to escape one value and keep the modelled form: the direct tier replaces a whole statement. A PolicyStatement is either constructed from properties or created from raw Cedar, and the two cannot be combined.
Accessing Policies on PolicyEngine
You can access the list of policies added to a PolicyEngine using policyEngine.policies.
PolicyEngine with KMS Encryption
Encrypt policy data with a custom KMS key.
// Create a custom KMS key
const policyKey = new kms.Key(this, "PolicyEngineKey", {
enableKeyRotation: true,
description: "KMS key for policy engine encryption",
});
// Create policy engine with encryption
const policyEngine = new agentcore.PolicyEngine(this, "EncryptedEngine", {
policyEngineName: "encrypted_engine",
description: "Policy engine with KMS encryption",
kmsKey: policyKey,
});
# Create a custom KMS key
policy_key = kms.Key(self, "PolicyEngineKey",
enable_key_rotation=True,
description="KMS key for policy engine encryption"
)
# Create policy engine with encryption
policy_engine = agentcore.PolicyEngine(self, "EncryptedEngine",
policy_engine_name="encrypted_engine",
description="Policy engine with KMS encryption",
kms_key=policy_key
)
// Create a custom KMS key
Key policyKey = Key.Builder.create(this, "PolicyEngineKey")
.enableKeyRotation(true)
.description("KMS key for policy engine encryption")
.build();
// Create policy engine with encryption
PolicyEngine policyEngine = PolicyEngine.Builder.create(this, "EncryptedEngine")
.policyEngineName("encrypted_engine")
.description("Policy engine with KMS encryption")
.kmsKey(policyKey)
.build();
// Create a custom KMS key
var policyKey = new Key(this, "PolicyEngineKey", new KeyProps {
EnableKeyRotation = true,
Description = "KMS key for policy engine encryption"
});
// Create policy engine with encryption
var policyEngine = new PolicyEngine(this, "EncryptedEngine", new PolicyEngineProps {
PolicyEngineName = "encrypted_engine",
Description = "Policy engine with KMS encryption",
KmsKey = policyKey
});
// Create a custom KMS key
policyKey := kms.NewKey(this, jsii.String("PolicyEngineKey"), &KeyProps{
EnableKeyRotation: jsii.Boolean(true),
Description: jsii.String("KMS key for policy engine encryption"),
})
// Create policy engine with encryption
policyEngine := agentcore.NewPolicyEngine(this, jsii.String("EncryptedEngine"), &PolicyEngineProps{
PolicyEngineName: jsii.String("encrypted_engine"),
Description: jsii.String("Policy engine with KMS encryption"),
KmsKey: policyKey,
})
Importing Existing PolicyEngine
Import an existing policy engine from its ARN:
const importedEngine = agentcore.PolicyEngine.fromPolicyEngineAttributes(
this,
"ImportedEngine",
{
policyEngineArn: "policy-engine-arn",
kmsKeyArn: "kms-arn",
}
);
// Use the imported engine
const policy = new agentcore.Policy(this, "PolicyForImportedEngine", {
policyEngine: importedEngine,
statement: agentcore.PolicyStatement.fromCedar("permit(principal, action, resource);"),
});
imported_engine = agentcore.PolicyEngine.from_policy_engine_attributes(self, "ImportedEngine",
policy_engine_arn="policy-engine-arn",
kms_key_arn="kms-arn"
)
# Use the imported engine
policy = agentcore.Policy(self, "PolicyForImportedEngine",
policy_engine=imported_engine,
statement=agentcore.PolicyStatement.from_cedar("permit(principal, action, resource);")
)
IPolicyEngine importedEngine = PolicyEngine.fromPolicyEngineAttributes(this, "ImportedEngine", PolicyEngineAttributes.builder()
.policyEngineArn("policy-engine-arn")
.kmsKeyArn("kms-arn")
.build());
// Use the imported engine
Policy policy = Policy.Builder.create(this, "PolicyForImportedEngine")
.policyEngine(importedEngine)
.statement(PolicyStatement.fromCedar("permit(principal, action, resource);"))
.build();
var importedEngine = PolicyEngine.FromPolicyEngineAttributes(this, "ImportedEngine", new PolicyEngineAttributes {
PolicyEngineArn = "policy-engine-arn",
KmsKeyArn = "kms-arn"
});
// Use the imported engine
var policy = new Policy(this, "PolicyForImportedEngine", new PolicyProps {
PolicyEngine = importedEngine,
Statement = PolicyStatement.FromCedar("permit(principal, action, resource);")
});
importedEngine := agentcore.PolicyEngine_FromPolicyEngineAttributes(this, jsii.String("ImportedEngine"), &PolicyEngineAttributes{
PolicyEngineArn: jsii.String("policy-engine-arn"),
KmsKeyArn: jsii.String("kms-arn"),
})
// Use the imported engine
policy := agentcore.NewPolicy(this, jsii.String("PolicyForImportedEngine"), &PolicyProps{
PolicyEngine: importedEngine,
Statement: agentcore.PolicyStatement_FromCedar(jsii.String("permit(principal, action, resource);")),
})
Importing Existing Policy
Import an existing policy from its ARN:
const importedEngine = agentcore.PolicyEngine.fromPolicyEngineAttributes(
this,
"ImportedEngine",
{
policyEngineArn: "policy-engine/my-engine-id",
}
);
const importedPolicy = agentcore.Policy.fromPolicyAttributes(
this,
"ImportedPolicy",
{
policyArn: "my-policy-arn",
policyEngine: importedEngine,
}
);
// Grant permissions to the imported policy
const role = new iam.Role(this, "PolicyRole", {
assumedBy: new iam.ServicePrincipal("lambda.amazonaws.com"),
});
importedPolicy.grantRead(role);
imported_engine = agentcore.PolicyEngine.from_policy_engine_attributes(self, "ImportedEngine",
policy_engine_arn="policy-engine/my-engine-id"
)
imported_policy = agentcore.Policy.from_policy_attributes(self, "ImportedPolicy",
policy_arn="my-policy-arn",
policy_engine=imported_engine
)
# Grant permissions to the imported policy
role = iam.Role(self, "PolicyRole",
assumed_by=iam.ServicePrincipal("lambda.amazonaws.com")
)
imported_policy.grant_read(role)
IPolicyEngine importedEngine = PolicyEngine.fromPolicyEngineAttributes(this, "ImportedEngine", PolicyEngineAttributes.builder()
.policyEngineArn("policy-engine/my-engine-id")
.build());
IPolicy importedPolicy = Policy.fromPolicyAttributes(this, "ImportedPolicy", PolicyAttributes.builder()
.policyArn("my-policy-arn")
.policyEngine(importedEngine)
.build());
// Grant permissions to the imported policy
Role role = Role.Builder.create(this, "PolicyRole")
.assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
.build();
importedPolicy.grantRead(role);
var importedEngine = PolicyEngine.FromPolicyEngineAttributes(this, "ImportedEngine", new PolicyEngineAttributes {
PolicyEngineArn = "policy-engine/my-engine-id"
});
var importedPolicy = Policy.FromPolicyAttributes(this, "ImportedPolicy", new PolicyAttributes {
PolicyArn = "my-policy-arn",
PolicyEngine = importedEngine
});
// Grant permissions to the imported policy
var role = new Role(this, "PolicyRole", new RoleProps {
AssumedBy = new ServicePrincipal("lambda.amazonaws.com")
});
importedPolicy.GrantRead(role);
importedEngine := agentcore.PolicyEngine_FromPolicyEngineAttributes(this, jsii.String("ImportedEngine"), &PolicyEngineAttributes{
PolicyEngineArn: jsii.String("policy-engine/my-engine-id"),
})
importedPolicy := agentcore.Policy_FromPolicyAttributes(this, jsii.String("ImportedPolicy"), &PolicyAttributes{
PolicyArn: jsii.String("my-policy-arn"),
PolicyEngine: importedEngine,
})
// Grant permissions to the imported policy
role := iam.NewRole(this, jsii.String("PolicyRole"), &RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("lambda.amazonaws.com")),
})
importedPolicy.GrantRead(role)
PolicyEngine IAM Permissions
Grant various levels of access to policy engines:
const policyEngine = new agentcore.PolicyEngine(this, "MyEngine", {
policyEngineName: "my_engine",
});
const lambdaRole = new iam.Role(this, "LambdaRole", {
assumedBy: new iam.ServicePrincipal("lambda.amazonaws.com"),
});
// Grant read permissions
policyEngine.grantRead(lambdaRole);
// Grant evaluation permissions
policyEngine.grantEvaluate(lambdaRole);
policy_engine = agentcore.PolicyEngine(self, "MyEngine",
policy_engine_name="my_engine"
)
lambda_role = iam.Role(self, "LambdaRole",
assumed_by=iam.ServicePrincipal("lambda.amazonaws.com")
)
# Grant read permissions
policy_engine.grant_read(lambda_role)
# Grant evaluation permissions
policy_engine.grant_evaluate(lambda_role)
PolicyEngine policyEngine = PolicyEngine.Builder.create(this, "MyEngine")
.policyEngineName("my_engine")
.build();
Role lambdaRole = Role.Builder.create(this, "LambdaRole")
.assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
.build();
// Grant read permissions
policyEngine.grantRead(lambdaRole);
// Grant evaluation permissions
policyEngine.grantEvaluate(lambdaRole);
var policyEngine = new PolicyEngine(this, "MyEngine", new PolicyEngineProps {
PolicyEngineName = "my_engine"
});
var lambdaRole = new Role(this, "LambdaRole", new RoleProps {
AssumedBy = new ServicePrincipal("lambda.amazonaws.com")
});
// Grant read permissions
policyEngine.GrantRead(lambdaRole);
// Grant evaluation permissions
policyEngine.GrantEvaluate(lambdaRole);
policyEngine := agentcore.NewPolicyEngine(this, jsii.String("MyEngine"), &PolicyEngineProps{
PolicyEngineName: jsii.String("my_engine"),
})
lambdaRole := iam.NewRole(this, jsii.String("LambdaRole"), &RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("lambda.amazonaws.com")),
})
// Grant read permissions
policyEngine.GrantRead(lambdaRole)
// Grant evaluation permissions
policyEngine.GrantEvaluate(lambdaRole)
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:
- CloudWatch Transaction Search enabled — this creates the
aws/spanslog group required by the evaluation service. See Enable Transaction Search. - AWS Distro for OpenTelemetry (ADOT) SDK instrumenting your agent to emit traces.
For full details, see AgentCore Evaluations Prerequisites.
Online Evaluation Properties
| Name | Type | Required | Description |
|---|---|---|---|
onlineEvaluationConfigName | 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 |
dataSource | DataSourceConfig | Yes | The data source configuration specifying where to read agent traces from |
executionRole | 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 |
samplingPercentage | 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 |
sessionTimeout | 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:
const evaluation = new agentcore.OnlineEvaluationConfig(this, 'MyEvaluation', {
onlineEvaluationConfigName: 'my_evaluation',
evaluators: [
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.HELPFULNESS),
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.CORRECTNESS),
],
dataSource: agentcore.DataSourceConfig.fromCloudWatchLogs({
logGroupNames: ['/aws/bedrock-agentcore/my-agent'],
serviceNames: ['my-agent.default'],
}),
});
evaluation = agentcore.OnlineEvaluationConfig(self, "MyEvaluation",
online_evaluation_config_name="my_evaluation",
evaluators=[
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.HELPFULNESS),
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.CORRECTNESS)
],
data_source=agentcore.DataSourceConfig.from_cloud_watch_logs(
log_group_names=["/aws/bedrock-agentcore/my-agent"],
service_names=["my-agent.default"]
)
)
OnlineEvaluationConfig evaluation = OnlineEvaluationConfig.Builder.create(this, "MyEvaluation")
.onlineEvaluationConfigName("my_evaluation")
.evaluators(List.of(EvaluatorSelector.builtin(BuiltinEvaluator.HELPFULNESS), EvaluatorSelector.builtin(BuiltinEvaluator.CORRECTNESS)))
.dataSource(DataSourceConfig.fromCloudWatchLogs(CloudWatchLogsDataSourceConfig.builder()
.logGroupNames(List.of("/aws/bedrock-agentcore/my-agent"))
.serviceNames(List.of("my-agent.default"))
.build()))
.build();
var evaluation = new OnlineEvaluationConfig(this, "MyEvaluation", new OnlineEvaluationConfigProps {
OnlineEvaluationConfigName = "my_evaluation",
Evaluators = new [] { EvaluatorSelector.Builtin(BuiltinEvaluator.HELPFULNESS), EvaluatorSelector.Builtin(BuiltinEvaluator.CORRECTNESS) },
DataSource = DataSourceConfig.FromCloudWatchLogs(new CloudWatchLogsDataSourceConfig {
LogGroupNames = new [] { "/aws/bedrock-agentcore/my-agent" },
ServiceNames = new [] { "my-agent.default" }
})
});
evaluation := agentcore.NewOnlineEvaluationConfig(this, jsii.String("MyEvaluation"), &OnlineEvaluationConfigProps{
OnlineEvaluationConfigName: jsii.String("my_evaluation"),
Evaluators: []EvaluatorSelector{
agentcore.EvaluatorSelector_Builtin(agentcore.BuiltinEvaluator_HELPFULNESS()),
agentcore.EvaluatorSelector_*Builtin(agentcore.BuiltinEvaluator_CORRECTNESS()),
},
DataSource: agentcore.DataSourceConfig_FromCloudWatchLogs(&CloudWatchLogsDataSourceConfig{
LogGroupNames: []*string{
jsii.String("/aws/bedrock-agentcore/my-agent"),
},
ServiceNames: []*string{
jsii.String("my-agent.default"),
},
}),
})
Built-in Evaluators
Amazon Bedrock AgentCore provides 13 built-in evaluators that assess different aspects of agent performance:
Session-Level Evaluators:
GOAL_SUCCESS_RATE- Evaluates whether the conversation successfully meets the user's goals
Trace-Level Evaluators:
HELPFULNESS- How useful and valuable the agent's response isCORRECTNESS- Whether the information is factually accurateFAITHFULNESS- Whether the response is faithful to the provided contextHARMFULNESS- Whether the response contains harmful contentSTEREOTYPING- Detects content that makes generalizations about individuals or groupsREFUSAL- Whether the agent appropriately refuses harmful requestsCOHERENCE- Whether the response is logically coherentRESPONSE_RELEVANCE- Whether the response appropriately addresses the user's queryCONCISENESS- Whether the response is appropriately conciseINSTRUCTION_FOLLOWING- How well the agent follows system instructions
Tool Call-Level Evaluators:
TOOL_SELECTION_ACCURACY- Whether the agent selected the appropriate toolTOOL_PARAMETER_ACCURACY- How accurately the agent extracts parameters from user queries
const evaluation = new agentcore.OnlineEvaluationConfig(this, 'ComprehensiveEval', {
onlineEvaluationConfigName: 'comprehensive_evaluation',
evaluators: [
// Session level
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.GOAL_SUCCESS_RATE),
// Trace level - quality
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.HELPFULNESS),
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.CORRECTNESS),
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.COHERENCE),
// Trace level - safety
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.HARMFULNESS),
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.STEREOTYPING),
// Tool call level
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.TOOL_SELECTION_ACCURACY),
],
dataSource: agentcore.DataSourceConfig.fromCloudWatchLogs({
logGroupNames: ['/aws/bedrock-agentcore/my-agent'],
serviceNames: ['my-agent.default'],
}),
});
evaluation = agentcore.OnlineEvaluationConfig(self, "ComprehensiveEval",
online_evaluation_config_name="comprehensive_evaluation",
evaluators=[
# Session level
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.GOAL_SUCCESS_RATE),
# Trace level - quality
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.HELPFULNESS),
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.CORRECTNESS),
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.COHERENCE),
# Trace level - safety
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.HARMFULNESS),
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.STEREOTYPING),
# Tool call level
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.TOOL_SELECTION_ACCURACY)
],
data_source=agentcore.DataSourceConfig.from_cloud_watch_logs(
log_group_names=["/aws/bedrock-agentcore/my-agent"],
service_names=["my-agent.default"]
)
)
OnlineEvaluationConfig evaluation = OnlineEvaluationConfig.Builder.create(this, "ComprehensiveEval")
.onlineEvaluationConfigName("comprehensive_evaluation")
.evaluators(List.of(EvaluatorSelector.builtin(BuiltinEvaluator.GOAL_SUCCESS_RATE), EvaluatorSelector.builtin(BuiltinEvaluator.HELPFULNESS), EvaluatorSelector.builtin(BuiltinEvaluator.CORRECTNESS), EvaluatorSelector.builtin(BuiltinEvaluator.COHERENCE), EvaluatorSelector.builtin(BuiltinEvaluator.HARMFULNESS), EvaluatorSelector.builtin(BuiltinEvaluator.STEREOTYPING), EvaluatorSelector.builtin(BuiltinEvaluator.TOOL_SELECTION_ACCURACY)))
.dataSource(DataSourceConfig.fromCloudWatchLogs(CloudWatchLogsDataSourceConfig.builder()
.logGroupNames(List.of("/aws/bedrock-agentcore/my-agent"))
.serviceNames(List.of("my-agent.default"))
.build()))
.build();
var evaluation = new OnlineEvaluationConfig(this, "ComprehensiveEval", new OnlineEvaluationConfigProps {
OnlineEvaluationConfigName = "comprehensive_evaluation",
Evaluators = new [] { EvaluatorSelector.Builtin(BuiltinEvaluator.GOAL_SUCCESS_RATE), EvaluatorSelector.Builtin(BuiltinEvaluator.HELPFULNESS), EvaluatorSelector.Builtin(BuiltinEvaluator.CORRECTNESS), EvaluatorSelector.Builtin(BuiltinEvaluator.COHERENCE), EvaluatorSelector.Builtin(BuiltinEvaluator.HARMFULNESS), EvaluatorSelector.Builtin(BuiltinEvaluator.STEREOTYPING), EvaluatorSelector.Builtin(BuiltinEvaluator.TOOL_SELECTION_ACCURACY) },
DataSource = DataSourceConfig.FromCloudWatchLogs(new CloudWatchLogsDataSourceConfig {
LogGroupNames = new [] { "/aws/bedrock-agentcore/my-agent" },
ServiceNames = new [] { "my-agent.default" }
})
});
evaluation := agentcore.NewOnlineEvaluationConfig(this, jsii.String("ComprehensiveEval"), &OnlineEvaluationConfigProps{
OnlineEvaluationConfigName: jsii.String("comprehensive_evaluation"),
Evaluators: []EvaluatorSelector{
agentcore.EvaluatorSelector_Builtin(agentcore.BuiltinEvaluator_GOAL_SUCCESS_RATE()),
agentcore.EvaluatorSelector_*Builtin(agentcore.BuiltinEvaluator_HELPFULNESS()),
agentcore.EvaluatorSelector_*Builtin(agentcore.BuiltinEvaluator_CORRECTNESS()),
agentcore.EvaluatorSelector_*Builtin(agentcore.BuiltinEvaluator_COHERENCE()),
agentcore.EvaluatorSelector_*Builtin(agentcore.BuiltinEvaluator_HARMFULNESS()),
agentcore.EvaluatorSelector_*Builtin(agentcore.BuiltinEvaluator_STEREOTYPING()),
agentcore.EvaluatorSelector_*Builtin(agentcore.BuiltinEvaluator_TOOL_SELECTION_ACCURACY()),
},
DataSource: agentcore.DataSourceConfig_FromCloudWatchLogs(&CloudWatchLogsDataSourceConfig{
LogGroupNames: []*string{
jsii.String("/aws/bedrock-agentcore/my-agent"),
},
ServiceNames: []*string{
jsii.String("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:
- LLM-as-a-Judge: Uses a foundation model with custom instructions and a rating scale to assess agent performance.
- Code-based: Uses a Lambda function for custom evaluation logic.
| Property | Type | Required | Description |
|---|---|---|---|
evaluatorName | string | Yes | Name of the evaluator. Must start with a letter, a-z, A-Z, 0-9, _ only. Maximum 48 characters |
evaluatorConfig | 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
const categoricalEvaluator = new agentcore.Evaluator(this, 'CategoricalEvaluator', {
evaluatorName: 'domain_accuracy_evaluator',
level: agentcore.EvaluationLevel.SESSION,
description: 'Evaluates domain-specific accuracy of agent responses',
evaluatorConfig: agentcore.EvaluatorConfig.llmAsAJudge({
instructions: 'Evaluate whether the agent response is accurate within the healthcare domain.',
modelId: 'us.anthropic.claude-sonnet-4-6',
ratingScale: agentcore.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
const numericalEvaluator = new agentcore.Evaluator(this, 'NumericalEvaluator', {
evaluatorName: 'response_quality_evaluator',
level: agentcore.EvaluationLevel.TRACE,
evaluatorConfig: agentcore.EvaluatorConfig.llmAsAJudge({
instructions: 'Rate the overall quality of the agent response on a scale of 1 to 5.',
modelId: 'us.anthropic.claude-sonnet-4-6',
ratingScale: agentcore.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 },
]),
inferenceConfig: {
maxTokens: 1024,
temperature: 0.1,
},
}),
});
# LLM-as-a-Judge with categorical rating scale
categorical_evaluator = agentcore.Evaluator(self, "CategoricalEvaluator",
evaluator_name="domain_accuracy_evaluator",
level=agentcore.EvaluationLevel.SESSION,
description="Evaluates domain-specific accuracy of agent responses",
evaluator_config=agentcore.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=agentcore.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 = agentcore.Evaluator(self, "NumericalEvaluator",
evaluator_name="response_quality_evaluator",
level=agentcore.EvaluationLevel.TRACE,
evaluator_config=agentcore.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=agentcore.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=agentcore.EvaluatorInferenceConfig(
max_tokens=1024,
temperature=0.1
)
)
)
// LLM-as-a-Judge with categorical rating scale
Evaluator categoricalEvaluator = Evaluator.Builder.create(this, "CategoricalEvaluator")
.evaluatorName("domain_accuracy_evaluator")
.level(EvaluationLevel.SESSION)
.description("Evaluates domain-specific accuracy of agent responses")
.evaluatorConfig(EvaluatorConfig.llmAsAJudge(LlmAsAJudgeOptions.builder()
.instructions("Evaluate whether the agent response is accurate within the healthcare domain.")
.modelId("us.anthropic.claude-sonnet-4-6")
.ratingScale(EvaluatorRatingScale.categorical(List.of(CategoricalRatingOption.builder().label("Accurate").definition("The response contains factually correct healthcare information.").build(), CategoricalRatingOption.builder().label("Inaccurate").definition("The response contains incorrect or misleading healthcare information.").build())))
.build()))
.build();
// LLM-as-a-Judge with numerical rating scale and inference config
Evaluator numericalEvaluator = Evaluator.Builder.create(this, "NumericalEvaluator")
.evaluatorName("response_quality_evaluator")
.level(EvaluationLevel.TRACE)
.evaluatorConfig(EvaluatorConfig.llmAsAJudge(LlmAsAJudgeOptions.builder()
.instructions("Rate the overall quality of the agent response on a scale of 1 to 5.")
.modelId("us.anthropic.claude-sonnet-4-6")
.ratingScale(EvaluatorRatingScale.numerical(List.of(NumericalRatingOption.builder().label("Poor").definition("Inadequate response.").value(1).build(), NumericalRatingOption.builder().label("Below Average").definition("Partially addresses the query.").value(2).build(), NumericalRatingOption.builder().label("Average").definition("Adequately addresses the query.").value(3).build(), NumericalRatingOption.builder().label("Good").definition("Well-structured and accurate response.").value(4).build(), NumericalRatingOption.builder().label("Excellent").definition("Outstanding response exceeding expectations.").value(5).build())))
.inferenceConfig(EvaluatorInferenceConfig.builder()
.maxTokens(1024)
.temperature(0.1)
.build())
.build()))
.build();
// LLM-as-a-Judge with categorical rating scale
var categoricalEvaluator = new Evaluator(this, "CategoricalEvaluator", new EvaluatorProps {
EvaluatorName = "domain_accuracy_evaluator",
Level = EvaluationLevel.SESSION,
Description = "Evaluates domain-specific accuracy of agent responses",
EvaluatorConfig = EvaluatorConfig.LlmAsAJudge(new LlmAsAJudgeOptions {
Instructions = "Evaluate whether the agent response is accurate within the healthcare domain.",
ModelId = "us.anthropic.claude-sonnet-4-6",
RatingScale = EvaluatorRatingScale.Categorical(new [] { new CategoricalRatingOption { Label = "Accurate", Definition = "The response contains factually correct healthcare information." }, new CategoricalRatingOption { Label = "Inaccurate", Definition = "The response contains incorrect or misleading healthcare information." } })
})
});
// LLM-as-a-Judge with numerical rating scale and inference config
var numericalEvaluator = new Evaluator(this, "NumericalEvaluator", new EvaluatorProps {
EvaluatorName = "response_quality_evaluator",
Level = EvaluationLevel.TRACE,
EvaluatorConfig = EvaluatorConfig.LlmAsAJudge(new LlmAsAJudgeOptions {
Instructions = "Rate the overall quality of the agent response on a scale of 1 to 5.",
ModelId = "us.anthropic.claude-sonnet-4-6",
RatingScale = EvaluatorRatingScale.Numerical(new [] { new NumericalRatingOption { Label = "Poor", Definition = "Inadequate response.", Value = 1 }, new NumericalRatingOption { Label = "Below Average", Definition = "Partially addresses the query.", Value = 2 }, new NumericalRatingOption { Label = "Average", Definition = "Adequately addresses the query.", Value = 3 }, new NumericalRatingOption { Label = "Good", Definition = "Well-structured and accurate response.", Value = 4 }, new NumericalRatingOption { Label = "Excellent", Definition = "Outstanding response exceeding expectations.", Value = 5 } }),
InferenceConfig = new EvaluatorInferenceConfig {
MaxTokens = 1024,
Temperature = 0.1
}
})
});
// LLM-as-a-Judge with categorical rating scale
categoricalEvaluator := agentcore.NewEvaluator(this, jsii.String("CategoricalEvaluator"), &EvaluatorProps{
EvaluatorName: jsii.String("domain_accuracy_evaluator"),
Level: agentcore.EvaluationLevel_SESSION(),
Description: jsii.String("Evaluates domain-specific accuracy of agent responses"),
EvaluatorConfig: agentcore.EvaluatorConfig_LlmAsAJudge(&LlmAsAJudgeOptions{
Instructions: jsii.String("Evaluate whether the agent response is accurate within the healthcare domain."),
ModelId: jsii.String("us.anthropic.claude-sonnet-4-6"),
RatingScale: agentcore.EvaluatorRatingScale_Categorical([]CategoricalRatingOption{
&CategoricalRatingOption{
Label: jsii.String("Accurate"),
Definition: jsii.String("The response contains factually correct healthcare information."),
},
&CategoricalRatingOption{
Label: jsii.String("Inaccurate"),
Definition: jsii.String("The response contains incorrect or misleading healthcare information."),
},
}),
}),
})
// LLM-as-a-Judge with numerical rating scale and inference config
numericalEvaluator := agentcore.NewEvaluator(this, jsii.String("NumericalEvaluator"), &EvaluatorProps{
EvaluatorName: jsii.String("response_quality_evaluator"),
Level: agentcore.EvaluationLevel_TRACE(),
EvaluatorConfig: agentcore.EvaluatorConfig_*LlmAsAJudge(&LlmAsAJudgeOptions{
Instructions: jsii.String("Rate the overall quality of the agent response on a scale of 1 to 5."),
ModelId: jsii.String("us.anthropic.claude-sonnet-4-6"),
RatingScale: agentcore.EvaluatorRatingScale_Numerical([]NumericalRatingOption{
&NumericalRatingOption{
Label: jsii.String("Poor"),
Definition: jsii.String("Inadequate response."),
Value: jsii.Number(1),
},
&NumericalRatingOption{
Label: jsii.String("Below Average"),
Definition: jsii.String("Partially addresses the query."),
Value: jsii.Number(2),
},
&NumericalRatingOption{
Label: jsii.String("Average"),
Definition: jsii.String("Adequately addresses the query."),
Value: jsii.Number(3),
},
&NumericalRatingOption{
Label: jsii.String("Good"),
Definition: jsii.String("Well-structured and accurate response."),
Value: jsii.Number(4),
},
&NumericalRatingOption{
Label: jsii.String("Excellent"),
Definition: jsii.String("Outstanding response exceeding expectations."),
Value: jsii.Number(5),
},
}),
InferenceConfig: &EvaluatorInferenceConfig{
MaxTokens: jsii.Number(1024),
Temperature: jsii.Number(0.1),
},
}),
})
The modelId 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:
declare const evalFunction: lambda.IFunction;
const codeEvaluator = new agentcore.Evaluator(this, 'CodeEvaluator', {
evaluatorName: 'custom_code_evaluator',
level: agentcore.EvaluationLevel.TOOL_CALL,
description: 'Evaluates tool call accuracy using custom logic',
evaluatorConfig: agentcore.EvaluatorConfig.codeBased({
lambdaFunction: evalFunction,
timeout: cdk.Duration.seconds(30),
}),
});
# eval_function: lambda.IFunction
code_evaluator = agentcore.Evaluator(self, "CodeEvaluator",
evaluator_name="custom_code_evaluator",
level=agentcore.EvaluationLevel.TOOL_CALL,
description="Evaluates tool call accuracy using custom logic",
evaluator_config=agentcore.EvaluatorConfig.code_based(
lambda_function=eval_function,
timeout=cdk.Duration.seconds(30)
)
)
IFunction evalFunction;
Evaluator codeEvaluator = Evaluator.Builder.create(this, "CodeEvaluator")
.evaluatorName("custom_code_evaluator")
.level(EvaluationLevel.TOOL_CALL)
.description("Evaluates tool call accuracy using custom logic")
.evaluatorConfig(EvaluatorConfig.codeBased(CodeBasedOptions.builder()
.lambdaFunction(evalFunction)
.timeout(Duration.seconds(30))
.build()))
.build();
IFunction evalFunction;
var codeEvaluator = new Evaluator(this, "CodeEvaluator", new EvaluatorProps {
EvaluatorName = "custom_code_evaluator",
Level = EvaluationLevel.TOOL_CALL,
Description = "Evaluates tool call accuracy using custom logic",
EvaluatorConfig = EvaluatorConfig.CodeBased(new CodeBasedOptions {
LambdaFunction = evalFunction,
Timeout = Duration.Seconds(30)
})
});
var evalFunction IFunction
codeEvaluator := agentcore.NewEvaluator(this, jsii.String("CodeEvaluator"), &EvaluatorProps{
EvaluatorName: jsii.String("custom_code_evaluator"),
Level: agentcore.EvaluationLevel_TOOL_CALL(),
Description: jsii.String("Evaluates tool call accuracy using custom logic"),
EvaluatorConfig: agentcore.EvaluatorConfig_CodeBased(&CodeBasedOptions{
LambdaFunction: evalFunction,
Timeout: cdk.Duration_Seconds(jsii.Number(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:
declare const customEvaluator: agentcore.Evaluator;
const evaluation = new agentcore.OnlineEvaluationConfig(this, 'MixedEvaluation', {
onlineEvaluationConfigName: 'mixed_evaluation',
evaluators: [
// Built-in evaluators
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.HELPFULNESS),
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.CORRECTNESS),
// Custom evaluator
agentcore.EvaluatorSelector.custom(customEvaluator),
],
dataSource: agentcore.DataSourceConfig.fromCloudWatchLogs({
logGroupNames: ['/aws/bedrock-agentcore/my-agent'],
serviceNames: ['my-agent.default'],
}),
});
# custom_evaluator: agentcore.Evaluator
evaluation = agentcore.OnlineEvaluationConfig(self, "MixedEvaluation",
online_evaluation_config_name="mixed_evaluation",
evaluators=[
# Built-in evaluators
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.HELPFULNESS),
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.CORRECTNESS),
# Custom evaluator
agentcore.EvaluatorSelector.custom(custom_evaluator)
],
data_source=agentcore.DataSourceConfig.from_cloud_watch_logs(
log_group_names=["/aws/bedrock-agentcore/my-agent"],
service_names=["my-agent.default"]
)
)
Evaluator customEvaluator;
OnlineEvaluationConfig evaluation = OnlineEvaluationConfig.Builder.create(this, "MixedEvaluation")
.onlineEvaluationConfigName("mixed_evaluation")
.evaluators(List.of(EvaluatorSelector.builtin(BuiltinEvaluator.HELPFULNESS), EvaluatorSelector.builtin(BuiltinEvaluator.CORRECTNESS), EvaluatorSelector.custom(customEvaluator)))
.dataSource(DataSourceConfig.fromCloudWatchLogs(CloudWatchLogsDataSourceConfig.builder()
.logGroupNames(List.of("/aws/bedrock-agentcore/my-agent"))
.serviceNames(List.of("my-agent.default"))
.build()))
.build();
Evaluator customEvaluator;
var evaluation = new OnlineEvaluationConfig(this, "MixedEvaluation", new OnlineEvaluationConfigProps {
OnlineEvaluationConfigName = "mixed_evaluation",
Evaluators = new [] { EvaluatorSelector.Builtin(BuiltinEvaluator.HELPFULNESS), EvaluatorSelector.Builtin(BuiltinEvaluator.CORRECTNESS), EvaluatorSelector.Custom(customEvaluator) },
DataSource = DataSourceConfig.FromCloudWatchLogs(new CloudWatchLogsDataSourceConfig {
LogGroupNames = new [] { "/aws/bedrock-agentcore/my-agent" },
ServiceNames = new [] { "my-agent.default" }
})
});
var customEvaluator Evaluator
evaluation := agentcore.NewOnlineEvaluationConfig(this, jsii.String("MixedEvaluation"), &OnlineEvaluationConfigProps{
OnlineEvaluationConfigName: jsii.String("mixed_evaluation"),
Evaluators: []EvaluatorSelector{
agentcore.EvaluatorSelector_Builtin(agentcore.BuiltinEvaluator_HELPFULNESS()),
agentcore.EvaluatorSelector_*Builtin(agentcore.BuiltinEvaluator_CORRECTNESS()),
agentcore.EvaluatorSelector_Custom(customEvaluator),
},
DataSource: agentcore.DataSourceConfig_FromCloudWatchLogs(&CloudWatchLogsDataSourceConfig{
LogGroupNames: []*string{
jsii.String("/aws/bedrock-agentcore/my-agent"),
},
ServiceNames: []*string{
jsii.String("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 fromAgentRuntimeEndpoint() which automatically derives the CloudWatch log group and service name:
const repository = new ecr.Repository(this, 'TestRepository', {
repositoryName: 'test-agent-runtime',
});
const runtime = new agentcore.Runtime(this, 'MyRuntime', {
runtimeName: 'my_agent',
agentRuntimeArtifact: agentcore.AgentRuntimeArtifact.fromEcrRepository(repository, 'v1.0.0'),
});
// Using default endpoint (simplest)
const evaluation = new agentcore.OnlineEvaluationConfig(this, 'RuntimeEval', {
onlineEvaluationConfigName: 'runtime_evaluation',
evaluators: [
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.HELPFULNESS),
],
dataSource: agentcore.DataSourceConfig.fromAgentRuntimeEndpoint(runtime),
});
repository = ecr.Repository(self, "TestRepository",
repository_name="test-agent-runtime"
)
runtime = agentcore.Runtime(self, "MyRuntime",
runtime_name="my_agent",
agent_runtime_artifact=agentcore.AgentRuntimeArtifact.from_ecr_repository(repository, "v1.0.0")
)
# Using default endpoint (simplest)
evaluation = agentcore.OnlineEvaluationConfig(self, "RuntimeEval",
online_evaluation_config_name="runtime_evaluation",
evaluators=[
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.HELPFULNESS)
],
data_source=agentcore.DataSourceConfig.from_agent_runtime_endpoint(runtime)
)
Repository repository = Repository.Builder.create(this, "TestRepository")
.repositoryName("test-agent-runtime")
.build();
Runtime runtime = Runtime.Builder.create(this, "MyRuntime")
.runtimeName("my_agent")
.agentRuntimeArtifact(AgentRuntimeArtifact.fromEcrRepository(repository, "v1.0.0"))
.build();
// Using default endpoint (simplest)
OnlineEvaluationConfig evaluation = OnlineEvaluationConfig.Builder.create(this, "RuntimeEval")
.onlineEvaluationConfigName("runtime_evaluation")
.evaluators(List.of(EvaluatorSelector.builtin(BuiltinEvaluator.HELPFULNESS)))
.dataSource(DataSourceConfig.fromAgentRuntimeEndpoint(runtime))
.build();
var repository = new Repository(this, "TestRepository", new RepositoryProps {
RepositoryName = "test-agent-runtime"
});
var runtime = new Runtime(this, "MyRuntime", new RuntimeProps {
RuntimeName = "my_agent",
AgentRuntimeArtifact = AgentRuntimeArtifact.FromEcrRepository(repository, "v1.0.0")
});
// Using default endpoint (simplest)
var evaluation = new OnlineEvaluationConfig(this, "RuntimeEval", new OnlineEvaluationConfigProps {
OnlineEvaluationConfigName = "runtime_evaluation",
Evaluators = new [] { EvaluatorSelector.Builtin(BuiltinEvaluator.HELPFULNESS) },
DataSource = DataSourceConfig.FromAgentRuntimeEndpoint(runtime)
});
repository := ecr.NewRepository(this, jsii.String("TestRepository"), &RepositoryProps{
RepositoryName: jsii.String("test-agent-runtime"),
})
runtime := agentcore.NewRuntime(this, jsii.String("MyRuntime"), &RuntimeProps{
RuntimeName: jsii.String("my_agent"),
AgentRuntimeArtifact: agentcore.AgentRuntimeArtifact_FromEcrRepository(repository, jsii.String("v1.0.0")),
})
// Using default endpoint (simplest)
evaluation := agentcore.NewOnlineEvaluationConfig(this, jsii.String("RuntimeEval"), &OnlineEvaluationConfigProps{
OnlineEvaluationConfigName: jsii.String("runtime_evaluation"),
Evaluators: []EvaluatorSelector{
agentcore.EvaluatorSelector_Builtin(agentcore.BuiltinEvaluator_HELPFULNESS()),
},
DataSource: agentcore.DataSourceConfig_FromAgentRuntimeEndpoint(runtime),
})
You can also specify a specific endpoint:
declare const runtime: agentcore.Runtime;
// Using a specific endpoint construct
const prodEndpoint = runtime.addEndpoint('PROD');
const evaluation = new agentcore.OnlineEvaluationConfig(this, 'ProdEval', {
onlineEvaluationConfigName: 'prod_evaluation',
evaluators: [
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.CORRECTNESS),
],
dataSource: agentcore.DataSourceConfig.fromAgentRuntimeEndpoint(runtime, prodEndpoint),
});
// Or using endpoint name as string
const stagingEval = new agentcore.OnlineEvaluationConfig(this, 'StagingEval', {
onlineEvaluationConfigName: 'staging_evaluation',
evaluators: [
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.CORRECTNESS),
],
dataSource: agentcore.DataSourceConfig.fromAgentRuntimeEndpointName(runtime, 'STAGING'),
});
# runtime: agentcore.Runtime
# Using a specific endpoint construct
prod_endpoint = runtime.add_endpoint("PROD")
evaluation = agentcore.OnlineEvaluationConfig(self, "ProdEval",
online_evaluation_config_name="prod_evaluation",
evaluators=[
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.CORRECTNESS)
],
data_source=agentcore.DataSourceConfig.from_agent_runtime_endpoint(runtime, prod_endpoint)
)
# Or using endpoint name as string
staging_eval = agentcore.OnlineEvaluationConfig(self, "StagingEval",
online_evaluation_config_name="staging_evaluation",
evaluators=[
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.CORRECTNESS)
],
data_source=agentcore.DataSourceConfig.from_agent_runtime_endpoint_name(runtime, "STAGING")
)
Runtime runtime;
// Using a specific endpoint construct
RuntimeEndpoint prodEndpoint = runtime.addEndpoint("PROD");
OnlineEvaluationConfig evaluation = OnlineEvaluationConfig.Builder.create(this, "ProdEval")
.onlineEvaluationConfigName("prod_evaluation")
.evaluators(List.of(EvaluatorSelector.builtin(BuiltinEvaluator.CORRECTNESS)))
.dataSource(DataSourceConfig.fromAgentRuntimeEndpoint(runtime, prodEndpoint))
.build();
// Or using endpoint name as string
OnlineEvaluationConfig stagingEval = OnlineEvaluationConfig.Builder.create(this, "StagingEval")
.onlineEvaluationConfigName("staging_evaluation")
.evaluators(List.of(EvaluatorSelector.builtin(BuiltinEvaluator.CORRECTNESS)))
.dataSource(DataSourceConfig.fromAgentRuntimeEndpointName(runtime, "STAGING"))
.build();
Runtime runtime;
// Using a specific endpoint construct
var prodEndpoint = runtime.AddEndpoint("PROD");
var evaluation = new OnlineEvaluationConfig(this, "ProdEval", new OnlineEvaluationConfigProps {
OnlineEvaluationConfigName = "prod_evaluation",
Evaluators = new [] { EvaluatorSelector.Builtin(BuiltinEvaluator.CORRECTNESS) },
DataSource = DataSourceConfig.FromAgentRuntimeEndpoint(runtime, prodEndpoint)
});
// Or using endpoint name as string
var stagingEval = new OnlineEvaluationConfig(this, "StagingEval", new OnlineEvaluationConfigProps {
OnlineEvaluationConfigName = "staging_evaluation",
Evaluators = new [] { EvaluatorSelector.Builtin(BuiltinEvaluator.CORRECTNESS) },
DataSource = DataSourceConfig.FromAgentRuntimeEndpointName(runtime, "STAGING")
});
var runtime Runtime
// Using a specific endpoint construct
prodEndpoint := runtime.AddEndpoint(jsii.String("PROD"))
evaluation := agentcore.NewOnlineEvaluationConfig(this, jsii.String("ProdEval"), &OnlineEvaluationConfigProps{
OnlineEvaluationConfigName: jsii.String("prod_evaluation"),
Evaluators: []EvaluatorSelector{
agentcore.EvaluatorSelector_Builtin(agentcore.BuiltinEvaluator_CORRECTNESS()),
},
DataSource: agentcore.DataSourceConfig_FromAgentRuntimeEndpoint(runtime, prodEndpoint),
})
// Or using endpoint name as string
stagingEval := agentcore.NewOnlineEvaluationConfig(this, jsii.String("StagingEval"), &OnlineEvaluationConfigProps{
OnlineEvaluationConfigName: jsii.String("staging_evaluation"),
Evaluators: []EvaluatorSelector{
agentcore.EvaluatorSelector_*Builtin(agentcore.BuiltinEvaluator_CORRECTNESS()),
},
DataSource: agentcore.DataSourceConfig_FromAgentRuntimeEndpointName(runtime, jsii.String("STAGING")),
})
CloudWatch Logs Data Source:
For external agents or when you need to specify log groups directly:
const evaluation = new agentcore.OnlineEvaluationConfig(this, 'CloudWatchEval', {
onlineEvaluationConfigName: 'cloudwatch_evaluation',
evaluators: [
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.HELPFULNESS),
],
dataSource: agentcore.DataSourceConfig.fromCloudWatchLogs({
logGroupNames: [
'/aws/bedrock-agentcore/agent1',
'/aws/bedrock-agentcore/agent2',
],
serviceNames: ['agent1.default'],
}),
});
evaluation = agentcore.OnlineEvaluationConfig(self, "CloudWatchEval",
online_evaluation_config_name="cloudwatch_evaluation",
evaluators=[
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.HELPFULNESS)
],
data_source=agentcore.DataSourceConfig.from_cloud_watch_logs(
log_group_names=["/aws/bedrock-agentcore/agent1", "/aws/bedrock-agentcore/agent2"
],
service_names=["agent1.default"]
)
)
OnlineEvaluationConfig evaluation = OnlineEvaluationConfig.Builder.create(this, "CloudWatchEval")
.onlineEvaluationConfigName("cloudwatch_evaluation")
.evaluators(List.of(EvaluatorSelector.builtin(BuiltinEvaluator.HELPFULNESS)))
.dataSource(DataSourceConfig.fromCloudWatchLogs(CloudWatchLogsDataSourceConfig.builder()
.logGroupNames(List.of("/aws/bedrock-agentcore/agent1", "/aws/bedrock-agentcore/agent2"))
.serviceNames(List.of("agent1.default"))
.build()))
.build();
var evaluation = new OnlineEvaluationConfig(this, "CloudWatchEval", new OnlineEvaluationConfigProps {
OnlineEvaluationConfigName = "cloudwatch_evaluation",
Evaluators = new [] { EvaluatorSelector.Builtin(BuiltinEvaluator.HELPFULNESS) },
DataSource = DataSourceConfig.FromCloudWatchLogs(new CloudWatchLogsDataSourceConfig {
LogGroupNames = new [] { "/aws/bedrock-agentcore/agent1", "/aws/bedrock-agentcore/agent2" },
ServiceNames = new [] { "agent1.default" }
})
});
evaluation := agentcore.NewOnlineEvaluationConfig(this, jsii.String("CloudWatchEval"), &OnlineEvaluationConfigProps{
OnlineEvaluationConfigName: jsii.String("cloudwatch_evaluation"),
Evaluators: []EvaluatorSelector{
agentcore.EvaluatorSelector_Builtin(agentcore.BuiltinEvaluator_HELPFULNESS()),
},
DataSource: agentcore.DataSourceConfig_FromCloudWatchLogs(&CloudWatchLogsDataSourceConfig{
LogGroupNames: []*string{
jsii.String("/aws/bedrock-agentcore/agent1"),
jsii.String("/aws/bedrock-agentcore/agent2"),
},
ServiceNames: []*string{
jsii.String("agent1.default"),
},
}),
})
Sampling and Filtering
Configure sampling percentage and filters to control which traces are evaluated:
const evaluation = new agentcore.OnlineEvaluationConfig(this, 'FilteredEval', {
onlineEvaluationConfigName: 'filtered_evaluation',
evaluators: [
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.HELPFULNESS),
],
dataSource: agentcore.DataSourceConfig.fromCloudWatchLogs({
logGroupNames: ['/aws/bedrock-agentcore/my-agent'],
serviceNames: ['my-agent.default'],
}),
// Sample 25% of traces
samplingPercentage: 25,
// Only evaluate traces matching these filters
filters: [
{
key: 'user.region',
operator: agentcore.FilterOperator.EQUAL,
value: agentcore.FilterValue.string('us-east-1'),
},
{
key: 'session.duration',
operator: agentcore.FilterOperator.GREATER_THAN,
value: agentcore.FilterValue.number(60),
},
],
// Consider sessions complete after 30 minutes of inactivity
sessionTimeout: cdk.Duration.minutes(30),
});
evaluation = agentcore.OnlineEvaluationConfig(self, "FilteredEval",
online_evaluation_config_name="filtered_evaluation",
evaluators=[
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.HELPFULNESS)
],
data_source=agentcore.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=[agentcore.FilterConfig(
key="user.region",
operator=agentcore.FilterOperator.EQUAL,
value=agentcore.FilterValue.string("us-east-1")
), agentcore.FilterConfig(
key="session.duration",
operator=agentcore.FilterOperator.GREATER_THAN,
value=agentcore.FilterValue.number(60)
)
],
# Consider sessions complete after 30 minutes of inactivity
session_timeout=cdk.Duration.minutes(30)
)
OnlineEvaluationConfig evaluation = OnlineEvaluationConfig.Builder.create(this, "FilteredEval")
.onlineEvaluationConfigName("filtered_evaluation")
.evaluators(List.of(EvaluatorSelector.builtin(BuiltinEvaluator.HELPFULNESS)))
.dataSource(DataSourceConfig.fromCloudWatchLogs(CloudWatchLogsDataSourceConfig.builder()
.logGroupNames(List.of("/aws/bedrock-agentcore/my-agent"))
.serviceNames(List.of("my-agent.default"))
.build()))
// Sample 25% of traces
.samplingPercentage(25)
// Only evaluate traces matching these filters
.filters(List.of(FilterConfig.builder()
.key("user.region")
.operator(FilterOperator.EQUAL)
.value(FilterValue.string("us-east-1"))
.build(), FilterConfig.builder()
.key("session.duration")
.operator(FilterOperator.GREATER_THAN)
.value(FilterValue.number(60))
.build()))
// Consider sessions complete after 30 minutes of inactivity
.sessionTimeout(Duration.minutes(30))
.build();
var evaluation = new OnlineEvaluationConfig(this, "FilteredEval", new OnlineEvaluationConfigProps {
OnlineEvaluationConfigName = "filtered_evaluation",
Evaluators = new [] { EvaluatorSelector.Builtin(BuiltinEvaluator.HELPFULNESS) },
DataSource = DataSourceConfig.FromCloudWatchLogs(new CloudWatchLogsDataSourceConfig {
LogGroupNames = new [] { "/aws/bedrock-agentcore/my-agent" },
ServiceNames = new [] { "my-agent.default" }
}),
// Sample 25% of traces
SamplingPercentage = 25,
// Only evaluate traces matching these filters
Filters = new [] { new FilterConfig {
Key = "user.region",
Operator = FilterOperator.EQUAL,
Value = FilterValue.String("us-east-1")
}, new FilterConfig {
Key = "session.duration",
Operator = FilterOperator.GREATER_THAN,
Value = FilterValue.Number(60)
} },
// Consider sessions complete after 30 minutes of inactivity
SessionTimeout = Duration.Minutes(30)
});
evaluation := agentcore.NewOnlineEvaluationConfig(this, jsii.String("FilteredEval"), &OnlineEvaluationConfigProps{
OnlineEvaluationConfigName: jsii.String("filtered_evaluation"),
Evaluators: []EvaluatorSelector{
agentcore.EvaluatorSelector_Builtin(agentcore.BuiltinEvaluator_HELPFULNESS()),
},
DataSource: agentcore.DataSourceConfig_FromCloudWatchLogs(&CloudWatchLogsDataSourceConfig{
LogGroupNames: []*string{
jsii.String("/aws/bedrock-agentcore/my-agent"),
},
ServiceNames: []*string{
jsii.String("my-agent.default"),
},
}),
// Sample 25% of traces
SamplingPercentage: jsii.Number(25),
// Only evaluate traces matching these filters
Filters: []FilterConfig{
&FilterConfig{
Key: jsii.String("user.region"),
Operator: agentcore.FilterOperator_EQUAL(),
Value: agentcore.FilterValue_String(jsii.String("us-east-1")),
},
&FilterConfig{
Key: jsii.String("session.duration"),
Operator: agentcore.FilterOperator_GREATER_THAN(),
Value: agentcore.FilterValue_Number(jsii.Number(60)),
},
},
// Consider sessions complete after 30 minutes of inactivity
SessionTimeout: cdk.Duration_Minutes(jsii.Number(30)),
})
Online Evaluation with Custom Execution Role
Provide a custom IAM role for the evaluation execution:
const executionRole = new iam.Role(this, 'EvaluationRole', {
assumedBy: new iam.ServicePrincipal('bedrock-agentcore.amazonaws.com'),
description: 'Custom role for online evaluation',
});
// Add required permissions
executionRole.addToPolicy(new iam.PolicyStatement({
actions: [
'logs:DescribeLogGroups',
'logs:GetQueryResults',
'logs:StartQuery',
],
resources: ['arn:aws:logs:*:*:log-group:/aws/bedrock-agentcore/*'],
}));
const evaluation = new agentcore.OnlineEvaluationConfig(this, 'CustomRoleEval', {
onlineEvaluationConfigName: 'custom_role_evaluation',
evaluators: [
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.HELPFULNESS),
],
dataSource: agentcore.DataSourceConfig.fromCloudWatchLogs({
logGroupNames: ['/aws/bedrock-agentcore/my-agent'],
serviceNames: ['my-agent.default'],
}),
executionRole: executionRole,
});
execution_role = iam.Role(self, "EvaluationRole",
assumed_by=iam.ServicePrincipal("bedrock-agentcore.amazonaws.com"),
description="Custom role for online evaluation"
)
# Add required permissions
execution_role.add_to_policy(iam.PolicyStatement(
actions=["logs:DescribeLogGroups", "logs:GetQueryResults", "logs:StartQuery"
],
resources=["arn:aws:logs:*:*:log-group:/aws/bedrock-agentcore/*"]
))
evaluation = agentcore.OnlineEvaluationConfig(self, "CustomRoleEval",
online_evaluation_config_name="custom_role_evaluation",
evaluators=[
agentcore.EvaluatorSelector.builtin(agentcore.BuiltinEvaluator.HELPFULNESS)
],
data_source=agentcore.DataSourceConfig.from_cloud_watch_logs(
log_group_names=["/aws/bedrock-agentcore/my-agent"],
service_names=["my-agent.default"]
),
execution_role=execution_role
)
Role executionRole = Role.Builder.create(this, "EvaluationRole")
.assumedBy(new ServicePrincipal("bedrock-agentcore.amazonaws.com"))
.description("Custom role for online evaluation")
.build();
// Add required permissions
executionRole.addToPolicy(PolicyStatement.Builder.create()
.actions(List.of("logs:DescribeLogGroups", "logs:GetQueryResults", "logs:StartQuery"))
.resources(List.of("arn:aws:logs:*:*:log-group:/aws/bedrock-agentcore/*"))
.build());
OnlineEvaluationConfig evaluation = OnlineEvaluationConfig.Builder.create(this, "CustomRoleEval")
.onlineEvaluationConfigName("custom_role_evaluation")
.evaluators(List.of(EvaluatorSelector.builtin(BuiltinEvaluator.HELPFULNESS)))
.dataSource(DataSourceConfig.fromCloudWatchLogs(CloudWatchLogsDataSourceConfig.builder()
.logGroupNames(List.of("/aws/bedrock-agentcore/my-agent"))
.serviceNames(List.of("my-agent.default"))
.build()))
.executionRole(executionRole)
.build();
var executionRole = new Role(this, "EvaluationRole", new RoleProps {
AssumedBy = new ServicePrincipal("bedrock-agentcore.amazonaws.com"),
Description = "Custom role for online evaluation"
});
// Add required permissions
executionRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps {
Actions = new [] { "logs:DescribeLogGroups", "logs:GetQueryResults", "logs:StartQuery" },
Resources = new [] { "arn:aws:logs:*:*:log-group:/aws/bedrock-agentcore/*" }
}));
var evaluation = new OnlineEvaluationConfig(this, "CustomRoleEval", new OnlineEvaluationConfigProps {
OnlineEvaluationConfigName = "custom_role_evaluation",
Evaluators = new [] { EvaluatorSelector.Builtin(BuiltinEvaluator.HELPFULNESS) },
DataSource = DataSourceConfig.FromCloudWatchLogs(new CloudWatchLogsDataSourceConfig {
LogGroupNames = new [] { "/aws/bedrock-agentcore/my-agent" },
ServiceNames = new [] { "my-agent.default" }
}),
ExecutionRole = executionRole
});
executionRole := iam.NewRole(this, jsii.String("EvaluationRole"), &RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("bedrock-agentcore.amazonaws.com")),
Description: jsii.String("Custom role for online evaluation"),
})
// Add required permissions
executionRole.AddToPolicy(iam.NewPolicyStatement(&PolicyStatementProps{
Actions: []*string{
jsii.String("logs:DescribeLogGroups"),
jsii.String("logs:GetQueryResults"),
jsii.String("logs:StartQuery"),
},
Resources: []*string{
jsii.String("arn:aws:logs:*:*:log-group:/aws/bedrock-agentcore/*"),
},
}))
evaluation := agentcore.NewOnlineEvaluationConfig(this, jsii.String("CustomRoleEval"), &OnlineEvaluationConfigProps{
OnlineEvaluationConfigName: jsii.String("custom_role_evaluation"),
Evaluators: []EvaluatorSelector{
agentcore.EvaluatorSelector_Builtin(agentcore.BuiltinEvaluator_HELPFULNESS()),
},
DataSource: agentcore.DataSourceConfig_FromCloudWatchLogs(&CloudWatchLogsDataSourceConfig{
LogGroupNames: []*string{
jsii.String("/aws/bedrock-agentcore/my-agent"),
},
ServiceNames: []*string{
jsii.String("my-agent.default"),
},
}),
ExecutionRole: executionRole,
})
Online Evaluation IAM Permissions
Grant IAM permissions to manage or read evaluation configurations:
declare const evaluation: agentcore.OnlineEvaluationConfig;
declare const role: iam.IRole;
// Grant specific permissions
evaluation.grant(role,
'bedrock-agentcore:GetOnlineEvaluationConfig',
'bedrock-agentcore:UpdateOnlineEvaluationConfig',
);
# evaluation: agentcore.OnlineEvaluationConfig
# role: iam.IRole
# Grant specific permissions
evaluation.grant(role, "bedrock-agentcore:GetOnlineEvaluationConfig", "bedrock-agentcore:UpdateOnlineEvaluationConfig")
OnlineEvaluationConfig evaluation;
IRole role;
// Grant specific permissions
evaluation.grant(role, "bedrock-agentcore:GetOnlineEvaluationConfig", "bedrock-agentcore:UpdateOnlineEvaluationConfig");
OnlineEvaluationConfig evaluation;
IRole role;
// Grant specific permissions
evaluation.Grant(role, "bedrock-agentcore:GetOnlineEvaluationConfig", "bedrock-agentcore:UpdateOnlineEvaluationConfig");
var evaluation OnlineEvaluationConfig
var role IRole
// Grant specific permissions
evaluation.Grant(role, jsii.String("bedrock-agentcore:GetOnlineEvaluationConfig"), jsii.String("bedrock-agentcore:UpdateOnlineEvaluationConfig"))
Types
| Name | Kind | Summary |
|---|---|---|
ApiKeyCredentialProvider | Construct (L2) | L2 construct for AWS::BedrockAgentCore::ApiKeyCredentialProvider. |
BrowserCustom | Construct (L2) | Browser resource for AWS Bedrock Agent Core. |
BrowserCustomBase | Construct (L2) | Abstract base class for a Browser. |
CodeInterpreterCustom | Construct (L2) | Custom code interpreter resource for AWS Bedrock Agent Core. |
CodeInterpreterCustomBase | Construct (L2) | Abstract base class for a Code Interpreter. |
Evaluator | Construct (L2) | A custom evaluator for Amazon Bedrock AgentCore. |
EvaluatorBase | Construct (L2) | Abstract base class for Evaluator. |
Gateway | Construct (L2) | Gateway resource for AWS Bedrock Agent Core. |
GatewayBase | Construct (L2) | **************************************************************************** Base Class ***************************************************************************. |
GatewayTarget | Construct (L2) | Defines tools that your gateway will host. |
GatewayTargetBase | Construct (L2) | Base class for gateway target implementations. |
Memory | Construct (L2) | Long-term memory store for extracted insights like user preferences, semantic facts and summaries. |
MemoryBase | Construct (L2) | Abstract base class for a Memory. |
OAuth2CredentialProvider | Construct (L2) | L2 construct for AWS::BedrockAgentCore::OAuth2CredentialProvider. |
OnlineEvaluationBase | Construct (L2) | Abstract base class for OnlineEvaluationConfig. |
OnlineEvaluationConfig | Construct (L2) | Online evaluation configuration for Amazon Bedrock AgentCore. |
Policy | Construct (L2) | Individual Cedar policy defining what agents can access. |
PolicyBase | Construct (L2) | Abstract base class for a Policy. |
PolicyEngine | Construct (L2) | Container that manages Cedar authorization policies associated with gateways. |
PolicyEngineBase | Construct (L2) | Abstract base class for a PolicyEngine. |
Runtime | Construct (L2) | Bedrock Agent Core Runtime Enables running containerized agents with specific network configurations, security settings, and runtime artifacts. |
RuntimeBase | Construct (L2) | Base class for Agent Runtime. |
RuntimeEndpoint | Construct (L2) | Bedrock Agent Core Runtime Endpoint Provides a stable endpoint for invoking agent runtimes with versioning support. |
RuntimeEndpointBase | Construct (L2) | Base class for Runtime Endpoint. |
WorkloadIdentity | Construct (L2) | L2 construct for AWS::BedrockAgentCore::WorkloadIdentity. |
CfnApiKeyCredentialProvider | Construct (L1) | Resource Type definition for AWS::BedrockAgentCore::ApiKeyCredentialProvider. |
CfnBrowserCustom | Construct (L1) | AgentCore Browser tool provides a fast, secure, cloud-based browser runtime to enable AI agents to interact with websites at scale. |
CfnBrowserProfile | Construct (L1) | Resource definition for AWS::BedrockAgentCore::BrowserProfile. |
CfnCapacityProvider | Construct (L1) | Resource Type definition for AWS::BedrockAgentCore::CapacityProvider. |
CfnCodeInterpreterCustom | Construct (L1) | The AgentCore Code Interpreter tool enables agents to securely execute code in isolated sandbox environments. |
CfnConfigurationBundle | Construct (L1) | Definition of AWS::BedrockAgentCore::ConfigurationBundle Resource Type. |
CfnDataset | Construct (L1) | Definition of AWS::BedrockAgentCore::Dataset Resource Type. |
CfnEvaluator | Construct (L1) | Resource Type definition for AWS::BedrockAgentCore::Evaluator - Creates a custom evaluator for agent quality assessment using LLM-as-a-Judge configurations. |
CfnGateway | Construct (L1) | Amazon Bedrock AgentCore Gateway provides a unified connectivity layer between agents and the tools and resources they need to interact with. |
CfnGatewayRateLimit | Construct (L1) | Definition of AWS::BedrockAgentCore::GatewayRateLimit Resource Type. |
CfnGatewayRule | Construct (L1) | Resource Type definition for AWS::BedrockAgentCore::GatewayRule. |
CfnGatewayTarget | Construct (L1) | After creating a gateway, you can add targets, which define the tools that your gateway will host. |
CfnHarness | Construct (L1) | Resource Type definition for AWS::BedrockAgentCore::Harness - a managed agentic loop service that provides a turnkey solution for running stateful, tool-equipped AI agents. |
CfnHarnessEndpoint | Construct (L1) | Resource Type definition for AWS::BedrockAgentCore::HarnessEndpoint - a named, stable reference to a specific version of a Harness that callers invoke, allowing the underlying version to be updated without changing how the agent is invoked. |
CfnMemory | Construct (L1) | Memory allows AI agents to maintain both immediate and long-term knowledge, enabling context-aware and personalized interactions. |
CfnOAuth2CredentialProvider | Construct (L1) | Resource Type definition for AWS::BedrockAgentCore::OAuth2CredentialProvider. |
CfnOnlineEvaluationConfig | Construct (L1) | Resource Type definition for AWS::BedrockAgentCore::OnlineEvaluationConfig - Creates an online evaluation configuration for continuous monitoring of agent performance. |
CfnPaymentConnector | Construct (L1) | Resource Type definition for AWS::BedrockAgentCore::PaymentConnector. |
CfnPaymentCredentialProvider | Construct (L1) | Resource Type definition for AWS::BedrockAgentCore::PaymentCredentialProvider. |
CfnPaymentManager | Construct (L1) | Resource Type definition for AWS::BedrockAgentCore::PaymentManager. |
CfnPolicy | Construct (L1) | Resource Type definition for AWS::BedrockAgentCore::Policy. |
CfnPolicyEngine | Construct (L1) | Resource Type definition for AWS::BedrockAgentCore::PolicyEngine. |
CfnResourcePolicy | Construct (L1) | Resource Type definition for AWS::BedrockAgentCore::ResourcePolicy. |
CfnRuntime | Construct (L1) | Contains information about an agent runtime. An agent runtime is the execution environment for a Amazon Bedrock Agent. |
CfnRuntimeEndpoint | Construct (L1) | AgentCore Runtime is a secure, serverless runtime purpose-built for deploying and scaling dynamic AI agents and tools using any open-source framework including LangGraph, CrewAI, and Strands Agents, any protocol, and any model. |
CfnWorkloadIdentity | Construct (L1) | Creates a workload identity for Amazon Bedrock AgentCore. |
AddApiGatewayTargetOptions | Struct | Options for adding an API Gateway target to a gateway. |
AddEndpointOptions | Struct | Options for adding an endpoint to the runtime. |
AddLambdaTargetOptions | Struct | Options for adding a Lambda target to a gateway. |
AddMcpServerTargetOptions | Struct | Options for adding an MCP Server target to a gateway. |
AddOpenApiTargetOptions | Struct | Options for adding an OpenAPI target to a gateway. |
AddPolicyOptions | Struct | Options for adding a policy via PolicyEngine.addPolicy(). |
AddSmithyTargetOptions | Struct | Options for adding a Smithy target to a gateway. |
AgentCoreRuntime | Class | Bedrock AgentCore runtime environment for code execution Allowed values: PYTHON_3_10 | PYTHON_3_11 | PYTHON_3_12 | PYTHON_3_13 | PYTHON_3_14 | NODE_22. |
AgentRuntimeArtifact | Class | Abstract base class for agent runtime artifacts. |
AgentRuntimeAttributes | Struct | Attributes for importing an existing Agent Runtime. |
ApiGatewayHttpMethod | Class | HTTP methods supported by API Gateway. |
ApiGatewayTargetConfiguration | Class | Configuration for API Gateway-based MCP targets. |
ApiGatewayTargetConfigurationProps | Struct | Properties for creating an API Gateway target configuration. |
ApiGatewayToolConfiguration | Struct | Configuration for API Gateway tools. |
ApiGatewayToolFilter | Struct | Configuration for filtering API Gateway tools. |
ApiGatewayToolOverride | Struct | Configuration for overriding API Gateway tool metadata. |
ApiKeyAdditionalConfiguration | Struct | API Key additional configuration. |
ApiKeyCredentialLocation | Class | API Key location within the request. |
ApiKeyCredentialProviderAttributes | Struct | Attributes for importing an existing API key credential provider. |
ApiKeyCredentialProviderIdentityPerms | Class | IAM actions for AgentCore API key credential providers (Token Vault). |
ApiKeyCredentialProviderOptions | Struct | API key credential provider ARNs for gateway outbound auth (Token Vault identity). |
ApiKeyCredentialProviderProps | Struct | Properties for a new {@link ApiKeyCredentialProvider} (Token Vault resource). |
ApiSchema | Class | Represents the concept of an API Schema for a Gateway Target. |
AssetApiSchema | Class | API Schema from a local asset. |
AssetToolSchema | Class | Tool Schema from a local asset. |
AtlassianOAuth2CredentialProviderProps | Struct | Props for {@link OAuth2CredentialProvider.usingAtlassian}. |
BrowserCustomAttributes | Struct | Attributes for specifying an imported Browser Custom. |
BrowserCustomProps | Struct | Properties for creating a Browser resource. |
BrowserNetworkConfiguration | Class | Network configuration for the Browser tool. |
BrowserSigning | Enum | Browser signing. |
BuiltinEvaluator | Class | Built-in evaluators provided by Amazon Bedrock AgentCore. |
CategoricalRatingOption | Struct | A categorical rating scale option for custom evaluators. |
CfnApiKeyCredentialProvider.ApiKeySecretArnProperty | Struct | Contains information about the API key secret in AWS Secrets Manager. |
CfnApiKeyCredentialProvider.SecretReferenceProperty | Struct | A reference to a customer-provided secret stored in AWS Secrets Manager. |
CfnApiKeyCredentialProviderProps | Struct | Properties for defining a CfnApiKeyCredentialProvider. |
CfnBrowserCustom.BrowserEnterprisePolicyProperty | Struct | Browser enterprise policy configuration. |
CfnBrowserCustom.BrowserNetworkConfigurationProperty | Struct | The network configuration. |
CfnBrowserCustom.BrowserSigningProperty | Struct | Browser signing configuration. |
CfnBrowserCustom.CertificateLocationProperty | Struct | Certificate location in Secrets Manager. |
CfnBrowserCustom.CertificateProperty | Struct | A root CA certificate configuration. |
CfnBrowserCustom.RecordingConfigProperty | Struct | The recording configuration. |
CfnBrowserCustom.S3LocationProperty | Struct | The S3 location. |
CfnBrowserCustom.VpcConfigProperty | Struct | Network mode configuration for VPC. |
CfnBrowserCustomProps | Struct | Properties for defining a CfnBrowserCustom. |
CfnBrowserProfileProps | Struct | Properties for defining a CfnBrowserProfile. |
CfnCapacityProvider.CapacityReservationSpecificationProperty | Struct | The Capacity Reservation targeting option. |
CfnCapacityProvider.CapacityReservationTargetProperty | Struct | Information about the target Capacity Reservation or Capacity Reservation group. |
CfnCapacityProvider.ComputeConfigurationProperty | Struct | The capacity configuration for the capacity provider. |
CfnCapacityProvider.EbsVolumeConfigurationProperty | Struct | Configuration for an EBS-backed persistent volume. |
CfnCapacityProvider.Ec2ConfigurationProperty | Struct | Configuration for EC2-based capacity. |
CfnCapacityProvider.EphemeralBlockDeviceMappingProperty | Struct | Describes an ephemeral block device mapping. |
CfnCapacityProvider.EphemeralEBSVolumeConfigurationProperty | Struct | Parameters used to automatically set up EBS volumes when the instance is launched. |
CfnCapacityProvider.InstanceLifecycleConfigurationProperty | Struct | Configuration for managing the lifecycle of instances in a capacity provider. |
CfnCapacityProvider.InstanceRequirementsProperty | Struct | Requirements for EC2 instance types. |
CfnCapacityProvider.LaunchParametersProperty | Struct | Parameters for launching EC2 instances. |
CfnCapacityProvider.LaunchTemplateSourceProperty | Struct | How the launch template is specified. |
CfnCapacityProvider.LicenseSpecificationProperty | Struct | Describes a license configuration. |
CfnCapacityProvider.PermissionsConfigurationProperty | Struct | Configuration for permissions associated with a capacity provider. |
CfnCapacityProvider.RootVolumeConfigurationProperty | Struct | Customer-facing configuration for the (service-managed) root volume. |
CfnCapacityProvider.VolumeConfigurationProperty | Struct | Configuration for a persistent volume attached to a capacity provider session. |
CfnCapacityProvider.VpcConfigurationProperty | Struct | VPC configuration for launching EC2 instances. |
CfnCapacityProviderProps | Struct | Properties for defining a CfnCapacityProvider. |
CfnCodeInterpreterCustom.CertificateLocationProperty | Struct | Certificate location in Secrets Manager. |
CfnCodeInterpreterCustom.CertificateProperty | Struct | A root CA certificate configuration. |
CfnCodeInterpreterCustom.CodeInterpreterNetworkConfigurationProperty | Struct | The network configuration. |
CfnCodeInterpreterCustom.VpcConfigProperty | Struct | Network mode configuration for VPC. |
CfnCodeInterpreterCustomProps | Struct | Properties for defining a CfnCodeInterpreterCustom. |
CfnConfigurationBundle.ComponentConfigurationProperty | Struct | The configuration for a component within a configuration bundle. |
CfnConfigurationBundle.VersionCreatedBySourceProperty | Struct | The source that created a configuration bundle version. |
CfnConfigurationBundle.VersionLineageMetadataProperty | Struct | The version lineage metadata that tracks parent versions and creation source. |
CfnConfigurationBundleProps | Struct | Properties for defining a CfnConfigurationBundle. |
CfnDataset.DataSourceTypeProperty | Struct | Source of initial examples. |
CfnDataset.InlineExamplesSourceProperty | Struct | Inline examples provided directly in the request body. |
CfnDataset.S3SourceProperty | Struct | S3 location of a JSONL file containing dataset examples. |
CfnDatasetProps | Struct | Properties for defining a CfnDataset. |
CfnEvaluator.BedrockEvaluatorModelConfigProperty | Struct | The configuration for using Amazon Bedrock models in evaluator assessments. |
CfnEvaluator.CategoricalScaleDefinitionProperty | Struct | A categorical rating scale option. |
CfnEvaluator.CodeBasedEvaluatorConfigProperty | Struct | The configuration for code-based evaluation using a Lambda function. |
CfnEvaluator.EvaluatorConfigProperty | Struct | The configuration that defines how an evaluator assesses agent performance. |
CfnEvaluator.EvaluatorModelConfigProperty | Struct | The model configuration that specifies which foundation model to use for evaluation. |
CfnEvaluator.InferenceConfigurationProperty | Struct | The inference configuration parameters that control model behavior during evaluation. |
CfnEvaluator.LambdaEvaluatorConfigProperty | Struct | The Lambda function configuration for code-based evaluation. |
CfnEvaluator.LlmAsAJudgeEvaluatorConfigProperty | Struct | The configuration for LLM-as-a-Judge evaluation. |
CfnEvaluator.NumericalScaleDefinitionProperty | Struct | A numerical rating scale option. |
CfnEvaluator.OpenResponsesEvaluatorModelConfigProperty | Struct | The configuration for using OpenResponses-compatible models in evaluator assessments. |
CfnEvaluator.RatingScaleProperty | Struct | The rating scale that defines how evaluators should score agent performance. |
CfnEvaluator.ReasoningConfigurationProperty | Struct | The reasoning configuration for reasoning models. |
CfnEvaluatorProps | Struct | Properties for defining a CfnEvaluator. |
CfnGateway.AuthorizerConfigurationProperty | Struct | |
CfnGateway.AuthorizingClaimMatchValueTypeProperty | Struct | |
CfnGateway.ClaimMatchValueTypeProperty | Struct | |
CfnGateway.CustomClaimValidationTypeProperty | Struct | |
CfnGateway.CustomJWTAuthorizerConfigurationProperty | Struct | |
CfnGateway.GatewayInterceptorConfigurationProperty | Struct | |
CfnGateway.GatewayPolicyEngineConfigurationProperty | Struct | |
CfnGateway.GatewayProtocolConfigurationProperty | Struct | The protocol configuration. |
CfnGateway.InterceptorConfigurationProperty | Struct | |
CfnGateway.InterceptorInputConfigurationProperty | Struct | |
CfnGateway.InterceptorPayloadExclusionSelectorProperty | Struct | |
CfnGateway.InterceptorPayloadFilterProperty | Struct | |
CfnGateway.LambdaInterceptorConfigurationProperty | Struct | |
CfnGateway.ManagedVpcResourceProperty | Struct | |
CfnGateway.MCPGatewayConfigurationProperty | Struct | The gateway configuration for MCP. |
CfnGateway.PrivateEndpointProperty | Struct | |
CfnGateway.SelfManagedLatticeResourceProperty | Struct | |
CfnGateway.SessionConfigurationProperty | Struct | |
CfnGateway.StreamingConfigurationProperty | Struct | |
CfnGateway.WafConfigurationProperty | Struct | |
CfnGateway.WorkloadIdentityDetailsProperty | Struct | The workload identity details for the gateway. |
CfnGatewayProps | Struct | Properties for defining a CfnGateway. |
CfnGatewayRateLimit.LimitEntryProperty | Struct | A single rule entry within a limit, mapping dimension values to rate configurations. |
CfnGatewayRateLimit.RateConfigProperty | Struct | Rate configuration for a metric (requests or tokens). |
CfnGatewayRateLimitProps | Struct | Properties for defining a CfnGatewayRateLimit. |
CfnGatewayRule.ActionProperty | Struct | |
CfnGatewayRule.ConditionProperty | Struct | |
CfnGatewayRule.ConfigurationBundleActionProperty | Struct | |
CfnGatewayRule.ConfigurationBundleReferenceProperty | Struct | |
CfnGatewayRule.IamPrincipalProperty | Struct | |
CfnGatewayRule.MatchPathsProperty | Struct | |
CfnGatewayRule.MatchPrincipalEntryProperty | Struct | |
CfnGatewayRule.MatchPrincipalsProperty | Struct | |
CfnGatewayRule.RouteToTargetActionProperty | Struct | |
CfnGatewayRule.StaticOverrideProperty | Struct | |
CfnGatewayRule.StaticRouteProperty | Struct | |
CfnGatewayRule.SystemManagedBlockProperty | Struct | |
CfnGatewayRule.TargetTrafficSplitEntryProperty | Struct | |
CfnGatewayRule.TrafficSplitEntryProperty | Struct | |
CfnGatewayRule.WeightedOverrideProperty | Struct | |
CfnGatewayRule.WeightedRouteProperty | Struct | |
CfnGatewayRuleProps | Struct | Properties for defining a CfnGatewayRule. |
CfnGatewayTarget.ApiGatewayTargetConfigurationProperty | Struct | |
CfnGatewayTarget.ApiGatewayToolConfigurationProperty | Struct | |
CfnGatewayTarget.ApiGatewayToolFilterProperty | Struct | |
CfnGatewayTarget.ApiGatewayToolOverrideProperty | Struct | |
CfnGatewayTarget.ApiKeyCredentialProviderProperty | Struct | The API key credential provider for the gateway target. |
CfnGatewayTarget.ApiSchemaConfigurationProperty | Struct | The API schema configuration for the gateway target. |
CfnGatewayTarget.AuthorizationDataProperty | Struct | |
CfnGatewayTarget.ConnectorConfigurationProperty | Struct | |
CfnGatewayTarget.ConnectorParameterOverrideProperty | Struct | |
CfnGatewayTarget.ConnectorSourceProperty | Struct | |
CfnGatewayTarget.ConnectorTargetConfigurationProperty | Struct | |
CfnGatewayTarget.CredentialProviderConfigurationProperty | Struct | The credential provider configuration for the gateway target. |
CfnGatewayTarget.CredentialProviderProperty | Struct | |
CfnGatewayTarget.HttpApiSchemaConfigurationProperty | Struct | |
CfnGatewayTarget.HttpConnectorSourceProperty | Struct | |
CfnGatewayTarget.HttpConnectorTargetConfigurationProperty | Struct | |
CfnGatewayTarget.HttpTargetConfigurationProperty | Struct | |
CfnGatewayTarget.IamCredentialProviderProperty | Struct | |
CfnGatewayTarget.InferenceConnectorSourceProperty | Struct | |
CfnGatewayTarget.InferenceConnectorTargetConfigurationProperty | Struct | |
CfnGatewayTarget.InferenceOperationConfigurationProperty | Struct | |
CfnGatewayTarget.InferenceProviderTargetConfigurationProperty | Struct | |
CfnGatewayTarget.InferenceTargetConfigurationProperty | Struct | |
CfnGatewayTarget.ManagedResourceDetailsProperty | Struct | |
CfnGatewayTarget.ManagedVpcResourceProperty | Struct | |
CfnGatewayTarget.McpLambdaTargetConfigurationProperty | Struct | The Lambda target configuration. |
CfnGatewayTarget.McpServerTargetConfigurationProperty | Struct | |
CfnGatewayTarget.McpTargetConfigurationProperty | Struct | The MCP target configuration for the gateway target. |
CfnGatewayTarget.McpToolSchemaConfigurationProperty | Struct | |
CfnGatewayTarget.MetadataConfigurationProperty | Struct | |
CfnGatewayTarget.ModelEntryProperty | Struct | |
CfnGatewayTarget.ModelMappingProperty | Struct | |
CfnGatewayTarget.OAuth2AuthorizationDataProperty | Struct | |
CfnGatewayTarget.OAuthCredentialProviderProperty | Struct | The OAuth credential provider for the gateway target. |
CfnGatewayTarget.PassthroughTargetConfigurationProperty | Struct | |
CfnGatewayTarget.PrivateEndpointProperty | Struct | |
CfnGatewayTarget.ProviderPrefixProperty | Struct | |
CfnGatewayTarget.RuntimeTargetConfigurationProperty | Struct | |
CfnGatewayTarget.S3ConfigurationProperty | Struct | The S3 configuration for the gateway target. |
CfnGatewayTarget.SchemaDefinitionProperty | Struct | The schema definition for the gateway target. |
CfnGatewayTarget.SelfManagedLatticeResourceProperty | Struct | |
CfnGatewayTarget.StickinessConfigurationProperty | Struct | |
CfnGatewayTarget.TargetConfigurationProperty | Struct | The target configuration. |
CfnGatewayTarget.ToolDefinitionProperty | Struct | The tool definition for the gateway. |
CfnGatewayTarget.ToolSchemaProperty | Struct | The tool schema for the gateway target. |
CfnGatewayTargetProps | Struct | Properties for defining a CfnGatewayTarget. |
CfnHarness.AuthorizerConfigurationProperty | Struct | |
CfnHarness.AuthorizingClaimMatchValueTypeProperty | Struct | |
CfnHarness.ClaimMatchValueTypeProperty | Struct | |
CfnHarness.ContainerConfigurationProperty | Struct | |
CfnHarness.CustomClaimValidationTypeProperty | Struct | |
CfnHarness.CustomJWTAuthorizerConfigurationProperty | Struct | |
CfnHarness.EfsAccessPointConfigurationProperty | Struct | Configuration for an Amazon EFS access point to mount into the AgentCore Runtime. |
CfnHarness.FilesystemConfigurationProperty | Struct | |
CfnHarness.HarnessAfterInvocationHookProperty | Struct | A hook that runs after an agent invocation. |
CfnHarness.HarnessAfterToolCallHookProperty | Struct | A hook that runs after each tool call. |
CfnHarness.HarnessAgentCoreBrowserConfigProperty | Struct | |
CfnHarness.HarnessAgentCoreCodeInterpreterConfigProperty | Struct | |
CfnHarness.HarnessAgentCoreGatewayConfigProperty | Struct | |
CfnHarness.HarnessAgentCoreMemoryConfigurationProperty | Struct | |
CfnHarness.HarnessAgentCoreMemoryRetrievalConfigProperty | Struct | |
CfnHarness.HarnessAgentCoreRuntimeEnvironmentProperty | Struct | |
CfnHarness.HarnessBedrockModelConfigProperty | Struct | |
CfnHarness.HarnessBeforeInvocationHookProperty | Struct | A hook that runs before an agent invocation. |
CfnHarness.HarnessBeforeToolCallHookProperty | Struct | A hook that runs before each tool call. |
CfnHarness.HarnessEnvironmentArtifactProperty | Struct | |
CfnHarness.HarnessEnvironmentProviderProperty | Struct | |
CfnHarness.HarnessGatewayOutboundAuthProperty | Struct | |
CfnHarness.HarnessGeminiModelConfigProperty | Struct | |
CfnHarness.HarnessHookEventBridgeTargetProperty | Struct | An EventBridge event bus that receives lifecycle hook events asynchronously. |
CfnHarness.HarnessHookLambdaTargetProperty | Struct | A Lambda function invoked synchronously for a lifecycle hook. |
CfnHarness.HarnessHookProperty | Struct | A lifecycle hook configured for one phase of the agent loop. |
CfnHarness.HarnessHookSnsTargetProperty | Struct | An SNS topic that receives lifecycle hook events asynchronously. |
CfnHarness.HarnessHookTargetProperty | Struct | The destination that receives lifecycle hook events. |
CfnHarness.HarnessInlineFunctionConfigProperty | Struct | |
CfnHarness.HarnessLiteLlmModelConfigProperty | Struct | |
CfnHarness.HarnessManagedMemoryConfigurationProperty | Struct | Configuration for managed memory. |
CfnHarness.HarnessMemoryConfigurationProperty | Struct | |
CfnHarness.HarnessModelConfigurationProperty | Struct | |
CfnHarness.HarnessOpenAiModelConfigProperty | Struct | |
CfnHarness.HarnessRemoteMcpConfigProperty | Struct | |
CfnHarness.HarnessSkillAwsSkillsSourceProperty | Struct | AWS Skills baked into the Harness's underlying Runtime. |
CfnHarness.HarnessSkillGitAuthProperty | Struct | Authentication configuration for accessing a private git repository. |
CfnHarness.HarnessSkillGitSourceProperty | Struct | A git repository containing the skill, cloned over HTTPS. |
CfnHarness.HarnessSkillProperty | Struct | |
CfnHarness.HarnessSkillS3SourceProperty | Struct | An S3 source containing the skill. |
CfnHarness.HarnessSlidingWindowConfigurationProperty | Struct | |
CfnHarness.HarnessSummarizationConfigurationProperty | Struct | |
CfnHarness.HarnessSystemContentBlockProperty | Struct | |
CfnHarness.HarnessToolConfigurationProperty | Struct | |
CfnHarness.HarnessToolProperty | Struct | |
CfnHarness.HarnessTruncationConfigurationProperty | Struct | |
CfnHarness.HarnessTruncationStrategyConfigurationProperty | Struct | |
CfnHarness.LifecycleConfigurationProperty | Struct | |
CfnHarness.ManagedVpcResourceProperty | Struct | Configuration for a service-managed VPC endpoint. |
CfnHarness.NetworkConfigurationProperty | Struct | |
CfnHarness.OAuthCredentialProviderProperty | Struct | |
CfnHarness.PrivateEndpointOverrideProperty | Struct | Maps a domain to a private endpoint for resolving that domain over a private network. |
CfnHarness.PrivateEndpointProperty | Struct | Private endpoint configuration for connecting to the OpenID Connect discovery endpoint over a private network. |
CfnHarness.S3FilesAccessPointConfigurationProperty | Struct | Configuration for an Amazon S3 Files access point to mount into the AgentCore Runtime. |
CfnHarness.SelfManagedLatticeResourceProperty | Struct | Configuration for connecting to a private resource using a self-managed VPC Lattice resource configuration. |
CfnHarness.SessionStorageConfigurationProperty | Struct | |
CfnHarness.VpcConfigProperty | Struct | |
CfnHarnessEndpointProps | Struct | Properties for defining a CfnHarnessEndpoint. |
CfnHarnessProps | Struct | Properties for defining a CfnHarness. |
CfnMemory.ContentConfigurationProperty | Struct | |
CfnMemory.CustomConfigurationInputProperty | Struct | The memory configuration input. |
CfnMemory.CustomMemoryStrategyProperty | Struct | The memory strategy. |
CfnMemory.EpisodicMemoryStrategyProperty | Struct | |
CfnMemory.EpisodicOverrideConsolidationConfigurationInputProperty | Struct | |
CfnMemory.EpisodicOverrideExtractionConfigurationInputProperty | Struct | |
CfnMemory.EpisodicOverrideProperty | Struct | |
CfnMemory.EpisodicOverrideReflectionConfigurationInputProperty | Struct | |
CfnMemory.EpisodicReflectionConfigurationInputProperty | Struct | |
CfnMemory.ExtractionConfigProperty | Struct | |
CfnMemory.IndexedKeyProperty | Struct | |
CfnMemory.InvocationConfigurationInputProperty | Struct | The memory invocation configuration input. |
CfnMemory.KinesisResourceProperty | Struct | |
CfnMemory.LlmExtractionConfigProperty | Struct | |
CfnMemory.MemoryRecordSchemaProperty | Struct | |
CfnMemory.MemoryStrategyProperty | Struct | The memory strategy. |
CfnMemory.MessageBasedTriggerInputProperty | Struct | The message based trigger input. |
CfnMemory.MetadataSchemaEntryProperty | Struct | |
CfnMemory.NamespaceKeyEntryProperty | Struct | A namespace variable key definition with optional validation rules. |
CfnMemory.NamespaceKeyValidationProperty | Struct | Validation rules for namespace variable values. |
CfnMemory.NumberValidationProperty | Struct | |
CfnMemory.SelfManagedConfigurationProperty | Struct | The self managed configuration. |
CfnMemory.SemanticMemoryStrategyProperty | Struct | The memory strategy. |
CfnMemory.SemanticOverrideConsolidationConfigurationInputProperty | Struct | The memory override configuration. |
CfnMemory.SemanticOverrideExtractionConfigurationInputProperty | Struct | The memory override configuration. |
CfnMemory.SemanticOverrideProperty | Struct | The memory override. |
CfnMemory.StreamDeliveryResourceProperty | Struct | |
CfnMemory.StreamDeliveryResourcesProperty | Struct | |
CfnMemory.StringListValidationProperty | Struct | |
CfnMemory.StringValidationProperty | Struct | |
CfnMemory.SummaryMemoryStrategyProperty | Struct | The memory strategy. |
CfnMemory.SummaryOverrideConsolidationConfigurationInputProperty | Struct | The consolidation configuration. |
CfnMemory.SummaryOverrideProperty | Struct | The memory summary override. |
CfnMemory.TimeBasedTriggerInputProperty | Struct | The memory trigger condition input for the time based trigger. |
CfnMemory.TokenBasedTriggerInputProperty | Struct | The token based trigger input. |
CfnMemory.TriggerConditionInputProperty | Struct | The memory trigger condition input. |
CfnMemory.UserPreferenceMemoryStrategyProperty | Struct | The memory strategy. |
CfnMemory.UserPreferenceOverrideConsolidationConfigurationInputProperty | Struct | The configuration input. |
CfnMemory.UserPreferenceOverrideExtractionConfigurationInputProperty | Struct | The memory override configuration. |
CfnMemory.UserPreferenceOverrideProperty | Struct | The memory user preference override. |
CfnMemory.ValidationProperty | Struct | |
CfnMemoryProps | Struct | Properties for defining a CfnMemory. |
CfnOAuth2CredentialProvider.AtlassianOauth2ProviderConfigInputProperty | Struct | Input configuration for an Atlassian OAuth2 provider. |
CfnOAuth2CredentialProvider.ClientSecretArnProperty | Struct | Contains information about a secret in AWS Secrets Manager. |
CfnOAuth2CredentialProvider.CustomOauth2ProviderConfigInputProperty | Struct | Input configuration for a custom OAuth2 provider. |
CfnOAuth2CredentialProvider.GithubOauth2ProviderConfigInputProperty | Struct | Input configuration for a GitHub OAuth2 provider. |
CfnOAuth2CredentialProvider.GoogleOauth2ProviderConfigInputProperty | Struct | Input configuration for a Google OAuth2 provider. |
CfnOAuth2CredentialProvider.IncludedOauth2ProviderConfigInputProperty | Struct | Input configuration for a supported non-custom OAuth2 provider. |
CfnOAuth2CredentialProvider.KmsKeySourceTypeProperty | Struct | Contains the KMS key configuration for a JWT client assertion. |
CfnOAuth2CredentialProvider.LinkedinOauth2ProviderConfigInputProperty | Struct | Input configuration for a LinkedIn OAuth2 provider. |
CfnOAuth2CredentialProvider.ManagedVpcResourceProperty | Struct | Configuration for a managed VPC Lattice resource. |
CfnOAuth2CredentialProvider.MicrosoftOauth2ProviderConfigInputProperty | Struct | Input configuration for a Microsoft OAuth2 provider. |
CfnOAuth2CredentialProvider.Oauth2AuthorizationServerMetadataProperty | Struct | Authorization server metadata for the OAuth2 provider. |
CfnOAuth2CredentialProvider.Oauth2DiscoveryProperty | Struct | Discovery information for an OAuth2 provider. |
CfnOAuth2CredentialProvider.Oauth2ProviderConfigInputProperty | Struct | Input configuration for an OAuth2 provider. |
CfnOAuth2CredentialProvider.Oauth2ProviderConfigOutputProperty | Struct | Output configuration for an OAuth2 provider. |
CfnOAuth2CredentialProvider.OnBehalfOfTokenExchangeConfigProperty | Struct | Configuration for on-behalf-of token exchange. |
CfnOAuth2CredentialProvider.PrivateEndpointOverrideProperty | Struct | A mapping of a specific domain to a private endpoint for secure connectivity through a VPC Lattice resource configuration. |
CfnOAuth2CredentialProvider.PrivateEndpointProperty | Struct | The private endpoint configuration for connecting to private resources in your VPC. |
CfnOAuth2CredentialProvider.PrivateKeyJwtConfigProperty | Struct | Configuration for private_key_jwt client authentication (RFC 7523). |
CfnOAuth2CredentialProvider.PrivateKeySourceProperty | Struct | Contains the private key source configuration for a JWT client assertion. |
CfnOAuth2CredentialProvider.SalesforceOauth2ProviderConfigInputProperty | Struct | Input configuration for a Salesforce OAuth2 provider. |
CfnOAuth2CredentialProvider.SecretReferenceProperty | Struct | A reference to a customer-provided secret stored in AWS Secrets Manager. |
CfnOAuth2CredentialProvider.SelfManagedLatticeResourceProperty | Struct | Configuration for a self-managed VPC Lattice resource. |
CfnOAuth2CredentialProvider.SlackOauth2ProviderConfigInputProperty | Struct | Input configuration for a Slack OAuth2 provider. |
CfnOAuth2CredentialProvider.TokenExchangeGrantTypeConfigProperty | Struct | Configuration for RFC 8693 Token Exchange. |
CfnOAuth2CredentialProviderProps | Struct | Properties for defining a CfnOAuth2CredentialProvider. |
CfnOnlineEvaluationConfig.CloudWatchLogsInputConfigProperty | Struct | The configuration for reading agent traces from CloudWatch logs. |
CfnOnlineEvaluationConfig.CloudWatchOutputConfigProperty | Struct | The CloudWatch configuration for writing evaluation results. |
CfnOnlineEvaluationConfig.ClusteringConfigProperty | Struct | The configuration for clustering analysis of evaluation results. |
CfnOnlineEvaluationConfig.DataSourceConfigProperty | Struct | The configuration that specifies where to read agent traces for online evaluation. |
CfnOnlineEvaluationConfig.EvaluatorReferenceProperty | Struct | The reference to an evaluator used in online evaluation configurations. |
CfnOnlineEvaluationConfig.FilterProperty | Struct | The filter that applies conditions to agent traces during online evaluation. |
CfnOnlineEvaluationConfig.FilterValueProperty | Struct | The value used in filter comparisons. |
CfnOnlineEvaluationConfig.InsightProperty | Struct | An insight configuration for failure analysis. |
CfnOnlineEvaluationConfig.OutputConfigProperty | Struct | The configuration that specifies where evaluation results should be written. |
CfnOnlineEvaluationConfig.RuleProperty | Struct | The evaluation rule that defines sampling configuration, filtering criteria, and session detection settings. |
CfnOnlineEvaluationConfig.SamplingConfigProperty | Struct | The configuration that controls what percentage of agent traces are sampled for evaluation. |
CfnOnlineEvaluationConfig.SessionConfigProperty | Struct | The configuration that defines how agent sessions are detected. |
CfnOnlineEvaluationConfigProps | Struct | Properties for defining a CfnOnlineEvaluationConfig. |
CfnPaymentConnector.CredentialsProviderConfigurationProperty | Struct | |
CfnPaymentConnector.PaymentCredentialProviderConfigurationProperty | Struct | |
CfnPaymentConnectorProps | Struct | Properties for defining a CfnPaymentConnector. |
CfnPaymentCredentialProvider.CoinbaseCdpConfigurationInputProperty | Struct | Coinbase CDP configuration with API credentials. |
CfnPaymentCredentialProvider.CoinbaseCdpConfigurationOutputProperty | Struct | Coinbase CDP configuration output with secret ARNs. |
CfnPaymentCredentialProvider.PaymentProviderConfigurationInputProperty | Struct | Provider configuration input containing secrets for creation/update. |
CfnPaymentCredentialProvider.PaymentProviderConfigurationOutputProperty | Struct | Provider configuration output containing secret ARNs (no raw secrets). |
CfnPaymentCredentialProvider.SecretInfoProperty | Struct | Contains information about a secret in AWS Secrets Manager. |
CfnPaymentCredentialProvider.SecretReferenceProperty | Struct | A reference to a customer-provided secret stored in AWS Secrets Manager. |
CfnPaymentCredentialProvider.StripePrivyConfigurationInputProperty | Struct | Stripe Privy configuration with credentials. |
CfnPaymentCredentialProvider.StripePrivyConfigurationOutputProperty | Struct | Stripe Privy configuration output with secret ARNs. |
CfnPaymentCredentialProviderProps | Struct | Properties for defining a CfnPaymentCredentialProvider. |
CfnPaymentManager.AuthorizerConfigurationProperty | Struct | |
CfnPaymentManager.AuthorizingClaimMatchValueTypeProperty | Struct | |
CfnPaymentManager.ClaimMatchValueTypeProperty | Struct | |
CfnPaymentManager.CustomClaimValidationTypeProperty | Struct | |
CfnPaymentManager.CustomJWTAuthorizerConfigurationProperty | Struct | |
CfnPaymentManager.WorkloadIdentityDetailsProperty | Struct | |
CfnPaymentManagerProps | Struct | Properties for defining a CfnPaymentManager. |
CfnPolicy.CedarPolicyProperty | Struct | A Cedar policy statement within the AgentCore Policy system. |
CfnPolicy.PolicyDefinitionProperty | Struct | The definition structure for policies. |
CfnPolicy.PolicyStatementProperty | Struct | A policy statement within the AgentCore Policy system. |
CfnPolicyEngineProps | Struct | Properties for defining a CfnPolicyEngine. |
CfnPolicyProps | Struct | Properties for defining a CfnPolicy. |
CfnResourcePolicyProps | Struct | Properties for defining a CfnResourcePolicy. |
CfnRuntime.AgentRuntimeArtifactProperty | Struct | The artifact of the agent. |
CfnRuntime.AllowedWorkloadConfigurationProperty | Struct | Allow-list of upstream workloads permitted to reach this resource via the workload identity chain. |
CfnRuntime.AuthorizerConfigurationProperty | Struct | The authorizer configuration. |
CfnRuntime.AuthorizingClaimMatchValueTypeProperty | Struct | The value or values in the custom claim to match and relationship of match. |
CfnRuntime.CapacityProviderConfigurationProperty | Struct | Configuration for a capacity provider. |
CfnRuntime.CapacityProviderVolumeConfigurationProperty | Struct | Configuration for a CapacityProvider-managed volume to mount into the agent runtime. |
CfnRuntime.ClaimMatchValueTypeProperty | Struct | The value or values in the custom claim to match for. |
CfnRuntime.CodeConfigurationProperty | Struct | Representation of a code configuration. |
CfnRuntime.CodeProperty | Struct | Object represents source code from zip file. |
CfnRuntime.ContainerConfigurationProperty | Struct | The container configuration. |
CfnRuntime.CustomClaimValidationTypeProperty | Struct | Required custom claim. |
CfnRuntime.CustomJWTAuthorizerConfigurationProperty | Struct | Configuration for custom JWT authorizer. |
CfnRuntime.EfsAccessPointConfigurationProperty | Struct | Configuration for EFS access point filesystem. |
CfnRuntime.FilesystemConfigurationProperty | Struct | Filesystem configuration for the runtime. |
CfnRuntime.HostingEnvironmentProperty | Struct | An upstream workload identified by the ARN of its hosting environment (for example a Gateway or Runtime ARN). |
CfnRuntime.LifecycleConfigurationProperty | Struct | Configuration for managing the lifecycle of runtime sessions and resources. |
CfnRuntime.ManagedVpcResourceProperty | Struct | Managed VPC resource configuration. |
CfnRuntime.NetworkConfigurationProperty | Struct | The network configuration for the agent. |
CfnRuntime.PrivateEndpointOverrideProperty | Struct | Override mapping of a domain to a private endpoint. |
CfnRuntime.PrivateEndpointProperty | Struct | |
CfnRuntime.RequestHeaderConfigurationProperty | Struct | Configuration for HTTP request headers. |
CfnRuntime.S3FilesAccessPointConfigurationProperty | Struct | Configuration for S3 Files access point filesystem. |
CfnRuntime.S3LocationProperty | Struct | S3 Location Configuration. |
CfnRuntime.SelfManagedLatticeResourceProperty | Struct | Self-managed VPC Lattice resource configuration. |
CfnRuntime.SessionStorageConfigurationProperty | Struct | Configuration for session storage. |
CfnRuntime.VpcConfigProperty | Struct | Network mode configuration for VPC. |
CfnRuntime.WorkloadIdentityDetailsProperty | Struct | The workload identity details for the agent. |
CfnRuntimeEndpointProps | Struct | Properties for defining a CfnRuntimeEndpoint. |
CfnRuntimeProps | Struct | Properties for defining a CfnRuntime. |
CfnWorkloadIdentityProps | Struct | Properties for defining a CfnWorkloadIdentity. |
CloudWatchLogsDataSourceConfig | Struct | Configuration for CloudWatch Logs data source. |
CodeAssetOptions | Struct | Options for configuring an S3 code asset from local files for agent runtime artifact. |
CodeBasedOptions | Struct | Options for configuring a code-based custom evaluator using a Lambda function. |
CodeInterpreterCustomAttributes | Struct | Attributes for specifying an imported Code Interpreter Custom. |
CodeInterpreterCustomProps | Struct | Properties for creating a CodeInterpreter resource. |
CodeInterpreterNetworkConfiguration | Class | Network configuration for the Code Interpreter tool. |
CognitoAuthorizerProps | Struct | **************************************************************************** Factory ***************************************************************************. |
CredentialProviderType | Enum | Credential provider types supported by gateway target. |
CustomClaimOperator | Enum | Custom claim match operator. |
CustomJwtAuthorizer | Class | Custom JWT authorizer configuration implementation. |
CustomJwtConfiguration | Struct | Custom JWT authorizer configuration. |
CustomOAuth2CredentialProviderProps | Struct | Props for {@link OAuth2CredentialProvider.usingCustom}. |
DataSourceConfig | Class | Configuration for the data source used in online evaluation. |
DataSourceConfigBindResult | Struct | The result of binding a DataSourceConfig. |
DropboxOAuth2CredentialProviderProps | Struct | Props for {@link OAuth2CredentialProvider.usingDropbox}. |
EpisodicReflectionConfiguration | Struct | Configuration for episodic memory reflection. |
EvaluationLevel | Class | The level at which a custom evaluator assesses agent performance. |
EvaluatorAttributes | Struct | Attributes for importing an existing Evaluator. |
EvaluatorConfig | Class | Configuration for a custom evaluator. |
EvaluatorInferenceConfig | Struct | Inference configuration for a custom LLM-as-a-Judge evaluator. |
EvaluatorProps | Struct | Properties for creating an Evaluator. |
EvaluatorRatingScale | Class | Represents a rating scale for custom LLM-as-a-Judge evaluators. |
EvaluatorSelector | Class | Represents a reference to an evaluator for online evaluation. |
EvaluatorSelectorBindResult | Struct | The result of binding an EvaluatorSelector. |
ExecutionStatus | Class | The execution status of an online evaluation configuration. |
FacebookOAuth2CredentialProviderProps | Struct | Props for {@link OAuth2CredentialProvider.usingFacebook}. |
FilterConfig | Struct | Filter configuration for online evaluation. |
FilterOperator | Class | Filter operators for online evaluation filtering. |
FilterValue | Class | A typed filter value for online evaluation filtering. |
FromApiKeyIdentityOptions | Struct | Optional gateway settings when binding an {@link IApiKeyCredentialProvider} to a target. |
FromOauthIdentityOptions | Struct | OAuth scopes (and optional custom parameters) when binding an {@link IOAuth2CredentialProvider} to a gateway target. |
GatewayApiKeyIdentityBinding | Struct | Provider and secret ARNs for wiring a Token Vault API key identity into a gateway target. |
GatewayAttributes | Struct | Attributes for importing an existing Gateway. |
GatewayAuthorizer | Class | Factory class for creating Gateway Authorizers. |
GatewayAuthorizerType | Enum | Gateway authorizer type. |
GatewayCredentialProvider | Class | Factory class for creating different Gateway Credential Providers. |
GatewayCustomClaim | Class | Represents a custom claim validation configuration for Gateway JWT authorizers. |
GatewayExceptionLevel | Class | Exception levels for gateway. |
GatewayIamRoleCredentialProviderProps | Struct | Properties for configuring the IAM role credential provider. |
GatewayOAuth2IdentityBinding | Struct | Provider ARN, secret ARN, and OAuth scopes for wiring a Token Vault OAuth2 identity into a gateway target. |
GatewayPolicyEngineConfig | Struct | Configuration for associating a policy engine with a gateway. |
GatewayProps | Struct | Properties for defining a Gateway. |
GatewayProtocol | Class | Factory class for instantiating Gateway Protocols. |
GatewayTargetApiGatewayProps | Struct | Properties for creating an API Gateway-based Gateway Target. |
GatewayTargetAttributes | Struct | Attributes for importing an existing Gateway Target. |
GatewayTargetCommonProps | Struct | Common properties for all Gateway Target types. |
GatewayTargetLambdaProps | Struct | Properties for creating a Lambda-based Gateway Target Convenience interface for the most common use case. |
GatewayTargetMcpServerProps | Struct | Properties for creating an MCP Server-based Gateway Target. |
GatewayTargetOpenApiProps | Struct | Properties for creating an OpenAPI-based Gateway Target. |
GatewayTargetProps | Struct | Properties for creating a Gateway Target resource. |
GatewayTargetProtocolType | Enum | Protocol types supported by gateway targets. |
GatewayTargetSmithyProps | Struct | Properties for creating a Smithy-based Gateway Target. |
GithubOAuth2CredentialProviderProps | Struct | Props for {@link OAuth2CredentialProvider.usingGithub}. |
GoogleOAuth2CredentialProviderProps | Struct | Props for {@link OAuth2CredentialProvider.usingGoogle}. |
HubspotOAuth2CredentialProviderProps | Struct | Props for {@link OAuth2CredentialProvider.usingHubspot}. |
IamAuthorizer | Class | AWS IAM authorizer configuration implementation. |
IApiKeyCredentialProvider | Interface | An API key credential provider registered in AgentCore Token Vault. |
IBedrockAgentRuntime | Interface | Interface for Agent Runtime resources. |
IBrowserCustom | Interface | Interface for Browser resources. |
ICodeInterpreterCustom | Interface | Interface for CodeInterpreterCustom resources. |
ICredentialProviderConfig | Interface | Abstract interface for gateway credential provider configuration. |
IEvaluator | Interface | Interface for Evaluator resources. |
IGateway | Interface | Interface for Gateway resources. |
IGatewayAuthorizerConfig | Interface | Abstract interface for gateway authorizer configuration. |
IGatewayProtocolConfig | Interface | Abstract interface for gateway protocol configuration. |
IGatewayTarget | Interface | Interface for GatewayTarget resources. |
IInterceptor | Interface | Represents an interceptor that can be bound to a Gateway. |
IMcpGatewayTarget | Interface | Interface for MCP gateway targets. |
IMemory | Interface | Interface for Memory resources. |
IMemoryStrategy | Interface | Interface for Memory strategies. |
IncludedOauth2TenantCredentialProviderProps | Struct | Props for IncludedOauth2ProviderConfig IdPs whose outbound documentation requires issuer, authorizationEndpoint, and/or tokenEndpoint (for example Okta, Auth0, Amazon Cognito, OneLogin, PingOne, CyberArk, FusionAuth). |
IncludedOauth2TenantEndpoints | Struct | Optional tenant OAuth endpoints for IdPs that use CloudFormation IncludedOauth2ProviderConfig with issuer and/or endpoints per the IdP’s outbound documentation. |
InlineApiSchema | Class | Class to define an API Schema from an inline string. |
InlineToolSchema | Class | Class to define a Tool Schema from an inline string. |
InterceptionPoint | Enum | The interception point where the interceptor will be invoked. |
InterceptorBindConfig | Struct | Configuration returned from binding an interceptor to a Gateway. |
InterceptorOptions | Struct | Options for configuring an interceptor. |
InvocationConfiguration | Struct | Invocation configuration for self managed memory strategy. |
IOAuth2CredentialProvider | Interface | An OAuth2 credential provider registered in AgentCore Token Vault. |
IOnlineEvaluationConfig | Interface | Interface for OnlineEvaluationConfig resources. |
IPolicy | Interface | Minimal reference interface for Policy resources. |
IPolicyEngine | Interface | Contains all properties and methods for both created and imported policy engines. |
IRuntimeEndpoint | Interface | Interface for Runtime Endpoint resources. |
ITargetConfiguration | Interface | Base interface for target configurations. |
IWorkloadIdentity | Interface | A workload identity for Amazon Bedrock AgentCore. |
KinesisStreamDeliveryOptions | Struct | Options for delivering memory record events to a Kinesis Data Stream. |
LambdaInterceptor | Class | A Lambda-based interceptor for Gateway. |
LambdaTargetConfiguration | Class | Configuration for Lambda-based MCP targets. |
LifecycleConfiguration | Struct | LifecycleConfiguration lets you manage the lifecycle of runtime sessions and resources in AgentCore Runtime. |
LinkedinOAuth2CredentialProviderProps | Struct | Props for {@link OAuth2CredentialProvider.usingLinkedin}. |
LlmAsAJudgeOptions | Struct | Options for configuring an LLM-as-a-Judge custom evaluator. |
LoggingConfig | Struct | Configuration for logging with log type and destination. |
LoggingDestination | Class | Represents a logging destination for AgentCore Runtime. |
LogType | Class | Log types for AgentCore Runtime observability. |
ManagedMemoryStrategy | Class | Managed memory strategy that handles both built-in and override configurations. |
ManagedStrategyProps | Struct | Configuration parameters for a memory strategy that can override existing built-in default prompts/models. |
McpConfiguration | Struct | MCP protocol configuration The configuration for the Model Context Protocol (MCP). |
McpGatewaySearchType | Class | Search types supported by MCP gateway. |
McpProtocolConfiguration | Class | MCP (Model Context Protocol) configuration implementation. |
MCPProtocolVersion | Class | MCP protocol versions. |
McpServerTargetConfiguration | Class | Configuration for MCP Server-based targets. |
McpTargetConfiguration | Class | Abstract base class for MCP target configurations Provides common functionality for all MCP target types. |
McpTargetType | Enum | MCP target types. |
MemoryAttributes | Struct | Attributes for specifying an imported Memory. |
MemoryProps | Struct | Properties for creating a Memory resource. |
MemoryStrategy | Class | Factory class for creating memory strategies 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. |
MemoryStrategyCommonProps | Struct | Configuration parameters common for any memory strategy. |
MemoryStrategyType | Enum | Long-term memory extraction strategy types. |
MetadataConfiguration | Struct | Configuration for passing metadata (headers and query parameters) to the API Gateway target. |
MicrosoftOAuth2CredentialProviderProps | Struct | Props for {@link OAuth2CredentialProvider.usingMicrosoft}. |
NetworkConfiguration | Class | Abstract base class for network configuration. |
NoAuthAuthorizer | Class | No authorization configuration implementation. |
NotionOAuth2CredentialProviderProps | Struct | Props for {@link OAuth2CredentialProvider.usingNotion}. |
NumericalRatingOption | Struct | A numerical rating scale option for custom evaluators. |
OAuth2AuthorizationServerMetadata | Struct | Static OAuth2 authorization server metadata for custom credential providers. |
OAuth2ClientCredentials | Struct | OAuth2 client identifier and secret registered with the identity provider (all vendors). |
OAuth2CredentialProviderAttributes | Struct | Attributes for importing an existing OAuth2 credential provider. |
OAuth2CredentialProviderBaseProps | Struct | Shared properties for OAuth2 credential providers created via {@link OAuth2CredentialProvider} factory methods. |
OAuth2CredentialProviderFactoryBaseProps | Struct | Naming, tags, and client credentials shared by every {@link OAuth2CredentialProvider} factory. |
OAuth2CredentialProviderIdentityPerms | Class | IAM actions for AgentCore OAuth2 credential providers (Token Vault). |
OAuth2CredentialProviderProps | Struct | Low-level properties when you need full control (prefer {@link OAuth2CredentialProvider.usingSlack} and other factories). |
OAuth2CredentialProviderVendor | Class | Built-in OAuth2 vendors supported by AWS::BedrockAgentCore::OAuth2CredentialProvider. |
OAuthConfiguration | Struct | OAuth configuration. |
OnlineEvaluationBaseProps | Struct | Base properties for creating an OnlineEvaluationConfig. |
OnlineEvaluationConfigAttributes | Struct | Attributes for importing an existing OnlineEvaluationConfig. |
OnlineEvaluationConfigProps | Struct | Properties for creating an OnlineEvaluationConfig. |
OpenApiTargetConfiguration | Class | Configuration for OpenAPI-based MCP targets. |
OverrideConfig | Struct | Configuration for overriding model and prompt template. |
PlatformVersion | Class | The platform version of the Agent Runtime. |
PolicyAction | Class | The action a policy statement applies to. |
PolicyAttribute | Class | An attribute of the request that a condition can compare against. |
PolicyAttributes | Struct | Attributes for importing an existing Policy. |
PolicyCondition | Class | A condition on a policy statement. |
PolicyEffect | Enum | Effect of a policy statement, whether it permits or forbids the action. |
PolicyEngineAttributes | Struct | Attributes for importing an existing PolicyEngine. |
PolicyEngineMode | Class | The enforcement mode for a policy engine associated with a gateway. |
PolicyEngineProps | Struct | Properties for creating a PolicyEngine resource. |
PolicyPrincipal | Class | The principal a policy statement applies to. |
PolicyProps | Struct | Properties for creating a Policy resource. |
PolicyResource | Class | The resource a policy statement applies to. |
PolicyStatement | Class | A Cedar authorization policy statement. |
PolicyStatementProps | Struct | Properties for a policy statement. |
PolicyValidationMode | Class | Validation mode for Cedar policy definitions. |
ProtocolType | Class | Protocol configuration for Agent Runtime. |
RecordingConfig | Struct | Recording configuration for browser. |
RedditOAuth2CredentialProviderProps | Struct | Props for {@link OAuth2CredentialProvider.usingReddit}. |
RequestHeaderConfiguration | Struct | Configuration for HTTP request headers that will be passed through to the runtime. |
RuntimeAuthorizerConfiguration | Class | Abstract base class for runtime authorizer configurations. |
RuntimeCustomClaim | Class | Represents a custom claim validation configuration for Runtime JWT authorizers. |
RuntimeEndpointAttributes | Struct | Attributes for importing an existing Runtime Endpoint. |
RuntimeEndpointProps | Struct | Properties for creating a Bedrock Agent Core Runtime Endpoint resource. |
RuntimeNetworkConfiguration | Class | Network configuration for the Runtime. |
RuntimeProps | Struct | Properties for creating a Bedrock Agent Core Runtime resource. |
S3ApiSchema | Class | Class to define an API Schema from an S3 object. |
S3ToolSchema | Class | Class to define a Tool Schema from an S3 object. |
SalesforceOAuth2CredentialProviderProps | Struct | Props for {@link OAuth2CredentialProvider.usingSalesforce}. |
SchemaDefinition | Struct | Schema definition for tool input/output. |
SchemaDefinitionType | Class | Schema definition types. |
SelfManagedMemoryStrategy | Class | Use AgentCore memory for event storage with custom triggers. |
SelfManagedStrategyProps | Struct | Configuration parameters for a self managed memory strategy existing built-in default prompts/models. |
SlackOAuth2CredentialProviderProps | Struct | Props for {@link OAuth2CredentialProvider.usingSlack}. |
SmithyTargetConfiguration | Class | Configuration for Smithy-based MCP targets. |
SpotifyOAuth2CredentialProviderProps | Struct | Props for {@link OAuth2CredentialProvider.usingSpotify}. |
StreamDeliveryContentConfiguration | Struct | Content configuration for a stream delivery resource. |
StreamDeliveryContentLevel | Enum | Content detail level for stream delivery. |
StreamDeliveryContentType | Enum | Content type for stream delivery. |
StreamDeliveryResource | Class | A delivery target for real-time streaming of memory record lifecycle events. |
TargetConfigurationConfig | Struct | Configuration returned by binding a target configuration. |
ToolDefinition | Struct | Tool definition for inline payload. |
ToolSchema | Class | **************************************************************************** TOOL SCHEMA CLASS ***************************************************************************. |
TriggerConditions | Struct | Trigger conditions for self managed memory strategy When first condition is met, batched payloads are sent to specified S3 bucket. |
TwitchOAuth2CredentialProviderProps | Struct | Props for {@link OAuth2CredentialProvider.usingTwitch}. |
VpcConfigProps | Struct | VPC configuration properties. |
WorkloadIdentityAttributes | Struct | Attributes for importing an existing workload identity. |
WorkloadIdentityPerms | Class | IAM actions for AgentCore workload identities. |
WorkloadIdentityProps | Struct | Properties for a new {@link WorkloadIdentity}. |
XOAuth2CredentialProviderProps | Struct | Props for {@link OAuth2CredentialProvider.usingX}. |
YandexOAuth2CredentialProviderProps | Struct | Props for {@link OAuth2CredentialProvider.usingYandex}. |
ZoomOAuth2CredentialProviderProps | Struct | Props for {@link OAuth2CredentialProvider.usingZoom}. |
TypeScript