🐎

Amazon Bedrock AgentCore Workshop in ServerlessDays Tokyo 2025

に公開

はじめに

9/19,20に「ServerlessDays Tokyo 2025」に参加してきました。初参加&初スタッフで運営(のお手伝い)もさせていただきました。2日目はスタッフをこなしつつ,AWSのワークショップに参加しました。1つめのワークショップは公開されているので,後日改めてじっくり取り組んだ内容をここに執筆しました。

  1. Amazon Bedrock AgentCore Workshop: From Basic to Advanced Agent Development
  2. Apache Icebergを体験しよう!サーバーレスのAthenaとS3でIcebergに入門する

ワークショップ

Lab1: Code Interpreter

Code InterpreterはAIエージェントがプログラムを実行するための独立した環境を提供。デフォルトの実行時間は15分,最大8時間まで延長可能。現在はPython,JavaScrip,TypeScriptをサポート。

実行コマンドとスクリプトの処理概要を記載します。

$uv run python test_cost_estimator_agent.py --architecture "パン屋のWebサイトをHTMLでなるべく安く作りたい"
  1. test_cost_estimator_agent.py
    test_regular()において,コスト見積エージェントをインスタンス化し,--architectureオプションの値を引数としてcost_estimator_agent.py estimate_cost() を呼び出す。

    # 1. インスタンスを作成
    interpreter = CodeInterpreter(region="us-west-2")
    
  2. コンテキストマネージャー _estimation_agent()
    Code Interpreter,AWS Pricing MCP Clientをインスタンス化。AWS Pricing MCP Clientが利用可能なツール一覧を取得&ツール一覧に execute_cost_calculation() を追加。これらツール群をAIエージェントに渡す(AIエージェントのインスタンス化)。プロンプトテンプレート(COST_ESTIMATION_PROMPT)に--architectureオプションの値を設定してAIエージェントを実行する。

    # 2. セッションを開始
    interpreter.start()
    
  3. AIエージェント実行
    AIエージェントはpricing toolsを用いてAWSサービスの料金を取得する。その後,Code Interpreterで料金計算スクリプトを実行する。

    # 3. コードを実行
    result = interpreter.invoke("executeCode", {
        "language": "python",
        "code": "print('Hello from secure sandbox!')"
    })
    
  4. cleanup()
    Code Interpreterを停止する。

    # 4. セッションを終了
    interpreter.stop()
    

Lab2: AgentCore Runtime

AgentCore Runtimeは実装言語/フレームワークによらずAIエージェントをデプロイする機能。各セッションは個別のmicroVMで稼働し,メモリ,ファイルシステム,CPUが独立している。最大8時間連続可能。LLMの応答待ち時間は課金対象外。

prepare.pyを実行するとIAMロール(AgentCoreRole-cost_estimator_agent)が作成されます。

次にagentcore configureコマンドを実行してAgentCore Runtimeの設定ファイル(.bedrock_agentcore.yaml,Dockerfile)を作成します。Dockerfileまで作成してくれるのはラクですね。

$uv run agentcore configure --entrypoint deployment/invoke.py \
--name cost_estimator_agent \
--execution-role arn:aws:iam::{AccountId}:role/AgentCoreRole-cost_estimator_agent \
--requirements-file deployment/requirements.txt \
--region us-west-2

Configuring Bedrock AgentCore...
Entrypoint parsed: file=/workshop/02_runtime/deployment/invoke.py, bedrock_agentcore_name=invoke
Agent name: cost_estimator_agent

🏗️  ECR Repository
Press Enter to auto-create ECR repository, or provide ECR Repository URI to use existing
ECR Repository URI (or press Enter to auto-create):
✓ Will auto-create ECR repository
✓ Using requirements file: /workshop/02_runtime/deployment/requirements.txt

🔐 Authorization Configuration
By default, Bedrock AgentCore uses IAM authorization.
Configure OAuth authorizer instead? (yes/no) [no]:
✓ Using default IAM authorization
Configuring BedrockAgentCore agent: cost_estimator_agent
Generated Dockerfile: /workshop/02_runtime/Dockerfile
Generated .dockerignore: /workshop/02_runtime/.dockerignore
Setting 'cost_estimator_agent' as default agent
╭─────────────────────────── Configuration Success ───────────────────────────────────╮
│ Configuration Complete                                                              │
│                                                                                     │
│ Agent Details:                                                                      │
│ Agent Name: cost_estimator_agent                                                    │
│ Runtime: Docker                                                                     │
│ Region: us-west-2                                                                   │
│ Account: {AccountId}                                                               │
│                                                                                     │
│ Configuration:                                                                      │
│ Execution Role: arn:aws:iam::{AccountId}:role/AgentCoreRole-cost_estimator_agent   │
│ ECR Repository: Auto-create                                                         │
│ Authorization: IAM (default)                                                        │
│                                                                                     │
│ 📄 Config saved to: /workshop/02_runtime/.bedrock_agentcore.yaml                   │
│                                                                                     │
│ Next Steps:                                                                         │
│    agentcore launch                                                                 │
╰─────────────────────────────────────────────────────────────────────────────────────╯
default_agent: cost_estimator_agent
agents:
  cost_estimator_agent:
    name: cost_estimator_agent
    entrypoint: deployment/invoke.py
    platform: linux/arm64
    container_runtime: docker
    aws:
      execution_role: arn:aws:iam::{AccountId}:role/AgentCoreRole-cost_estimator_agent
      execution_role_auto_create: true
      account: '{AccountId}'
      region: us-west-2
      ecr_repository: null
      ecr_auto_create: true
      network_configuration:
        network_mode: PUBLIC
      protocol_configuration:
        server_protocol: HTTP
      observability:
        enabled: true
    bedrock_agentcore:
      agent_id: null
      agent_arn: null
      agent_session_id: null
    codebuild:
      project_name: null
      execution_role: null
      source_bucket: null
    authorizer_configuration: null
    oauth_configuration: null
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim

# All environment variables in one layer
ENV UV_SYSTEM_PYTHON=1 UV_COMPILE_BYTECODE=1 PYTHONUNBUFFERED=1 \
    AWS_REGION=us-west-2 AWS_DEFAULT_REGION=us-west-2 \
    DOCKER_CONTAINER=1

COPY deployment/requirements.txt deployment/requirements.txt

RUN uv pip install -r deployment/requirements.txt && \
    uv pip install aws-opentelemetry-distro>=0.10.1

EXPOSE 8080 8000

# Copy entire project
COPY . .

# Use the full module path
CMD ["opentelemetry-instrument", "python", "-m", "deployment.invoke"]

最後にagentcore launchコマンドでAgentCore Runtimeを作成します。

$uv run agentcore launch
🚀 Launching Bedrock AgentCore (codebuild mode - RECOMMENDED)...
   • Build ARM64 containers in the cloud with CodeBuild
   • No local Docker required (DEFAULT behavior)
   • Production-ready deployment

💡 Deployment options:
   • agentcore launch                → CodeBuild (current)
   • agentcore launch --local        → Local development
   • agentcore launch --local-build  → Local build + cloud deploy

Starting CodeBuild ARM64 deployment for agent 'cost_estimator_agent' to account {AccountId} (us-west-2)
Setting up AWS resources (ECR repository, execution roles)...
Getting or creating ECR repository for agent: cost_estimator_agent
Repository doesn't exist, creating new ECR repository: bedrock-agentcore-cost_estimator_agent
⠹ Launching Bedrock AgentCore...✅ ECR repository available: {AccountId}.dkr.ecr.us-west-2.amazonaws.com/bedrock-agentcore-cost_estimator_agent
Using execution role from config: arn:aws:iam::{AccountId}:role/AgentCoreRole-cost_estimator_agent
Preparing CodeBuild project and uploading source...
⠼ Launching Bedrock AgentCore...Getting or creating CodeBuild execution role for agent: cost_estimator_agent
Role name: AmazonBedrockAgentCoreSDKCodeBuild-us-west-2-bbbbbbbbbb
⠇ Launching Bedrock AgentCore...Reusing existing CodeBuild execution role: arn:aws:iam::{AccountId}:role/AmazonBedrockAgentCoreSDKCodeBuild-us-west-2-bbbbbbbbbb
⠏ Launching Bedrock AgentCore...Using .dockerignore with 44 patterns
Uploaded source to S3: cost_estimator_agent/source.zip
⠴ Launching Bedrock AgentCore...Updated CodeBuild project: bedrock-agentcore-cost_estimator_agent-builder
Starting CodeBuild build (this may take several minutes)...
⠇ Launching Bedrock AgentCore...Starting CodeBuild monitoring...
🔄 QUEUED started (total: 0s)
⠙ Launching Bedrock AgentCore...✅ QUEUED completed in 1.0s
🔄 PROVISIONING started (total: 1s)
⠸ Launching Bedrock AgentCore...✅ PROVISIONING completed in 11.3s
🔄 DOWNLOAD_SOURCE started (total: 12s)
⠴ Launching Bedrock AgentCore...✅ DOWNLOAD_SOURCE completed in 1.0s
🔄 BUILD started (total: 13s)
⠙ Launching Bedrock AgentCore...✅ BUILD completed in 16.4s
🔄 POST_BUILD started (total: 30s)
⠦ Launching Bedrock AgentCore...✅ POST_BUILD completed in 12.4s
🔄 FINALIZING started (total: 42s)
⠏ Launching Bedrock AgentCore...✅ FINALIZING completed in 1.0s
🔄 COMPLETED started (total: 43s)
⠹ Launching Bedrock AgentCore...✅ COMPLETED completed in 1.0s
🎉 CodeBuild completed successfully in 0m 44s
CodeBuild completed successfully
✅ CodeBuild project configuration saved
Deploying to Bedrock AgentCore...
⠋ Launching Bedrock AgentCore...✅ Agent created/updated: arn:aws:bedrock-agentcore:us-west-2:{AccountId}:runtime/cost_estimator_agent-rrrrrrrrrr
Observability is enabled, configuring Transaction Search...
⠹ Launching Bedrock AgentCore...Created/updated CloudWatch Logs resource policy
X-Ray trace destination already configured
⠸ Launching Bedrock AgentCore...X-Ray indexing rule already configured
✅ Transaction Search configured: resource_policy
🔍 GenAI Observability Dashboard:
   https://console.aws.amazon.com/cloudwatch/home?region=us-west-2#gen-ai-observability/agent-core
Polling for endpoint to be ready...
⠏ Launching Bedrock AgentCore...Agent endpoint: arn:aws:bedrock-agentcore:us-west-2:{AccountId}:runtime/cost_estimator_agent-rrrrrrrrrr/runtime-endpoint/DEFAULT
Deployment completed successfully - Agent: arn:aws:bedrock-agentcore:us-west-2:{AccountId}:runtime/cost_estimator_agent-rrrrrrrrrr
# (省略)

実行が成功すると以下のリソースが作成されます。コンテナのビルド環境はCodeBuildを使っているようです。コマンド2つでデプロイできるのでとてもお手軽です。

  • CodeBuild ビルドプロジェクト
  • ECR リポジトリ
  • AgentCore Runtime

Lab3: Identity

AIエージェントの認証・認可を管理するための機能です。

  • インバウンド認証:AIエージェントを呼び出す側の認証・認可
  • アウトバウンド認証:AIエージェントが外部サービスにアクセスするための認証・認可

サポートされている認証方法は3つ。

  • IAM(SigV4)
  • OAuth2.0
  • API Key

setup_inbound_authorizer.pyを実行します。

$uv run python setup_inbound_authorizer.py
INFO: Found credentials from IAM Role: BedrockAgentCoreCodeEdito-CodeEditorInstanceBootstr-mmmmmmmmmmmm
INFO: Creating Cognito OAuth authorizer...
2025-09-23 10:23:40,217 - bedrock_agentcore.gateway - INFO - Starting EZ Auth setup: Creating Cognito resources...
INFO: Starting EZ Auth setup: Creating Cognito resources...
INFO: Found credentials from IAM Role: BedrockAgentCoreCodeEdito-CodeEditorInstanceBootstr-mmmmmmmmmmmm
2025-09-23 10:23:41,083 - bedrock_agentcore.gateway - INFO -   ✓ Created User Pool: us-west-2_XXXXXXXXX
INFO:   ✓ Created User Pool: us-west-2_XXXXXXXXX
2025-09-23 10:23:42,115 - bedrock_agentcore.gateway - INFO -   ✓ Created domain: agentcore-66666666
INFO:   ✓ Created domain: agentcore-66666666
2025-09-23 10:23:42,115 - bedrock_agentcore.gateway - INFO -   ⏳ Waiting for domain to be available...
INFO:   ⏳ Waiting for domain to be available...
2025-09-23 10:23:42,187 - bedrock_agentcore.gateway - INFO -   ✓ Domain is active
INFO:   ✓ Domain is active
2025-09-23 10:23:42,445 - bedrock_agentcore.gateway - INFO -   ✓ Created resource server: InboundAuthorizerForCostEstimatorAgent
INFO:   ✓ Created resource server: InboundAuthorizerForCostEstimatorAgent
2025-09-23 10:23:42,717 - bedrock_agentcore.gateway - INFO -   ✓ Created client: {clientId}
INFO:   ✓ Created client: {clientId}
2025-09-23 10:23:42,717 - bedrock_agentcore.gateway - INFO -   ⏳ Waiting for DNS propagation of domain: agentcore-66666666.auth.us-west-2.amazoncognito.com
INFO:   ⏳ Waiting for DNS propagation of domain: agentcore-66666666.auth.us-west-2.amazoncognito.com
2025-09-23 10:24:42,717 - bedrock_agentcore.gateway - INFO - ✓ EZ Auth setup complete!
INFO: ✓ EZ Auth setup complete!
INFO: ✅ Cognito configuration saved
INFO: Creating Identity Provider ...
INFO: ⏳ Waiting for OIDC endpoint: {トークン署名キー URL}/openid-configuration
INFO: ⏳ Timeout: 600s, Check interval: 30s
INFO: ⏳ Attempt 1: HTTP 200
INFO: ✅ OIDC endpoint available after 0.1s
INFO: ✅ OIDC discovery document is valid
INFO: ✅ Provider configuration saved
INFO: Creating Runtime with Identity...
INFO: ✅ Runtime configuration saved
{
  "cognito": {
    "client_id": "{clientId}",
    "client_secret": "{シークレットの値}",
    "token_endpoint": "https://agentcore-66666666.auth.us-west-2.amazoncognito.com/oauth2/token",
    "discovery_url": "{トークン署名キー URL}/openid-configuration",
    "scope": "InboundAuthorizerForCostEstimatorAgent/invoke",
    "user_pool_id": "us-west-2_XXXXXXXXX",
    "region": "us-west-2"
  },
  "provider": {
    "name": "inbound-identity-for-cost-estimator-agent",
    "arn": "arn:aws:bedrock-agentcore:us-west-2:{AccountId}:token-vault/default/oauth2credentialprovider/inbound-identity-for-cost-estimator-agent"
  },
  "runtime": {
    "id": "cost_estimator_agent_with_identity-YYYYYYYYYY",
    "name": "cost_estimator_agent_with_identity",
    "url": "https://bedrock-agentcore.us-west-2.amazonaws.com/runtimes/arn%3Aaws%3Abedrock-agentcore%3Aus-west-2%3A{AccountId}%3Aruntime%2Fcost_estimator_agent_with_identity-YYYYYYYYYY/invocations?qualifier=DEFAULT"
  }
}
# (省略)

作成されるリソースは以下です。

  • AgentCore Runtime
    • 認証が必要なAIエージェント
    • 実行ロールはLab1と同じ
  • Identity
    • アウトバウンド認証
  • Secrets Manager
    • Identityマネージドなシークレットでユーザによる変更不可
    • Cognitoにアクセスするのに必要なクライアントシークレットを管理する
    • アクセストークンを払い出す際に必要
  • Cognito
    • ユーザープール
    • 認証サーバとしての機能する

コンソールからAIエージェントの実行を試みると認証方法が一致しないため失敗します(OAuthではなくIAMで認証したため)。

次にtest_identity_agent.pyを実行します。Cognitoからアクセストークンを取得した上でAgentCore Runtimeにアクセスしていることがログから見て取れます。

$uv run python test_identity_agent.py
# (省略)
Tool #1: cost_estimator_tool
Found existing workload identity from /workshop/03_identity/.agentcore.json: workload-11111111
Found existing user id from /workshop/03_identity/.agentcore.json: 41d25aef
2025-09-23 10:52:50,991 - bedrock_agentcore.identity_client - INFO - Getting workload access token for user id...
2025-09-23 10:52:51,070 - bedrock_agentcore.identity_client - INFO - Successfully retrieved workload access token
2025-09-23 10:52:51,071 - bedrock_agentcore.identity_client - INFO - Getting OAuth2 token...
2025-09-23 10:52:51,627 - __main__ - INFO - ✅ Successfully load the access token from AgentCore Identity!
2025-09-23 10:52:51,627 - __main__ - INFO -     Token part 0: {'kid': '{kid}', 'alg': 'RS256'}
2025-09-23 10:52:51,627 - __main__ - INFO -     Token part 1: {'sub': '{clientId}', 'token_use': 'access', 'scope': 'InboundAuthorizerForCostEstimatorAgent/invoke', 'auth_time': 1758624771, 'iss': 'https://cognito-idp.us-west-2.amazonaws.com/us-west-2_XXXXXXXXX', 'exp': 1758628371, 'iat': 1758624771, 'version': 2, 'jti': '{jti}', 'client_id': '{clientId}'}
# (省略)
This2025-09-23 10:55:52,615 - __main__ - INFO - ✅ Successfully called agent!

Lab4: Gateway

外部サービス・APIをAIエージェントが扱えるようにMCP形式に変換するコネクタ。AgentCore Gatewayもインバウント認証・アウトバウンド認証をサポートします。ここではインバウント認証にLab2で作成したCognito,アウトバウンド認証(AgentCore Gateway → Lambda)にIAMを使います。

deploy.shを実行すると下記のリソースが作成されます。

  • SES ID
  • Lambda Function
    • AIエージェントがアクセスする外部サービスとしての関数(MCP Server)
    • AWS-Cost-Estimator-Tool-M-AgentCoreGatewayFunction-XXX
  • IAM Role
    • Lambda実行ロール
    • AWS-Cost-Estimator-Tool-M-AgentCoreGatewayFunctionR-XXX

次にsetup_outbound_gateway.pyを実行してAgentCore Gatewayを作成します。


test_gateway.pyでAgentCore Gatewayの動作確認を行います。

$uv run python test_gateway.py --architecture 会員1000人への推薦メール配信 --address {your email address}
2025-09-23 13:03:06,907 - botocore.credentials - INFO - Found credentials from IAM Role: BedrockAgentCoreCodeEdito-CodeEditorInstanceBootstr-mmmmmmmmmmmm
2025-09-23 13:03:06,975 - __main__ - INFO - Testing Gateway with MCP client (Strands Agents)...
2025-09-23 13:03:06,976 - bedrock_agentcore.identity_client - INFO - Creating workload identity...
Created a workload identity
Created an user id
2025-09-23 13:03:07,037 - bedrock_agentcore.identity_client - INFO - Getting workload access token for user id...
2025-09-23 13:03:07,114 - bedrock_agentcore.identity_client - INFO - Successfully retrieved workload access token
2025-09-23 13:03:07,114 - bedrock_agentcore.identity_client - INFO - Getting OAuth2 token...
2025-09-23 13:03:07,706 - __main__ - INFO - ✅ Successfully loaded the access token!
2025-09-23 13:03:07,707 - __main__ - INFO - Prepare agent's tools...
2025-09-23 13:03:08,099 - httpx - INFO - HTTP Request: POST https://awscostestimatorgateway-gggggggggg.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp "HTTP/1.1 200 OK"
2025-09-23 13:03:08,100 - mcp.client.streamable_http - INFO - Negotiated protocol version: 2025-03-26
2025-09-23 13:03:08,314 - httpx - INFO - HTTP Request: POST https://awscostestimatorgateway-gggggggggg.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp "HTTP/1.1 202 Accepted"
2025-09-23 13:03:08,552 - httpx - INFO - HTTP Request: POST https://awscostestimatorgateway-gggggggggg.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp "HTTP/1.1 200 OK"
2025-09-23 13:03:08,553 - __main__ - INFO - Found the following tools: ['cost_estimator_tool', 'AWSCostEstimatorGatewayTarget___markdown_to_email']
2025-09-23 13:03:08,553 - __main__ - INFO -
Asking agent to estimate AWS costs...
2025-09-23 13:03:08,569 - botocore.credentials - INFO - Found credentials from IAM Role: BedrockAgentCoreCodeEdito-CodeEditorInstanceBootstr-mmmmmmmmmmmm
I'll help you estimate the AWS cost for your email recommendation system and send the results to your email address.

Let me break this down:
1. First, I'll summarize your requirements
2. Get a cost estimation
3. Send the results to your email
Tool #1: cost_estimator_tool
2025-09-23 13:03:12,659 - cost_estimator_agent.cost_estimator_agent - INFO - Initializing AWS Cost Estimator Agent in region: us-west-2
2025-09-23 13:03:12,659 - __main__ - INFO - We will estimate about Email recommendation system for 1000 members using AWS SES for email delivery, Lambda for processing, and database for member management
2025-09-23 13:03:12,659 - cost_estimator_agent.cost_estimator_agent - INFO - 📊 Starting cost estimation...
2025-09-23 13:03:12,659 - cost_estimator_agent.cost_estimator_agent - INFO - Architecture: Email recommendation system for 1000 members using AWS SES for email delivery, Lambda for processing, and database for member management
2025-09-23 13:03:12,659 - cost_estimator_agent.cost_estimator_agent - INFO - 🚀 Initializing AWS Cost Estimation Agent...
2025-09-23 13:03:12,659 - cost_estimator_agent.cost_estimator_agent - INFO - Setting up AgentCore Code Interpreter...
2025-09-23 13:03:12,681 - botocore.credentials - INFO - Found credentials from IAM Role: BedrockAgentCoreCodeEdito-CodeEditorInstanceBootstr-mmmmmmmmmmmm
2025-09-23 13:03:13,714 - cost_estimator_agent.cost_estimator_agent - INFO - ✅ AgentCore Code Interpreter session started successfully
2025-09-23 13:03:13,714 - cost_estimator_agent.cost_estimator_agent - INFO - Setting up AWS Pricing MCP Client...
2025-09-23 13:03:13,714 - cost_estimator_agent.cost_estimator_agent - INFO - Getting current AWS credentials...
2025-09-23 13:03:13,728 - botocore.credentials - INFO - Found credentials from IAM Role: BedrockAgentCoreCodeEdito-CodeEditorInstanceBootstr-mmmmmmmmmmmm
2025-09-23 13:03:13,769 - cost_estimator_agent.cost_estimator_agent - INFO - Using AWS identity: arn:aws:sts::{AccountId}:assumed-role/BedrockAgentCoreCodeEdito-CodeEditorInstanceBootstr-mmmmmmmmmmmm/{インスタンスID}
2025-09-23 13:03:13,769 - cost_estimator_agent.cost_estimator_agent - INFO - ✅ Using AWS credentials with session token (likely from EC2 instance role)
2025-09-23 13:03:13,771 - cost_estimator_agent.cost_estimator_agent - INFO - ✅ AWS Pricing MCP Client setup successfully with AWS credentials
Installed 46 packages in 153ms
INFO:mcp.server.lowlevel.server:Processing request of type ListToolsRequest
2025-09-23 13:03:16,802 - cost_estimator_agent.cost_estimator_agent - INFO - Found 9 AWS pricing tools
2025-09-23 13:03:16,817 - botocore.credentials - INFO - Found credentials from IAM Role: BedrockAgentCoreCodeEdito-CodeEditorInstanceBootstr-mmmmmmmmmmmm
I'll analyze this architecture and provide a cost estimate for your email recommendation system. Let me break down the components and retrieve pricing data for each service.
# (省略)
This2025-09-23 13:05:52,264 - cost_estimator_agent.cost_estimator_agent - INFO - ✅ Cost estimation completed
2025-09-23 13:05:52,512 - cost_estimator_agent.cost_estimator_agent - INFO - 🧹 Cleaning up resources...
2025-09-23 13:05:52,727 - cost_estimator_agent.cost_estimator_agent - INFO - ✅ Code Interpreter session stopped
 architecture provides a highly cost-effective solution for delivering email recommendations to 1000 members, with total costs under $5 per year, primarily driven by SES email sending charges.
Tool #2: AWSCostEstimatorGatewayTarget___markdown_to_email
2025-09-23 13:06:04,732 - httpx - INFO - HTTP Request: POST https://awscostestimatorgateway-gggggggggg.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp "HTTP/1.1 200 OK"
Perfect! I've successfully completed the AWS cost estimation for your email recommendation system and sent the detailed report to your email address ({your email address}).
# (省略)

test_gateway.pyの処理を概説します。

  1. AgentCore Identity
    CongnitoからOAuth2トークンを取得。

    access_token = asyncio.run(get_access_token())
    
  2. AgentCore Gateway
    Authorizationヘッダーにトークンを入れてAgentCore Gatewayのエンドポイント(Gateway resource URL)に接続。

    mcp_client = MCPClient(create_transport) # AgentCore Gatewayに接続
    
  3. ツール設定

    logger.info("Prepare agent's tools...")
    tools = [cost_estimator_tool] # コスト見積エージェント(ローカルのツール)
    with mcp_client:
        more_tools = True
        pagination_token = None
        while more_tools:
            tmp_tools = mcp_client.list_tools_sync(pagination_token=pagination_token) # MCP Server = AgentCore Gatway -> Lambda からリモートのツール一覧を取得
            tools.extend(tmp_tools) # ツールを追加
            if tmp_tools.pagination_token is None:
                more_tools = False
            else:
                more_tools = True 
                pagination_token = tmp_tools.pagination_token
    
        _names = [tool.tool_name for tool in tools]
        logger.info(f"Found the following tools: {_names}")
    
  4. AgentCore Runtime
    ツール指定の上,AIエージェントを実行。

    agent = Agent(
            system_prompt=(
                "Your are a professional solution architect. Please estimate cost of AWS platform."
                "1. Please summarize customer's requirement to `architecture_description` in 10~50 words."
                "2. Pass `architecture_description` to 'cost_estimator_tool'."
                "3. Send estimation by `markdown_to_email`."
            ),
            tools=tools
        )
    

Lab5: Observability

AgentCore ObservabilityはAIエージェントがリクエストを受けてからレスポンスを返すまでの各ステップをリアルタイムに監視・トレースする機能。設定はCloudWatchから行う。収集したテレメトリデータはOpen Telemetry形式で出力可能。以下3つの階層構造で可観測性が提供される。

  • Session
    • ユーザーの初回アクセスから会話終了までのすべてのやり取りがまとめて記録される
    • セッションごとに一意の識別子が付与される
    • 複数回のインタラクションも1つのセッションとして記録される
  • Trace
    • AIエージェントの呼び出しから始まる単一のリクエスト-レスポンスが詳細に記録される
    • 他のAIエージェント呼び出しが含まれる場合もある
    • AIエージェントの内部動作に関する詳細情報を提供する
  • Span
    • 個別の作業(モデル・Tool・API呼び出し,内部処理)を階層的に整理して記録される
    • Spanの中にさらに階層構造をもつ

まずはCloudWatch > Application Signals(APM) > トランザクション検索 から「Enable Transaction Search」をクリックしてTransaction Searchを有効化します(以下は有効化後の画面)。

次にtest_observability.pyを実行してAIエージェントの実行がどのように記録されるのか確認します。なぜかタイムアウトしてしまうので調査し甲斐のあるワークショップになりました。

--- Invocation 1/3 ---
2025-09-23 14:53:17,609 - INFO - Prompt: I would like to prepare small EC2 for ssh. How much does it cost?
2025-09-23 14:58:30,367 - ERROR - ❌ Invocation 1 failed: Read timeout on endpoint URL: "https://bedrock-agentcore.us-west-2.amazonaws.com/runtimes/arn%3Aaws%3Abedrock-agentcore%3Aus-west-2%3A{AccountId}%3Aruntime%2Fcost_estimator_agent-rrrrrrrrrr/invocations"
--- Invocation 2/3 ---
2025-09-23 14:58:30,367 - INFO - Prompt: What about the cost for a medium-sized RDS MySQL database?
2025-09-23 15:03:33,806 - ERROR - ❌ Invocation 2 failed: Read timeout on endpoint URL: "https://bedrock-agentcore.us-west-2.amazonaws.com/runtimes/arn%3Aaws%3Abedrock-agentcore%3Aus-west-2%3A{AccountId}%3Aruntime%2Fcost_estimator_agent-rrrrrrrrrr/invocations"
--- Invocation 3/3 ---
2025-09-23 15:03:33,806 - INFO - Prompt: Can you estimate costs for a simple S3 bucket with 100GB storage?
2025-09-23 15:08:40,285 - ERROR - ❌ Invocation 3 failed: Read timeout on endpoint URL: "https://bedrock-agentcore.us-west-2.amazonaws.com/runtimes/arn%3Aaws%3Abedrock-agentcore%3Aus-west-2%3A{AccountId}%3Aruntime%2Fcost_estimator_agent-rrrrrrrrrr/invocations"

Spanを見ると429エラーであることが判明しました。CloudWatch Logs > ロググループ > aws/spans からも確認できます。

「ThrottlingException」,「An error occurred (ThrottlingException) when calling the ConverseStream operation (reached max retries: 3): Too many requests, please wait before trying again.」といったログと,1日あたりの入力・出力トークンの合計値がサービスクオータとして定められていることから,ThrottlingExceptionが発生したと結論付けました。Span → CloudWatch Logs, CloudTrail → Service Quotas の順に調査しました。翌日はエラーは発生しなかったので一時的にクオータによる制限がかかっていたようです。

Lab6: Memory

Memoryには短期記憶と長期記憶があります。

  • 短期記憶:ユーザーとAIエージェントの対話を保存する。セッション内で保持される
  • 長期記憶:短期記憶から自動的に重要な情報を抽出・統合して保存する。Memory Strategyによってどのような情報を保存するのか決定する。長期記憶はnamespaceで論理的にグループ化される。実装次第で以下のように細かく記憶を管理することができます。IAMでMemoryやnamespaceへのアクセスを制限することも可能です。他のユーザーと記憶が混同せずプライバシーやセキュリティに配慮された仕組みになっています(AgentCoreの機能の中で一番感動)。
レベル namespece pattern 用途
セッション単位 /strategy/{strategyId}/actor/{actorId}/session/{sessionId} セッション単位で記憶を管理
アクター単位 /strategy/{strategyId}/actor/{actorId} ユーザー単位で記憶を管理
Memory Strategy 単位 /strategy/{strategyId} Memory Strategy単位で記憶を管理
グローバル / システム全体の記憶を管理

Memory Strategyは4種類。

  • SemanticMemoryStrategy: 会話で言及された事実や知識を将来の参照用に保存
  • SummaryMemoryStrategy: 要点や決定事項を保存
  • UserPreferenceMemoryStrategy: ユーザーの好みや選択パターンを保存
  • CustomMemoryStrategy: プロンプトをオーバーライドして特定のユースケースやドメイン情報を保存

test_memory.pyを実行するとMemoryが作成されます(ログは膨大なので省略)。

トラブルシュート

翌日,EC2を起動してワークショップを再開しようとしたら...。CodeEditorはCloudFrontのオリジン(EC2)でホストされています。EC2を停止→起動した際はDNS名・IPアドレスが変わるためオリジンドメインを更新しましょう。

参考文献

さいごに

初めてAgentCoreをさわりました。一通りの基本を学べました!
上級者向け(レベル300)のワークショップもあるのでいずれこちらも挑戦したい。

  • Getting started with Bedrock AgentCore
  • Diving Deep into Bedrock AgentCore

AWS Workshops

Discussion