Guide · Amazon Bedrock Agents · Memory Configuration
Amazon Bedrock Agents Memory for MCP Servers — Session Summaries, Memory IDs, and Cross-Session Retrieval
Amazon Bedrock Agents memory enables an agent to retain context across separate conversation sessions — not just within one session. Without memory, every new sessionId starts the agent with a blank slate. With memory enabled, Bedrock automatically summarizes completed sessions and stores those summaries against a stable memoryId. On subsequent sessions with the same memoryId, the agent retrieves past summaries and incorporates them into its context, allowing it to reference prior user preferences, completed tasks, and established facts from earlier conversations. For MCP server platforms, this is the mechanism that makes a Bedrock-backed agent feel persistent rather than stateless.
TL;DR
Enable memory in the agent's memoryConfiguration during CreateAgentCommand or UpdateAgentCommand. Set enabledMemoryTypes: ['SESSION_SUMMARY'] and storageDays (1–365). Pass a stable memoryId alongside sessionId in every InvokeAgentCommand — the memoryId identifies the user (e.g., a hashed user ID), while sessionId identifies the current conversation turn. When a session ends (TTL expires or is explicitly ended), Bedrock summarizes it and stores the summary under the memoryId. On the next session for the same memoryId, the agent loads those summaries into its orchestration context automatically. Use GetAgentMemoryCommand to inspect stored memories and DeleteAgentMemoryCommand to clear them for GDPR/right-to-forget compliance.
The memoryId / sessionId distinction
Bedrock Agents uses two separate identifiers, and conflating them is the most common source of memory not persisting across conversations:
| Field | Scope | Lifecycle | Typical value |
|---|---|---|---|
sessionId |
Single conversation (one or more turns) | Created per conversation; expires after idleSessionTTLInSeconds of inactivity |
Random UUID, or {userId}-{timestamp} |
memoryId |
User identity across all conversations | Persists for storageDays; explicitly deleted via DeleteAgentMemoryCommand |
Hashed user ID: sha256(userId) or opaque external ID |
The memoryId acts as the durable user identifier that Bedrock uses to group session summaries. If you omit memoryId from an invocation, Bedrock uses the sessionId as the memory identifier — which means every new session gets its own isolated memory bucket and cross-session retention does not work. Always pass an explicit memoryId that maps to a stable user identity.
Avoid using raw user IDs or email addresses as memoryId values. Memory IDs are stored in Bedrock's managed storage and may appear in CloudWatch logs. Use a one-way hash (SHA-256 of the user's internal ID) or an opaque token to avoid PII in log data.
Enabling memory on an agent
Memory is configured at the agent level in the memoryConfiguration field. The only currently supported memory type is SESSION_SUMMARY, which instructs Bedrock to summarize each completed session into a compact text block.
import { BedrockAgentClient, UpdateAgentCommand } from "@aws-sdk/client-bedrock-agent";
const client = new BedrockAgentClient({ region: "us-east-1" });
await client.send(new UpdateAgentCommand({
agentId: "YOURAGENTID",
agentName: "platform-assistant",
agentResourceRoleArn: "arn:aws:iam::123456789012:role/BedrockAgentRole",
foundationModel: "anthropic.claude-3-5-sonnet-20241022-v2:0",
instruction: "You are a helpful assistant with memory of past conversations.",
memoryConfiguration: {
enabledMemoryTypes: ["SESSION_SUMMARY"],
storageDays: 90
}
}));
// Memory config takes effect after the next preparation
await client.send(new PrepareAgentCommand({
agentId: "YOURAGENTID"
}));
storageDays accepts values from 1 to 365. It controls how long Bedrock retains session summaries before automatically deleting them. Choose a value appropriate for your use case: 7 days for short-term operational assistants, 90–365 days for personal assistants where long-term preference retention is a core feature. Changes to storageDays apply only to summaries created after the update — existing summaries retain their original expiry.
Memory is not available on all foundation models. Verify that your chosen model supports memory in the Bedrock console before configuring it — the PrepareAgentCommand will return a ValidationException if the model does not support the SESSION_SUMMARY memory type.
Invoking the agent with memory
Pass both sessionId and memoryId in every InvokeAgentCommand call. The memoryId can be the same across multiple different sessionId values — that is the intended pattern.
import {
BedrockAgentRuntimeClient,
InvokeAgentCommand
} from "@aws-sdk/client-bedrock-agent-runtime";
const runtime = new BedrockAgentRuntimeClient({ region: "us-east-1" });
// userId from your application's auth layer
const userId = "user_8f3a9d2c";
// Hash the user ID to avoid PII in Bedrock logs
const memoryId = crypto.createHash("sha256").update(userId).digest("hex").slice(0, 32);
// A new sessionId per conversation
const sessionId = `${memoryId}-${Date.now()}`;
const response = await runtime.send(new InvokeAgentCommand({
agentId: "YOURAGENTID",
agentAliasId: "YOURAGENTALIASID",
sessionId,
memoryId, // The key field for cross-session memory
inputText: "What was the last report we generated together?",
enableTrace: false
}));
let answer = "";
for await (const event of response.completion) {
if (event.chunk?.bytes) {
answer += new TextDecoder().decode(event.chunk.bytes);
}
}
console.log(answer);
When a session with memory enabled ends, Bedrock generates a summary automatically. The summary is created either when the session TTL expires (the agent received no invocations for idleSessionTTLInSeconds) or when you explicitly end the session by calling InvokeAgentCommand with endSession: true. Use endSession: true when you know the conversation is complete — this triggers immediate summarization rather than waiting for the TTL to expire.
// Signal end of conversation to trigger immediate summarization
await runtime.send(new InvokeAgentCommand({
agentId: "YOURAGENTID",
agentAliasId: "YOURAGENTALIASID",
sessionId,
memoryId,
inputText: "",
endSession: true
}));
Retrieving stored memories
Use GetAgentMemoryCommand to inspect what Bedrock has stored for a given memoryId. This is useful for debugging why the agent is or is not using prior context, and for compliance audits that require knowing what user data is retained.
import { GetAgentMemoryCommand } from "@aws-sdk/client-bedrock-agent-runtime";
const { memoryContents } = await runtime.send(new GetAgentMemoryCommand({
agentId: "YOURAGENTID",
agentAliasId: "YOURAGENTALIASID",
memoryId,
memoryType: "SESSION_SUMMARY"
}));
for (const memory of memoryContents) {
if (memory.sessionSummary) {
console.log("Session:", memory.sessionSummary.sessionId);
console.log("Summary:", memory.sessionSummary.summaryText);
console.log("Created:", memory.sessionSummary.createdAt);
console.log("Expires:", memory.sessionSummary.expiresAt);
}
}
The memoryContents array contains one entry per summarized session. The summaryText field holds the model-generated summary of that session — a compact representation of key facts, preferences, and outcomes from the conversation. This is the text that gets injected into future sessions' context when the agent loads memories for the same memoryId.
GetAgentMemoryCommand supports pagination via nextToken for users with many stored sessions. For typical use cases (retention up to 365 days at one session per day), pagination is rarely needed, but build it in for production implementations.
// Paginate through all stored memories
let nextToken: string | undefined;
const allMemories = [];
do {
const result = await runtime.send(new GetAgentMemoryCommand({
agentId: "YOURAGENTID",
agentAliasId: "YOURAGENTALIASID",
memoryId,
memoryType: "SESSION_SUMMARY",
maxItems: 20,
nextToken
}));
allMemories.push(...(result.memoryContents || []));
nextToken = result.nextToken;
} while (nextToken);
Deleting memories for GDPR compliance
Use DeleteAgentMemoryCommand to remove all stored memories for a user. This is the right tool for right-to-erasure (GDPR Article 17) requests. The deletion removes all session summaries associated with the memoryId immediately — there is no soft-delete or recovery period.
import { DeleteAgentMemoryCommand } from "@aws-sdk/client-bedrock-agent-runtime";
await runtime.send(new DeleteAgentMemoryCommand({
agentId: "YOURAGENTID",
agentAliasId: "YOURAGENTALIASID",
memoryId
}));
console.log(`Memories deleted for memoryId: ${memoryId}`);
Build your data deletion pipeline to call DeleteAgentMemoryCommand as part of your account deletion workflow. Because memoryId is a one-way hash of the user ID in the recommended pattern, store a mapping from user ID to memoryId in your own database — Bedrock does not provide a lookup from raw user identity to memoryId.
Memory deletion does not affect active sessions. If a user is in an active session when their memories are deleted, the current session's context continues using whatever memories were loaded at the start of the session. Future sessions will start with an empty memory slate.
What the session summary contains and how to influence it
The session summary is generated by the foundation model that powers the agent, using an internal summarization prompt managed by Bedrock. The summary typically captures:
- Key facts learned about the user (stated preferences, role, context)
- Tasks completed in the session (files created, queries run, emails sent)
- Decisions made and their rationale
- Open items or follow-ups mentioned
You cannot directly control the summarization prompt without using PromptOverrideConfiguration. However, you can influence summary quality indirectly:
- Add memory instructions to the agent instruction: Tell the agent what to emphasize. For example: "At the end of each conversation, explicitly state the key facts learned, decisions made, and any action items. This helps build accurate memory for future sessions."
- Use structured outputs in the final turn: Ask the agent to produce a structured summary at the end of a conversation: "Please summarize what we accomplished today." The summarizer will incorporate this explicit summary.
- Keep sessions focused: A session covering one or two topics produces a tighter summary than a meandering multi-topic session. For longer workflows, break the work into distinct sessions aligned with phases.
Memory and MCP server session management
When building an MCP server that wraps a Bedrock Agent, the memory management pattern should map your MCP server's notion of user identity to Bedrock's memoryId. A typical implementation:
// In your MCP server's tool handler
class BedrockAgentTool {
private sessionMap = new Map<string, string>(); // userId → current sessionId
async chat(userId: string, message: string): Promise<string> {
// Get or create a session for this user
let sessionId = this.sessionMap.get(userId);
if (!sessionId) {
sessionId = `${this.getMemoryId(userId)}-${Date.now()}`;
this.sessionMap.set(userId, sessionId);
}
const response = await this.runtime.send(new InvokeAgentCommand({
agentId: process.env.BEDROCK_AGENT_ID!,
agentAliasId: process.env.BEDROCK_AGENT_ALIAS_ID!,
sessionId,
memoryId: this.getMemoryId(userId),
inputText: message
}));
let answer = "";
for await (const event of response.completion) {
if (event.chunk?.bytes) {
answer += new TextDecoder().decode(event.chunk.bytes);
}
}
return answer;
}
async endUserSession(userId: string): Promise<void> {
const sessionId = this.sessionMap.get(userId);
if (!sessionId) return;
// Trigger immediate summarization
await this.runtime.send(new InvokeAgentCommand({
agentId: process.env.BEDROCK_AGENT_ID!,
agentAliasId: process.env.BEDROCK_AGENT_ALIAS_ID!,
sessionId,
memoryId: this.getMemoryId(userId),
inputText: "",
endSession: true
}));
this.sessionMap.delete(userId);
}
private getMemoryId(userId: string): string {
return crypto.createHash("sha256").update(userId).digest("hex").slice(0, 32);
}
}
The in-process sessionMap works for single-instance deployments. For multi-instance MCP servers, store the sessionId-to-userId mapping in Redis or DynamoDB so any instance can continue a session started by another instance. The sessionId can be used from any process — Bedrock manages the actual session state server-side.
Memory pricing and quotas
Memory in Bedrock Agents is billed as token usage for the summarization calls that happen at session end. Each summary generation consumes input tokens (the full session transcript) and output tokens (the summary text). These tokens are billed at the same rate as the foundation model powering the agent.
Service quotas to be aware of:
- Maximum
storageDays: 365 - Maximum stored sessions per
memoryId: 25 session summaries (older summaries are dropped when the limit is reached) - Maximum summary text size: limited by the model's output token capacity — practically around 2,000–4,000 tokens of summary text
GetAgentMemoryCommandmaximum items per page: 100
The 25-summary cap per memoryId means that highly active users (more than 25 sessions within storageDays) will see older memories automatically evicted. If your use case requires indefinite retention across more sessions, supplement Bedrock's built-in memory with an external storage layer: store session summaries from GetAgentMemoryCommand in your own database, and inject the most relevant historical context into the agent via sessionState.sessionAttributes at invocation time.