AWS Builder Center Article

Build a Sovereign Risk Trading Agent with Amazon Bedrock AgentCore for Yield Spreads, FX Hedging, and Debt Repricing

Amazon Bedrock AgentCore helps teams build production-grade sovereign risk trading agents for government bond yield spreads, credit spread widening, debt repricing, FX volatility, liquidity stress, and defensive asset rotation. This guide walks through Runtime deployment, Gateway, MCP tool servers, Cognito authentication, streaming responses, session management, and large-payload handling to deliver secure, governed, real-time market intelligence across enterprise trading workflows.

Disclaimer

Not Investment Advice

Information provided is for general education and risk awareness only. It is not financial, investment, tax, legal, or trading advice, nor a recommendation to buy, sell, or hold any instruments.

Legitimate Thailand Planning Only

This assistant supports lawful Thailand travel, relocation, vacation, and retreat planning, including itinerary ideas, logistics, cultural preparation, accommodation research, wellness options, and compliant, transparent decision support for legitimate travelers only.

No Illegal Evasion or Escape Assistance

This service will not assist with hiding, evading authorities, circumventing immigration, court orders, debts, sanctions, or legal obligations, unlawful flight, false documents, concealment, or any illegal escape under any circumstances.

Short Straddle Trading-Risk Governance Scope

Short Straddle Trading-Risk Governance content follows the uploaded framework, emphasizing Delta, Gamma, Vega, margin, liquidity, stress loss, anti-martingale behavior, limits, escalation, monitoring, documentation, approvals, and governance controls for oversight discipline.


Demo: Sovereign Risk AgentCore Runtime Quality

User: Analyze the US-China government bond yield spread for next-position action. Assess duration demand, China growth risk, capital flows, RMB pressure, UST-CGB relative value, credit spread widening, and sovereign debt repricing.

AgentCore runtime output: Start with risk regime, not trade direction. A widening US-China yield spread can indicate stronger demand for US duration, weaker confidence in China growth, capital-flow pressure, RMB depreciation risk, or a relative-value reset between U.S. Treasuries and Chinese government bonds. The next action should be framed as a governed risk review: reduce risk, add duration defensively, hedge currency exposure, rotate into higher-quality sovereign bonds, or wait for confirmation. Confirmation signals include Fed policy expectations, PBOC easing, China credit impulse, USD/CNH movement, real yield changes, foreign inflows or outflows, liquidity, and risk appetite.

Demo: Gateway Tool Selection Quality

User: Find the right tools for sovereign debt repricing, credit spread widening, and FX pressure.

AgentCore Gateway output: Use semantic tool discovery before loading every schema into the prompt. Relevant tools may include sovereign_debt_risk_repricing, credit_spread_widening, funding_liquidity, currency_mismatch, policy_reaction_function, and correlation_shock. The gateway should enforce authentication, translate the MCP call to the target Lambda or API, and preserve observability for latency, invocation status, and error taxonomy.


Table of Contents

Part 1. Executive Overview Introduces a production-grade sovereign risk trading agent using AgentCore Runtime, Gateway, MCP tools, authentication, streaming, sessions, and payload handling for secure, global institutional market intelligence and governed workflows at scale.

Part 2. Agent-as-Tools Architecture Explains a hierarchical orchestration model where a central macro agent dynamically delegates survival, cyclical, and shock-capital tasks to specialized sub-agents across dollar liquidity, China demand, and European credit risk regimes.

Part 3. Create the Runtime Agent Shows how to securely deploy a serverless AgentCore Runtime application with Strands, Amazon Nova Pro, calculator tools, and a system prompt for sovereign credit and yield-spread analysis in production environments.

Part 4. Invoke the Runtime Agent Demonstrates invoking the deployed runtime through boto3, passing JSON prompts, session identifiers, and payload bytes to return model responses for safe real-time trading workflow integration across desk applications and services.

Part 5. Create an MCP Tool Server Defines a stateless streamable HTTP MCP server that securely exposes domain-specific tools for liquidity, credit spreads, sovereign repricing, FX volatility, commodity shocks, CDS hedging, and correlation risk inside AgentCore Runtime deployments.

Part 6. Local and Remote MCP Testing Provides local and remote MCP client patterns for tool discovery, session initialization, Cognito bearer-token authentication, and runtime endpoint testing before production deployment and broader agent integration across controlled environments.

Part 7. Configure Amazon Cognito Authentication Describes Cognito user pools, custom JWT authorizers, allowed clients, discovery URLs, and refresh-token logic for securing inbound AgentCore Runtime and MCP Gateway access with enterprise identity controls and auditability requirements.

Part 8. Stream AgentCore Runtime Responses Explains asynchronous entrypoints, Server-Sent Events, chunked output, content-type handling, and boto3 stream processing for secure, low-latency market commentary and responsive agent experiences during volatile trading and risk monitoring sessions.

Part 9. Manage AgentCore Runtime Sessions Covers runtime session lifecycle, conversation history, application state, session identifiers, inactivity termination, and explicit stop calls for contextual multi-turn analysis and controlled resource usage across institutional workflows at scale.

Part 10. Handle Large Payloads Shows how to securely process base64-encoded Excel files and images up to large payload limits, combining structured data with chart signals for multimodal financial analysis and portfolio risk review workflows.

Part 11. Amazon Bedrock AgentCore Gateway Introduces AgentCore Gateway as a managed MCP integration layer that converts APIs, Lambda, Smithy, and OpenAPI definitions into secure, agent-accessible enterprise tools with authentication translation, observability, and built-in governance controls.

Part 12. Transform Lambda Functions into MCP Tools Outlines how to create Lambda-backed MCP tools, IAM roles, Cognito authorization, gateway targets, tool schemas, and credential providers for consistent, governed business-logic execution through agents in secure AWS production environments and workflows.

Part 13. Call AgentCore Gateway from a Strands Agent Demonstrates how to use Strands Agent with SigV4-authenticated MCP transport, temporary STS credentials, tool discovery, direct tool invocation, and agent-driven execution through AgentCore Gateway for secure enterprise integration and governed automation scenarios.

Part 14. AgentCore Gateway Semantic Search Explains how Gateway indexes tool metadata with embeddings and exposes semantic search so agents discover relevant tools without loading every schema into the prompt, reducing latency cost and complexity significantly.

Part 15. Sovereign Risk Trading Methodology Frames the market methodology around growth, liquidity, solvency, monetary power, policy reaction functions, capital flows, credit spread migration, FX pressure, and cross-asset rotation for institutional sovereign risk decision-making and hedging.

Part 16. Historical Crisis Context Uses historical crises including the Long Depression, Baring Crisis, Great Depression, oil shocks, Asian Financial Crisis, and LTCM to explain liquidity repricing, leverage contagion, and defensive portfolio rotation discipline lessons.


Part 1. Executive Overview

Introduces a production-grade sovereign risk trading agent using AgentCore Runtime, Gateway, MCP tools, authentication, streaming, sessions, and payload handling for secure, global institutional market intelligence and governed workflows at scale.

Amazon Bedrock AgentCore can be used to build a secure, production-grade sovereign risk trading agent for institutional financial services workflows.

The agent can analyze:

  • Government bond yield spreads
  • Credit spread widening
  • Sovereign debt repricing
  • FX volatility
  • Funding liquidity
  • Capital flows
  • Portfolio exposure
  • Defensive asset rotation
  • Policy reaction functions
  • Cross-asset risk migration

The architecture combines:

  • AgentCore Runtime for scalable agent execution
  • AgentCore Gateway for tool discovery and API transformation
  • MCP servers for structured financial tools
  • Amazon Cognito for authentication
  • Streaming responses for real-time market commentary
  • Session management for multi-turn workflows
  • Large-payload handling for Excel files, charts, and multimodal data

Part 2. Agent-as-Tools Architecture

Explains a hierarchical orchestration model where a central macro agent dynamically delegates survival, cyclical, and shock-capital tasks to specialized sub-agents across dollar liquidity, China demand, and European credit risk regimes.

Agent as Tools

Description

The agent uses a hierarchical architecture. A central orchestrator agent manages a disciplined three-tier capital strategy:

  • Survival capital
  • Cyclical capital
  • Shock capital

The orchestrator continuously assesses macroeconomic shifts and delegates specialized asset-allocation tasks to sub-agents focused on:

  • U.S. dollar liquidity cycles
  • Chinese industrial demand
  • European sovereign credit fractures
  • Global risk-premium migration
  • Multi-asset defensive rotation

Benefit

This decoupled design reduces the risk of catastrophic losses during periods of irrational market exuberance.

By separating macro-level strategic oversight from localized trade execution, financial institutions can execute disciplined capital migration before market consensus fully forms. This helps reduce exposure to:

  • Shadow-banking leverage
  • Liquidity illusions
  • Crowded trades
  • Correlation shocks
  • Sudden systemic repricing
  • Hidden global risk-premium shocks

Use Case

An investment bank can use this orchestrator to monitor policy reaction functions.

For example:

  • If Chinese infrastructure orders rise, the orchestrator can delegate to cyclical agents that analyze copper, shipping equities, resource stocks, and high-beta Asian equities.
  • If European sovereign-bank spreads widen, the orchestrator can trigger shock-capital agents to analyze gold, volatility instruments, credit default swap hedges, and U.S. dollar liquidity positions.

Demo

AgentCore runtime Input:

You are a senior institutional markets expert specializing in credit spread widening, sovereign debt risk repricing, and cross-asset risk rotation. You can perform math calculations. Provide concise trading views on sovereign risk, US-China government bond yield spreads, credit spreads, duration, FX hedging, liquidity, capital flows, portfolio exposures, and defensive positioning. When Excel files or images are provided, combine structured data and visual signals to deliver insights, trading implications, hedge ideas, confirmation signals, and invalidation triggers.

AgentCore runtime Output:

The core keywords of credit are growth, liquidity, solvency, monetary power, and political mobilization capacity. The United States has the Federal Reserve, reserve-currency status, deep capital markets, and quantitative easing. Therefore, a U.S. credit crisis can be repriced through the expansion of the central bank’s balance sheet.

China has benefited from the WTO dividend, state-owned banks, infrastructure demand, capital controls, and policy mobilization capacity. Therefore, China’s credit market is not priced purely as market-based default risk, but rather as a policy reaction function. China’s risks lie in its dependence on commodities, local government debt, overcapacity, and environmental pressure.

Europe has a strong currency but lacks unified fiscal authority. Therefore, the weakness of the euro area is not the currency itself, but the cyclical pressure between sovereign credit and the banking system.

Credit risk keywords include funding liquidity, credit spread migration, currency mismatch, policy reaction function, crowded trades, and correlation shocks. China credit trading should pay particular attention to the “National Ten Measures,” the “New National Ten Measures,” and medium-term debt reduction.

When policy expands, credit spreads compress. When policy focuses on stabilizing growth, state-owned enterprises, local government financing vehicles, and the infrastructure chain receive support. When policy shifts toward deleveraging, weak private enterprises, weak property developers, and weak local platforms are repriced.

Carnegie’s research on China’s financial system shows that China’s financial system can both serve growth and accumulate downside risks.

The next trading action should be based on a three-layer rotation structure: survival capital, cyclical capital, and shock capital.

Survival capital is used to ensure that one is not forced into liquidation by the market. It should be allocated to U.S. dollar cash, short-duration U.S. Treasuries, high-grade credit bonds, and gold.

Cyclical capital is used to follow the dominant macro engine. If U.S. corporate earnings, employment, real estate, and credit spreads improve, one should buy U.S. equities, recapitalized financial stocks, investment-grade credit bonds, and technology stocks with real cash flow.

If China’s PMI, copper prices, coal prices, iron ore, Asian exports, and infrastructure orders rise, one should buy China-related cyclical stocks, resource stocks, shipping stocks, and high-beta Asian equities.

If Europe weakens due to wider PIIGS spreads, banking pressure, and euro depreciation, one should reduce euro credit exposure, avoid weak banks, and hold German Bunds or U.S. dollar assets.

Shock capital is used to buy protection: gold, volatility instruments, credit default swap hedges, long U.S. dollar positions, and cash reserves.

The trading lesson from Dell’Ariccia and Mauro’s Rethinking Macroeconomic Policy is that the real winner is not the person who predicts every crisis, but the person who can execute rotation discipline when macro policy changes.

Carnegie’s research on capital-flow risks and global rebalancing also shows that macro risk migrates across equities, bonds, foreign exchange, commodities, and credit, rather than remaining in one single market.

From 1873 to 1879, the Long Depression was created by railways, banks, industrial capacity, and cross-border credit together, producing a long deflationary adjustment. Similar to 2008, excessive financing met insufficient demand, and leveraged optimism eventually turned into balance-sheet pain. The result was liquidation, low growth, and anti-globalization pressure.

The Baring Crisis of 1890 saw Argentine debt pressure strike the London financial system, showing that credit risk in peripheral markets can threaten core financial centers. Similar to the eurozone debt crisis and emerging-market capital outflows, confidence depended on creditor coordination. The result was that rescue efforts prevented collapse, but risk was repriced.

From 1929 to 1933, the Great Depression saw stock-market mania, debt, fragile banks, and policy mistakes turn a market decline into an economic collapse. Similar to 2008, leverage and asset bubbles infected the real economy. The result was deleveraging, unemployment, and strong state intervention.

From 1973 to 1975, the oil shock hit traditional portfolios through commodity-price shocks, inflation, low growth, and policy confusion. Similar to the risk of a reversal in China’s commodity supercycle, energy and raw materials changed macro pricing. The result was capital rotation toward inflation-resistant assets.

From 1997 to 1998, the Asian Financial Crisis and the LTCM event involved capital-flow reversals, currency collapses, and leverage-amplified pressure. Similar to Carnegie’s warning about dangerous capital flows, economies that absorb unstable capital are the most vulnerable. The result was contagion, forced selling, and a repricing of liquidity.


Amazon Bedrock AgentCore Core Component

Amazon Bedrock AgentCore Runtime (Covered in Article)

Serverless runtime for deploying scalable agents. Benefit: secure isolation and fast starts. Use case: production orchestration across frameworks and models.

Amazon Bedrock AgentCore Gateway (Covered in Article)

Tool discovery and API transformation for agents. Benefit: faster integrations and lower latency. Use case: agents selecting relevant tools contextually.

Amazon Bedrock AgentCore Identity

Agent identity management integrating providers. Benefit: delegated access with less consent fatigue. Use case: agents accessing AWS and third-party tools.

Amazon Bedrock AgentCore Code Interpreter

Sandboxed code execution for agents. Benefit: secure analytics with configurable isolation. Use case: running secure calculations, transformations, and data workflows.

Amazon Bedrock AgentCore Browser

Cloud browser runtime for website interaction. Benefit: secure scaling and observability. Use case: automated web research, form completion, and testing.

Amazon Bedrock AgentCore Memory

Managed memory for context-aware agents. Benefit: controlled short-term and long-term recall. Use case: personalized conversations across sessions and agents securely.

Amazon Bedrock AgentCore Observability

Monitoring for agent workflows in production. Benefit: faster debugging through telemetry dashboards. Use case: tracing latency, failures, and tool behavior.

Amazon Bedrock AgentCore Evaluations

Managed agent quality evaluation. Benefit: continuous scoring for correctness, safety, and helpfulness. Use case: production governance using built-in or custom evaluators.

Amazon Bedrock AgentCore Policy

Policy layer for verifying tool calls. Benefit: fine-grained action control. Use case: blocking unauthorized data, system, or tool access securely.


Part 3. Create the Runtime Agent

Shows how to securely deploy a serverless AgentCore Runtime application with Strands, Amazon Nova Pro, calculator tools, and a system prompt for sovereign credit and yield-spread analysis in production environments.

AgentCore Runtime supports both traditional HTTP request-response patterns and MCP-based tool protocols.

  • HTTP protocol: Traditional REST-style request and response endpoints
  • MCP protocol: Model Context Protocol for tools and agent servers
  • Default port: The agent is hosted on port 8080
from strands import Agent
from strands_tools import calculator
from bedrock_agentcore.runtime import BedrockAgentCoreApp
from strands.models import BedrockModel

app = BedrockAgentCoreApp()

model = BedrockModel(
    model_id="amazon.nova-pro-v1:0"
)

agent = Agent(
    model=model,
    tools=[calculator],
    system_prompt="You're a credit spread widening and sovereign debt risk repricing expert. You can do math calculations."
)

@app.entrypoint
def strands_agent_bedrock(payload):
    user_input = payload.get("prompt")
    response = agent(user_input)
    return response.message["content"][0]["text"]

if __name__ == "__main__":
    app.run()

Part 4. Invoke the Runtime Agent

Demonstrates invoking the deployed runtime through boto3, passing JSON prompts, session identifiers, and payload bytes to return model responses for safe real-time trading workflow integration across desk applications and services.

import boto3, json

client = boto3.client("bedrock-agentcore", region_name="us-east-1")

response = client.invoke_agent_runtime(
    agentRuntimeArn=agent_arn,
    runtimeSessionId=session_id,
    payload=json.dumps({"prompt": prompt}).encode()
)

Part 5. Create an MCP Tool Server

Defines a stateless streamable HTTP MCP server that securely exposes domain-specific tools for liquidity, credit spreads, sovereign repricing, FX volatility, commodity shocks, CDS hedging, and correlation risk inside AgentCore Runtime deployments.

The MCP server uses stateless streamable HTTP and the Mcp-Session-Id header for session isolation.

Key characteristics:

  • Runs on 0.0.0.0:8000
  • Exposes the /mcp endpoint
  • Runs inside AgentCore Runtime
  • Provides financial-domain tools for sovereign risk and cross-asset analysis

A specific tool:

  • usd_liquidity_cycle()
  • china_industrial_demand_engine()
  • european_sovereign_credit_fractures()
  • global_risk_premium_migration()
  • disciplined_multi_asset_rotation()
  • credit_spread_widening()
  • bank_funding_pressure()
  • sovereign_debt_risk_repricing()
  • heightened_fx_volatility()
  • sharp_commodity_price_volatility()
  • credit_default_swap_hedging()
  • funding_liquidity()
  • credit_spread_migration()
  • currency_mismatch()
  • policy_reaction_function()
  • crowded_trades()
  • correlation_shock()
from mcp.server.fastmcp import FastMCP

mcp = FastMCP(host="0.0.0.0", stateless_http=True)

@mcp.tool()
def usd_liquidity_cycle() -> str:
	"""Analyze the USD liquidity cycle"""
	return "USD liquidity cycle analysis"

@mcp.tool()
def china_industrial_demand_engine() -> str:
	"""Analyze China's industrial demand engine"""
	return "China industrial demand engine analysis"

@mcp.tool()
def european_sovereign_credit_fractures() -> str:
	"""Analyze European sovereign credit fractures"""
	return "European sovereign credit fractures analysis"

@mcp.tool()
def global_risk_premium_migration() -> str:
	"""Analyze global risk premium migration"""
	return "Global risk premium migration analysis"

@mcp.tool()
def disciplined_multi_asset_rotation() -> str:
	"""Analyze disciplined multi-asset rotation"""
	return "Disciplined multi-asset rotation analysis"

@mcp.tool()
def credit_spread_widening() -> str:
	"""Analyze credit spread widening"""
	return "Credit spread widening analysis"

@mcp.tool()
def bank_funding_pressure() -> str:
	"""Analyze bank funding pressure"""
	return "Bank funding pressure analysis"

@mcp.tool()
def sovereign_debt_risk_repricing() -> str:
	"""Analyze sovereign debt risk repricing"""
	return "Sovereign debt risk repricing analysis"

@mcp.tool()
def heightened_fx_volatility() -> str:
	"""Analyze heightened foreign exchange volatility"""
	return "Heightened FX volatility analysis"

@mcp.tool()
def sharp_commodity_price_volatility() -> str:
	"""Analyze sharp commodity price volatility"""
	return "Sharp commodity price volatility analysis"

@mcp.tool()
def credit_default_swap_hedging() -> str:
	"""Analyze credit default swap hedging"""
	return "Credit default swap hedging analysis"

@mcp.tool()
def funding_liquidity() -> str:
	"""Analyze funding liquidity"""
	return "Funding liquidity analysis"

@mcp.tool()
def credit_spread_migration() -> str:
	"""Analyze credit spread migration"""
	return "Credit spread migration analysis"

@mcp.tool()
def currency_mismatch() -> str:
	"""Analyze currency mismatch"""
	return "Currency mismatch analysis"

@mcp.tool()
def policy_reaction_function() -> str:
	"""Analyze policy reaction function"""
	return "Policy reaction function analysis"

@mcp.tool()
def crowded_trades() -> str:
	"""Analyze crowded trades"""
	return "Crowded trades analysis"

@mcp.tool()
def correlation_shock() -> str:
	"""Analyze correlation shock"""
	return "Correlation shock analysis"

if __name__ == "__main__":
	mcp.run(transport="streamable-http")

Part 6. Local and Remote MCP Testing

Provides local and remote MCP client patterns for tool discovery, session initialization, Cognito bearer-token authentication, and runtime endpoint testing before production deployment and broader agent integration across controlled environments.

Create and Run Local Testing Client

import asyncio
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client

async def main():
    async with streamablehttp_client(
        "http://localhost:8000/mcp", {}, timeout=120, terminate_on_close=False
    ) as (read, write, _):
        async with ClientSession(read, write) as session:
            await session.initialize()
            return await session.list_tools()

if __name__ == "__main__":
    asyncio.run(main())

Terminal 1: Start MCP server

python mcp_server.py

Terminal 2: Run the test client

python mcp_client.py

Create Remote Testing Client

The remote client retrieves the runtime ARN, refreshes the Cognito token if necessary, and connects to the AgentCore Runtime MCP endpoint.

import asyncio, base64, json, time, boto3
from datetime import timedelta
from urllib.parse import quote
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client


def refresh_token(client_id, refresh_token, region):
	return boto3.client("cognito-idp", region_name=region).initiate_auth(
    	ClientId=client_id,
    	AuthFlow="REFRESH_TOKEN_AUTH",
    	AuthParameters={"REFRESH_TOKEN": refresh_token},
	)["AuthenticationResult"]["AccessToken"]


def valid_token(token, client_id, refresh, region):
	try:
    	payload = token.split(".")[1] + "=" * (-len(token.split(".")[1]) % 4)
    	exp = json.loads(base64.b64decode(payload))["exp"]
    	return refresh_token(client_id, refresh, region) if exp - time.time() < 300 else token
	except Exception:
    	return refresh_token(client_id, refresh, region)


async def main():
	region = boto3.session.Session().region_name

	agent_arn = boto3.client("ssm", region_name=region).get_parameter(
    	Name="/mcp_server/runtime/agent_arn"
	)["Parameter"]["Value"]

	token = valid_token(
    	cognito_config["bearer_token"],
    	cognito_config["client_id"],
    	cognito_config["refresh_token"],
    	region,
	)

	url = (
    	f"https://bedrock-agentcore.{region}.amazonaws.com/runtimes/"
    	f"{quote(agent_arn, safe='')}/invocations?qualifier=DEFAULT"
	)

	async with streamablehttp_client(
    	url,
    	{"authorization": f"Bearer {token}", "Content-Type": "application/json"},
    	timeout=timedelta(seconds=120),
    	terminate_on_close=False,
	) as (read, write, _):
    	async with ClientSession(read, write) as session:
        	await session.initialize()
        	return await session.list_tools()


if __name__ == "__main__":
	asyncio.run(main())

Run MCP client remote

python mcp_server_remote.py

Part 7. Configure Amazon Cognito Authentication

Describes Cognito user pools, custom JWT authorizers, allowed clients, discovery URLs, and refresh-token logic for securing inbound AgentCore Runtime and MCP Gateway access with enterprise identity controls and auditability requirements.

Create Amazon Cognito for Authentication

import sys
sys.path.insert(0, "../..")
from utils import setup_cognito_user_pool
cognito_config = setup_cognito_user_pool()

Config AgentCore Runtime

import os
from bedrock_agentcore_starter_toolkit import Runtime

auth_config = {
    "customJWTAuthorizer": {
        "allowedClients": [cognito_config["client_id"]],
        "discoveryUrl": cognito_config["discovery_url"],
    }
}

response = Runtime().configure(
    entrypoint="mcp_server.py",
    auto_create_execution_role=True,
    auto_create_ecr=True,
    requirements_file="requirements.txt",
    region=region,
    authorizer_configuration=auth_config,
    protocol="MCP",
    agent_name=tool_name,
)

Launch AgentCore Runtime

launch_result = agentcore_runtime.launch()

Output: agent_arn, agent_id


Part 8. Stream AgentCore Runtime Responses

Explains asynchronous entrypoints, Server-Sent Events, chunked output, content-type handling, and boto3 stream processing for secure, low-latency market commentary and responsive agent experiences during volatile trading and risk monitoring sessions.

AgentCore Runtime streaming responses

AgentCore Runtime supports streaming responses through asynchronous entrypoints.

Key concepts:

  • Use async def for the entrypoint function
  • Use yield to stream chunks
  • Return Server-Sent Events format
  • Use Content-Type: text/event-stream
  • The stream ends when the function completes or raises an unhandled exception
from strands import Agent, tool
from bedrock_agentcore.runtime import BedrockAgentCoreApp
from strands.models import BedrockModel

app = BedrockAgentCoreApp()

@tool
def credit_spread_widening():
	"""Analyze credit spread widening"""
	return "Credit spread widening analysis"

@tool
def sovereign_debt_risk_repricing():
	"""Analyze sovereign debt risk repricing"""
	return "Sovereign debt risk repricing analysis"

agent = Agent(
	model=BedrockModel(model_id="amazon.nova-pro-v1:0"),
	tools=[credit_spread_widening, sovereign_debt_risk_repricing],
	system_prompt="You're a credit spread widening and sovereign debt risk repricing expert. You can do math calculations." ,
)

@app.entrypoint
async def strands_agent_bedrock_streaming(payload):
	try:
    	async for event in agent.stream_async(payload.get("prompt")):
        	if "data" in event:
            	yield event["data"]
	except Exception as e:
    	yield {"error": str(e), "type": "stream_error"}

if __name__ == "__main__":
	app.run()

Deploy AgentCore Runtime streaming responses

Package code as container and push to ECR using CI/CD pipelines and IaC.

Use the Amazon Bedrock AgentCore Python SDK to package artifacts and deploy to AgentCore Runtime.

from boto3.session import Session
from bedrock_agentcore_starter_toolkit import Runtime

response = Runtime().configure(
    entrypoint="strands_claude_streaming.py",
    auto_create_execution_role=True,
    auto_create_ecr=True,
    requirements_file="requirements.txt",
    region=Session().region_name,
    agent_name="strands_claude_streaming",
)

Launch AgentCore Runtime streaming responses

launch_result = agentcore_runtime.launch()

Direct Invoke AgentCore Runtime with Streaming

invoke_response = agentcore_runtime.invoke({
    "prompt": "Focus specifically on the US-China government bond yield spread and what it implies for the next position action. Assess whether the spread movement suggests stronger demand for US duration, weaker confidence in China growth, capital flow pressure, currency pressure on the renminbi, or a relative-value opportunity between US Treasuries and Chinese government bonds. Provide a practical trading view rather than a theoretical essay. Explain whether the preferred action is to reduce risk, add duration, hedge currency exposure, rotate into higher-quality sovereign bonds, stay defensive, or wait for confirmation. Include the key signals to watch: Fed policy expectations, PBOC easing, China credit demand, USD/CNH movement, real yield changes, foreign inflows or outflows, and risk appetite. Finally, give clear invalidation points that would require changing the position quickly."
})

invoke_response

Streaming responses with AgentCore Runtime

Handle the Server-Sent Events format.

Use boto3 for Streaming

import boto3, json

prompt = "Analyze the US-China government bond yield spread for next-position action. Assess duration demand, China growth risk, capital flows, RMB pressure, and UST-CGB relative value. Provide a professional trading view covering risk bias, duration positioning, FX hedging, sovereign rotation, confirmation signals, and invalidation triggers. Key factors: Fed path, PBOC easing, China credit impulse, USD/CNH, real yields, cross-border flows, liquidity, and risk appetite."

res = boto3.client("bedrock-agentcore", region_name=region).invoke_agent_runtime(
    agentRuntimeArn=launch_result.agent_arn,
    qualifier="DEFAULT",
    payload=json.dumps({"prompt": prompt}),
)

if "text/event-stream" in res.get("contentType", ""):
    response = " ".join(
        line.decode("utf-8")[6:].replace('"', "")
        for line in res["response"].iter_lines(chunk_size=1)
        if line and line.decode("utf-8").startswith("data: ")
    )
else:
    events = list(res.get("response", []))
    response = json.loads(events[0].decode("utf-8")) if events else None

response

Streaming responses Markdown AgentCore Runtime

import boto3, json
from IPython.display import Markdown, display

prompt = "Analyze the US-China government bond yield spread for next-position action. Assess duration demand, China growth risk, capital flows, RMB pressure, and UST-CGB relative value. Provide a professional trading view covering risk bias, duration positioning, FX hedging, sovereign rotation, confirmation signals, and invalidation triggers. Key factors: Fed path, PBOC easing, China credit impulse, USD/CNH, real yields, cross-border flows, liquidity, and risk appetite."

res = boto3.client("bedrock-agentcore", region_name=region).invoke_agent_runtime(
    agentRuntimeArn=launch_result.agent_arn,
    qualifier="DEFAULT",
    payload=json.dumps({"prompt": prompt}),
)

if "text/event-stream" in res.get("contentType", ""):
    response = " ".join(
        line.decode("utf-8")[6:].replace('"', "")
        for line in res["response"].iter_lines(chunk_size=1)
        if line and line.decode("utf-8").startswith("data: ")
    )
else:
    events = list(res.get("response", []))
    response = json.loads(events[0].decode("utf-8")) if events else ""

display(Markdown(response))

Part 9. Manage AgentCore Runtime Sessions

Covers runtime session lifecycle, conversation history, application state, session identifiers, inactivity termination, and explicit stop calls for contextual multi-turn analysis and controlled resource usage across institutional workflows at scale.

AgentCore Runtime session management

AgentCore Runtime sessions support contextual, multi-turn workflows.

Session Lifecycle

  • Creation: The first invocation creates the session.
  • Active state: The session processes requests.
  • Idle state: The session waits for the next invocation.
  • Termination: Sessions terminate after inactivity or maximum lifetime limits.

Session State

A session may preserve:

  • Conversation history
  • Previous responses
  • Application state
  • Runtime variables
  • Files created or modified during the session
from strands import Agent, tool
from strands_tools import calculator
from bedrock_agentcore.runtime import BedrockAgentCoreApp
from strands.models import BedrockModel

app = BedrockAgentCoreApp()

@tool
def credit_spread_widening():
    """Assess credit spread widening, funding stress, liquidity risk, and risk-asset pressure."""
    return "Credit spread widening may signal rising default risk, tighter funding, weaker liquidity, and defensive risk positioning."

@tool
def sovereign_debt_risk_repricing():
    """Assess sovereign debt repricing, yield spread pressure, duration risk, and FX implications."""
    return "Sovereign debt repricing may reflect policy divergence, fiscal risk, real-yield shifts, capital flows, and currency pressure."


agent = Agent(
    model=BedrockModel(model_id="amazon.nova-pro-v1:0"),
    tools=[calculator, credit_spread_widening, sovereign_debt_risk_repricing],
    system_prompt= “You're a professional FSI markets assistant. Always acknowledge the user's name. Provide concise institutional trading views on credit spreads, sovereign risk, US-China bond yield spread, duration, FX hedging, liquidity, and risk rotation.",
)

users = {
    "1": "María García",
    "2": "Carlos Rodríguez",
    "3": "Lucía Fernández",
    "4": "Diego Martínez",
    "5": "Sofía López",
}

@app.entrypoint
def strands_agent_bedrock_handling_context(payload, context):
    name = users[payload["user_id"]]
    prompt = f"My name is {name}. Request: {payload.get('prompt')}\nSession: {context.session_id}. Analyze the US-China government bond yield spread for next-position action. Assess duration demand, China growth risk, capital flows, RMB pressure, UST-CGB relative value, credit spread widening, and sovereign debt repricing. Provide risk bias, trade action, hedge options, confirmation signals, and invalidation triggers. Please acknowledge my name and assist."
    return agent(prompt).message["content"][0]["text"]

if __name__ == "__main__":
    app.run()

Create a session for AgentCore Runtime session management

import uuid
from IPython.display import Markdown, display

session_id = str(uuid.uuid4())

invoke_response = agentcore_runtime.invoke(
    {
        "prompt": "Analyze the US-China government bond yield spread for next-position action. Assess duration demand, China growth risk, capital flows, RMB pressure, and UST-CGB relative value. Provide a professional trading view covering risk bias, duration positioning, FX hedging, sovereign rotation, confirmation signals, and invalidation triggers. Key factors: Fed path, PBOC easing, China credit impulse, USD/CNH, real yields, cross-border flows, liquidity, and risk appetite.",
        "user_id": "1",
    },
    session_id=session_id,
)

display(Markdown(invoke_response["response"][0]))

Stop a session for AgentCore Runtime session management

import boto3

boto3.client("bedrock-agentcore", region_name=region).stop_runtime_session(
    agentRuntimeArn=launch_result.agent_arn,
    runtimeSessionId=str(session_id),
    qualifier="DEFAULT",
)

Part 10. Handle Large Payloads

Shows how to securely process base64-encoded Excel files and images up to large payload limits, combining structured data with chart signals for multimodal financial analysis and portfolio risk review workflows.

AgentCore Runtime large payload handling

AgentCore Runtime can process large payloads, such as Excel files and images. This is useful for financial services workflows involving:

  • Bond-yield datasets
  • Credit-spread datasets
  • Sovereign-risk dashboards
  • FX charts
  • Liquidity reports
  • Portfolio-exposure files
  • Capital-flow analytics

Important:

Payloads up to 100MB

import base64
from strands import Agent
from strands.models import BedrockModel
from bedrock_agentcore.runtime import BedrockAgentCoreApp

app = BedrockAgentCoreApp()

agent = Agent(
    model=BedrockModel(
        model_id="amazon.nova-pro-v1:0",
        max_tokens=16000,
    ),
    system_prompt="You are a professional FSI data analysis assistant. Analyze Excel files containing financial services data such as bond yields, credit spreads, sovereign risk, FX, liquidity, capital flows, and portfolio exposures. If images are provided, combine the visual signals with the Excel data. Provide concise institutional insights, risk drivers, trading implications, hedge ideas, confirmation signals, and invalidation triggers.",
)

@app.entrypoint
def multimodal_data_processor(payload, context):
    prompt = payload.get("prompt", "Analyze the provided data.")
    excel = base64.b64decode(payload.get("excel_data", ""))
    image = base64.b64decode(payload.get("image_data", ""))

    response = agent([
        {
            "document": {
                "format": "xlsx",
                "name": "excel_data",
                "source": {"bytes": excel},
            }
        },
        {
            "image": {
                "format": "png",
                "source": {"bytes": image},
            }
        },
        {
            "text": f"{prompt}\nAnalyze both data sources and provide combined insights."
        },
    ])

    return response.message["content"][0]["text"]

if __name__ == "__main__":
    app.run()

Run AgentCore Runtime large payload handling

import base64, uuid
from IPython.display import Markdown, display

def b64(path):
    with open(path, "rb") as f:
        return base64.b64encode(f.read()).decode()

payload = {
    "prompt": "Analyze the FSI Excel data and chart. Focus on bond yields, credit spreads, sovereign risk, FX pressure, liquidity, capital flows, portfolio exposures, risk drivers, trading implications, hedge ideas, confirmation signals, and invalidation triggers.",
    "excel_data": b64("large_credit_spreads_data.xlsx"),
    "image_data": b64("credit_spreads_chart.png"),
}

res = agentcore_runtime.invoke(payload, session_id=str(uuid.uuid4()))
display(Markdown("".join(res["response"])))

Demo: AgentCore Runtime with Gateway

AgentCore runtime Input:

You are a senior institutional markets expert specializing in credit spread widening, sovereign debt risk repricing, and cross-asset risk rotation. You can perform math calculations. Provide concise trading views on sovereign risk, US-China government bond yield spreads, credit spreads, duration, FX hedging, liquidity, capital flows, portfolio exposures, and defensive positioning. When Excel files or images are provided, combine structured data and visual signals to deliver insights, trading implications, hedge ideas, confirmation signals, and invalidation triggers.

AgentCore runtime with gateway output 1:

U.S. Dollar Liquidity Cycle -> China’s Industrial Demand Engine -> Cracks in European Sovereign Credit -> Migration of Global Risk Premia -> Disciplined Multi-Asset Rotation

(1) Social pressure, unemployment, austerity, urbanization, inequality, migration, and the collapse of trust are not background noise, but future risk premia.

Core Lesson From Robert Shiller’s Irrational Exuberance:

(1) Excessive valuations can persist longer than rationality, but they cannot persist forever.

(2) When prices detach from earnings, belief itself becomes an asset, and belief can disappear suddenly.

(3) The real advantage lies in completing a disciplined migration before consensus forms.

Raghuram Rajan, in Has Financial Development Made the World Riskier? Markus Brunnermeier, in Deciphering the Liquidity and Credit Crunch 2007–2008

(1) The United States rebuilt risk appetite through low interest rates, a housing bubble, subprime mortgages, securitization, leverage, and shadow banking.

Thomas Friedman’s The World Is Flat

(1) China became the global demand engine.

(2) Steel, coal, copper, aluminum, ports, exports, urbanization, state-owned enterprise listings, and infrastructure construction.

(3) A globalized world, but a heavier one, carrying coal smoke, resources, and balance sheets.

Shiller, Akerlof, and Shiller’s Animal Spirits Taleb’s The Black Swan

(1) Market psychology, narratives, and extreme shocks are not side issues, but pricing forces.

Reinhart and Rogoff’s This Time Is Different

Gorton’s Slapped by the Invisible Hand

(1) A banking crisis is a balance-sheet crisis, not an ordinary recession.

(2) Reduce leverage and buy liquidity: U.S. dollar cash, U.S. Treasuries, gold, and high-grade credit bonds.

Blanchard, Dell’Ariccia, and Mauro’s Rethinking Macroeconomic Policy

(1) The true winner is rotation discipline.

AgentCore runtime with gateway output 2:

Three-Layer Rotation Structure: Survival Capital, Cyclical Capital, and Shock Capital

Survival Capital:

(1) Allocate to U.S. dollar cash, short-duration U.S. Treasuries, high-grade credit bonds, and gold.

Cyclical Capital:

(1) Rotate among dominant macro engines. If U.S. corporate earnings, employment, housing, and credit spreads improve, buy U.S. equities, recapitalized financials, investment-grade credit, and technology stocks with real cash flows.

(2) If China’s PMI, copper prices, coal prices, iron ore, Asian exports, and infrastructure orders rise, buy China-linked cyclicals, resource stocks, shipping, and high-beta Asian equities.

(3) If Europe weakens because PIIGS spreads widen, banking stress rises, and the euro depreciates, reduce euro credit exposure, avoid weak banks, and hold German Bunds or U.S. dollar assets.

Shock Capital:

(1) Buy protection: gold, volatility instruments, credit default swap hedges, long U.S. dollar positions, and cash reserves.

AgentCore runtime with gateway output 3:

Credit Keywords:

(1) Growth, liquidity, solvency, monetary power, and political mobilization capacity.

Credit Risk Keywords:

(1) Funding liquidity, credit spread migration, currency mismatch, policy reaction function, crowded positioning, and correlation shocks.

(2) The United States has the Federal Reserve, reserve-currency status, deep capital markets, and quantitative easing.

(3) China has WTO dividends, state-owned banks, infrastructure demand, capital controls, and policy mobilization capacity. It also has commodity dependence, local government debt, overcapacity, and environmental pressure.

(4) Europe has a strong currency.

Too Big to Fail, The Big Short, The Root of All Evil, and Crisis Economics

(1) Visible prices are not as dangerous as hidden leverage.

AgentCore runtime with gateway final output:

Tactical Arbitrage and Convexity Trades

(1) Macro liquidity surplus -> real estate credit expansion -> structured credit mispricing -> leveraged convexity arbitrage -> disciplined and controlled exit.

(2) He did not merely see “subprime mortgages.” He saw household debt being converted into cash flows, cash flows being converted into securities, securities being converted into ratings, and ratings being converted into balance-sheet leverage.

(3) The psychological keyword here is controlled greed: not blind optimism, but recognition that capital was being forced outward along the risk curve.

(4) Housing prices were rising, default correlations appeared low, credit spreads were being compressed, and AAA-rated structured products offered higher yields than corporate bonds with the same rating.

(5) When policy, demographics, financial engineering, and investor constraints all point in the same direction, the trade may be crowded, but before it becomes fatal, it is often profitable.

(6) Hold the higher-quality parts of the mortgage credit machine, finance them at low cost, and hedge clear tail risks.

(7) Traders allocated capital to senior and mezzanine mortgage-backed securities, selected CDO tranches, and more liquid credit default swap indices.

(8) Avoid the most toxic no-doc loan pools, and prefer structures with excess spread, overcollateralization, trigger mechanisms, and shorter weighted-average maturities.

(9) Understand that banks, insurers, pension funds, hedge funds, and foreign reserve managers were all buying the same illusion of yield, thereby creating tradable price trends before the credit cycle broke.

Barbell Credit Allocation

(1) More liquid senior structured-credit exposure, relative-value credit default swap positions, and cash reserves to meet margin pressure.

(2) Increase exposure to AAA and AA mortgage tranches, because these assets still offered higher spread compensation relative to corporate credit.

(3) Buy protection through credit default swaps to hedge weaker mortgage indices, high-risk loan originators, and highly leveraged financial institutions.

Trading Keywords:

(1) Housing price appreciation, delinquency migration, ABX index spreads, and repo financing haircuts.

(2) If housing price gains slow while delinquencies rise and financing haircuts widen, the trade must shift from harvesting arbitrage income to protecting capital.

(3) Use late-cycle structured-credit buying pressure, hold positions with less financing fragility than peers, preserve liquid hedges, and exit before forced sellers dominate the market.

(4) Buy senior arbitrage assets, hedge systemic shocks, and prepare for a reverse exit. The trade must not be used as one-way leverage.

(5) Collect premium where structural subordination protection is strong, and buy protection where underwriting quality has clearly deteriorated.

Risk Keywords:

(1) Correlation shock, funding spiral, model error, counterparty wrong-way risk, and liquidity illusion.

(2) Securitization can turn a localized mortgage problem into global balance-sheet contagion.

(3) Subprime mortgages appear diversified, but if underwriting standards decline nationwide at the same time, diversification fails.

(4) Credit default swaps appear to transfer risk, but they can also concentrate counterparty exposure and create a false sense of safety.

(5) Exploit the market crowd’s hunger for yield, but never rely on the crowd’s mercy.

Tranche-Rating Keywords:

(1) Housing prices, default correlation, recovery rate, refinancing capacity, and market liquidity.

(2) Hold transparent collateral.

(3) Hold shorter-duration instruments with strong subordination protection and exit liquidity.


Part 11. Amazon Bedrock AgentCore Gateway

Introduces AgentCore Gateway as a managed MCP integration layer that converts APIs, Lambda, Smithy, and OpenAPI definitions into secure, agent-accessible enterprise tools with authentication translation, observability, and built-in governance controls.

Gateway Duty:

  • Convert APIs, Lambda functions, and existing services into MCP-compatible tools.
  • Supports OpenAPI, Smithy, and AWS Lambda.
  • Provides ingress authentication and egress authentication in a fully managed service.
  • Offers 1-click integration with Salesforce, Slack, Jira, Asana, and Zendesk.

Component Summary:

  • Lambda Function: Business logic
  • Authorizer: OAuth/OIDC configuration
  • Smithy: Strongly typed tools
  • Translation Engine: Converts MCP JSON-RPC into REST or Lambda payloads
  • Semantic Search Index: Catalogues tools with embeddings
  • Observability Pipeline: Tracks per-call latency, status, error taxonomy, and target-level invocation counts in CloudWatch

Create Gateway and MCP Endpoint URL:

Calls CreateMcpGateway, an OAuth authorizer configuration, and an IAM role.

Target Registration:

Attaches Lambda, OpenAPI, or Smithy definitions.

Agent Invocation:

  • The agent obtains an access token from the OIDC provider.
  • The agent calls the MCP endpoint with tools/list or tools/call.
  • The request is signed with SigV4 using the execution role.
  • The Translation Engine rewrites the payload to match the target protocol.

Semantic Tool Selection:

  • The agent sends tools/call to the built-in search tool.
  • The Gateway queries its embedding index and returns a ranked list of matching tools.

Part 12. Transform Lambda Functions into MCP Tools

Outlines how to create Lambda-backed MCP tools, IAM roles, Cognito authorization, gateway targets, tool schemas, and credential providers for consistent, governed business-logic execution through agents in secure AWS production environments and workflows.

Transform lambda into MCP tools

Step 1. Use uv_install() to install required AWS SDK packages. Step 2. Set REGION from AWS_DEFAULT_REGION. Step 3. Configure constants like LAMBDA_ZIP_FILE, GATEWAY_NAME, and TARGET_NAME. Step 4. Use create_lambda_function() to create the sample Lambda function. Step 5. Use create_gateway_iam_role() to create the AgentCore Gateway IAM role. Step 6. Use setup_cognito_authorization() to create Cognito authorization resources. Step 7. Use create_agentcore_gateway() to create the MCP AgentCore Gateway. Step 8. Configure auth_config with Cognito custom JWT authorizer. Step 9. Use create_lambda_gateway_target() to register Lambda as MCP tools. Step 10. Define tool schemas for get_order_tool and update_order_tool. Step 11. Use credential_config with GATEWAY_IAM_ROLE. Step 12. Use main() to run the end-to-end Gateway setup. Step 13. Return Lambda, Cognito, Gateway, and target creation outputs.

import utils
import os
import sys
import shutil
import subprocess


# Step 1: Ensure uv, boto3, and botocore are installed

def ensure_uv_installed():
    if shutil.which("uv") is None:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "uv"])


def uv_install(*packages):
    ensure_uv_installed()
    uv_path = shutil.which("uv")

    if uv_path is None:
        raise RuntimeError("uv installation failed or uv is not available in PATH.")

    subprocess.check_call([uv_path, "pip", "install", "--upgrade", *packages])


uv_install("botocore", "boto3")


# Step 2: Import AWS SDK dependencies

import boto3
from botocore.exceptions import ClientError
import utils


# Step 3: Configure constants

REGION = os.environ.get("AWS_DEFAULT_REGION")

if not REGION:
    raise EnvironmentError("AWS_DEFAULT_REGION environment variable is not set.")

LAMBDA_ZIP_FILE = "lambda_function_code.zip"

GATEWAY_ROLE_NAME = "sample-lambdagateway"

USER_POOL_NAME = "sample-agentcore-gateway-pool"
RESOURCE_SERVER_ID = "sample-agentcore-gateway-id"
RESOURCE_SERVER_NAME = "sample-agentcore-gateway-name"
CLIENT_NAME = "sample-agentcore-gateway-client"

SCOPES = [
    {
        "ScopeName": "gateway:read",
        "ScopeDescription": "Read access"
    },
    {
        "ScopeName": "gateway:write",
        "ScopeDescription": "Write access"
    }
]

GATEWAY_NAME = "TestGWforLambda"
GATEWAY_DESCRIPTION = "AgentCore Gateway with AWS Lambda target type"

TARGET_NAME = "LambdaUsingSDK"
TARGET_DESCRIPTION = "Lambda Target using SDK"


# Step 4: Create sample AWS Lambda function

def create_lambda_function():
    lambda_resp = utils.create_gateway_lambda(LAMBDA_ZIP_FILE)

    if lambda_resp is None:
        raise RuntimeError("Lambda function creation returned None.")

    if lambda_resp.get("exit_code") == 0:
        return lambda_resp.get("lambda_function_arn")

    raise RuntimeError(
        lambda_resp.get(
            "lambda_function_arn",
            "Lambda function creation failed."
        )
    )


# Step 5: Create IAM role for AgentCore Gateway

def create_gateway_iam_role():
    role_response = utils.create_agentcore_gateway_role(GATEWAY_ROLE_NAME)
    return role_response["Role"]["Arn"]


# Step 6: Create Amazon Cognito resources for inbound authorization

def setup_cognito_authorization():
    cognito = boto3.client("cognito-idp", region_name=REGION)

    user_pool_id = utils.get_or_create_user_pool(
        cognito,
        USER_POOL_NAME
    )

    utils.get_or_create_resource_server(
        cognito,
        user_pool_id,
        RESOURCE_SERVER_ID,
        RESOURCE_SERVER_NAME,
        SCOPES
    )

    client_id, client_secret = utils.get_or_create_m2m_client(
        cognito,
        user_pool_id,
        CLIENT_NAME,
        RESOURCE_SERVER_ID
    )

    cognito_discovery_url = (
        f"https://cognito-idp.{REGION}.amazonaws.com/"
        f"{user_pool_id}/.well-known/openid-configuration"
    )

    return client_id, client_secret, cognito_discovery_url


# Step 7: Create AgentCore Gateway with Amazon Cognito authorizer

def create_agentcore_gateway(role_arn, client_id, cognito_discovery_url):
    gateway_client = boto3.client(
        "bedrock-agentcore-control",
        region_name=REGION
    )

    auth_config = {
        "customJWTAuthorizer": {
            "allowedClients": [client_id],
            "discoveryUrl": cognito_discovery_url
        }
    }

    create_response = gateway_client.create_gateway(
        name=GATEWAY_NAME,
        roleArn=role_arn,
        protocolType="MCP",
        authorizerType="CUSTOM_JWT",
        authorizerConfiguration=auth_config,
        description=GATEWAY_DESCRIPTION
    )

    gateway_id = create_response["gatewayId"]
    gateway_url = create_response["gatewayUrl"]

    return gateway_client, gateway_id, gateway_url, create_response


# Step 8: Register Lambda target as MCP tools

def create_lambda_gateway_target(gateway_client, gateway_id, lambda_arn):
    lambda_target_config = {
        "mcp": {
            "lambda": {
                "lambdaArn": lambda_arn,
                "toolSchema": {
                    "inlinePayload": [
                        {
                            "name": "get_order_tool",
                            "description": "tool to get the order",
                            "inputSchema": {
                                "type": "object",
                                "properties": {
                                    "orderId": {
                                        "type": "string"
                                    }
                                },
                                "required": ["orderId"]
                            }
                        },
                        {
                            "name": "update_order_tool",
                            "description": "tool to update the orderId",
                            "inputSchema": {
                                "type": "object",
                                "properties": {
                                    "orderId": {
                                        "type": "string"
                                    }
                                },
                                "required": ["orderId"]
                            }
                        }
                    ]
                }
            }
        }
    }

    credential_config = [
        {
            "credentialProviderType": "GATEWAY_IAM_ROLE"
        }
    ]

    response = gateway_client.create_gateway_target(
        gatewayIdentifier=gateway_id,
        name=TARGET_NAME,
        description=TARGET_DESCRIPTION,
        targetConfiguration=lambda_target_config,
        credentialProviderConfigurations=credential_config
    )

    return response


# Step 9: Run end-to-end setup

def main():
    lambda_arn = create_lambda_function()

    gateway_role_arn = create_gateway_iam_role()

    client_id, client_secret, cognito_discovery_url = setup_cognito_authorization()

    gateway_client, gateway_id, gateway_url, gateway_response = create_agentcore_gateway(
        role_arn=gateway_role_arn,
        client_id=client_id,
        cognito_discovery_url=cognito_discovery_url
    )

    target_response = create_lambda_gateway_target(
        gateway_client=gateway_client,
        gateway_id=gateway_id,
        lambda_arn=lambda_arn
    )

    return {
        "lambda_arn": lambda_arn,
        "gateway_role_arn": gateway_role_arn,
        "client_id": client_id,
        "client_secret": client_secret,
        "cognito_discovery_url": cognito_discovery_url,
        "gateway_id": gateway_id,
        "gateway_url": gateway_url,
        "gateway_response": gateway_response,
        "target_response": target_response
    }


if __name__ == "__main__":
    main()

Part 13. Call AgentCore Gateway from a Strands Agent

Demonstrates how to use Strands Agent with SigV4-authenticated MCP transport, temporary STS credentials, tool discovery, direct tool invocation, and agent-driven execution through AgentCore Gateway for secure enterprise integration and governed automation scenarios.

Call Bedrock AgentCore Gateway via Strands Agent

Step 1. Set SERVICE for AgentCore Gateway SigV4 authentication. Step 2. Initialize model with BedrockModel. Step 3. Use create_streamable_http_transport_sigv4() to create IAM-authenticated MCP transport. Step 4. Use get_full_tools_list() to retrieve all MCP tools from Gateway. Step 5. Use call_tool_sync() to directly invoke an MCP tool. Step 6. Use run_agent() to create MCPClient and load tools into Strands Agent. Step 7. Use agent() to ask for order status using MCP tools. Step 8. Use assume_gateway_invoke_role() to get temporary STS credentials. Step 9. Read gateway_url, role_arn, and region from environment variables. Step 10. Call run_agent() with Gateway URL and assumed IAM credentials.

pip3 install --upgrade strands-agents strands-agents-tools boto3 botocore
import os
import time
import boto3

from botocore.credentials import Credentials
from strands import Agent
from strands.models import BedrockModel
from strands.tools.mcp.mcp_client import MCPClient
from mcp.client.streamable_http import streamablehttp_client
from streamable_http_sigv4 import streamablehttp_client_with_sigv4


SERVICE = "bedrock-agentcore"

model = BedrockModel(
    model_id="us.amazon.nova-pro-v1:0",
    temperature=0.7,
)

def create_streamable_http_transport_sigv4(
    mcp_url, key, secret, session_token, service_name, aws_region
):
    return streamablehttp_client_with_sigv4(
        url=mcp_url,
        credentials=Credentials(
            access_key=key,
            secret_key=secret,
            token=session_token,
        ),
        service=service_name,
        region=aws_region,
    )


def get_full_tools_list(client):
    tools, pagination_token = [], None

    while True:
        result = client.list_tools_sync(pagination_token=pagination_token)
        tools.extend(result)
        pagination_token = result.pagination_token

        if pagination_token is None:
            return tools


def call_tool_sync(client, tool_id, tool_name, parameters=None):
    response = client.call_tool_sync(
        tool_use_id=tool_id,
        name=tool_name,
        arguments=parameters or {},
    )

    if hasattr(response, "results") and response.results:
        return response.results
    if hasattr(response, "output") and response.output:
        return response.output
    if hasattr(response, "content"):
        return response.content

    return response


def run_agent(mcp_url, key, secret, session_token, service_name, aws_region):
    mcp_client = MCPClient(
        lambda: create_streamable_http_transport_sigv4(
            mcp_url,
            key,
            secret,
            session_token,
            service_name,
            aws_region,
        )
    )

    with mcp_client:
        tools = get_full_tools_list(mcp_client)

        print(f"Found the following tools: {[tool.tool_name for tool in tools]}")
        print(f"First tool name: {tools[0].tool_name}")

        agent = Agent(model=model, tools=tools)

        print(f"Tools loaded in the agent are: {agent.tool_names}")

        agent_response = agent(
            "Check the order status for order id 123 and show me the exact response from the tool"
        )

        print("Agent response:")
        print(agent_response)

        result = call_tool_sync(
            mcp_client,
            "get-order-id-123-call-1",
            tools[0].tool_name,
            {"orderId": "123"},
        )

        print("Tool Call result:")

        try:
            print(result["content"][0]["text"])
        except Exception:
            print(result)


def assume_gateway_invoke_role(role_arn):
    return boto3.client("sts").assume_role(
        RoleArn=role_arn,
        RoleSessionName="invoke_mcp_session",
        DurationSeconds=3600,
    )["Credentials"]


def main():
    gateway_url = os.environ["AGENTCORE_GATEWAY_URL"]
    role_arn = os.environ["AGENTCORE_GATEWAY_INVOKE_ROLE_ARN"]
    region = os.environ.get("AWS_DEFAULT_REGION") or os.environ["AWS_REGION"]

    creds = assume_gateway_invoke_role(role_arn)

    run_agent(
        gateway_url,
        creds["AccessKeyId"],
        creds["SecretAccessKey"],
        creds["SessionToken"],
        SERVICE,
        region,
    )

if __name__ == "__main__":
    main()
export AWS_DEFAULT_REGION=us-east-1
export AGENTCORE_GATEWAY_URL="https://your-gateway-url"
export AGENTCORE_GATEWAY_INVOKE_ROLE_ARN="arn:aws:iam::123456789012:role/your-gateway-invoke-role"

python agentcore_gateway_strands_mcp.py

Part 14. AgentCore Gateway Semantic Search

Explains how Gateway indexes tool metadata with embeddings and exposes semantic search so agents discover relevant tools without loading every schema into the prompt, reducing latency cost and complexity significantly.

AgentCore Gateway semantic search core component

AgentCore Gateways:

Intelligently discover and select only the most relevant tools with multiple Lambda-backed targets

Strands Agent:

Framework-agnostic agent layer using Amazon Bedrock models for natural language understanding, reasoning, and orchestration tasks.

AgentCore Gateway:

Centralized tool management hub enabling agents to discover, select, and invoke enterprise tools efficiently and securely.

Lambda Targets:

Collections of AWS Lambda functions grouped by categories, representing diverse enterprise capabilities and integration workflows.

Semantic Search Engine:

Intelligent discovery layer matching agent intents to relevant tools without processing exhaustive inventories or lists.

Security Guard:

Manages OAuth authorization, ensuring only verified users and agents can access approved tools and resources.

Translator:

Converts MCP and other agent protocol requests into API calls and Lambda invocations without servers.

Composer:

Combines multiple APIs, functions, and tools into one MCP endpoint that agents can use seamlessly and efficiently.

Keychain:

Injects the correct credentials for each tool, enabling agents to use protected services securely and reliably.

Researcher:

Searches tool inventories contextually, selecting relevant tools, reducing prompt size, latency, and operating costs significantly.

Infrastructure Manager:

Provides serverless gateway infrastructure with observability and auditing, reducing operational burden for developers and teams.

Vector Store Semantic Search Flow

Vector Store Created:

Gateway automatically provisions a serverless, fully managed vector store for semantic tool search capabilities.

Vector Store Populated:

Gateway uses embeddings to index tool metadata from Lambda targets, JSON definitions, and OpenAPI schemas.

Search Tool Provided:

Gateway adds x-amz-bedrock-agentcore-search, an MCP tool for semantic discovery across available Gateway tools.

Semantic Query Argument:

Search tool accepts a single query argument and returns tools ranked by contextual relevance.

Metadata Matching:

Search compares queries against tool names, descriptions, input schemas, and output schemas for accurate discovery.

Create AgentCore Gateway semantic search

  • Amazon Cognito as the identity provider (IdP)
  • AWS Lambda functions as targets
  • AWS IAM for outbound authentication

Step 1: Set gateway name

GATEWAY_NAME stores the AgentCore gateway name.

Step 2: Define tool schema

TOOL_SCHEMA defines sovereign_debt_risk_repricing.

Step 3: Create AWS session

session = boto3.Session() creates AWS session.

Step 4: Create AgentCore client

agentcore_client connects to bedrock-agentcore-control.

Step 5: Create gateway

create_gateway(cognito, gateway_role_arn) creates MCP gateway.

Step 6: Configure JWT auth

cognito["client_id"] and cognito["discovery_url"] configure auth.

Step 7: Configure MCP search

protocolConfiguration enables semantic MCP search.

Step 8: Return gateway ID

create_gateway() returns response["gatewayId"].

Step 9: Create gateway target

create_gateway_target(gateway_id, lambda_arn) creates Lambda target.

Step 10: Attach Lambda ARN

lambda_arn links Lambda to gateway target.

Step 11: Attach tool schema

TOOL_SCHEMA is passed as inlinePayload.

Step 12: Return target ID

create_gateway_target() returns response["targetId"].

Step 13: Create Lambda function

utils.create_gateway_lambda() returns lambda_resp.

Step 14: Set up Cognito

utils.setup_cognito_user_pool() returns cognito.

Step 15: Get bearer token

utils.get_bearer_token() returns bearer_token.

Step 16: Create IAM role

utils.create_gateway_iam_role() returns gateway_role_arn.

Step 17: Create gateway resource

gateway_id = create_gateway(...).

Step 18: Wait for propagation

time.sleep(5) waits for AWS readiness.

Step 19: Create target resource

target_id = create_gateway_target(...).

Step 20: List targets

targets_response stores gateway target list.

Step 21: Return outputs

main() returns IDs, targets, and token.

import time
import boto3
import utils

GATEWAY_NAME = "gateway-sdr-repricing"

TOOL_SCHEMA = [
    {
        "name": "sovereign_debt_risk_repricing",
        "description": "Sovereign debt risk repricing",
        "inputSchema": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": (
                        "Question, analysis request, or market context "
                        "for sovereign debt risk repricing."
                    ),
                }
            },
            "required": ["query"],
        },
    }
]


session = boto3.Session()
agentcore_client = session.client("bedrock-agentcore-control")


def create_gateway(cognito, gateway_role_arn):
    response = agentcore_client.create_gateway(
        name=GATEWAY_NAME,
        roleArn=gateway_role_arn,
        authorizerType="CUSTOM_JWT",
        description="AgentCore Gateway Sovereign Debt Risk Repricing",
        protocolType="MCP",
        authorizerConfiguration={
            "customJWTAuthorizer": {
                "allowedClients": [cognito["client_id"]],
                "discoveryUrl": cognito["discovery_url"],
            }
        },
        protocolConfiguration={
            "mcp": {
                "searchType": "SEMANTIC",
                "supportedVersions": ["2025-03-26"],
            }
        },
    )

    return response["gatewayId"]


def create_gateway_target(gateway_id, lambda_arn):
    response = agentcore_client.create_gateway_target(
        gatewayIdentifier=gateway_id,
        name="SDRRepricingTools",
        description="Sovereign Debt Risk Repricing Tools",
        targetConfiguration={
            "mcp": {
                "lambda": {
                    "lambdaArn": lambda_arn,
                    "toolSchema": {
                        "inlinePayload": TOOL_SCHEMA,
                    },
                }
            }
        },
        credentialProviderConfigurations=[
            {
                "credentialProviderType": "GATEWAY_IAM_ROLE",
            }
        ],
    )

    return response["targetId"]


def main():
    lambda_resp = utils.create_gateway_lambda(
        "calc/lambda_function_code.zip",
        lambda_function_name="sdr_repricing_lambda_gateway",
    )

    cognito = utils.setup_cognito_user_pool()

    bearer_token = utils.get_bearer_token(
        client_id=cognito["client_id"],
        username="testuser",
        password="MyPassword123!",
    )

    gateway_role_arn = utils.create_gateway_iam_role(
        lambda_arns=[lambda_resp["lambda_function_arn"]]
    )

    gateway_id = create_gateway(
        cognito=cognito,
        gateway_role_arn=gateway_role_arn,
    )

    target_id = create_gateway_target(
        gateway_id=gateway_id,
        lambda_arn=lambda_resp["lambda_function_arn"],
    )

    targets_response = agentcore_client.list_gateway_targets(
        gatewayIdentifier=gateway_id
    )

    return {
        "gateway_id": gateway_id,
        "target_id": target_id,
        "targets_response": targets_response,
        "bearer_token": bearer_token,
    }


if __name__ == "__main__":
    main()

Search tools from an AgentCore Gateway semantic search

Step 1: get_gateway_endpoint retrieves gateway_endpoint using agentcore_client and gateway_id, returning gatewayUrl for MCP client connections.

Step 2: main gets jwt_token via utils.get_bearer_token, using cognito_response, username, and password for Gateway authentication.

Step 3: MCPClient opens client with gateway_endpoint and jwt_token headers, enabling JSON-RPC agent_ready_tools creation.

Step 4: get_all_agent_tools_from_mcp_endpoint paginates next_cursor, converting each tool into MCPTool and MCPAgentTool.

Step 5: Second MCPClient opens client again, isolating mcp_tools retrieval through Strands list_tools_sync pagination.

Step 6: get_all_mcp_tools_from_mcp_client loops pagination_token, extending tools with each returned page until complete.

Step 7: tool_search builds tool_params with search_query, calling x_amz_bedrock_agentcore_search through invoke_gateway_tool.

Step 8: invoke_gateway_tool posts tool_params to gateway_endpoint with jwt_token, returning JSON-RPC response from tools/call.

Step 9: main returns gateway_endpoint, jwt_token, agent_ready_tools, mcp_tools, semantic_search_results, and elapsed search seconds.

import time
import requests

from strands.tools.mcp import MCPClient
from strands.tools.mcp.mcp_agent_tool import MCPAgentTool
from mcp import Tool as MCPTool
from mcp.client.streamable_http import streamablehttp_client


def get_gateway_endpoint(agentcore_client, gateway_id):
    return agentcore_client.get_gateway(
        gatewayIdentifier=gateway_id
    )["gatewayUrl"]


def invoke_gateway_tool(gateway_endpoint, jwt_token, tool_params):
    return requests.post(
        gateway_endpoint,
        json={
            "jsonrpc": "2.0",
            "id": 2,
            "method": "tools/call",
            "params": tool_params,
        },
        headers={
            "Authorization": f"Bearer {jwt_token}",
            "Content-Type": "application/json",
        },
    ).json()


def get_all_agent_tools_from_mcp_endpoint(gateway_endpoint, jwt_token, client):
    tools_list = []
    next_cursor = None

    while True:
        result = requests.post(
            gateway_endpoint,
            json={
                "jsonrpc": "2.0",
                "id": 2,
                "method": "tools/list",
                "params": {"cursor": next_cursor} if next_cursor else {},
            },
            headers={
                "Authorization": f"Bearer {jwt_token}",
                "Content-Type": "application/json",
            },
        ).json()["result"]

        for tool in result["tools"]:
            tools_list.append(
                MCPAgentTool(
                    MCPTool(
                        name=tool["name"],
                        description=tool.get("description", ""),
                        inputSchema=tool.get("inputSchema", {}),
                    ),
                    client,
                )
            )

        next_cursor = result.get("nextCursor")

        if next_cursor is None:
            return tools_list


def get_all_mcp_tools_from_mcp_client(client):
    tools = []
    pagination_token = None

    while True:
        page = client.list_tools_sync(
            pagination_token=pagination_token
        )

        tools.extend(page)
        pagination_token = page.pagination_token

        if pagination_token is None:
            return tools


def tool_search(gateway_endpoint, jwt_token, query):
    return invoke_gateway_tool(
        gateway_endpoint=gateway_endpoint,
        jwt_token=jwt_token,
        tool_params={
            "name": "x_amz_bedrock_agentcore_search",
            "arguments": {
                "query": query
            },
        },
    )["result"]["structuredContent"]["tools"]


def main(
    agentcore_client,
    utils,
    cognito_response,
    gateway_id,
    username="user",
    password="pwd",
    search_query="search credit spread widening and extra 2 related tools",
):
    gateway_endpoint = get_gateway_endpoint(
        agentcore_client=agentcore_client,
        gateway_id=gateway_id,
    )

    jwt_token = utils.get_bearer_token(
        client_id=cognito_response["client_id"],
        username=username,
        password=password,
    )

    with MCPClient(
        lambda: streamablehttp_client(
            gateway_endpoint,
            headers={
                "Authorization": f"Bearer {jwt_token}"
            },
        )
    ) as client:
        agent_ready_tools = get_all_agent_tools_from_mcp_endpoint(
            gateway_endpoint=gateway_endpoint,
            jwt_token=jwt_token,
            client=client,
        )

    with MCPClient(
        lambda: streamablehttp_client(
            gateway_endpoint,
            headers={
                "Authorization": f"Bearer {jwt_token}"
            },
        )
    ) as client:
        mcp_tools = get_all_mcp_tools_from_mcp_client(client)

    start_time = time.time()

    semantic_search_results = tool_search(
        gateway_endpoint=gateway_endpoint,
        jwt_token=jwt_token,
        query=search_query,
    )

    return {
        "gateway_endpoint": gateway_endpoint,
        "jwt_token": jwt_token,
        "agent_ready_tools": agent_ready_tools,
        "mcp_tools": mcp_tools,
        "semantic_search_results": semantic_search_results,
        "semantic_search_elapsed_seconds": time.time() - start_time,
    }

Part 15. Sovereign Risk Trading Methodology

Frames the market methodology around growth, liquidity, solvency, monetary power, policy reaction functions, capital flows, credit spread migration, FX pressure, and cross-asset rotation for institutional sovereign risk decision-making and hedging.

The sovereign risk trading methodology centers on growth, liquidity, solvency, monetary power, political mobilization capacity, funding liquidity, credit spread migration, currency mismatch, policy reaction function, crowded trades, and correlation shocks.

The practical trading structure uses three layers:

  • Survival capital
  • Cyclical capital
  • Shock capital

Survival capital protects against forced liquidation. Cyclical capital follows the dominant macro engine. Shock capital buys protection when credit, liquidity, or policy regimes break.


Part 16. Historical Crisis Context

Uses historical crises including the Long Depression, Baring Crisis, Great Depression, oil shocks, Asian Financial Crisis, and LTCM to explain liquidity repricing, leverage contagion, and defensive portfolio rotation discipline lessons.

Historical crisis context includes:

  • Long Depression
  • Baring Crisis
  • Great Depression
  • Oil shocks
  • Asian Financial Crisis
  • LTCM

These events explain liquidity repricing, leverage contagion, capital-flow reversal, defensive portfolio rotation, and the need to migrate capital before consensus forms.