Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

Add opt-in local worker proxy for AgentCore invocations (#1839)

Lisandro Pintos94a0aaef521f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cafd412e..21c06af7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
+- **Bedrock AgentCore — opt-in Docker runtime** — set `MINISTACK_AGENTCORE_DOCKER=1` to start the declared `containerConfiguration.containerUri` image on first invocation, connect via a localhost port when MiniStack runs on the host or via MiniStack's Docker network when containerized, call `/ping`, and forward `InvokeAgentRuntime` to `/invocations` on port 8080. The container is reused and removed on update, delete, or reset. Container and worker HTTP errors become `RuntimeClientError` (424); caller credentials are not forwarded. Without Docker mode, the existing deterministic echo remains for SDK tests. This covers HTTP only and does not emulate AWS IAM/VPC isolation or model inference.
- **CloudWatch Logs — delivery destination policy** — `PutDeliveryDestinationPolicy`, `GetDeliveryDestinationPolicy`, `DeleteDeliveryDestinationPolicy`. Required by an operator that authorizes `delivery.logs.amazonaws.com` to create deliveries to a `DeliveryDestination` (e.g. CloudFront access-log delivery to a log group) — `PutDeliveryDestinationPolicy` previously had no route, blocking the delivery from ever being created. Contributed by @fabio-andre-rodrigues.
- **S3 — object annotations** — `PutObjectAnnotation`, `GetObjectAnnotation`, `ListObjectAnnotations` (prefix, `max-annotation-results`, continuation tokens) and `DeleteObjectAnnotation`: named UTF-8 payloads of 1 byte to 1 MiB, up to 1,000 per object version, with S3's naming rules (`InvalidAnnotationName`, `AnnotationNameTooLong`), `AnnotationLimitExceeded`, `UnsupportedMediaType` and `x-amz-object-if-match`. Each belongs to one object version: a new version starts with none, deleting a version deletes its annotations, a delete marker keeps them, and an unversioned overwrite or delete drops them; writing one changes neither the object's ETag nor its version. `CopyObject` carries them unless `x-amz-object-annotation-directive: EXCLUDE`, and recomputes their checksums when the copy names a new algorithm. Payload checksums are verified (`BadDigest`) and default to CRC64NVME; CRC32, CRC32C, CRC64NVME, SHA1, SHA256, SHA512, MD5 and XXHASH64 are computed, while XXHASH3 and XXHASH128 are refused rather than stored unverified. Annotations take the object's encryption and are refused on SSE-C objects, replicate with the object (`COMPLETED` / `REPLICA`), respect Object Lock on every write (governance retention needs `x-amz-bypass-governance-retention` to put, overwrite or delete one; compliance retention and a legal hold refuse all three, bypass or not, each as 403 `AccessDenied` naming retention or the legal hold, as observed on AWS), persist per version with `S3_PERSIST=1`, and send `s3:ObjectAnnotation:Put` / `s3:ObjectAnnotation:Delete` events with the record's `objectAnnotation` block; a `CopyObject` event reports `hasObjectAnnotation`. Previously a `PUT ?annotation` fell through to `PutObject` and replaced the object with the payload. The S3 Metadata annotation table (`UpdateBucketMetadataAnnotationTableConfiguration`) is not included: MiniStack has no S3 Metadata configuration for it to belong to. Checked against the S3 API Reference, the S3 User Guide's "Annotating your objects" page and the botocore model; the Object Lock behaviour was validated against AWS (ap-southeast-2).
diff --git a/README.md b/README.md
index cc2c186d..af9dc11c 100644
--- a/README.md
+++ b/README.md
@@ -432,7 +432,7 @@ subnet = ec2.create_subnet(
| **Bedrock Runtime** | Converse, ConverseStream, InvokeModel, InvokeModelWithResponseStream, ApplyGuardrail, StartAsyncInvoke, GetAsyncInvoke, ListAsyncInvokes | Real eventstream wire format on streaming operations; **guardrails enforce their deterministic policies** — word policy, sensitive-information regexes, and the pattern-matchable PII types with `BLOCK`/`ANONYMIZE` per input/output stage — on `ApplyGuardrail` and on `Converse`/`ConverseStream` via `guardrailConfig` (`GUARDRAIL_INTERVENED`, blocked messaging, per-policy assessments, `ResourceNotFoundException` for an unknown id); the model-graded policies (topic, content, contextual grounding, `PROFANITY`) are not evaluated; deterministic family-aware mock responses selected by model ID prefix (`anthropic.*`, `amazon.titan*`, `amazon.nova*`, `meta.llama*`, `mistral.*`, `cohere.*`, `ai21.*`); verified against botocore `bedrock-runtime-2023-09-30` |
| **Bedrock Agent** | 72 operations — agents (versions, aliases, action groups, collaborators, agent knowledge bases, PrepareAgent), knowledge bases (data sources, ingestion jobs — `StartIngestionJob` reads the S3 data source and reports real statistics, `FAILED` with `failureReasons` when the source is unreadable — documents), flows (aliases, versions, ValidateFlowDefinition, PrepareFlow), prompts with versions, tagging | All 72 operations verified against botocore `bedrock-agent-2023-06-05` |
| **Bedrock Agent Runtime** | InvokeAgent, InvokeInlineAgent, GetAgentMemory, DeleteAgentMemory, Retrieve, RetrieveAndGenerate, RetrieveAndGenerateStream, Rerank, CreateSession, GetSession, UpdateSession, DeleteSession, EndSession, ListSessions, CreateInvocation, ListInvocations, PutInvocationStep, GetInvocationStep, ListInvocationSteps, InvokeFlow, StartFlowExecution, StopFlowExecution, GetFlowExecution, ListFlowExecutions, ListFlowExecutionEvents, GetExecutionFlowSnapshot, OptimizePrompt | All 31 operations verified against botocore `bedrock-agent-runtime-2023-07-26`; eventstream responses on streaming operations; `Retrieve` searches the documents Knowledge Base ingestion stored (lexical scoring — no embeddings) and returns content, `s3Location` and score; `InvokeAgent` answers a canned reply without orchestration and emits no trace events — it never fabricates an `ORCHESTRATE` trace |
-| **Bedrock AgentCore** | Control plane (`bedrock-agentcore-control`): CreateAgentRuntime, GetAgentRuntime, ListAgentRuntimes, UpdateAgentRuntime, DeleteAgentRuntime, ListAgentRuntimeVersions, CreateAgentRuntimeEndpoint, GetAgentRuntimeEndpoint, ListAgentRuntimeEndpoints, UpdateAgentRuntimeEndpoint, DeleteAgentRuntimeEndpoint. Data plane (`bedrock-agentcore`): InvokeAgentRuntime | Agent-runtime lifecycle with `CREATING`/`UPDATING`→`READY` transitions, versioned ARNs (`agent/{uuid}:{version}`, `agentEndpoint/{uuid}`); request/response shapes verified against botocore `bedrock-agentcore-control` / `bedrock-agentcore`; account- and region-scoped state; `InvokeAgentRuntime` is a deterministic echo (no model inference), matching the requested emulation scope |
+| **Bedrock AgentCore** | Control plane (`bedrock-agentcore-control`): CreateAgentRuntime, GetAgentRuntime, ListAgentRuntimes, UpdateAgentRuntime, DeleteAgentRuntime, ListAgentRuntimeVersions, CreateAgentRuntimeEndpoint, GetAgentRuntimeEndpoint, ListAgentRuntimeEndpoints, UpdateAgentRuntimeEndpoint, DeleteAgentRuntimeEndpoint. Data plane (`bedrock-agentcore`): InvokeAgentRuntime | Agent-runtime lifecycle with `CREATING`/`UPDATING`→`READY` transitions, versioned ARNs (`agent/{uuid}:{version}`, `agentEndpoint/{uuid}`); request/response shapes verified against botocore `bedrock-agentcore-control` / `bedrock-agentcore`; account- and region-scoped state; `InvokeAgentRuntime` echoes by default or, with `MINISTACK_AGENTCORE_DOCKER=1`, starts the declared container image and forwards HTTP invocations to its port 8080 (no model inference in MiniStack) |
| **Transcribe** | StartTranscriptionJob, GetTranscriptionJob, ListTranscriptionJobs, DeleteTranscriptionJob | Batch transcription jobs only; streaming is a separate endpoint (`transcribestreaming`). All four operations verified against botocore `transcribe-2017-10-26`. A job starts `IN_PROGRESS` with `StartTime` set, as on AWS, and reaches `COMPLETED` over two seconds; `QUEUED`, which AWS reaches only for a request that opted into job queueing (`JobExecutionSettings.AllowDeferredExecution`) while the account is at its concurrent job limit, is not modelled; the media object is read from MiniStack S3 via an `s3://`, path-style or virtual-hosted HTTPS URI, and an unreadable URI fails the job with a `FailureReason` rather than erroring at `Start`, as on AWS; the transcript is written back to S3 in the real result format (`results.transcripts`, word-level `results.items`, `results.audio_segments`, plus `results.segments` and `results.speaker_labels` when the matching `Settings` are set) at `OutputBucketName`/`OutputKey`, or to an auto-created `ministack-transcribe-output` bucket. `IdentifyLanguage` and `IdentifyMultipleLanguages` resolve a language on completion, `ContentRedaction` controls whether a `redacted-` copy replaces or accompanies the transcript, and `Subtitles` writes WebVTT and SubRip files, redacted alongside the transcript when redaction is on. Reaching a terminal state publishes a `Transcribe Job State Change` event, so EventBridge rules downstream of a job fire. There is no speech recognition, so the transcript is deterministic canned text keyed on a digest of the media URI |
| **Translate** | StartTextTranslationJob, DescribeTextTranslationJob, ListTextTranslationJobs, StopTextTranslationJob | Batch text translation jobs only; the synchronous `TranslateText` / `TranslateDocument` pair and the custom terminology / parallel data families are not implemented. All four operations verified against botocore `translate-2017-07-01`. Jobs walk `SUBMITTED` → `IN_PROGRESS` → `COMPLETED` over `TRANSLATE_JOB_RUN_SECONDS` (default 2, `0` completes immediately); every document under `InputDataConfig.S3Uri` is read from MiniStack S3 and written back to the rewritten output location AWS uses — `OutputDataConfig.S3Uri` is reported as `s3://<bucket>/<prefix><account-id>-TranslateText-<JobId>/` — as `<target-code>.<input name>`, with a `details/<code>.auxiliary-translation-details.json` summary per target language. `text/plain` is translated line by line, `text/html` keeps its markup and translates only text nodes, `application/x-xliff+xml` gets a populated `<target>` in every `<trans-unit>` plus `target-language` on every `<file>`, and the three Office ZIP types are copied through. A document that can't be read as its content type is counted in `JobDetails` and the job ends `COMPLETED_WITH_ERROR`; an empty or unreadable input location fails the job with a `Message` rather than erroring at `Start`. `ClientToken` is idempotent, `StopTextTranslationJob` reaches a running worker, and reaching a terminal state publishes a `Translate TextTranslationJob State Change` event, so EventBridge rules downstream of a job fire. There is no machine translation, so the output is deterministic canned text derived from the source |
| **MSK** | CreateCluster, ListClusters, DescribeCluster, DeleteCluster, GetBootstrapBrokers, ListNodes, CreateConfiguration, ListConfigurations, DescribeConfiguration, ListConfigurationRevisions, DescribeConfigurationRevision, BatchAssociateScramSecret, BatchDisassociateScramSecret, ListScramSecrets, TagResource, UntagResource, ListTagsForResource | Kafka control plane; `GetBootstrapBrokers` honors `MINISTACK_MSK_BOOTSTRAP` so clients route to a real broker you bring (Redpanda, Kafka, KRaft) — the Kafka wire protocol itself is not emulated |
@@ -865,6 +865,7 @@ end-to-end without any client config.
| `MINISTACK_IMDS_V2_REQUIRED` | `0` | Reject token-less GETs on `/latest/meta-data/...`. When set, callers must first `PUT /latest/api/token` and pass the token as `X-aws-ec2-metadata-token`, matching real-AWS hop-limit-1 IMDSv2-only instances |
| `MINISTACK_BEDROCK_PROXY_URL` | _(unset)_ | OpenAI-compatible `/chat/completions` endpoint (Ollama, llama.cpp, vLLM). When set, Bedrock `Converse`/`InvokeModel` prompts are translated to OpenAI shape, forwarded, and translated back to Bedrock shape — real completions through the Bedrock API. Falls back to the deterministic mock on connection error |
| `MINISTACK_BEDROCK_PROXY_TIMEOUT_SECONDS` | `30` | Upstream request timeout for the Bedrock proxy |
+| `MINISTACK_AGENTCORE_DOCKER` | _(unset)_ | Set to `1` to run the image in `agentRuntimeArtifact.containerConfiguration.containerUri` on first `InvokeAgentRuntime`. When MiniStack runs on the host, it publishes the worker's port 8080 on localhost; when MiniStack runs in Docker, it joins the worker to MiniStack's Docker network. It calls `/ping`, then forwards to `/invocations`. The container is reused until the runtime is updated, deleted, or MiniStack resets. Requires a reachable Docker daemon and an image Docker can pull or find locally. Container and HTTP errors return `RuntimeClientError` (424). Without this opt-in, the existing deterministic echo remains available for control-plane and SDK tests. This covers HTTP; IAM, VPC isolation, MCP, A2A and WebSocket are not emulated. **Keep the MiniStack API private when this is enabled:** anyone who can create and invoke a runtime can cause Docker to start an image of their choosing. Use only trusted images. |
| `MINISTACK_MSK_BOOTSTRAP` | _(unset)_ | Plaintext bootstrap broker string returned by MSK `GetBootstrapBrokers` — point it at a real broker you bring (Redpanda, Kafka, KRaft). Unset → placeholder endpoint (control-plane only) |
| `MINISTACK_MSK_BOOTSTRAP_TLS` | _(unset)_ | TLS bootstrap string (`BootstrapBrokerStringTls`) |
| `MINISTACK_MSK_BOOTSTRAP_SASL_SCRAM` | _(unset)_ | SASL/SCRAM bootstrap string (`BootstrapBrokerStringSaslScram`) |
diff --git a/ministack/services/bedrock_agentcore.py b/ministack/services/bedrock_agentcore.py
index bd9b04d5..89f375b8 100644
--- a/ministack/services/bedrock_agentcore.py
+++ b/ministack/services/bedrock_agentcore.py
@@ -21,17 +21,24 @@ Shapes, HTTP methods, URIs, ARN/ID patterns, and status enums are verified
against botocore ``bedrock-agentcore-control`` / ``bedrock-agentcore``
service-2.json.
"""
+import asyncio
import copy
import datetime
import json
import logging
+import os
import re
import secrets
import string
+import threading
+import time
+import urllib.error
+import urllib.request
from urllib.parse import unquote
from ministack.core.responses import (
AccountRegionScopedDict,
+ StreamingResponse,
error_response_json,
get_account_id,
get_region,
@@ -48,6 +55,8 @@ logger = logging.getLogger("bedrock_agentcore")
_runtimes = AccountRegionScopedDict() # agentRuntimeId -> runtime record
_endpoints = AccountRegionScopedDict() # agentRuntimeId -> {endpointName -> endpoint record}
+_containers = {} # (account, region, runtime id) -> Docker container
+_container_lock = threading.RLock()
# AgentRuntimeName / EndpointName: start with a letter, then letters/digits/_,
# up to 48 chars total (botocore pattern ^[a-zA-Z][a-zA-Z0-9_]{0,47}$).
@@ -74,6 +83,10 @@ def _restore_state(data):
def reset():
+ with _container_lock:
+ for container in _containers.values():
+ _remove_container(container)
+ _containers.clear()
_runtimes.clear()
_endpoints.clear()
@@ -241,6 +254,7 @@ def _update_agent_runtime(runtime_id, body):
for field in ("agentRuntimeArtifact", "roleArn", "networkConfiguration"):
if not data.get(field):
return _validation(f"{field} is required")
+ _stop_container(runtime_id)
now = now_iso()
new_version = str(int(record["agentRuntimeVersion"]) + 1)
record["agentRuntimeVersion"] = new_version
@@ -270,6 +284,7 @@ def _delete_agent_runtime(runtime_id):
record = _runtimes.get(runtime_id)
if record is None:
return _not_found(f"Agent runtime {runtime_id} not found")
+ _stop_container(runtime_id)
_runtimes.pop(runtime_id, None)
_endpoints.pop(runtime_id, None)
return json_response({"status": "DELETING", "agentRuntimeId": runtime_id})
@@ -411,6 +426,14 @@ def _invoke_agent_runtime(runtime_arn, headers, body):
session_id = (headers.get("x-amzn-bedrock-agentcore-runtime-session-id")
or new_uuid())
content_type = headers.get("content-type", "application/json")
+ if os.environ.get("MINISTACK_AGENTCORE_DOCKER") == "1":
+ try:
+ url = _container_invocations_url(runtime)
+ except (RuntimeError, ValueError) as error:
+ logger.warning("AgentCore runtime container failed: %s", error)
+ return error_response_json("RuntimeClientError", str(error), 424)
+ return _invoke_container(url, body, headers, content_type, session_id)
+
# Deterministic echo: return the request payload back under a stable shape
# so contract tests can assert Invoke request/response handling without a
# real model. No inference is performed.
@@ -430,6 +453,178 @@ def _invoke_agent_runtime(runtime_arn, headers, body):
return 200, out_headers, out_body
+_WORKER_REQUEST_HEADERS = (
+ "accept", "x-amzn-trace-id", "traceparent", "tracestate", "baggage",
+)
+_WORKER_RESPONSE_HEADERS = (
+ "x-amzn-trace-id", "traceparent", "tracestate", "baggage",
+)
+
+_LOCAL_HTTP = urllib.request.build_opener(urllib.request.ProxyHandler({}))
+
+
+def _local_open(request, *, timeout):
+ """Reach the local Docker endpoint without inheriting HTTP proxy settings."""
+ return _LOCAL_HTTP.open(request, timeout=timeout)
+
+
+def _container_key(runtime_id):
+ return get_account_id(), get_region(), runtime_id
+
+
+def _remove_container(container):
+ try:
+ container.remove(force=True)
+ except Exception:
+ logger.exception("Could not remove AgentCore runtime container")
+
+
+def _remove_orphan_containers(client, labels):
+ """Recover a container created just before a Docker API timeout."""
+ try:
+ matches = client.containers.list(
+ all=True,
+ filters={"label": [f"{name}={value}" for name, value in labels.items()]},
+ )
+ for match in matches:
+ _remove_container(match)
+ except Exception:
+ logger.exception("Could not inspect orphaned AgentCore runtime containers")
+
+
+def _stop_container(runtime_id):
+ with _container_lock:
+ container = _containers.pop(_container_key(runtime_id), None)
+ if container is not None:
+ _remove_container(container)
+
+
+def _container_invocations_url(runtime):
+ """Start the declared image once per runtime version, then use its port 8080."""
+ artifact = runtime.get("agentRuntimeArtifact", {}).get("containerConfiguration", {})
+ image = artifact.get("containerUri")
+ if not isinstance(image, str) or not image:
+ raise ValueError("Agent runtime has no containerConfiguration.containerUri")
+ key = _container_key(runtime["agentRuntimeId"])
+ with _container_lock:
+ container = _containers.get(key)
+ if container is not None:
+ try:
+ container.reload()
+ if container.status != "running":
+ _remove_container(container)
+ _containers.pop(key, None)
+ container = None
+ except Exception as error:
+ raise RuntimeError(f"Could not inspect runtime container: {error}") from error
+ if container is None:
+ client = None
+ labels = {"ministack": "agentcore",
+ "ministack.agentcore.runtime": runtime["agentRuntimeId"],
+ "ministack.agentcore.account": key[0],
+ "ministack.agentcore.region": key[1]}
+ try:
+ import docker
+ client = docker.from_env(timeout=60)
+ run_kwargs = {
+ "environment": runtime.get("environmentVariables", {}),
+ "labels": labels,
+ }
+ network = None
+ try:
+ self_container = client.containers.get(os.environ.get("HOSTNAME", ""))
+ self_container.reload()
+ networks = self_container.attrs["NetworkSettings"]["Networks"]
+ network = next(iter(networks), None)
+ except Exception:
+ pass # MiniStack is running directly on the host.
+ if network:
+ run_kwargs["network"] = network
+ else:
+ run_kwargs["ports"] = {"8080/tcp": ("127.0.0.1", None)}
+ try:
+ container = client.containers.create(image, **run_kwargs)
+ except docker.errors.ImageNotFound:
+ client.images.pull(image)
+ container = client.containers.create(image, **run_kwargs)
+ container.start()
+ container.reload()
+ if network:
+ address = container.attrs["NetworkSettings"]["Networks"][network]["IPAddress"]
+ if not address:
+ raise RuntimeError("Container has no address on MiniStack's network")
+ url = f"http://{address}:8080/invocations"
+ else:
+ bindings = container.attrs["NetworkSettings"]["Ports"]["8080/tcp"]
+ if not bindings:
+ raise RuntimeError("Container port 8080 was not published")
+ url = f"http://127.0.0.1:{bindings[0]['HostPort']}/invocations"
+ deadline = time.monotonic() + 30
+ while True:
+ try:
+ with _local_open(url.removesuffix("/invocations") + "/ping", timeout=1):
+ break
+ except (urllib.error.URLError, TimeoutError, ConnectionError):
+ container.reload()
+ if container.status == "exited" or time.monotonic() >= deadline:
+ raise RuntimeError("Container did not become ready on port 8080")
+ time.sleep(0.1)
+ container._ministack_invocations_url = url
+ _containers[key] = container
+ except Exception as error:
+ if container is not None:
+ _remove_container(container)
+ elif client is not None:
+ _remove_orphan_containers(client, labels)
+ raise RuntimeError(f"Could not start runtime image {image}: {error}") from error
+ return container._ministack_invocations_url
+
+
+def _invoke_container(url, body, headers, content_type, session_id):
+ """Forward only invocation data, never the caller's AWS credentials."""
+ forwarded_headers = {
+ "Content-Type": content_type,
+ "x-amzn-bedrock-agentcore-runtime-session-id": session_id,
+ }
+ forwarded_headers.update({name: headers[name] for name in _WORKER_REQUEST_HEADERS if name in headers})
+ request = urllib.request.Request(
+ url, data=body or b"", method="POST",
+ headers=forwarded_headers,
+ )
+ try:
+ response = _local_open(request, timeout=30)
+ except urllib.error.HTTPError as error:
+ error.close()
+ return error_response_json("RuntimeClientError",
+ f"Received error ({error.code}) from runtime.", 424)
+ except (urllib.error.URLError, TimeoutError, ConnectionError) as error:
+ logger.warning("AgentCore container unavailable: %s", error)
+ return error_response_json("RuntimeClientError",
+ "AgentCore runtime container is unavailable", 424)
+
+ out_headers = {
+ "Content-Type": response.headers.get("Content-Type", "application/octet-stream"),
+ "x-amzn-bedrock-agentcore-runtime-session-id": session_id,
+ }
+ out_headers.update({name: response.headers[name] for name in _WORKER_RESPONSE_HEADERS
+ if name in response.headers})
+ if "Content-Length" in response.headers:
+ out_headers["Content-Length"] = response.headers["Content-Length"]
+
+ async def _stream(send, receive):
+ try:
+ while chunk := await asyncio.to_thread(response.read1, 64 * 1024):
+ await send({"type": "http.response.body", "body": chunk, "more_body": True})
+ except Exception:
+ logger.exception("AgentCore container response stream failed")
+ else:
+ await send({"type": "http.response.body", "body": b"", "more_body": False})
+ finally:
+ response.close()
+
+ return response.status, out_headers, StreamingResponse(_stream)
+
+
# ---------------------------------------------------------------------------
# Router — dispatch by rest-json HTTP method + path
# ---------------------------------------------------------------------------
@@ -442,7 +637,7 @@ async def handle_request(method, path, headers, body, query_params):
if (method == "POST" and inner.startswith("runtimes/")
and inner.endswith("/invocations")):
arn = inner[len("runtimes/"):-len("/invocations")]
- return _invoke_agent_runtime(unquote(arn), headers, body)
+ return await asyncio.to_thread(_invoke_agent_runtime, unquote(arn), headers, body)
parts = [p for p in inner.split("/") if p]
# All remaining AgentCore paths are rooted at /runtimes.
@@ -467,7 +662,7 @@ async def handle_request(method, path, headers, body, query_params):
elif n == 3:
seg = parts[2]
if seg == "invocations" and method == "POST":
- return _invoke_agent_runtime(unquote(parts[1]), headers, body)
+ return await asyncio.to_thread(_invoke_agent_runtime, unquote(parts[1]), headers, body)
runtime_id = unquote(parts[1])
if seg == "versions" and method == "POST":
return _list_agent_runtime_versions(runtime_id, body)
diff --git a/tests/test_bedrock_agentcore_container.py b/tests/test_bedrock_agentcore_container.py
new file mode 100644
index 00000000..5cba2cc4
--- /dev/null
+++ b/tests/test_bedrock_agentcore_container.py
@@ -0,0 +1,319 @@
+"""AgentCore container invocation contract, without a live AWS account."""
+
+import asyncio
+import json
+import sys
+import threading
+import types
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+from ministack.core.responses import StreamingResponse
+from ministack.services import bedrock_agentcore as agentcore
+
+
+def _runtime(name="container_test", image="example.local/worker:1"):
+ status, _, body = agentcore._create_agent_runtime(json.dumps({
+ "agentRuntimeName": name,
+ "agentRuntimeArtifact": {"containerConfiguration": {"containerUri": image}},
+ "roleArn": "arn:aws:iam::000000000000:role/agentcore",
+ "networkConfiguration": {"networkMode": "PUBLIC"},
+ "environmentVariables": {"WORKER_MODE": "test"},
+ }).encode())
+ assert status == 200
+ return json.loads(body)
+
+
+def _invoke(arn, headers=None, body=b"{}"):
+ return asyncio.run(agentcore.handle_request(
+ "POST", f"/runtimes/{arn}/invocations",
+ headers or {"content-type": "application/json"}, body, {},
+ ))
+
+
+def _fake_docker(monkeypatch, port, *, fail=False, network=None,
+ fail_on_start=False, fail_after_create=False, missing_image=False):
+ started = []
+ removed = []
+ created = []
+ pulled = []
+
+ class ImageNotFound(Exception):
+ pass
+
+ class Container:
+ status = "running"
+ attrs = {"NetworkSettings": {
+ "Ports": {"8080/tcp": [{"HostPort": str(port)}]},
+ "Networks": {network: {"IPAddress": "127.0.0.1"}} if network else {},
+ }}
+
+ def reload(self):
+ pass
+
+ def start(self):
+ if fail_on_start:
+ raise TimeoutError("Docker start timed out")
+
+ def remove(self, force=False):
+ removed.append(force)
+
+ class Containers:
+ def get(self, _name):
+ if not network:
+ raise RuntimeError("MiniStack is not in Docker")
+ return Container()
+
+ def create(self, image, **kwargs):
+ if fail:
+ raise RuntimeError("image unavailable")
+ if missing_image and not pulled:
+ raise ImageNotFound(image)
+ started.append((image, kwargs))
+ container = Container()
+ created.append(container)
+ if fail_after_create:
+ raise TimeoutError("Docker create timed out after allocation")
+ return container
+
+ def list(self, **_kwargs):
+ return created
+
+ fake_docker = types.SimpleNamespace(
+ errors=types.SimpleNamespace(ImageNotFound=ImageNotFound),
+ from_env=lambda **_kwargs: types.SimpleNamespace(
+ containers=Containers(),
+ images=types.SimpleNamespace(pull=lambda image: pulled.append(image)),
+ ),
+ )
+ monkeypatch.setitem(sys.modules, "docker", fake_docker)
+ monkeypatch.setenv("MINISTACK_AGENTCORE_DOCKER", "1")
+ return started, removed
+
+
+def _worker(response_status=200):
+ requests = []
+
+ class Worker(BaseHTTPRequestHandler):
+ def do_GET(self):
+ self.send_response(200 if self.path == "/ping" else 404)
+ self.end_headers()
+
+ def do_POST(self):
+ requests.append((self.path, dict(self.headers),
+ self.rfile.read(int(self.headers["Content-Length"]))))
+ payload = b'{"evidence":[{"id":"deployment-1"}]}'
+ self.send_response(response_status)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+
+ def log_message(self, *_args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Worker)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ return server, thread, requests
+
+
+async def _discard(_message):
+ pass
+
+
+def test_container_image_invoked_and_removed(monkeypatch):
+ server, thread, requests = _worker()
+ started, removed = _fake_docker(monkeypatch, server.server_port)
+ runtime = _runtime()
+ try:
+ headers = {"content-type": "application/json", "authorization": "secret",
+ "x-amzn-bedrock-agentcore-runtime-session-id": "session-1"}
+ status, response_headers, body = _invoke(runtime["agentRuntimeArn"], headers,
+ b'{"prompt":"why?"}')
+ assert status == 200
+ assert isinstance(body, StreamingResponse)
+ messages = []
+
+ async def send(message):
+ messages.append(message)
+
+ asyncio.run(body.runner(send, None))
+ assert json.loads(b"".join(m["body"] for m in messages)) == {
+ "evidence": [{"id": "deployment-1"}]}
+ assert response_headers["x-amzn-bedrock-agentcore-runtime-session-id"] == "session-1"
+ assert started[0][0] == "example.local/worker:1"
+ assert started[0][1]["ports"] == {"8080/tcp": ("127.0.0.1", None)}
+ assert started[0][1]["environment"] == {"WORKER_MODE": "test"}
+ path, forwarded, payload = requests[0]
+ assert path == "/invocations" and payload == b'{"prompt":"why?"}'
+ assert "authorization" not in {key.lower() for key in forwarded}
+ _, _, second_body = _invoke(runtime["agentRuntimeArn"])
+ asyncio.run(second_body.runner(_discard, None))
+ assert len(started) == 1
+ finally:
+ agentcore._delete_agent_runtime(runtime["agentRuntimeId"])
+ server.shutdown()
+ server.server_close()
+ thread.join()
+ assert removed == [True]
+
+
+def test_container_joins_ministack_network(monkeypatch):
+ started, _ = _fake_docker(monkeypatch, 8080, network="ministack-net")
+ class Healthy:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ pass
+
+ monkeypatch.setattr(agentcore, "_local_open", lambda *_args, **_kwargs: Healthy())
+ runtime = _runtime("network_test")
+ try:
+ url = agentcore._container_invocations_url(agentcore._runtimes[runtime["agentRuntimeId"]])
+ assert url == "http://127.0.0.1:8080/invocations"
+ assert started[0][1]["network"] == "ministack-net"
+ assert "ports" not in started[0][1]
+ finally:
+ agentcore._delete_agent_runtime(runtime["agentRuntimeId"])
+
+
+def test_worker_error_is_runtime_client_error(monkeypatch):
+ server, thread, _ = _worker(400)
+ _fake_docker(monkeypatch, server.server_port)
+ runtime = _runtime("worker_error")
+ try:
+ status, headers, body = _invoke(runtime["agentRuntimeArn"])
+ assert status == 424
+ assert headers["x-amzn-errortype"] == "RuntimeClientError"
+ assert json.loads(body)["__type"] == "RuntimeClientError"
+ finally:
+ agentcore._delete_agent_runtime(runtime["agentRuntimeId"])
+ server.shutdown()
+ server.server_close()
+ thread.join()
+
+
+def test_container_start_failure_is_not_echo(monkeypatch):
+ _fake_docker(monkeypatch, 1, fail=True)
+ runtime = _runtime("image_failure")
+ try:
+ status, headers, body = _invoke(runtime["agentRuntimeArn"])
+ assert status == 424
+ assert headers["x-amzn-errortype"] == "RuntimeClientError"
+ assert b"image unavailable" in body
+ finally:
+ agentcore._delete_agent_runtime(runtime["agentRuntimeId"])
+
+
+def test_container_is_removed_if_start_times_out(monkeypatch):
+ _, removed = _fake_docker(monkeypatch, 1, fail_on_start=True)
+ runtime = _runtime("start_timeout")
+ try:
+ status, _, _ = _invoke(runtime["agentRuntimeArn"])
+ assert status == 424
+ assert removed == [True]
+ finally:
+ agentcore._delete_agent_runtime(runtime["agentRuntimeId"])
+
+
+def test_missing_image_is_pulled_then_started(monkeypatch):
+ server, thread, _ = _worker()
+ started, _ = _fake_docker(monkeypatch, server.server_port, missing_image=True)
+ runtime = _runtime("pull_image")
+ try:
+ status, _, response = _invoke(runtime["agentRuntimeArn"])
+ assert status == 200
+ asyncio.run(response.runner(_discard, None))
+ assert [image for image, _ in started] == ["example.local/worker:1"]
+ finally:
+ agentcore._delete_agent_runtime(runtime["agentRuntimeId"])
+ server.shutdown()
+ server.server_close()
+ thread.join()
+
+
+def test_orphan_is_removed_if_create_times_out(monkeypatch):
+ _, removed = _fake_docker(monkeypatch, 1, fail_after_create=True)
+ runtime = _runtime("create_timeout")
+ try:
+ status, _, _ = _invoke(runtime["agentRuntimeArn"])
+ assert status == 424
+ assert removed == [True]
+ finally:
+ agentcore._delete_agent_runtime(runtime["agentRuntimeId"])
+
+
+def test_connection_reset_maps_to_runtime_client_error(monkeypatch):
+ server, thread, _ = _worker()
+ _fake_docker(monkeypatch, server.server_port)
+ runtime = _runtime("connection_reset")
+ try:
+ agentcore._container_invocations_url(agentcore._runtimes[runtime["agentRuntimeId"]])
+ monkeypatch.setattr(agentcore, "_local_open", lambda *_args, **_kwargs:
+ (_ for _ in ()).throw(ConnectionResetError("peer reset")))
+ status, headers, _ = _invoke(runtime["agentRuntimeArn"])
+ assert status == 424
+ assert headers["x-amzn-errortype"] == "RuntimeClientError"
+ finally:
+ agentcore._delete_agent_runtime(runtime["agentRuntimeId"])
+ server.shutdown()
+ server.server_close()
+ thread.join()
+
+
+def test_stream_failure_leaves_response_truncated(monkeypatch):
+ class BrokenResponse:
+ status = 200
+ headers = {"Content-Type": "text/event-stream"}
+ closed = False
+ reads = 0
+
+ def read1(self, _size):
+ self.reads += 1
+ if self.reads == 1:
+ return b"first\n"
+ raise ConnectionResetError("stream interrupted")
+
+ def close(self):
+ self.closed = True
+
+ response = BrokenResponse()
+ monkeypatch.setattr(agentcore, "_local_open", lambda *_args, **_kwargs: response)
+ status, _, stream = agentcore._invoke_container(
+ "http://127.0.0.1:8080/invocations", b"{}", {}, "application/json", "session-1")
+ assert status == 200
+ frames = []
+
+ async def send(frame):
+ frames.append(frame)
+
+ asyncio.run(stream.runner(send, None))
+ assert frames == [{"type": "http.response.body", "body": b"first\n", "more_body": True}]
+ assert response.closed
+
+
+def test_update_restarts_image(monkeypatch):
+ server, thread, _ = _worker()
+ started, removed = _fake_docker(monkeypatch, server.server_port)
+ runtime = _runtime("update_image")
+ try:
+ status, _, response = _invoke(runtime["agentRuntimeArn"])
+ assert status == 200
+ asyncio.run(response.runner(_discard, None))
+ agentcore._update_agent_runtime(runtime["agentRuntimeId"], json.dumps({
+ "agentRuntimeArtifact": {"containerConfiguration": {"containerUri": "example.local/worker:2"}},
+ "roleArn": "arn:aws:iam::000000000000:role/agentcore",
+ "networkConfiguration": {"networkMode": "PUBLIC"},
+ }).encode())
+ assert removed == [True]
+ current = agentcore._runtimes[runtime["agentRuntimeId"]]
+ status, _, response = _invoke(current["agentRuntimeArn"])
+ assert status == 200
+ assert [image for image, _ in started] == ["example.local/worker:1", "example.local/worker:2"]
+ asyncio.run(response.runner(_discard, None))
+ finally:
+ agentcore._delete_agent_runtime(runtime["agentRuntimeId"])
+ server.shutdown()
+ server.server_close()
+ thread.join()