Memstate + Claude Agent SDK
Give Claude Agent SDK agents persistent, structured memory via MCP.
The Claude Agent SDK (formerly Claude Code SDK) runs Claude Code as a Python library. It accepts MCP servers via ClaudeAgentOptions.mcp_servers, making it straightforward to add Memstate as a persistent memory layer.
Claude Agent SDK vs Claude Desktop
This guide covers the Claude Agent SDK — a Python library for programmatic agent workflows. If you want to add memory to the Claude Desktop app or Claude Code CLI, see the Claude setup guide instead.
Requirements
- Python 3.10+
- Node.js 18+ (for npx @memstate/mcp)
- Claude Code installed and authenticated (
claudeCLI) - Memstate API key — get one free
1
Install the SDK
Terminal
pip install claude-agent-sdk2
Set environment variables
Shell
export MEMSTATE_API_KEY="mst_..."
# The Claude Agent SDK uses Claude Code under the hood — no separate API key needed3
Connect Memstate via MCP
Pass the Memstate MCP server in ClaudeAgentOptions. Use allowed_tools to scope which Memstate tools the agent can call.
agent.py
"""
Memstate AI + Claude Agent SDK
Requires: pip install claude-agent-sdk
Env: MEMSTATE_API_KEY
Note: The Claude Agent SDK runs Claude Code as a library.
MCP servers are passed via ClaudeAgentOptions using stdio transport.
"""
import asyncio
import os
from claude_agent_sdk import query, ClaudeAgentOptions
async def main() -> None:
options = ClaudeAgentOptions(
mcp_servers=[
{
"type": "stdio",
"command": "npx",
"args": ["-y", "@memstate/mcp"],
"env": {
"MEMSTATE_API_KEY": os.environ["MEMSTATE_API_KEY"],
},
"name": "memstate",
}
],
allowed_tools=["memstate_remember", "memstate_get", "memstate_search"],
)
async for message in query(
prompt=(
'Save a memory: memstate_remember(project_id="demo", '
'content="## Claude Agent SDK\\nMemstate connected via Claude Agent SDK MCP.", '
'source="agent"). Then call memstate_get(project_id="demo") and show the result.'
),
options=options,
):
if hasattr(message, "content"):
for block in message.content or []:
if hasattr(block, "text"):
print(block.text, end="")
print()
if __name__ == "__main__":
asyncio.run(main())✓
Test it — run the onboarding prompt
Onboarding prompt
I'm onboarding Memstate AI memory for this project. Please:
1. Analyze this codebase and write a concise high-level architecture overview in markdown.
2. Save it with: memstate_remember(project_id="<your_project>", content="<the markdown>", source="agent")
3. Then call memstate_get(project_id="<your_project>") and show me the memory tree.