### AgentCore CLI Invocation and Status Source: https://context7.com/tttingzhang999/agentcore-looping-backup/llms.txt Demonstrates how to invoke the deployed AgentCore runtime using the command-line interface (CLI). It includes examples for invoking with a JSON payload, checking the agent's status, and viewing the runtime configuration. ```bash # Invoke via CLI with JSON payload agentcore invoke '{"prompt": "what can you do?"}' # Check agent status agentcore status # View runtime configuration cat .bedrock_agentcore.yaml ``` -------------------------------- ### Dockerfile for AgentCore Runtime Source: https://context7.com/tttingzhang999/agentcore-looping-backup/llms.txt Defines the Dockerfile used to containerize the AgentCore runtime. It utilizes a Python 3.10 image, sets up the working directory, installs dependencies using `uv`, configures user permissions, exposes necessary ports, and sets the command to run the agent with OpenTelemetry instrumentation. ```dockerfile FROM ghcr.io/astral-sh/uv:python3.10-bookworm-slim WORKDIR /app ENV UV_SYSTEM_PYTHON=1 \ UV_COMPILE_BYTECODE=1 \ PYTHONUNBUFFERED=1 COPY pyproject.toml pyproject.toml RUN uv pip install -r pyproject.toml RUN useradd -m -u 1000 bedrock_agentcore USER bedrock_agentcore EXPOSE 9000 8000 8080 COPY . . CMD ["opentelemetry-instrument", "python", "-m", "src.main"] ``` -------------------------------- ### Check Terraform Version Source: https://github.com/tttingzhang999/agentcore-looping-backup/blob/main/README.md Verifies that the installed Terraform version meets the minimum requirement of version 1.2 or higher. This command outputs the version in JSON format, which is then parsed to extract the version string. ```bash terraform version -json | jq -r '.terraform_version' ``` -------------------------------- ### Custom Tool Definition - Strands Decorator - Python Source: https://context7.com/tttingzhang999/agentcore-looping-backup/llms.txt Defines custom function tools using the `@tool` decorator from the Strands framework, enabling the agent to invoke these functions during conversations. Tools are automatically discovered for LLM function calling. This example shows a simple `add_numbers` function. ```python from strands import tool @tool def add_numbers(a: int, b: int) -> int: """Return the sum of two numbers. Args: a: First number to add b: Second number to add Returns: The sum of a and b """ return a + b # Usage: The agent will automatically call this when prompted # "What is 42 + 58?" -> Agent invokes add_numbers(42, 58) -> Returns 100 ``` -------------------------------- ### Deploy Infrastructure with Terraform Source: https://context7.com/tttingzhang999/agentcore-looping-backup/llms.txt This section outlines the steps to deploy the AgentCore infrastructure using Terraform. It includes initializing Terraform, planning changes, and applying the deployment to AWS. Prerequisites include having Terraform version 1.2 or higher and verified AWS credentials. ```bash terraform init terraform plan terraform apply ``` -------------------------------- ### Manual Docker Build and Push to ECR Source: https://context7.com/tttingzhang999/agentcore-looping-backup/llms.txt Provides bash commands for manually building and pushing the Docker container to an Amazon Elastic Container Registry (ECR) repository. This is an alternative to the automated process handled by Terraform. ```bash aws ecr get-login-password | docker login --username AWS --password-stdin docker build -t :latest . docker push :latest ``` -------------------------------- ### Terraform Initialization and Deployment Commands Source: https://github.com/tttingzhang999/agentcore-looping-backup/blob/main/README.md Provides essential commands for initializing and deploying AWS resources using Terraform. This includes navigating to the terraform directory, downloading dependencies, planning the deployment, and applying the changes. ```bash cd terraform && terraform init && terraform apply ``` ```bash cd terraform ``` ```bash terraform init ``` ```bash # optional] overview resources to be deployed: terraform plan ``` ```bash terraform apply ``` -------------------------------- ### Agent Runtime Main Entrypoint - Python Source: https://context7.com/tttingzhang999/agentcore-looping-backup/llms.txt The `invoke()` function serves as the primary entry point for the agent runtime, handling incoming requests, session management, memory configuration, and tool orchestration. It utilizes the Bedrock AgentCore SDK and Strands framework to process user prompts and stream responses. Dependencies include `bedrock_agentcore`, `strands`, and AWS SDKs. ```python # src/main.py from bedrock_agentcore import BedrockAgentCoreApp from strands import Agent, tool from bedrock_agentcore.memory.integrations.strands.config import AgentCoreMemoryConfig, RetrievalConfig from bedrock_agentcore.memory.integrations.strands.session_manager import AgentCoreMemorySessionManager import os app = BedrockAgentCoreApp() @app.entrypoint async def invoke(payload, context): """ Main entrypoint for agent invocation. Args: payload: dict with "prompt" key containing user input context: Contains session_id and other runtime context Yields: str: Streamed response chunks from the agent """ session_id = getattr(context, 'session_id', 'default') # Configure memory session manager for conversation persistence session_manager = AgentCoreMemorySessionManager( AgentCoreMemoryConfig( memory_id=os.getenv("BEDROCK_AGENTCORE_MEMORY_ID"), session_id=session_id, actor_id="quickstart-user", retrieval_config={ "/users/quickstart-user/facts": RetrievalConfig(top_k=3, relevance_score=0.5), "/users/quickstart-user/preferences": RetrievalConfig(top_k=3, relevance_score=0.5) } ), os.getenv("AWS_REGION") ) # Create agent with tools and stream response agent = Agent( model=load_model(), session_manager=session_manager, system_prompt="You are a helpful assistant with code execution capabilities.", tools=[code_interpreter.code_interpreter, add_numbers] + mcp_tools ) stream = agent.stream_async(payload.get("prompt")) async for event in stream: if "data" in event and isinstance(event["data"], str): yield event["data"] # Invoke via CLI # agentcore invoke '{"prompt": "what can you do?"}' ``` -------------------------------- ### Local Development Mode Logic in Python Source: https://context7.com/tttingzhang999/agentcore-looping-backup/llms.txt Illustrates the Python code logic that enables local development mode. It checks for the `LOCAL_DEV` environment variable and conditionally mocks the `strands_mcp_client` if the variable is set to '1'. ```python import os if os.getenv("LOCAL_DEV") == "1": from contextlib import nullcontext from types import SimpleNamespace strands_mcp_client = nullcontext(SimpleNamespace(list_tools_sync=lambda: [])) else: strands_mcp_client = get_streamable_http_mcp_client() ``` -------------------------------- ### Python Entrypoint for Bedrock AgentCore SDK Source: https://github.com/tttingzhang999/agentcore-looping-backup/blob/main/README.md Defines the main entrypoint for a Bedrock AgentCore application using the Strands library. It expects a payload with a 'prompt' key and uses the Bedrock AgentCore SDK. ```python @app.entrypoint def invoke(payload): # assume payload input is structured as { "prompt": "" } ``` -------------------------------- ### Local Development Mode for AgentCore Source: https://context7.com/tttingzhang999/agentcore-looping-backup/llms.txt Enables running the AgentCore agent locally without deploying to AWS by setting the `LOCAL_DEV` environment variable. This mode mocks the MCP client, allowing for testing agent logic without AWS dependencies. ```bash # Set environment for local development export LOCAL_DEV=1 export AWS_REGION=us-east-1 # Run the agent locally (MCP client is mocked) python -m src.main ``` -------------------------------- ### Load Bedrock Model Client (Python) Source: https://context7.com/tttingzhang999/agentcore-looping-backup/llms.txt Initializes the Bedrock model client using IAM authentication, automatically leveraging the execution role's credentials. It specifically configures the client for Claude 3.5 Sonnet via the global inference profile. ```python # src/model/load.py from strands.models import BedrockModel MODEL_ID = "anthropic.claude-3-5-sonnet-20240620-v1:0" def load_model() -> BedrockModel: """ Initialize Bedrock model client with IAM authentication. Uses the execution role's IAM credentials automatically. Model ID references Claude 3.5 Sonnet global inference profile. Returns: BedrockModel: Configured model client for agent use """ return BedrockModel(model_id=MODEL_ID) # Usage model = load_model() agent = Agent(model=model, tools=[...]) ``` -------------------------------- ### Create MCP Client with Cognito Auth (Python) Source: https://context7.com/tttingzhang999/agentcore-looping-backup/llms.txt This function creates an MCP Client for AgentCore Gateway, enabling tool discovery and invocation. It uses Cognito for OAuth2 access token authentication and requires GATEWAY_URL environment variable. ```python import os import requests from mcp.client.streamable_http import streamablehttp_client from strands.tools.mcp.mcp_client import MCPClient def _get_access_token(): """Obtain OAuth2 access token from Cognito using client credentials.""" response = requests.post( os.getenv("COGNITO_TOKEN_URL"), auth=(os.getenv("COGNITO_CLIENT_ID"), os.getenv("COGNITO_CLIENT_SECRET")), data={ "grant_type": "client_credentials", "scope": os.getenv("COGNITO_SCOPE"), }, headers={"Content-Type": "application/x-www-form-urlencoded"}, ) return response.json()["access_token"] def get_streamable_http_mcp_client() -> MCPClient: """ Create an MCP Client for AgentCore Gateway with Cognito authentication. Returns: MCPClient: Strands-compatible MCP client for tool discovery and invocation Raises: RuntimeError: If GATEWAY_URL environment variable is not set """ gateway_url = os.getenv("GATEWAY_URL") if not gateway_url: raise RuntimeError("Missing required environment variable: GATEWAY_URL") access_token = _get_access_token() return MCPClient( lambda: streamablehttp_client( gateway_url, headers={"Authorization": f"Bearer {access_token}"} ) ) # Usage in agent runtime with get_streamable_http_mcp_client() as client: tools = client.list_tools_sync() # Discover available MCP tools # tools are now available for agent invocation ``` -------------------------------- ### Terraform Variables and Configuration Source: https://context7.com/tttingzhang999/agentcore-looping-backup/llms.txt Defines the key variables and configuration settings for the Terraform deployment. `variables.tf` specifies input variables like `app_name` and `agent_runtime_version`, while `terraform.tfvars` provides the actual values for these variables. ```hcl variable "app_name" { description = "Application name" type = string } variable "agent_runtime_version" { description = "Runtime version for PROD endpoint" type = string default = "1" } # terraform/terraform.tfvars - Configuration app_name = "ultraCyan" agent_runtime_version = "1" ``` -------------------------------- ### MCP Lambda Handler for Tool Execution (Python) Source: https://context7.com/tttingzhang999/agentcore-looping-backup/llms.txt This Lambda function acts as the tool execution endpoint for the AgentCore Gateway. It parses tool names based on the 'LambdaTarget___' convention and routes invocations to the appropriate tool function, handling errors gracefully. ```python # mcp/lambda/handler.py import json from typing import Any, Dict def lambda_handler(event, context): """ Lambda handler for MCP tool invocations from AgentCore Gateway. Args: event: Tool input parameters from the gateway context: Lambda context with client_context.custom["bedrockAgentCoreToolName"] Returns: dict: Response with statusCode and JSON body Expected tool name format: "LambdaTarget___" """ try: # Extract tool name from AgentCore Gateway convention extended_name = context.client_context.custom.get("bedrockAgentCoreToolName") tool_name = None if extended_name and "___" in extended_name: tool_name = extended_name.split("___", 1)[1] if not tool_name: return {"statusCode": 400, "body": json.dumps({"error": "Missing tool name"})} if tool_name == "placeholder_tool": result = placeholder_tool(event) return {"statusCode": 200, "body": json.dumps({"result": result})} return {"statusCode": 400, "body": json.dumps({"error": f"Unknown tool '{tool_name}'"})} except Exception as e: return {"statusCode": 500, "body": json.dumps({"system_error": str(e)})} def placeholder_tool(event: Dict[str, Any]): """ Example MCP tool implementation demonstrating parameter handling. Args: event: Input parameters including string_param, int_param, float_array_param Returns: dict: Tool execution result with received parameters """ return { "message": "Placeholder tool executed.", "string_param": event.get("string_param"), "int_param": event.get("int_param"), "float_array_param": event.get("float_array_param"), "event_args_received": event, } # Tool schema defined in terraform/bedrock_agentcore.tf: # { # "name": "placeholder_tool", # "description": "Placeholder tool (no-op).", # "input_schema": { # "type": "object", # "properties": { # "string_param": {"type": "string"}, # "int_param": {"type": "integer"}, # "float_array_param": {"type": "array", "items": {"type": "number"}} # } # } # } ``` -------------------------------- ### Invoke Runtime via CLI - AgentCore Source: https://github.com/tttingzhang999/agentcore-looping-backup/blob/main/README.md Invokes the deployed runtime using the 'agentcore invoke' command. Requires a JSON string as input, typically containing a 'prompt' field. This method is useful for scripting and automated testing. ```bash agentcore invoke '{"prompt": "what can you do?"}' ``` -------------------------------- ### Invoke Runtime via AWS Console - AgentCore Source: https://github.com/tttingzhang999/agentcore-looping-backup/blob/main/README.md Invokes the deployed runtime through the 'Test Console' in the AWS Bedrock AgentCore console. Users select the runtime and version, then provide input in JSON format. This provides a visual interface for testing. ```json {"prompt": "what can you do?"} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.