Skip to content

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

feat(agentcore): add Memory resource lifecycle (#1961)

Lisandro Pintos46423a18593e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1361cf75..486bbd32 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **STS — role trust denies and conditions are enforced** — with `AUTH=true`, `AssumeRole` now rejects matching explicit denies, including `NotAction` exclusions, and evaluates `sts:ExternalId` and `sts:RoleSessionName` conditions before issuing credentials. A denied call registers no session. Local JSON requests use the supplied role ARN for authorization and receive JSON trust-denial errors; Query requests retain XML responses. With `AUTH=false`, trust denies and conditions remain permissive.
### Added
+- **Bedrock AgentCore — Memory resource lifecycle** — `CreateMemory`, `GetMemory`, `ListMemories`, `UpdateMemory` and `DeleteMemory` now provide account- and region-scoped local resources with pagination. Memory strategies and tagging return explicit validation errors instead of being silently discarded. Contributed by @pingedbrain.
+- **CloudFormation — `IMPORT` change sets execute** — existing SQS queues, SSM parameters, S3 buckets, DynamoDB tables, IAM roles, log groups, Lambda functions, IoT policies, IoT CA certificates and Cognito user pools are adopted into a new or existing stack without being changed (`IMPORT_IN_PROGRESS` to `IMPORT_COMPLETE`, or a rollback when a resource is gone), and an import that changes `Outputs` or stack tags is refused, as on AWS.
+- **CloudFormation — `Capabilities` check without `AUTH`** — `CFN_ENFORCE_CAPABILITIES=1` refuses a template whose IAM resources or macros the request does not acknowledge also without `AUTH=true`, as AWS always does.
- **Athena — databases, DDL, and Trino-style table references** — `ListDatabases` and `GetDatabase` read the Glue Data Catalog; `CREATE EXTERNAL TABLE` and `DROP TABLE` apply to it, creating the Glue table Athena would (formats, SerDe, TBLPROPERTIES); `CREATE TABLE` without `EXTERNAL` is rejected as Athena rejects it, and Iceberg tables are not supported; a query may name a table as `"awsdatacatalog"."db"."t"` or `db.t`. Contributed by @sjincho.
- **CloudFront — distributions serve traffic, plus the AWS-managed policies and monitoring subscriptions** — a request to `<label>.cloudfront.net` (or `<label>.cloudfront.<MINISTACK_HOST>`) is served: ordered cache behaviors, `ViewerProtocolPolicy`, `AllowedMethods`, `DefaultRootObject`, cache and origin request policy forwarding (and legacy `ForwardedValues`), `viewer-request` / `viewer-response` CloudFront Functions, response headers policies, and S3 or custom origins; an S3 origin is read only as the bucket policy allows it (OAC, OAI or public). `DomainName` has the AWS `d` + 13-character shape. `List*Policies` return the AWS-managed cache, origin request and response headers policies, and `Create`/`Get`/`DeleteMonitoringSubscription` are implemented. Not modelled: caching, WAF, logging, geo restrictions, custom error pages, signed URLs and cookies, Lambda@Edge. Contributed by @skialpine.
- **CloudFormation — EKS cluster and node group updates** — `AWS::EKS::Cluster` applies `Version`, `Logging`, `ResourcesVpcConfig`, `AccessConfig.AuthenticationMode` and `Tags` in place and `AWS::EKS::Nodegroup` applies `ScalingConfig`, `Labels`, `Taints`, `UpdateConfig`, `LaunchTemplate`, `Version`, `ReleaseVersion` and `Tags`, where every such change used to report `UPDATE_COMPLETE` and was dropped. Contributed by @iot-rocket.
diff --git a/README.md b/README.md
index f02856db..db1125f1 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, PutResourcePolicy, GetResourcePolicy, DeleteResourcePolicy. 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; resource policies are evaluated for runtime and endpoint invocation when `AUTH=true`; `InvokeAgentRuntime` runs the runtime's `containerUri` image in Docker (full image), waits for `/ping` and forwards to `/invocations` on port 8080, with container errors as `RuntimeClientError` (424); without Docker (slim image) or for a code artifact it answers a deterministic echo |
+| **Bedrock AgentCore** | Control plane (`bedrock-agentcore-control`): CreateAgentRuntime, GetAgentRuntime, ListAgentRuntimes, UpdateAgentRuntime, DeleteAgentRuntime, ListAgentRuntimeVersions, CreateAgentRuntimeEndpoint, GetAgentRuntimeEndpoint, ListAgentRuntimeEndpoints, UpdateAgentRuntimeEndpoint, DeleteAgentRuntimeEndpoint, CreateMemory, GetMemory, ListMemories, UpdateMemory, DeleteMemory, PutResourcePolicy, GetResourcePolicy, DeleteResourcePolicy. Data plane (`bedrock-agentcore`): InvokeAgentRuntime | Agent-runtime lifecycle, versions, endpoint pinning and resource policies; Memory lifecycle with account- and region-scoped state. Memory strategies and tagging are not emulated. Shapes verified against botocore `bedrock-agentcore-control` / `bedrock-agentcore`; `InvokeAgentRuntime` runs the runtime's `containerUri` image in Docker (full image), waits for `/ping` and forwards to `/invocations` on port 8080, with container errors as `RuntimeClientError` (424); without Docker (slim image) or for a code artifact it answers a deterministic echo |
| **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 |
diff --git a/ministack/services/bedrock_agentcore.py b/ministack/services/bedrock_agentcore.py
index 2b992f24..4826b21e 100644
--- a/ministack/services/bedrock_agentcore.py
+++ b/ministack/services/bedrock_agentcore.py
@@ -59,6 +59,7 @@ logger = logging.getLogger("bedrock_agentcore")
_runtimes = AccountRegionScopedDict() # agentRuntimeId -> runtime record
_endpoints = AccountRegionScopedDict() # agentRuntimeId -> {endpointName -> endpoint record}
_resource_policies = AccountRegionScopedDict() # resource ARN -> policy string
+_memories = AccountRegionScopedDict() # memoryId -> memory record
_containers = {} # (account, region, runtime id, version) -> Docker container
_container_lock = threading.RLock()
@@ -72,6 +73,7 @@ def get_state():
"runtimes": _runtimes,
"endpoints": _endpoints,
"resourcePolicies": _resource_policies,
+ "memories": _memories,
})
@@ -85,9 +87,11 @@ def _restore_state(data):
_runtimes.clear()
_endpoints.clear()
_resource_policies.clear()
+ _memories.clear()
_runtimes.update(data.get("runtimes", {}))
_endpoints.update(data.get("endpoints", {}))
_resource_policies.update(data.get("resourcePolicies", {}))
+ _memories.update(data.get("memories", {}))
_migrate_legacy_arns()
# Backfill one snapshot for state written before version history existed.
for runtime in _runtimes._data.values():
@@ -127,6 +131,7 @@ def reset():
_runtimes.clear()
_endpoints.clear()
_resource_policies.clear()
+ _memories.clear()
# ---------------------------------------------------------------------------
@@ -342,6 +347,133 @@ def _paginate_agentcore_results(items, query_params):
return page, None
+def _memory_id(identifier):
+ """Accept the memory ID or its ARN, as the AgentCore data plane does."""
+ if isinstance(identifier, str) and ":memory/" in identifier:
+ return identifier.rsplit(":memory/", 1)[1]
+ return identifier
+
+
+def _memory_arn(memory_id):
+ return (f"arn:aws:bedrock-agentcore:{get_region()}:{get_account_id()}:"
+ f"memory/{memory_id}")
+
+
+def _memory_public_record(record):
+ return {key: copy.deepcopy(value) for key, value in record.items()
+ if not key.startswith("_")}
+
+
+def _memory_page(items, data, default=20):
+ query = {"maxResults": data.get("maxResults", default)}
+ if "nextToken" in data:
+ query["nextToken"] = data["nextToken"]
+ return _paginate_agentcore_results(items, query)
+
+
+def _create_memory(body):
+ data = _parse_body(body)
+ name = data.get("name")
+ duration = data.get("eventExpiryDuration")
+ if not isinstance(name, str) or not _NAME_RE.fullmatch(name):
+ return _validation("name must start with a letter and contain only letters, digits, and underscores")
+ if any(memory.get("name") == name for memory in _memories.values()):
+ return _conflict(f"A memory with name '{name}' already exists")
+ if not isinstance(duration, int) or isinstance(duration, bool) or not 3 <= duration <= 365:
+ return _validation("eventExpiryDuration must be an integer from 3 to 365")
+ if data.get("tags"):
+ return _validation("Tagging is not supported by MiniStack AgentCore Memory yet")
+ # MiniStack implements explicit record storage/retrieval. Built-in
+ # extraction strategies invoke managed model pipelines and are not emulated.
+ if data.get("memoryStrategies"):
+ return _validation("Memory strategies are not supported by MiniStack AgentCore Memory")
+
+ memory_id = _resource_id(name)
+ now = time.time()
+ record = {
+ "id": memory_id,
+ "arn": _memory_arn(memory_id),
+ "name": name,
+ "description": data.get("description", ""),
+ "eventExpiryDuration": duration,
+ "status": "ACTIVE",
+ "createdAt": now,
+ "updatedAt": now,
+ "indexedKeys": copy.deepcopy(data.get("indexedKeys", [])),
+ "namespaceKeys": copy.deepcopy(data.get("namespaceKeys", [])),
+ "strategies": [],
+ }
+ for field in ("encryptionKeyArn", "memoryExecutionRoleArn", "streamDeliveryResources"):
+ if field in data:
+ record[field] = copy.deepcopy(data[field])
+ _memories[memory_id] = record
+
+ response = _memory_public_record(record)
+ response["status"] = "CREATING"
+ return json_response({"memory": response}, 202)
+
+
+def _get_memory(memory_id, query_params):
+ record = _memories.get(_memory_id(memory_id))
+ if record is None:
+ return _not_found(f"Memory '{memory_id}' not found")
+ view = _agentcore_query_value(query_params, "view", "full")
+ if view not in ("full", "without_decryption"):
+ return _validation("view must be 'full' or 'without_decryption'")
+ return json_response({"memory": _memory_public_record(record)})
+
+
+def _list_memories(body):
+ data = _parse_body(body)
+ items = [{key: record[key] for key in (
+ "arn", "createdAt", "id", "status", "updatedAt"
+ ) if key in record} for record in _memories.values()]
+ page, error = _memory_page(items, data, default=10)
+ if error:
+ return error
+ return json_response({
+ "memories": page["items"],
+ **({"nextToken": page["nextToken"]} if "nextToken" in page else {}),
+ })
+
+
+def _update_memory(memory_id, body):
+ record = _memories.get(_memory_id(memory_id))
+ if record is None:
+ return _not_found(f"Memory '{memory_id}' not found")
+ data = _parse_body(body)
+ if "memoryStrategies" in data and data["memoryStrategies"]:
+ return _validation("Memory strategies are not supported by MiniStack AgentCore Memory")
+ if "eventExpiryDuration" in data:
+ duration = data["eventExpiryDuration"]
+ if not isinstance(duration, int) or isinstance(duration, bool) or not 3 <= duration <= 365:
+ return _validation("eventExpiryDuration must be an integer from 3 to 365")
+ record["eventExpiryDuration"] = duration
+ if "description" in data:
+ record["description"] = data["description"]
+ for field in ("memoryExecutionRoleArn", "namespaceKeys", "streamDeliveryResources"):
+ if field in data:
+ record[field] = copy.deepcopy(data[field])
+ if data.get("addIndexedKeys"):
+ existing = {item.get("key") for item in record.get("indexedKeys", [])}
+ record.setdefault("indexedKeys", []).extend(
+ copy.deepcopy(item) for item in data["addIndexedKeys"]
+ if item.get("key") not in existing
+ )
+ record["updatedAt"] = time.time()
+ response = _memory_public_record(record)
+ response["status"] = "UPDATING"
+ return json_response({"memory": response}, 202)
+
+
+def _delete_memory(memory_id):
+ memory_id = _memory_id(memory_id)
+ record = _memories.pop(memory_id, None)
+ if record is None:
+ return _not_found(f"Memory '{memory_id}' not found")
+ return json_response({"memoryId": memory_id, "status": "DELETING"}, 202)
+
+
def _version_snapshot(runtime):
return {key: copy.deepcopy(value) for key, value in runtime.items()
if not key.startswith("_")}
@@ -1067,6 +1199,18 @@ def _invoke_container(url, body, headers, content_type, session_id):
async def handle_request(method, path, headers, body, query_params):
inner = path.strip("/")
+ if inner == "memories" and method == "POST":
+ return _list_memories(body)
+ if inner == "memories/create" and method == "POST":
+ return _create_memory(body)
+ if inner.startswith("memories/"):
+ parts = [unquote(part) for part in inner.split("/") if part]
+ if len(parts) == 3 and parts[2] == "details" and method == "GET":
+ return _get_memory(parts[1], query_params)
+ if len(parts) == 3 and parts[2] == "update" and method == "PUT":
+ return _update_memory(parts[1], body)
+ if len(parts) == 3 and parts[2] == "delete" and method == "DELETE":
+ return _delete_memory(parts[1])
if inner.startswith("resourcepolicy/"):
resource_arn = unquote(inner[len("resourcepolicy/"):])
if method == "PUT":
diff --git a/tests/test_bedrock_agentcore.py b/tests/test_bedrock_agentcore.py
index 275f6e9e..21c0e417 100644
--- a/tests/test_bedrock_agentcore.py
+++ b/tests/test_bedrock_agentcore.py
@@ -1027,3 +1027,61 @@ def test_agentcore_state_with_legacy_arns_moves_to_aws_arns():
assert eps["DEFAULT"]["liveVersion"] == "3"
finally:
svc.load_persisted_state(saved)
+
+
+def test_agentcore_memory_lifecycle_and_pagination():
+ control = _client("bedrock-agentcore-control")
+ name = f"memory_{_uuid_mod.uuid4().hex[:8]}"
+ with pytest.raises(ClientError) as exc:
+ control.create_memory(
+ name=f"memory_{_uuid_mod.uuid4().hex[:8]}",
+ eventExpiryDuration=30,
+ tags={"purpose": "unsupported"},
+ )
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+
+ created = control.create_memory(name=name, eventExpiryDuration=30)
+ memory_id = created["memory"]["id"]
+ second_memory_id = None
+
+ try:
+ memory = control.get_memory(memoryId=memory_id)["memory"]
+ assert memory["name"] == name
+ assert memory["eventExpiryDuration"] == 30
+
+ second = control.create_memory(
+ name=f"memory_{_uuid_mod.uuid4().hex[:8]}", eventExpiryDuration=14
+ )
+ second_memory_id = second["memory"]["id"]
+ assert control.list_memories(maxResults=1)["nextToken"]
+
+ updated = control.update_memory(
+ memoryId=memory_id,
+ description="Explicit long-term records",
+ eventExpiryDuration=60,
+ addIndexedKeys=[{"key": "source", "type": "STRING"}],
+ namespaceKeys=[{"key": "tenant"}],
+ )["memory"]
+ assert updated["status"] == "UPDATING"
+ memory = control.get_memory(memoryId=memory_id)["memory"]
+ assert memory["description"] == "Explicit long-term records"
+ assert memory["eventExpiryDuration"] == 60
+ assert memory["indexedKeys"] == [{"key": "source", "type": "STRING"}]
+ assert memory["namespaceKeys"] == [{"key": "tenant"}]
+
+ with pytest.raises(ClientError) as exc:
+ control.update_memory(
+ memoryId=memory_id,
+ eventExpiryDuration=90,
+ memoryStrategies={
+ "deleteMemoryStrategies": [{"memoryStrategyId": "unsupported"}]
+ },
+ )
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+ assert control.get_memory(memoryId=memory_id)["memory"][
+ "eventExpiryDuration"
+ ] == 60
+ finally:
+ control.delete_memory(memoryId=memory_id)
+ if second_memory_id:
+ control.delete_memory(memoryId=second_memory_id)