【AWS re:Invent 2025】Amazon Bedrock AgentCore PolicyでAIエージェントのツール実行権限を制御してみる

目次
1. はじめに
こんにちは!ベンジャミンの松延(まつのぶ)です!
AWS re:Invent 2025のKeynoteで発表された「Amazon Bedrock AgentCore Policy」(以下、AgentCore Policy)について、情報シェアさせていただきます。
AgentCore Policyは、現時点(2025年12月時点)でプレビュー版として提供されています。
2. AgentCoreの主要コンポーネントについて
AgentCoreの主要コンポーネントについて、現時点(2025年12月時点)では下記になります。
本記事では「Policy」に焦点を当てて解説したいと思います。
他にもAgentCore Evaluationsが、AWS re:Invent 2025で発表されましたが、AgentCore Evaluationsについては本記事では解説しません。改めて別記事にて紹介したいと思います。
| コンポーネント | 役割 / 目的 |
|---|---|
| Runtime | エージェントの実行基盤 |
| Memory | コンテキスト・記憶管理 |
| Policy | 実行可否・権限制御 |
| Evaluations | 出力・振る舞いに関する評価 |
| Observability | 可観測性 |
| Gateway | 外部ツール(MCP等)との接続 |
| Identity | 実行主体の識別 |
3. AgentCore Policyとは
AgentCore Policyは、エージェントに何をしてよいか/してはいけないかを実行前にチェックする仕組みとなります。
AgentCore Policyでは、主に以下を制御することが可能になっています。
- エージェントが使えるツール
- API
- AWS Lambda
- MCP(Model Context Protocol)サーバー
- 外部SaaS
- 実行できるアクション
- 読み取りのみに制御
- 書き込み禁止に制御
- 金額・件数・条件付き許可など
- 条件付きルール
- ユーザーのロール
- JWT / OAuthのクレーム
- ツール引数(例:金額、対象ID)
- 時間帯、環境(prod / dev)など
1. AgentCore Policyの仕組み
ユーザーのリクエストを受け取ったAIエージェントは、推論や計画を行い、必要に応じてツールの実行を試みます。
ただし、エージェントがツールを呼び出したからといって、すぐに実行されるわけではありません。
ツール呼び出しのリクエストは、まずAgentCore Gatewayに送られます。
Gatewayは、AIエージェントとツールの間に立つ入口の役割を持ちます。
Gatewayに到達したリクエストはPolicy Engineに渡され、あらかじめ定義されたポリシーに基づいて「このツール実行を許可してよいか」が判定されます。
判定結果がPermitの場合のみツールが実行され、Denyの場合は実行されません(またはログのみが記録されます)。
この仕組みにより、AIの判断とは独立してツール実行を安全に制御できるようになります。

2. Policyの書き方
AgentCore Policyは「Cedar」と呼ばれる言語によって記載することが可能になっており、下記2パターンによって実現できます。
パターン1:AgentCore Policyコンソールにて自然言語で作成
例:
「refund-agentロールのユーザーのみが、200ドル未満の返金処理を実行できる」
パターン2:Cedar(宣言的ポリシー言語)
permit(
principal is AgentCore::OAuthUser,
action == AgentCore::Action::"RefundTool__process_refund",
resource == AgentCore::Gateway::"<GATEWAY_ARN>"
)
when {
principal.getTag("role") == "refund-agent"
&& context.input.amount < 200
};
3. ログモードと強制モード
Policy Engineは主に2つの動作モードがサポートされています。
| モード | 説明 |
|---|---|
| Log only | 実行は許可、結果だけ記録(検証用) |
| Enforce | Permit / Denyを強制(本番) |
Enabling enforcement: Consider testing and validating policies in log only mode before enabling enforcement to avoid unintended denials or adversely affecting production traffic.
本番運用適用前にLog onlyモードを使用して、ポリシーを事前確認しておいた方が良いと思います。
4. AgentCore Policyを検証してみる
AWS公式ドキュメントにて、AgentCore Policyのハンズオンが提供されていましたので、こちらを検証してみたいと思います。
1. ハンズオンシナリオについて
AWS公式ドキュメントのハンズオンシナリオについては下記になります。
AIエージェントに「返金処理」という危険になり得る操作を任せるとき、“金額が一定以下の場合のみ実行を許可する” という業務ルールをAgentCore Policy(Cedar)で強制する
例えば、「カスタマーサポート向けAIエージェントを運用している」といったユースケースを仮定します。
このエージェントでは次のような会話をします。
ユーザー:「商品を返品したいです」
エージェント:「返金処理を行います」
ここで下記が問題になります。
- AIがいくらでも返金できてしまうと危険
- プロンプトだけで制御すると幻覚(ハルシネーション)・誤判断のリスク
- 監査・統制の観点でも不十分
そこで導入したいルールは下記とします。
- 「1000ドル以上の返金」の場合、AIでは不可
- 「1000ドル未満の返金」の場合、AIに許可
この業務ルールをLLMではなくAWS側のPolicy Engineで強制するといった形になります。
一方で、技術的な観点で言うと登場人物は下記になります。
| 役割 | サービス |
|---|---|
| ツール実行の入口 | AgentCore Gateway |
| 実際の処理 | Lambda(返金処理ツール) |
| 認可判断 | AgentCore Policy Engine |
| ポリシー定義 | Cedar |
処理フローとしては下記になります。
- AIエージェントが「返金処理ツール(process_refund)」を使おうとする
- リクエストはAgentCore Gatewayに届く
- GatewayがPolicy Engineへ問い合わせ
- Policy EngineがCedarポリシーを評価
- 条件を満たせば → Lambda実行
- 満たさなければ → 実行前に拒否
2. ハンズオンの前提条件
ハンズオンを実施するにあたり前提条件は下記となります。
- AWSアカウント
- このハンズオンでは、オレゴンリージョン(us-west-2)にてAgentCore Policyがデプロイされます
- Python3.10以上
- ローカル環境に事前にPython3.10以上をインストールしてください
- IAM権限
- Lambda、Policy Engine、Gateway作成などの権限を持ったIAMユーザーが必要です
- 事前にローカル端末上にAWS認証情報を設定してください
3. Step 1: 事前準備
ローカル環境にてPython仮想環境を作成し、必要なライブラリをインストールしましょう!
1. 作業用ディレクトリを作成し、ディレクトリを移動します。
mkdir hands-on-agent-core-policy
cd hands-on-agent-core-policy
2. Python仮想環境を作成します。
python3 -m venv .venv
source .venv/bin/activate
3. 必要なライブラリをインストールします。
pip install boto3
pip install bedrock-agentcore-starter-toolkit
pip install requests
4. Step 2: Policyを作成する
AWS公式ドキュメントのハンズオンでは、スクリプトを使用して効率よくPolicyを構築するようになっています。
1. スクリプトファイルを作成します。
touch setup_policy.py
2. 下記スクリプトをsetup_policy.pyに保存します。
"""
Setup script to create Gateway with Policy Engine
Run this first: python setup_policy.py
"""
from bedrock_agentcore_starter_toolkit.operations.gateway.client import GatewayClient
from bedrock_agentcore_starter_toolkit.operations.policy.client import PolicyClient
from bedrock_agentcore_starter_toolkit.utils.lambda_utils import create_lambda_function
import boto3
import json
import logging
import time
def setup_policy():
# Configuration
region = "us-west-2"
refund_limit = 1000
print("🚀 Setting up AgentCore Gateway with Policy Engine...")
print(f"Region: {region}\n")
# Initialize clients
gateway_client = GatewayClient(region_name=region)
gateway_client.logger.setLevel(logging.INFO)
policy_client = PolicyClient(region_name=region)
policy_client.logger.setLevel(logging.INFO)
# Step 1: Create OAuth authorizer
print("Step 1: Creating OAuth authorization server...")
cognito_response = gateway_client.create_oauth_authorizer_with_cognito("PolicyGateway")
print("✓ Authorization server created\n")
# Step 2: Create Gateway
print("Step 2: Creating Gateway...")
gateway = gateway_client.create_mcp_gateway(
name=None,
role_arn=None,
authorizer_config=cognito_response["authorizer_config"],
enable_semantic_search=False,
)
print(f"✓ Gateway created: {gateway['gatewayUrl']}\n")
# Fix IAM permissions
gateway_client.fix_iam_permissions(gateway)
print("⏳ Waiting 30s for IAM propagation...")
time.sleep(30)
print("✓ IAM permissions configured\n")
# Step 3: Create Lambda function with refund tool
print("Step 3: Creating Lambda function with refund tool...")
refund_lambda_code = """
def lambda_handler(event, context):
amount = event.get('amount', 0)
return {
"status": "success",
"message": f"Refund of ${amount} processed successfully",
"amount": amount
}
"""
session = boto3.Session(region_name=region)
lambda_arn = create_lambda_function(
session=session,
logger=gateway_client.logger,
function_name=f"RefundTool-{int(time.time())}",
lambda_code=refund_lambda_code,
runtime="python3.13",
handler="lambda_function.lambda_handler",
gateway_role_arn=gateway["roleArn"],
description="Refund tool for policy demo",
)
print("✓ Lambda function created\n")
# Step 4: Add Lambda target with refund tool schema
print("Step 4: Adding Lambda target with refund tool schema...")
lambda_target = gateway_client.create_mcp_gateway_target(
gateway=gateway,
name="RefundTarget",
target_type="lambda",
target_payload={
"lambdaArn": lambda_arn,
"toolSchema": {
"inlinePayload": [
{
"name": "process_refund",
"description": "Process a customer refund",
"inputSchema": {
"type": "object",
"properties": {
"amount": {
"type": "integer",
"description": "Refund amount in dollars"
}
},
"required": ["amount"],
},
}
]
},
},
credentials=None,
)
print("✓ Lambda target added\n")
# Step 5: Create Policy Engine
print("Step 5: Creating Policy Engine...")
engine = policy_client.create_or_get_policy_engine(
name="RefundPolicyEngine",
description="Policy engine for refund governance"
)
print(f"✓ Policy Engine: {engine['policyEngineId']}\n")
# Step 6: Create Cedar policy
print(f"Step 6: Creating Cedar policy (refund limit: ${refund_limit})...")
cedar_statement = (
f"permit(principal, "
f'action == AgentCore::Action::"RefundTarget___process_refund", '
f'resource == AgentCore::Gateway::"{gateway["gatewayArn"]}") '
f"when {{ context.input.amount < {refund_limit} }};"
)
policy = policy_client.create_or_get_policy(
policy_engine_id=engine["policyEngineId"],
name="refund_limit_policy",
description=f"Allow refunds under ${refund_limit}",
definition={"cedar": {"statement": cedar_statement}},
)
print(f"✓ Policy: {policy['policyId']}\n")
# Step 7: Attach Policy Engine to Gateway
print("Step 7: Attaching Policy Engine to Gateway (ENFORCE mode)...")
gateway_client.update_gateway_policy_engine(
gateway_identifier=gateway["gatewayId"],
policy_engine_arn=engine["policyEngineArn"],
mode="ENFORCE"
)
print("✓ Policy Engine attached to Gateway\n")
# Step 8: Save configuration
config = {
"gateway_url": gateway["gatewayUrl"],
"gateway_id": gateway["gatewayId"],
"gateway_arn": gateway["gatewayArn"],
"policy_engine_id": engine["policyEngineId"],
"policy_engine_arn": engine["policyEngineArn"],
"policy_id": policy["policyId"],
"region": region,
"client_info": cognito_response["client_info"],
"refund_limit": refund_limit
}
with open("config.json", "w") as f:
json.dump(config, f, indent=2)
print("=" * 60)
print("✅ Setup complete!")
print(f"Gateway URL: {gateway['gatewayUrl']}")
print(f"Policy Engine ID: {engine['policyEngineId']}")
print(f"Refund limit: ${refund_limit}")
print("\nConfiguration saved to: config.json")
print("\nNext step: Run 'python test_policy.py' to test your Policy")
print("=" * 60)
return config
if __name__ == "__main__":
setup_policy()
上記スクリプトで作成されるリソースは下記になります。
- Cognito
- MCPツール(Lambda関数)
- Cedarポリシー
- AgentCore Gateway
- Inbound Authの設定(Cognito)
- Lambda関数をターゲットに関連付け
5. Step 3: Policyをデプロイする
スクリプトを実行し、Policyをデプロイしましょう!
1. スクリプトを実行します。
python setup_policy.py
正常にスクリプトが実行されると下記のような出力結果が得られると思います。
(.venv) matsunobu@KoheiMatsunobuBJM hands-on-agent-core-policy % python setup_policy.py
🚀 Setting up AgentCore Gateway with Policy Engine...
Region: us-west-2
Step 1: Creating OAuth authorization server...
2025-12-15 19:59:35,267 - bedrock_agentcore.gateway - INFO - Starting EZ Auth setup: Creating Cognito resources...
2025-12-15 19:59:36,816 - bedrock_agentcore.gateway - INFO - ✓ Created User Pool: us-west-2_OeMDAXLeF
2025-12-15 19:59:38,141 - bedrock_agentcore.gateway - INFO - ✓ Created domain: agentcore-2796be2e
2025-12-15 19:59:38,141 - bedrock_agentcore.gateway - INFO - ⏳ Waiting for domain to be available...
2025-12-15 19:59:38,355 - bedrock_agentcore.gateway - INFO - ✓ Domain is active
2025-12-15 19:59:38,713 - bedrock_agentcore.gateway - INFO - ✓ Created resource server: PolicyGateway
2025-12-15 19:59:39,107 - bedrock_agentcore.gateway - INFO - ✓ Created client: 2cn4s0mqu5p2f2vdkj92976ot6
2025-12-15 19:59:39,107 - bedrock_agentcore.gateway - INFO - ⏳ Waiting for DNS propagation of domain: agentcore-2796be2e.auth.us-west-2.amazoncognito.com
2025-12-15 20:00:39,111 - bedrock_agentcore.gateway - INFO - ✓ EZ Auth setup complete!
✓ Authorization server created
Step 2: Creating Gateway...
2025-12-15 20:00:39,119 - bedrock_agentcore.gateway - INFO - Role not provided, creating an execution role to use
2025-12-15 20:00:41,166 - bedrock_agentcore.gateway - INFO - ✓ Successfully created execution role for Gateway
2025-12-15 20:00:41,166 - bedrock_agentcore.gateway - INFO - Creating Gateway
2025-12-15 20:00:41,781 - bedrock_agentcore.gateway - INFO - ✓ Created Gateway: arn:aws:bedrock-agentcore:us-west-2:123456789012:gateway/testgatewayba14d022-toqm9nri99
2025-12-15 20:00:41,781 - bedrock_agentcore.gateway - INFO - Gateway URL: https://testgatewayba14d022-toqm9nri99.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp
2025-12-15 20:00:41,781 - bedrock_agentcore.gateway - INFO - Waiting for Gateway to be ready...
2025-12-15 20:00:44,222 - bedrock_agentcore.gateway - INFO -
✅Gateway is ready
ObservabilityDeliveryManager initialized for region: us-west-2, account: 123456789012
Created log group: /aws/vendedlogs/bedrock-agentcore/gateway/APPLICATION_LOGS/testgatewayba14d022-toqm9nri99
✅ Logs delivery enabled for gateway/testgatewayba14d022-toqm9nri99
✅ Traces delivery enabled for gateway/testgatewayba14d022-toqm9nri99
Observability enabled for gateway/testgatewayba14d022-toqm9nri99 - logs: True, traces: True
2025-12-15 20:00:47,807 - bedrock_agentcore.gateway - INFO - ✅ Observability enabled for gateway testgatewayba14d022-toqm9nri99
2025-12-15 20:00:47,808 - bedrock_agentcore.gateway - INFO - Log group: /aws/vendedlogs/bedrock-agentcore/gateway/APPLICATION_LOGS/testgatewayba14d022-toqm9nri99
✓ Gateway created: https://testgatewayba14d022-toqm9nri99.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp
2025-12-15 20:00:49,482 - bedrock_agentcore.gateway - INFO - ✓ Fixed IAM permissions for Gateway
⏳ Waiting 30s for IAM propagation...
✓ IAM permissions configured
Step 3: Creating Lambda function with refund tool...
2025-12-15 20:01:20,648 - bedrock_agentcore.gateway - INFO - ✓ Created Lambda execution role: arn:aws:iam::123456789012:role/RefundTool-1765796479Role
⏳ IAM role not ready to be asssumed (attempt 1/4), retrying in 5s... Role: arn:aws:iam::123456789012:role/RefundTool-1765796479Role
⏳ IAM role not ready to be asssumed (attempt 2/4), retrying in 10s... Role: arn:aws:iam::123456789012:role/RefundTool-1765796479Role
2025-12-15 20:01:37,175 - bedrock_agentcore.gateway - INFO - ✓ Created Lambda function: arn:aws:lambda:us-west-2:123456789012:function:RefundTool-1765796479
2025-12-15 20:01:37,175 - bedrock_agentcore.gateway - INFO - ✓ Attaching access policy to: arn:aws:lambda:us-west-2:123456789012:function:RefundTool-1765796479 for arn:aws:iam::123456789012:role/AgentCoreGatewayExecutionRole
2025-12-15 20:01:37,383 - bedrock_agentcore.gateway - INFO - ✓ Attached permissions for role invocation: arn:aws:lambda:us-west-2:123456789012:function:RefundTool-1765796479
✓ Lambda function created
Step 4: Adding Lambda target with refund tool schema...
2025-12-15 20:01:37,387 - bedrock_agentcore.gateway - INFO - Creating Target
2025-12-15 20:01:37,387 - bedrock_agentcore.gateway - INFO - {'gatewayIdentifier': 'testgatewayba14d022-toqm9nri99', 'name': 'RefundTarget', 'targetConfiguration': {'mcp': {'lambda': {'lambdaArn': 'arn:aws:lambda:us-west-2:123456789012:function:RefundTool-1765796479', 'toolSchema': {'inlinePayload': [{'name': 'process_refund', 'description': 'Process a customer refund', 'inputSchema': {'type': 'object', 'properties': {'amount': {'type': 'integer', 'description': 'Refund amount in dollars'}}, 'required': ['amount']}}]}}}}, 'credentialProviderConfigurations': [{'credentialProviderType': 'GATEWAY_IAM_ROLE'}]}
2025-12-15 20:01:37,727 - bedrock_agentcore.gateway - INFO - ✓ Added target successfully (ID: PN3VQXKUYO)
2025-12-15 20:01:37,727 - bedrock_agentcore.gateway - INFO - Waiting for target to be ready...
2025-12-15 20:01:40,257 - bedrock_agentcore.gateway - INFO -
✅Target is ready
✓ Lambda target added
Step 5: Creating Policy Engine...
2025-12-15 20:01:40,257 - bedrock_agentcore.policy - INFO - Creating or getting Policy Engine: RefundPolicyEngine
2025-12-15 20:01:40,736 - bedrock_agentcore.policy - INFO - Creating Policy Engine: RefundPolicyEngine
2025-12-15 20:01:40,941 - bedrock_agentcore.policy - INFO - ✓ Policy Engine creation initiated: arn:aws:bedrock-agentcore:us-west-2:123456789012:policy-engine/RefundPolicyEngine-4uzy3mp8cw
2025-12-15 20:01:40,942 - bedrock_agentcore.policy - INFO - Waiting for Policy Engine to be active...
2025-12-15 20:01:43,293 - bedrock_agentcore.policy - INFO - ✓ Policy Engine is active
✓ Policy Engine: RefundPolicyEngine-4uzy3mp8cw
Step 6: Creating Cedar policy (refund limit: $1000)...
2025-12-15 20:01:43,294 - bedrock_agentcore.policy - INFO - Creating or getting Policy: refund_limit_policy
2025-12-15 20:01:43,457 - bedrock_agentcore.policy - INFO - Creating Policy: refund_limit_policy
2025-12-15 20:01:43,793 - bedrock_agentcore.policy - INFO - ✓ Policy creation initiated: arn:aws:bedrock-agentcore:us-west-2:123456789012:policy-engine/RefundPolicyEngine-4uzy3mp8cw/policy/refund_limit_policy-130esibtzd
2025-12-15 20:01:43,793 - bedrock_agentcore.policy - INFO - Waiting for Policy to be active...
2025-12-15 20:01:50,484 - bedrock_agentcore.policy - INFO - ✓ Policy is active
✓ Policy: refund_limit_policy-130esibtzd
Step 7: Attaching Policy Engine to Gateway (ENFORCE mode)...
2025-12-15 20:01:50,484 - bedrock_agentcore.gateway - INFO - Attaching policy engine to gateway
2025-12-15 20:01:50,484 - bedrock_agentcore.gateway - INFO - Updating gateway testgatewayba14d022-toqm9nri99
2025-12-15 20:01:50,684 - bedrock_agentcore.gateway - INFO - Policy Engine ARN: arn:aws:bedrock-agentcore:us-west-2:123456789012:policy-engine/RefundPolicyEngine-4uzy3mp8cw
2025-12-15 20:01:50,684 - bedrock_agentcore.gateway - INFO - Mode: ENFORCE
2025-12-15 20:01:51,029 - bedrock_agentcore.gateway - INFO - ✓ Gateway update initiated
2025-12-15 20:01:51,029 - bedrock_agentcore.gateway - INFO - Waiting for gateway to be ready...
2025-12-15 20:01:53,473 - bedrock_agentcore.gateway - INFO - ✓ Gateway update complete
✓ Policy Engine attached to Gateway
============================================================
✅ Setup complete!
Gateway URL: https://testgatewayba14d022-toqm9nri99.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp
Policy Engine ID: RefundPolicyEngine-4uzy3mp8cw
Refund limit: $1000
Configuration saved to: config.json
Next step: Run 'python test_policy.py' to test your Policy
============================================================
念の為、AWSマネジメントコンソール上でリソースが作成されていることも確認しておきましょう!
2. AWSマネジメントコンソールにアクセスします
3. リージョンをオレゴンリージョン(us-west-2)に切り替えます
4. AgentCoreコンソールを開きます


5. AgentCoreコンソール画面左側の[Build] > [Policy]を開きます

6. Policy一覧にリソース(RefundPolicyEngine)が作成されていることを確認します。

スクリプトファイルによって構築されたAgentCore Policyは下記のようになっています。

Cedarによるポリシー定義は下記のようになっています。

AgentCore Gatewayは下記のようになっています。




AgentCore GatewayのターゲットエンドポイントはLambda関数になっています。



6. Step 4: Policyをテストする
では、実際にPolicyをテストしてみましょう!
ハンズオンでは、テストスクリプトを使用します。
1. テストスクリプトファイルを作成します。
touch test_policy.py
2. 下記ソースコードをtest_policy.pyに保存します。
"""
Test Policy Engine with direct HTTP calls to Gateway
Run after setup: python test_policy.py
"""
import json
import sys
import requests
from bedrock_agentcore_starter_toolkit.operations.gateway.client import GatewayClient
def test_refund(gateway_url, bearer_token, amount):
"""Test a refund request - print raw response"""
response = requests.post(
gateway_url,
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {bearer_token}",
},
json={
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "RefundTarget___process_refund",
"arguments": {"amount": amount}
},
},
)
print(f"Status Code: {response.status_code}")
print(f"Response Body: {json.dumps(response.json(), indent=2)}")
return response
def main():
print("=" * 60)
print("🧪 Testing Policy Engine")
print("=" * 60 + "\n")
# Load configuration
try:
with open("config.json", "r") as f:
config = json.load(f)
except FileNotFoundError:
print("❌ Error: config.json not found!")
print("Please run 'python setup_policy.py' first.")
sys.exit(1)
gateway_url = config["gateway_url"]
refund_limit = config["refund_limit"]
print(f"Gateway: {gateway_url}")
print(f"Refund limit: ${refund_limit}\n")
# Get access token
print("🔑 Getting access token...")
gateway_client = GatewayClient(region_name=config["region"])
token = gateway_client.get_access_token_for_cognito(config["client_info"])
print("✅ Token obtained\n")
# Test 1: Refund $500 (should be allowed)
print(f"📝 Test 1: Refund $500 (Expected: ALLOW)")
print("-" * 40)
test_refund(gateway_url, token, 500)
print()
# Test 2: Refund $2000 (should be denied)
print(f"📝 Test 2: Refund $2000 (Expected: DENY)")
print("-" * 40)
test_refund(gateway_url, token, 2000)
print()
print("=" * 60)
print("✅ Testing complete!")
print("=" * 60)
if __name__ == "__main__":
main()
スクリプトファイルの内容は下記になります。
| 項目 | 内容 |
|---|---|
| テスト対象 | AgentCore Gateway + Policy Engine |
| テスト方法 | Gatewayに直接HTTPリクエストを送信 |
| 認証 | Cognitoで取得したBearerトークン |
| 呼び出すツール | RefundTarget___process_refund |
| 入力パラメータ | amount(返金金額) |
| 期待する制御 | CedarポリシーによるPermit / Deny判定 |
実行されるテストケースは下記になります。
| テスト名 | 返金額 | 期待結果 | 確認ポイント |
|---|---|---|---|
| Test 1 | $500 | ALLOW | ポリシー条件($1000未満)を満たし、ツールが実行される |
| Test 2 | $2000 | DENY | ポリシー条件を満たさず、ツール実行がブロックされる |
3. テストスクリプトを実行します。
python test_policy.py
実行すると下記のような出力結果が得られます。
(.venv) matsunobu@KoheiMatsunobuBJM hands-on-agent-core-policy % python test_policy.py
============================================================
🧪 Testing Policy Engine
============================================================
Gateway: https://testgatewayba14d022-toqm9nri99.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp
Refund limit: $1000
🔑 Getting access token...
2025-12-15 20:09:03,825 - bedrock_agentcore.gateway - INFO - Fetching test token from Cognito...
2025-12-15 20:09:03,825 - bedrock_agentcore.gateway - INFO - Attempting to connect to token endpoint: https://agentcore-2796be2e.auth.us-west-2.amazoncognito.com/oauth2/token
2025-12-15 20:09:04,867 - bedrock_agentcore.gateway - INFO - ✓ Got test token successfully
✅ Token obtained
📝 Test 1: Refund $500 (Expected: ALLOW)
----------------------------------------
Status Code: 200
Response Body: {
"jsonrpc": "2.0",
"id": 1,
"result": {
"isError": false,
"content": [
{
"type": "text",
"text": "{\"status\":\"success\",\"message\":\"Refund of $500 processed successfully\",\"amount\":500}"
}
]
}
}
📝 Test 2: Refund $2000 (Expected: DENY)
----------------------------------------
Status Code: 200
Response Body: {
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32002,
"message": "Tool Execution Denied: Tool call not allowed due to policy enforcement [No policy applies to the request (denied by default).]"
}
}
============================================================
✅ Testing complete!
============================================================
実行結果によると、テストケース1においては、$500のためPolicyによりツール実行が許可されています。
一方で、テストケース2においては、$2000のためPolicyによりツール実行が拒否されています。
AgentCore Policyによって、ツール実行の許可・拒否が機能していることがわかりました!
7. Step 5: ハンズオンで使用したリソースをクリーンアップする
最後にハンズオンで作成されたリソースについては、利用料金が発生する可能性があるためクリーンアップしておきましょう!
クリーンアップ用のスクリプトが準備されていますので、こちらを実行して検証を終了したいと思います。
1. クリーンアップ用スクリプトファイルを作成します。
touch cleanup_policy.py
2. 下記ソースコードをcleanup_policy.pyに保存します。
"""
Cleanup script to remove Gateway and Policy Engine resources
Run this to clean up: python cleanup_policy.py
"""
from bedrock_agentcore_starter_toolkit.operations.gateway.client import GatewayClient
from bedrock_agentcore_starter_toolkit.operations.policy.client import PolicyClient
import json
def cleanup():
with open("config.json", "r") as f:
config = json.load(f)
# Clean up Policy Engine first
print("🧹 Cleaning up Policy Engine...")
policy_client = PolicyClient(region_name=config["region"])
policy_client.cleanup_policy_engine(config["policy_engine_id"])
print("✓ Policy Engine cleaned up\n")
# Then clean up Gateway
print("🧹 Cleaning up Gateway...")
gateway_client = GatewayClient(region_name=config["region"])
gateway_client.cleanup_gateway(config["gateway_id"], config["client_info"])
print("✅ Cleanup complete!")
if __name__ == "__main__":
cleanup()
3. クリーンアップ用スクリプトファイルを実行します。
python cleanup_policy.py
正常実行されると、下記のような出力結果が得られると思います。
(.venv) matsunobu@KoheiMatsunobuBJM hands-on-agent-core-policy % python cleanup_policy.py
🧹 Cleaning up Policy Engine...
2025-12-15 20:40:08,920 - bedrock_agentcore.policy - INFO - 🧹 Cleaning up Policy Engine: RefundPolicyEngine-4uzy3mp8cw
2025-12-15 20:40:09,573 - bedrock_agentcore.policy - INFO - Found 1 policies to delete
2025-12-15 20:40:09,574 - bedrock_agentcore.policy - INFO - • Deleting policy: refund_limit_policy
2025-12-15 20:40:09,574 - bedrock_agentcore.policy - INFO - Deleting Policy: refund_limit_policy-130esibtzd
2025-12-15 20:40:09,833 - bedrock_agentcore.policy - INFO - ✓ Policy deletion initiated: refund_limit_policy-130esibtzd
2025-12-15 20:40:09,833 - bedrock_agentcore.policy - INFO - ✓ Policy deletion initiated: refund_limit_policy
2025-12-15 20:40:12,210 - bedrock_agentcore.policy - INFO - ✓ Policy deleted
2025-12-15 20:40:12,210 - bedrock_agentcore.policy - INFO - • Deleting policy engine: RefundPolicyEngine-4uzy3mp8cw
2025-12-15 20:40:12,210 - bedrock_agentcore.policy - INFO - Deleting Policy Engine: RefundPolicyEngine-4uzy3mp8cw
2025-12-15 20:40:12,442 - bedrock_agentcore.policy - INFO - ✓ Policy Engine deletion initiated: RefundPolicyEngine-4uzy3mp8cw
2025-12-15 20:40:12,442 - bedrock_agentcore.policy - INFO - ✓ Policy engine deleted
2025-12-15 20:40:12,442 - bedrock_agentcore.policy - INFO - ✅ Policy Engine cleanup complete
✓ Policy Engine cleaned up
🧹 Cleaning up Gateway...
2025-12-15 20:40:12,460 - bedrock_agentcore.gateway - INFO - 🧹 Cleaning up Gateway resources...
2025-12-15 20:40:12,460 - bedrock_agentcore.gateway - INFO - • Finding targets for gateway: testgatewayba14d022-toqm9nri99
2025-12-15 20:40:12,990 - bedrock_agentcore.gateway - INFO - Found 1 targets to delete
2025-12-15 20:40:12,991 - bedrock_agentcore.gateway - INFO - • Deleting target: PN3VQXKUYO
2025-12-15 20:40:13,228 - bedrock_agentcore.gateway - INFO - ✓ Target deletion initiated: PN3VQXKUYO
2025-12-15 20:40:18,232 - bedrock_agentcore.gateway - INFO - • Verifying targets deletion...
2025-12-15 20:40:23,463 - bedrock_agentcore.gateway - INFO - ✓ All targets deleted
2025-12-15 20:40:23,464 - bedrock_agentcore.gateway - INFO - • Deleting gateway: testgatewayba14d022-toqm9nri99
2025-12-15 20:40:23,694 - bedrock_agentcore.gateway - INFO - ✓ Gateway deleted: testgatewayba14d022-toqm9nri99
2025-12-15 20:40:23,716 - bedrock_agentcore.gateway - INFO - • Deleting Cognito domain: agentcore-2796be2e
2025-12-15 20:40:24,990 - bedrock_agentcore.gateway - INFO - ✓ Cognito domain deleted
2025-12-15 20:40:29,992 - bedrock_agentcore.gateway - INFO - • Deleting Cognito user pool: us-west-2_OeMDAXLeF
2025-12-15 20:40:30,296 - bedrock_agentcore.gateway - INFO - ✓ Cognito user pool deleted
2025-12-15 20:40:30,296 - bedrock_agentcore.gateway - INFO - ✅ Cleanup complete
✅ Cleanup complete!
このクリーンアップスクリプトでは、Lambda関数はクリーンアップされません。
AWSマネジメントコンソール上から手動でクリーンアップしておきましょう。
5. まとめ
AgentCore Policyは、エージェントに何をしてよいか/してはいけないかを実行前にチェックする仕組みとなります。
プロンプトだけでツール実行を制御すると幻覚(ハルシネーション)・誤判断のリスクがあるため、AgentCore Policyによってツール実行の許可・拒否を制御できることはとても便利だと感じました!
