Skip to content

feat(runtime): add HTTP invocation and execute_command support to AgentCoreRuntimeClient#422

Open
EashanKaushik wants to merge 2 commits intoaws:mainfrom
EashanKaushik:main
Open

feat(runtime): add HTTP invocation and execute_command support to AgentCoreRuntimeClient#422
EashanKaushik wants to merge 2 commits intoaws:mainfrom
EashanKaushik:main

Conversation

@EashanKaushik
Copy link
Copy Markdown

@EashanKaushik EashanKaushik commented Apr 20, 2026

Closes #423

Summary

Extends AgentCoreRuntimeClient (which previously only generated WebSocket URLs and SigV4/OAuth headers) with HTTP invocation, SSE streaming, async streaming, and the InvokeAgentRuntimeCommand shell-exec API using bearer-token auth. Methods take runtime_arn and bearer_token per call, mirroring the existing generate_ws_connection_oauth shape.

Design (per reviewer guidance)

  • Single client, one import. HTTP methods live on AgentCoreRuntimeClient alongside the existing URL-generation methods. No new sibling class.
  • Per-call bearer auth. invoke, invoke_streaming, invoke_streaming_async, execute_command, execute_command_streaming, and stop_runtime_session all take (runtime_arn, bearer_token, ...) positionally — identical shape to generate_ws_connection_oauth.
  • Lazy PoolManager. self._http is a @property that imports and constructs urllib3.PoolManager on first access. Callers that only use SigV4 URL-generation methods never trigger the import or pay the allocation cost.
  • Reuses existing helpers. URL construction goes through the new _build_http_url, which extracts region via _parse_runtime_arn and builds the base URL via get_data_plane_endpoint from bedrock_agentcore._utils.endpoints. No hardcoded host or region.

Usage

Setup

from bedrock_agentcore.runtime import AgentCoreRuntimeClient

client = AgentCoreRuntimeClient(region="us-west-2")

Streaming invocation (SSE)

for chunk in client.invoke_streaming(
    runtime_arn="arn:aws:bedrock-agentcore:us-west-2:…:runtime/my-runtime",
    bearer_token="your-bearer-token",
    body={"prompt": "Hello"},
    session_id="my-session-id",
):
    print(chunk, end="", flush=True)

Async variant for FastAPI / MCP servers:

async for chunk in client.invoke_streaming_async(
    runtime_arn, bearer_token, {"prompt": "Hello"}, session_id="my-session-id",
):
    print(chunk, end="", flush=True)

Shell command execution (InvokeAgentRuntimeCommand)

Blocking, collects full output:

result = client.execute_command(
    runtime_arn, bearer_token, "uname -a",
    session_id="my-session-id",
)
# {'stdout': 'Linux ...', 'stderr': '', 'exitCode': 0, 'status': 'COMPLETED'}

Streaming EventStream events for long-running commands:

import sys

for event in client.execute_command_streaming(
    runtime_arn, bearer_token, "sh -c 'for i in 1 2 3; do echo $i; sleep 1; done'",
    session_id="my-session-id",
):
    if "contentDelta" in event:
        d = event["contentDelta"]
        if d.get("stdout"):
            print(d["stdout"], end="", flush=True)
        if d.get("stderr"):
            print(d["stderr"], end="", flush=True, file=sys.stderr)
    elif "contentStop" in event:
        stop = event["contentStop"]
        print(f"exit={stop['exitCode']} status={stop['status']}")

Each execute_command call runs in a fresh shell — working directory and environment variables do not persist across calls in the same session. Wrap sequences in sh -c 'cd … && …' if you need to chain.

Stop a session

client.stop_runtime_session(
    runtime_arn, bearer_token, session_id="my-session-id",
)

What's included

  • src/bedrock_agentcore/runtime/agent_core_runtime_client.py — six new HTTP methods on AgentCoreRuntimeClient, AgentRuntimeError exception, _build_http_url helper reusing _parse_runtime_arn + get_data_plane_endpoint, lazy _http property, and response-parsing helpers.
  • src/bedrock_agentcore/runtime/__init__.py — exports AgentRuntimeError.
  • tests/unit/runtime/test_agent_core_runtime_client.py — 72 new unit tests (lazy-pool lifecycle, per-method behavior, all _decode_sse_line branches, EventStream parsing). 96% branch coverage on the merged class.
  • CHANGELOG.md[Unreleased] entry.

Design notes

  • Uses urllib3 (already an SDK dep) — no new top-level dependency.
  • EventStream framing parsed via botocore.eventstream.EventStreamBuffer (already transitive via boto3).
  • execute_command(..., command_timeout=DEFAULT_COMMAND_TIMEOUT) — the server-side wall-clock limit. The HTTP read timeout is derived internally as command_timeout + 30 (not caller-facing).
  • No changes to existing generate_ws_connection / generate_presigned_url / generate_ws_connection_oauth signatures or behavior.

Test plan

  • uv run ruff check src/ tests/ — clean
  • uv run mypy src/bedrock_agentcore/runtime/agent_core_runtime_client.py — only pre-existing warning on generate_presigned_url (line 518, unchanged from upstream main; verified via git stash)
  • uv run pytest tests/unit/runtime/test_agent_core_runtime_client.py — 106/106 pass (34 pre-existing SigV4 tests preserved + 72 new HTTP tests)
  • uv run pytest tests/ --cov=src — 1505 passed, 0 failed, total coverage 92.77% (above 90% gate)
  • Branch coverage on agent_core_runtime_client.py: 96%
  • Integration tests under tests_integ/runtime/not added (would require a deployed exec-capable runtime; happy to follow up)

Possible follow-up (not in this PR)

region in __init__ becomes redundant when the ARN is supplied per-call (HTTP methods use the ARN-parsed region). The SigV4 URL-generation methods still rely on self.region for signing, so changing this touches more than I wanted to in one PR. Happy to open a separate issue/PR if it's worth relaxing.

@EashanKaushik EashanKaushik changed the title feat(runtime): add AgentCoreRuntimeHttpClient for HTTP invocation and execute_command feat(runtime): add HTTP invocation and execute_command support to AgentCoreRuntimeClient Apr 20, 2026
@EashanKaushik
Copy link
Copy Markdown
Author

Pushed the rework per the review:

  • HTTP methods (invoke, invoke_streaming, invoke_streaming_async, execute_command, execute_command_streaming, stop_runtime_session) now live on AgentCoreRuntimeClient. The sibling AgentCoreRuntimeHttpClient class and file are gone.
  • Per-call (runtime_arn, bearer_token) matches the existing generate_ws_connection_oauth signature.
  • self._http is a @property that imports urllib3 and constructs the PoolManager on first HTTP call. SigV4-URL-only callers never trigger it.
  • URL construction reuses _parse_runtime_arn and get_data_plane_endpoint — no hardcoded region / host.

Commits on the branch:

  • 7820df5 — original "add sibling client" commit (kept for history)
  • 1fe1dbe — merge into AgentCoreRuntimeClient + lazy pool + helper reuse

Happy to squash before merge if that's the preferred shape.

Test numbers (run from bedrock-agentcore-sdk-python/):

  • tests/unit/runtime/test_agent_core_runtime_client.py → 106 passed (34 pre-existing SigV4 tests preserved + 72 merged HTTP tests)
  • tests/ full suite → 1505 passed, 0 failed
  • Branch coverage on the modified class → 96%

PR body and #423 updated to match.

@codecov-commenter
Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.24895% with 16 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (main@625d8ec). Learn more about missing BASE report.

Files with missing lines Patch % Lines
...ock_agentcore/runtime/agent_core_runtime_client.py 93.61% 7 Missing and 8 partials ⚠️
src/bedrock_agentcore/runtime/__init__.py 50.00% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main     #422   +/-   ##
=======================================
  Coverage        ?   91.34%           
=======================================
  Files           ?       58           
  Lines           ?     5197           
  Branches        ?      803           
=======================================
  Hits            ?     4747           
  Misses          ?      256           
  Partials        ?      194           
Flag Coverage Δ
unittests 91.34% <93.24%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request] Bearer-token HTTP client for runtime invocation and InvokeAgentRuntimeCommand

2 participants