Python SDK for Kagura Memory Cloud — memory management, document ingestion (PDF → memory graph), and R2 file storage for AI agents
pip install kagura-memory==0.42.0 Copy PIP instructions
Memory SDK — Python client for Kagura Memory Cloud
Recall past memories straight from Claude Code — Kagura Memory over MCP.
This SDK connects your Python code to Kagura Memory Cloud, giving AI assistants the ability to remember, search, and learn from past interactions — and to ingest documents (PDFs, URLs) directly into a searchable memory graph. It provides seven clients (plus a document ingestor) for different use cases:
Turn a PDF into a structured graph of memories — one overview memory plus per-section summaries, linked via declared_link edges. The original file is archived to your workspace's storage so you can always pull the bytes back.
pip install 'kagura-memory[ingest-pdf]' kagura auth login kagura ingest ./report.pdf
kagura recall "report findings" -k 5 # search across sections kagura files download-url -c # short-lived GET on the original Ingestion extracts text — from PDFs, Office/HTML/EPUB documents, audio/video transcripts, and YouTube captions. Images embedded in a document are detected and counted (IngestResult.skipped_images) but not yet OCR'd: a vision provider (Gemini 2.5 Flash by default) is configured and validated, but the orchestrator does not currently invoke Provider.describe_image() — image-to-text memories are a planned follow-up. Pass --no-vision to skip provider configuration entirely, or --dry-run to see token / cost estimates without calling an LLM.
pip install kagura-memory # core SDK pip install 'kagura-memory[ingest-pdf]' # adds PDF ingestion support pip install 'kagura-memory[ingest-all]' # all document formats (see below) # or uv add kagura-memory Supported document formats kagura ingest (and FileIngestor) dispatch to a structural extractor based on the file's MIME type / extension. Heavy parser dependencies are opt-in extras — install only what you need, or ingest-all for everything:
Each extractor is pure-parse — no network, no LLM. It maps the document into structural sections (Markdown/HTML headings, Word heading styles, one section per sheet/slide, PDF/EPUB outline) that the chunker and summarizer then turn into memories. Office and EPUB files are ZIP containers, so each extractor enforces decompression-bomb caps (max sheets/rows/slides/pages and total decoded text). A missing extra surfaces as a clear KaguraIngestError naming the package to install.
Copy the example and fill in your credentials:
cp .kagura.json.example .kagura.json # Edit .kagura.json — set api_key and mcp_url Used by the CLI (kagura commands) and load_config() in Python code:
{ "api_key": "kagura_your_api_key", "mcp_url": "http://localhost:8080/mcp/w/{workspace_id}", "context_id": "auto" } Or use environment variables: KAGURA_API_KEY, KAGURA_MCP_URL, KAGURA_CONTEXT_ID
Get your API key from the Kagura Memory Cloud Web UI: Integrations > API Keys
Looking for KaguraAgent? The LLM-powered session-analysis actor was removed in v0.37.0 — its role moved to dedicated ecosystem packages: kagura-agent (memory-backed autonomous agent) with kagura-brain as its LLM head, while conversation→memory compilation is handled server-side (Memory Analysis) and by the connector workers. This SDK stays a pure substrate client, and base installs no longer pull the litellm dependency tree (it now ships with the [ingest] extra).
kagura ingest reads OLLAMA_API_KEY and OLLAMA_API_BASE from the environment (litellm picks them up directly for the ollama_chat/ route), for both local Ollama and Ollama Cloud (ollama signin sets the key automatically):
export OLLAMA_API_KEY="..." # Ollama Cloud only; local needs no key export OLLAMA_API_BASE="https://ollama.com" kagura ingest report.pdf --text-provider ollama The ingest provider uses litellm's ollama_chat/ route (system messages preserved), so cloud and local share the same code path.
from kagura_memory import KaguraClient async with KaguraClient(api_key="kagura_...", mcp_url="https://...") as client: await client.remember(context_id="dev", summary="OAuth2 pattern", content="Use Authlib...") results = await client.recall(context_id="dev", query="OAuth2", k=5) await client.explore(context_id="dev", memory_id="uuid", depth=3) # Filtered recall — ALL listed tags, optional date range results = await client.recall( context_id="dev", query="budget", filters={"tags": ["予算", "2026"], "tags_match": "all", "created_after": "2026-03-01T00:00:00Z"}, ) # Cross-context recall — search several contexts at once results = await client.recall(query="auth", context_ids=["ctx-1", "ctx-2"], k=10) # Optional response keys (degraded, tag_suggestions, ...) are absent when they do not apply — use .get(). # degraded=True: the semantic half was down, so results are keyword-only (v0.66.0+); # an empty result then means "search impaired", not "nothing stored". # tags_normalize also matches "Dev_Environment" for "dev-environment" (v0.65.0+). results = await client.recall(context_id="dev", query="setup", filters={"tags": ["dev-environment"], "tags_normalize": True}) if results.get("degraded"): print("keyword-only:", results.get("degraded_reason")) # Reranking is tri-state (memory-cloud v0.69.0+). Omit use_rerank to follow the # context's search config (update_search_config); True requests it, applied only # when the context enables it; False skips it for this call, e.g. to save latency. # With context_ids, the first listed context's config decides. # Servers before v0.69.0 rerank only on True. fast = await client.recall(context_id="dev", query="OAuth2", use_rerank=False) # Find a context by name. On memory-cloud v0.73.0+ rows are slim # (id/name/is_private/is_locked/last_used_at); summaries are opt-in. found = await client.list_contexts(name_contains="auth", include_summary=True) # Trust-tier filter (provenance) — exclude untrusted / connector-ingested # memories from behaviour-influencing reads (OWASP LLM01/LLM03) safe = await client.recall(context_id="dev", query="policy", filters={"trust_tier": "trusted"}) AI agent memory substrate Primitives for autonomous agents — a deterministic load path, a retrieval-feedback signal, and a TTL-bounded run-state lane kept separate from knowledge:
async with KaguraClient(api_key="kagura_...", mcp_url="https://...") as client: # Deterministic delivery — pin on write, load the full pinned set every turn # (Goal / critical-policy memories, distinct from probabilistic recall). # For a rule tied to a tool call, use a tool guardrail (next section). await client.remember(context_id="dev", summary="Goal: ship the v2 importer by June", content="...", delivery_mode="always") pinned = await client.load_pinned(context_id="dev") # Time Memories — deterministic "what's upcoming" query (no semantic search). # Items carry `trigger` on server v0.73.0+; include_details=True returns `details`. upcoming = await client.recall_upcoming(context_id="dev", from_="now") # WHERE axis — deterministic "what's near here" query, nearest first # (SDK v0.38.0, server v0.53.0+). radius_m/k are keyword-only. # lat/lon must be JSON numbers; the server 422s string-typed coordinates. await client.remember(context_id="dev", summary="Coffee with Sato", content="...", details={"location": {"lat": 35.68, "lon": 139.76, "label": "Tokyo HQ"}}) nearby = await client.recall_nearby(context_id="dev", lat=35.68, lon=139.76, radius_m=500) # update_memory(details=...) REPLACES details wholesale — no deep-merge. Read the # current value with reference() and re-send location, or this drops off the map # (the CLI's `kagura update-memory --merge-details` does that round-trip). # Map viewport over the REST list (SDK v0.40.0, server v0.54.0+): keyword-only, # one-sided bounds OK, any bound keeps only located memories (item.location). page = await client.list_memories(context_id="dev", lat_min=35.5, lat_max=35.9, lon_min=139.5, lon_max=140.0) # HOW-MUCH axis — an append-only numeric series (SDK v0.40.0, server v0.54.0+). # Separate from memories: never embedded, never returned by recall(), never # merged or rewritten by Sleep consolidation. No delete — an operator-set # retention window is the only thing that removes rows (see Compatibility). # Raw numbers here; prose ("hit goal weight") via remember(). await client.record_measurement(context_id="dev", metric="weight_kg", value=71.5, unit="kg") # measured_at: ISO str or datetime (naive = UTC) weekly = await client.recall_series(context_id="dev", metric="weight_kg", period="week", agg="avg") # default: last 30 days for b in weekly.series: # empty buckets omitted; max window 365 days print(b.bucket, b.value, b.count) # Supersede — store a newer version WITHOUT destroying history (server v0.45.0+). # The old memory is shadowed, not deleted: it leaves default recall but stays # reachable, and deleting the edge restores it. Prefer this over forget() + # remember(), which throws away the history the supersede edge exists to keep. await client.remember(context_id="dev", summary="Deploy target: ap-northeast-1", content="...", supersedes="old-memory-uuid") # Read the history back. NOTE: a top-level argument, NOT a filters key. history = await client.recall(context_id="dev", query="deploy target", include_superseded=True) # results carry superseded_by # Reject a wrong supersede_candidate suggestion (server v0.65.0+; memory_id only). res = await client.update_memory(context_id="dev", memory_id="uuid", dismiss_supersede_candidate=True) # Only res.get("supersede_candidate_dismissed") confirms it: older servers drop the flag. # Retrieval feedback — teach the substrate which recall results were useful await client.feedback(context_id="dev", memory_id="uuid", helpful=True, query="OAuth2") # Agent session-state lane — TTL-bounded, structurally excluded from recall() await client.set_state(context_id="dev", key="step", value={"n": 3}, ttl_seconds=3600) state = await client.get_state(context_id="dev", key="step") # omit key → all live entries Tool guardrails (v0.39.0, server v0.74.0+) A memory whose details.tool_trigger names a tool (and optionally a pattern in its input) is a tool guardrail: a client-side hook injects its summary when a matching call happens (action="inform"), or denies the call with the summary as the reason (action="block"). The server validates the patterns on write and never runs them; matching happens in the hook, which loads the set deterministically with load_guardrails:
from kagura_memory import AgentsClient, KaguraClient async with KaguraClient() as client: # MCP surface # One-time provisioning (owner/admin): register the agent, bind its context agent = await client.register_agent("ci-agent", framework="claude-code") await client.bind_agent_context(agent.id, "ctx-uuid", is_default=True) bootstrap = await client.get_agent_bootstrap( "agent-uuid", # context_id omitted → default binding session_id="run-42", # echoed in the correlation block query="current task", # enables the trusted-only recall component include=["pinned", "recall", "state"], ) pinned = bootstrap.components["pinned"] # {"status": "ok", "memories": [...], ...} async with AgentsClient.from_mcp_url() as agents: # REST companion bootstrap = await agents.bootstrap("agent-uuid", include=["pinned"]) ⚠️ Error handling changed in v0.29.0 (breaking). Every KaguraClient MCP tool method now raises on a server domain error instead of returning an error dict: a missing context/memory raises KaguraNotFoundError, any other domain error raises KaguraError. Replace result["status"] == "error" checks with try/except:
from kagura_memory import KaguraNotFoundError, KaguraError try: results = await client.recall(context_id="dev", query="auth") except KaguraNotFoundError: ... # context or memory not found except KaguraError: ... # other server-side error A success response the SDK cannot parse — usually a server newer than this SDK — raises KaguraResponseError from every KaguraClient method and the REST clients (a KaguraError subclass; .operation names the MCP tool or . , e.g. KaguraClient.get_server_info, which check_server_version reports too) instead of a raw pydantic ValidationError or KeyError. The message names the failing fields, not their values. Upgrading kagura-memory is the likely fix. A network failure, a non-JSON 2xx body and a non-2xx status other than 401/429 raise KaguraConnectionError instead.
Plan and quota refusals raise typed errors, from the KaguraClient MCP tool methods and the REST clients alike. All three are KaguraError subclasses:
Against memory-cloud 0.75.0+ the SDK types a refusal by its gate descriptor (#1644). Against older servers it falls back to the error code and the legacy fields. A quota_exceeded refusal that names no quota, such as the 1 MB memory-size guard, stays a plain KaguraError, because no plan lifts it and waiting does not help. kagura commands print the reset time and the required plan under the error message.
from kagura_memory import KaguraFeatureNotAvailableError, KaguraQuotaError try: await client.remember(context_id="dev", summary="...", content="...") except KaguraQuotaError as e: print(e.quota_type, e.resets_at, e.retry_after) except KaguraFeatureNotAvailableError as e: print(e.feature, e.required_plan_display) More operations — tag-vocabulary discovery (list_tags), merge_contexts, context lifecycle (create_context/update_context/delete_context), workspace get_usage, get_memory_stats, find_duplicates, get_embedding_status — are runnable in examples/client_advanced.py; the API Coverage table lists the full surface.
Push data from external systems into Kagura so AI can search it:
from kagura_memory import ResourceClient, ResourceEventRequest async with ResourceClient.from_mcp_url(api_key="kagura_...", mcp_url="http://localhost:8080/mcp/w/...") as client: # One-call setup: create public context + set resource_id + create token. # The context is named after the resource unless you pass context_name. token = await client.setup_resource(resource_id="products") print(f"Save this token: {token.token}") # Shown only once! event = ResourceEventRequest( op="upsert", doc_id="SKU-001", version=1, payload={"name": "Wireless Headphones", "price": 79.99}, ) await client.ingest_event("products", token.token, event) # Check ingestion stats stats = await client.get_resource_impact("products") print(f"Memories: {stats.memory_count}, Tokens: {stats.token_count}") The server requires a context name: setup_resource (and kagura resource setup) uses resource_id unless you pass context_name (--name). A resource id always matches the context-name pattern, but it needs a name of its own when it is longer than the 100-character name limit, or when the workspace already has a context of that name (the server refuses with validation_error: "Context '' already exists in this workspace."). summary is deprecated and no longer sent, because the server's setup_resource has none; set it afterwards with KaguraClient.update_context or kagura context update --summary ... (context owner only).
Creating a resource, a resource token or a public context is plan-gated (plan_required). Since memory-cloud 0.68.0 (#1551) the gate is the plan's resources / public_contexts feature (XL only by default); earlier servers gated it on the plan's shared contexts and token cap. Resources, tokens and public contexts that already exist keep serving.
Upload files to the workspace's object store via short-lived presigned PUT URLs. The SDK binds the body's sha256 into the PUT signature so the server (memory-cloud v0.15.1+, R2_CHECKSUM_BINDING_ENABLED=true) can reject tampered uploads with 400 BadDigest:
from pathlib import Path from kagura_memory import FilesClient async with FilesClient.from_mcp_url(api_key="kagura_...", mcp_url="https://memory.kagura-ai.com/mcp") as client: # Upload from a Path (read fully into memory; server caps file size at 100 MiB) f = await client.upload(context_id="ctx-uuid", source=Path("./report.pdf")) print(f"Uploaded {f.id}, sha256={f.sha256}, size={f.size_bytes}") # Upload from bytes — filename is required (server enforces non-empty) f2 = await client.upload(context_id="ctx-uuid", source=b"...", filename="payload.bin") # Optionally bind a file to an owning context for access control (server # v0.41.0+). binding_context_id is the wire `context_id` — distinct from the # `context_id` arg, which is the workspace. Omit it for a workspace-scoped # (NULL-context) file. FileObject.context_id reflects the binding (or None). f3 = await client.upload( context_id="ctx-uuid", source=Path("./plan.pdf"), binding_context_id="owning-ctx-uuid", ) print(f3.context_id) # -> "owning-ctx-uuid" # Short-lived presigned GET URL. download_url / delete require the owning # context_id (workspace) — server v0.41.0 scopes file-id lookups to it. url = await client.download_url(f.id, context_id="ctx-uuid") # List & delete page = await client.list(context_id="ctx-uuid", limit=50) await client.delete(f.id, context_id="ctx-uuid") Re-uploading bytes whose sha256 already exists in the workspace returns the existing FileObject (idempotent dedup happy-path) — no exception.
A file bound via binding_context_id routes read/write/list/delete through that context's ACL (server v0.41.0+): you need write (EDITOR+) access to the context, and it must belong to the upload's workspace (else 403 / 422). A denied download surfaces as a 404 (existence-hiding), not a 403. Unbound uploads stay workspace-scoped and fully listable.
Client side of the secret store (memory-cloud v0.39.0+, requires the [secret] extra: pip install 'kagura-memory[secret]'). Secrets are encrypted to recipients' age/X25519 public keys and decrypted locally — memory-cloud only ever stores armored ciphertext, never plaintext. All crypto is delegated to the audited pyrage binding; the age private key is held in your OS keychain (keyring) and never transmitted.
from kagura_memory.secrets.client import SecretClient async with SecretClient.from_mcp_url(api_key="kagura_...", mcp_url="https://memory.kagura-ai.com/mcp") as client: # Register your public key (lands in `pending` until an owner approves it). me = await client.register_pubkey("age1...", label="laptop") # Encrypt-and-store in one call. recipients_snapshot / grant_pubkey_ids are # derived 1:1 from the recipient set, so the server's grant-consistency # invariant holds by construction. actives = [p for p in await client.list_pubkeys() if p.status == "active"] await client.put_secret_for_recipients("db-prod", b"hunter2", actives) # Fetch ciphertext (decrypt locally with your own key — not shown here). sv = await client.fetch_secret("db-prod") Most workflows use the CLI instead — see kagura secret below, which handles keychain custody and the get/put/grant/rotate flows with built-in misuse guards.
Owner-key operational tooling for workspace members and invitations (memory-cloud v0.42.0+). Every endpoint requires the workspace owner's static API key when called programmatically — OAuth tokens are rejected by the server with an actionable 403, and the assignable roles are member / admin / viewer (owner changes go through the ownership transfer flow):
from kagura_memory import WorkspaceClient async with WorkspaceClient.from_mcp_url(api_key="kagura_...") as client: members = await client.list_members("workspace-uuid") for m in members: print(m.user_id, m.role, m.user_email) # Invite a new user by email. member/viewer invitations REQUIRE a # context grant (allowed_context_ids, min 1); expires_in_days accepts # only the server presets 7/30/90/365 (None = never expires). inv = await client.create_invitation( "workspace-uuid", "new@example.com", role="member", allowed_context_ids=["context-uuid"], expires_in_days=30, ) print(inv.invitation_url) # shown once — a join credential # Role changes / removal await client.update_member_role("workspace-uuid", "google_123", role="admin") await client.remove_member("workspace-uuid", "google_123") Notes: add_member does not validate the user id server-side (a typo creates a dangling row — prefer create_invitation for onboarding); invitation ids are integers with no status field (derive pending from is_accepted/is_expired); listing invitations programmatically returns token/invitation_url as None (server-side token hygiene).
The same client also provisions member API keys (memory-cloud #1165): mint_member_key(ws, user_id, name, expires_days) (member/viewer targets only, never yourself — leaked-owner-key self-replication is blocked server-side; plaintext_key is returned exactly once), list_member_keys (metadata only), and revoke_member_key (soft revoke). CLI: kagura auth create-key|list-keys|revoke-key.
MIN_SERVER_VERSION in src/kagura_memory/client.py is the SDK's tested floor, and it is advisory: the SDK does not pre-check the server version and block a call. check_server_version() only logs a warning, and kagura doctor is the one place a too-old server fails outright. The two read the version the same way: a v prefix and +build metadata are ignored, a pre-release sorts below its release (0.17.1-rc1 is below 0.17.1, 0.17.2-rc1 above it), and a version that does not start with MAJOR.MINOR.PATCH (0.17, main-abc123) is not compared, so no warning is logged and kagura doctor reports it as info. Version mismatches therefore surface at call time, in two different ways: a tool the server doesn't have raises KaguraError ("tool not found"), while a newer parameter on a tool it does have is typically ignored server-side — silently. That silent case is why the per-surface floors above matter. When pointing the SDK at a backend with R2_CHECKSUM_BINDING_ENABLED=true, the SDK must be v0.14.0+; older versions don't send the signed checksum header and uploads fail with HTTP 403 SignatureDoesNotMatch.
Log in once with kagura auth login — the SDK stores credentials at ~/.kagura/credentials.json (mode 0600) and KaguraClient() plus all kagura CLI commands pick them up automatically:
kagura auth login # default: memory:read + memory:write kagura auth login --read-only # read-only scope kagura auth login --scope "memory:read profile:read" # custom scope set kagura auth login --no-browser # SSH / headless kagura auth login --profile work # named profile for a second workspace kagura auth login --invite https:// /join/ # invite-only sign-up (link or bare token) kagura auth status # show profile, server, expiry, scope kagura auth list # list all stored profiles (default marked *) kagura auth list --json # machine-readable profile list kagura auth refresh # manual token rotation kagura auth refresh --scope "memory:write" # incremental consent (re-runs device flow) kagura auth token # raw access_token to stdout (CI use) kagura auth logout # revoke + delete profile kagura auth logout --all --yes # remove every profile Invite-only servers. When a deployment admits new accounts only by invite link (/join/ ), pass that link — or its bare token — to kagura auth login --invite. The token is checked locally against the server's pattern before any network call, is never sent to the API, and is never written to credentials.json or included in an error message. The CLI builds the /join link on the web app's host (taken from the device flow's verification_uri, not from --server, since the API can live on another origin) and refuses a full link for a different server. It then reads the public /api/v1/system/info: when features.beta_invites is not true (invites turned off, or a server older than v0.70.0) it says invites have no effect and shows the normal prompt. On memory-cloud v0.76.0 and later it prints one link, /join/ ?return_to=…, that signs you up and lands on the approval page with the code filled in, followed by the plain approval URL in case you end up on the dashboard. On an older server, or when that probe fails, it prints two steps in order — open the invite link and sign up, then open the approval URL. Either way the browser opens only the invite link (--no-browser just prints).
Sign-in rate limit. memory-cloud v0.76.0 and later limit device sign-in requests per client address. When the server refuses one with HTTP 429, kagura auth login says so and how many seconds to wait (from the Retry-After header, 60 when it is missing).
Claude Code's MCP client reads its config once at startup and never refreshes tokens, so a short-lived OAuth access_token baked into .mcp.json would 401 silently after it expires. kagura setup claude --profile instead points .mcp.json at the kagura-mcp stdio proxy, which owns ~/.kagura/credentials.json, forwards every MCP request to the server, and injects an always-fresh bearer token — so the same kagura auth login credentials power both the CLI and Claude Code. If the server rejects an expired MCP session (the MCP Streamable HTTP 404), the proxy — like a long-lived KaguraClient — re-runs the initialize handshake and retries the request once, so Claude Code keeps working without a restart. Use the long-lived API-key path only for CI / service accounts, where a static token is preferable.
Credential resolution order when KaguraClient() is called with no arguments: KAGURA_API_KEY env (CI / service accounts always win) → KAGURA_PROFILE env or explicit profile= arg → default_profile from ~/.kagura/credentials.json → legacy .kagura.json.
Run kagura doctor when a local setup is not behaving as expected:
kagura doctor # human-readable pass/warn/fail report kagura doctor --profile work # inspect a named OAuth profile kagura doctor --json # machine-readable output for CI/scripts The report covers effective auth source, OAuth/static API-key health, the Claude Code kagura-memory MCP entry in effect (from local, project .mcp.json or user scope, plus any entry it shadows), kagura-mcp PATH wiring, MCP URL HTTPS, server reachability/version, optional ingestion extras, LiteLLM supply-chain status, and local LLM provider key/model diagnostics. Provider diagnostics are local-only: GEMINI_API_KEY, ANTHROPIC_API_KEY, OPENAI_API_KEY, and OLLAMA_API_KEY are reported with redacted previews, and model/key mismatches are warnings only. doctor exits non-zero only on fail checks; warnings do not fail CI.
# Direct memory operations kagura remember -s "FastAPI DI" --content "Use Depends()..." -c dev kagura remember -s "Coffee with Sato" --content "..." --location "35.68,139.76,Tokyo HQ" kagura recall "dependency injection" -k 10 kagura recall "dependency injection" --no-rerank # skip reranking; no flag follows the context config (v0.69.0+) kagura recall "project context" --trusted-only # exclude connector-ingested memories (filters.trust_tier, v0.24.0+) kagura explore -m "memory-uuid" --depth 3 kagura forget -m "memory-uuid" kagura update-memory -m "memory-uuid" --dismiss-supersede-candidate # server v0.65.0+ # --details replaces details wholesale; --merge-details does a reference() round-trip and keeps the other keys kagura update-memory -m "memory-uuid" --details '{"location": {"lat": 35.68, "lon": 139.76}, "client": "acme"}' kagura update-memory -m "memory-uuid" --location "35.68,139.76,Tokyo HQ" --merge-details kagura contexts kagura context list --name-contains auth --summary # server v0.73.0+; --details, --stats # Resource tokens kagura resource setup -r products # context named after the resource; --name to override kagura resource tokens create -r products -d "Product sync" kagura resource ingest -r products -k TOKEN --doc-id SKU-001 -V 1 -p '{"name":"Widget"}' kagura resource ingest-batch -r products -k TOKEN -f events.json kagura resource stats -r products kagura resource schema -r products # Sleep Maintenance — observability + rollback kagura sleep history --limit 5 kagura sleep report kagura sleep rollback -y # destructive: prompts unless --yes / -y is set # Tool guardrails (server v0.74.0+); context-id defaults to .kagura.json kagura guardrails load --cap 200 # pinned + tool-triggered lanes as JSON kagura guardrails digest # print the AGENTS.md export block kagura guardrails digest --out AGENTS.md # splice it in; unchanged set → no write, empty set → block removed # (keep it out of commits: untracked file or --skip-worktree) kagura guardrails digest --target instructions --profile core # preview the MCP instructions for ?profile=core # Measurement lane — numeric series kept apart from memories (server v0.54.0+) kagura measure record weight_kg 71.5 --unit kg --at 2026-09-01T07:30:00Z # --at defaults to now kagura measure series weight_kg --period week --agg avg # default: day/avg over the last 30 days # File uploads (R2 checksum binding) kagura files upload ./report.pdf -c kagura files upload ./plan.pdf -c --binding-context-id # bind to an owning context for ACL (v0.41.0+) kagura files list -c --limit 50 kagura files download-url -c # -c required (server v0.41.0) kagura files delete -c # -c required (server v0.41.0) # Workspace member management — owner API key ONLY (server v0.42.0+; OAuth tokens are rejected) kagura workspace member list [--json] kagura workspace member add --role member|admin|viewer # user must already exist — prefer invite kagura workspace member set-role --role member|admin|viewer kagura workspace member remove --yes kagura workspace invite create --role member -c --expires-days 30 kagura workspace invite list [--include-accepted] kagura workspace invite revoke # Owner-provisioned member API keys — owner API key ONLY (server v0.42.0+) kagura auth create-key --user --name ci-bot --expires-days 90 # key printed ONCE; member/viewer targets only, never yourself kagura auth list-keys --user # metadata only — plaintext is never re-shown kagura auth revoke-key --user # soft revoke (row kept for audit) # Config kagura config show Zero-knowledge secrets (kagura secret) Requires the [secret] extra (pip install 'kagura-memory[secret]') and memory-cloud 0.39.0+. Your age private key lives in the OS keychain; memory-cloud only ever stores armored ciphertext.
kagura secret keygen --label laptop # generate keypair → keychain, register public key (pending) kagura secret approve # owner: approve a pending key (verify its fingerprint out-of-band) kagura secret put db-prod # re-encrypt to the expanded recipient set kagura secret revoke db-prod --to # revoke a grant (then `rotate` — revoke ≠ invalidation) kagura secret rotate db-prod # encrypt a NEW value to the remaining recipients kagura secret list # secret metadata (never the values) kagura secret delete db-prod # owner-only hard delete (cleanup, not invalidation — rotate first) kagura secret audit-verify # verify the tamper-evident audit chain delete is cleanup, not a security control. It removes the stored ciphertext (all versions + grants) but does not un-share a value a recipient already fetched, nor rotate the live upstream credential. To contain a leak, rotate the upstream credential first, then delete. Owner-only; needs memory-cloud 0.41.0+.
See the 60-second demo above for the happy path. The full option surface:
# Local file or URL → one overview + N sections + R2 archive kagura ingest ./report.pdf kagura ingest https://example.com/report.pdf --tags "Q1,research" # Preview cost / sections without calling any LLM kagura ingest ./report.pdf --dry-run # Skip vision-provider configuration entirely (images are not OCR'd yet, so # this just avoids validating a vision provider you don't need) kagura ingest ./report.pdf --no-vision # Storage: skip the R2 archive (no file_id stamped on the overview memory) kagura ingest ./report.pdf --no-archive # Machine-readable output for scripts kagura ingest ./report.pdf --json Exit codes: 0 when the overview memory is created (per-section errors are still 0, they show up in result.errors); 1 when the overview itself fails (corrupted PDF, network error, etc.); 0 for any --dry-run invocation.
For the SDK-level FileIngestor API, see examples/ingest_pdf.py.
Provider configuration (env vars, picked up automatically via litellm):
Wire Kagura Memory into Claude Code as an MCP server. Recommended: OAuth via the refresh-aware kagura-mcp proxy — log in once, then setup claude writes the stdio .mcp.json form and tokens refresh automatically:
kagura auth login --profile default # one-time OAuth device flow kagura setup claude --profile default # writes .mcp.json → kagura-mcp stdio proxy This writes a .mcp.json that launches kagura-mcp as the MCP server (no secret in the file), plus .claude/ hooks and /kagura-recall · /kagura-remember skills. Check the active mode any time with kagura auth status (it reports refresh-aware vs legacy static API-key token for the entry Claude Code uses in the current directory, and which scope it comes from).
CI / service accounts — use a long-lived API key instead (static token, no refresh needed):
kagura setup claude --api-key kagura_xxx --mcp-url https://memory.kagura-ai.com/mcp One entry for every project — the stdio entry holds nothing project-specific (a local command and a profile name), so when one profile serves all your projects, put it at Claude Code's user scope:
kagura setup claude --profile default --scope user # via `claude mcp add-json --scope user` With an API key instead of --profile, the user-scope entry does not hold the key: it sends Authorization: Bearer ${KAGURA_MCP_API_KEY}, which Claude Code fills in from its own environment when it connects. The key is never on the claude mcp add-json command line, where any local user could read it in the process list, and never in ~/.claude.json. Set the variable in the environment that starts Claude Code, e.g. export KAGURA_MCP_API_KEY=kagura_xxx in your shell profile. Setup says whether the current shell has it, and kagura doctor warns when it is unset. It is a separate variable from KAGURA_API_KEY, which the SDK ranks above .kagura.json and OAuth profiles for every kagura command. (The --profile entry needs no key at all. --scope project still writes the key into .mcp.json, so keep that file out of version control.)
--scope project (the default) writes /.mcp.json: that is the scope Claude Code shares through version control, and it asks you to approve a new project server before first use. --scope user writes through the claude CLI, since Claude Code owns ~/.claude.json; without claude on PATH, setup prints the command and stops. A different user-scope kagura-memory entry is replaced: an interactive run asks first, -y replaces it (and says so). Each run still writes the project's .kagura.json and hooks. Claude Code uses the kagura-memory entry from the strongest scope — local > project > user — and ignores the rest (local scope belongs to the git repository root, whichever subdirectory you start in; project scope is the closest .mcp.json defining it, in that directory or any parent), so setup checks every scope first: it warns (and with -y exits 1 without writing) when a stronger entry would hide the new one, and notes any weaker entry the new one hides. kagura doctor reports the same.
Upstream URL query — --guardrails off| (server v0.74.0+) and --tool-profile (server v0.73.0+) put memory-cloud's ?guardrails= / ?profile= on the upstream MCP URL: as kagura-mcp --guardrails … --tool-profile … arguments for --profile (the proxy adds them to the profile's URL at run time, replacing any earlier value), or in the url's query for an API key. Nothing is copied into --server or ~/.kagura/credentials.json, and changing them never forces a re-login. The entry is rebuilt from the flags on every run, so pass them again when you re-run setup (it notes any it dropped). --guardrails off also removes the guardrails block from get_context_info: use it only when hooks deliver guardrails (see below). --tool-profile core limits tools/list to the memory loop; the server knows full and core (case-sensitive), fails tools/list for any other name, and ignores the profile when the URL already has a ?tools= allowlist. Older servers ignore both parameters.
Hooks and commands — the SessionStart hook recalls project context with kagura recall --trusted-only (server v0.24.0+), so connector-ingested memories never reach the session unreviewed. --no-session-hook, --no-sync-hook (the .claude/memory sync) and --no-commands (/kagura-recall · /kagura-remember) skip them; re-running with one removes only what setup itself wrote. When the memory-cloud kagura-memory plugin is installed (claude plugin list), an interactive run offers to skip /kagura-recall and /kagura-remember, which duplicate its /kagura-memory:recall and :remember (default: skip), and asks separately about the SessionStart hook (default: keep — the plugin recalls nothing automatically: its SessionStart hook only announces active guardrails, and /kagura-memory:session-start is a command you run). -y keeps both and names --no-commands. Setup never sets --guardrails off for you: once the plugin's guardrail hooks are configured (/kagura-memory:setup), re-run with --guardrails off. Setup prints the plugin's server_url and context_id values (never an API key); the plugin's context_id is one guardrail context for every project, and its hooks need a user API key even when setup uses --profile.
kagura remember -s "FastAPIのDIパターン" --content "DIはDepends()を使う" -c dev Also running the memory-cloud kagura-memory Claude Code plugin (its guardrail hooks and /kagura-memory:setup)? Both expect the MCP entry named kagura-memory, and the plugin's hooks need their own API key — see the coexistence note in skills/setup/SKILL.md.
This repo also ships a thin Claude Code plugin under .claude-plugin/ + skills/ that wraps the high-value CLI commands as skills (doctor, auth, setup, memory, ingest, resource, files, secret) — each shells out to the installed kagura CLI and returns clear guidance when it is not installed/authenticated. The plugin is named kagura-cli (distinct from the kagura-memory SDK package and the existing kagura-memory MCP plugin). Registration in the kagura-plugins marketplace (so it installs via /plugin install kagura-cli@kagura-plugins) is tracked as a follow-up.
OpenAI Codex, Hermes Agent and OpenClaw can each spawn a stdio MCP server, so kagura setup points them at the same refresh-aware kagura-mcp proxy Claude Code uses — log in once, and no API key goes anywhere. That entry stays the default. memory-cloud's OAuth dynamic client registration accepts the three harnesses' own clients on a loopback redirect only from 0.77.0 (memory-cloud#1657), and rejects them before that. From 0.77.0 the opt-in --url-form --oauth form (below) writes an entry with no key, which the harness then signs in to itself. From memory-cloud 0.78.0 (memory-cloud#1671), Hermes can also sign in with its device flow, which needs no loopback callback.
kagura auth login --profile default kagura setup codex --profile default # or: hermes, openclaw kagura setup codex --profile default --dry-run # show what it would do, change nothing Each harness passes a filtered environment to the servers it starts, so the entry names kagura-mcp by its absolute path (resolved when setup runs) and always passes --profile; it never depends on PATH, KAGURA_PROFILE or the default profile. Re-run setup after moving the SDK to another environment.
Setup changes a harness's config only through that harness's own CLI. Without the CLI on PATH (or, for Hermes and for Codex with --oauth, without a terminal or with -y), it prints the block and the file to add it to and edits nothing. When Hermes's config.yaml already has a top-level mcp_servers: key, it prints the entry alone, indented to go under that key: a second mcp_servers: key would replace the first, and every server under it. An entry of the same name stops setup unless you pass --force; setup says what kind of entry it is (stdio, URL with a bearer from an environment variable, URL with OAuth) and never prints its values. Setup asks questions only with a terminal and without -y; run from an agent's shell or CI, it behaves as with -y and never stops at a prompt.
The connection check, the context lookup and the AGENTS.md export use the --profile login alone, even when KAGURA_API_KEY is set, because that is the only credential the entry's kagura-mcp uses (kagura setup claude does the same).
Guardrails. Codex reads the server's MCP instructions, so with --context-id the entry runs kagura-mcp --guardrails and Codex receives that context's tool guardrail digest at every connect (server v0.74.0+). Use a context whose editor list you control: every editor's guardrail summaries reach the model. The server falls back to its base text, silently, when the entry's credential cannot read the context, the context has no guardrails, or the deployment turns the digest off; setup prints the kagura guardrails digest --target instructions command that previews what Codex receives. Hermes and OpenClaw do not read instructions: they see guardrails in the guardrails block of get_context_info, which ?guardrails=off would remove, so --guardrails off is refused for them (exit 2) and a context id is never written into their entry: a ?guardrails= already in --mcp-url is dropped with a warning (a ?guardrails=off the server would read is kept, alone and with a warning).
AGENTS.md export (opt-in; server v0.74.0+). --agents-md [PATH] writes a snapshot of the context's tool guardrails — the same block as kagura guardrails digest --out — into a file the harness loads every session: for Hermes the context file it loads from the current directory, found as Hermes finds it, so the user's own file keeps loading. Hermes loads only the first type that has text: the nearest .hermes.md / HERMES.md from here up to the git root (an empty one ends that search), then the AGENTS.override.md / AGENTS.md / agents.md chain from the git root down, then CLAUDE.md / claude.md, then Cursor rules. The block goes into the loaded .hermes.md / HERMES.md, else this directory's loaded AGENTS file (a new AGENTS.md when the chain loads only from parent directories), else the loaded CLAUDE.md, else a new AGENTS.md. When only .cursorrules / .cursor/rules/*.mdc load, a new AGENTS.md would stop them loading: setup makes no offer, and --agents-md needs a PATH. The Hermes gateway and cron start from terminal.cwd instead of the current directory, so pass --agents-md PATH for them. For OpenClaw AGENTS.md in its default workspace, found as OpenClaw finds it: $OPENCLAW_WORKSPACE_DIR, else workspace in $OPENCLAW_STATE_DIR, else ~/.openclaw/workspace (setup does not read an agents.defaults.workspace set in openclaw.json: pass that path to --agents-md); for Codex $CODEX_HOME/AGENTS.md (~/.codex), or AGENTS.override.md there when it exists, since Codex reads it instead — rarely needed, as the digest already arrives in instructions. An interactive Hermes or OpenClaw run offers it (default no) and lists the profile's contexts; without a terminal or with -y, pass --context-id. Only the text between the kagura-memory:guardrails markers changes. A context with no guardrails this credential can see writes nothing, and removes an earlier block, as guardrails digest --out does, so the harness stops loading guardrails the server no longer serves. Setup prints the command that refreshes the block.
Codex and the kagura-memory plugin's hooks. memory-cloud's Codex plugin reads the credential for its guardrail hooks only from a URL entry with a bearer (bearer_token_env_var, env_http_headers or http_headers), so a stdio entry, or an --oauth one, turns them into no-ops. When the hooks are turned on for the entry being written (their config.json's mcp_server, kagura-memory by default, equals --name), setup says so and suggests --url-form with an API key; an interactive run asks before writing the stdio or --oauth entry.
URL form. With a long-lived API key, and no wish to run the proxy on the harness host, --url-form --mcp-url https://memory.kagura-ai.com/mcp/w/ writes a URL entry instead. The key never passes through setup: the entry references an environment variable, and you put the key there yourself. --profile is optional here: it only lists contexts and fetches the AGENTS.md export, so it must be a login on the --mcp-url server (exit 2 otherwise). Without it, the export uses the usual kagura credential chain, which must point at that server too (KAGURA_MCP_URL for KAGURA_API_KEY).
OAuth URL form (memory-cloud 0.77.0+). From 0.77.0 memory-cloud's dynamic client registration accepts the three harnesses' own OAuth clients on a loopback redirect (memory-cloud#1657), so --url-form --oauth --mcp-url https://memory.kagura-ai.com/mcp/w/ writes a URL entry with no key, no header and no key variable: the harness registers its own client, signs in itself and keeps the token in its own store. Setup never sees the token, and never offers this form on its own. Before it detects, runs or writes anything, a real run sends one unauthenticated GET /api/v1/system/info to the --mcp-url server and stops (exit 1) unless it reports 0.77.0 or later; a version setup cannot read (no answer, not a 200, unparseable) stops it too. --dry-run sends no request. --oauth needs --url-form and --mcp-url and refuses --api-key-env (exit 2); --profile keeps its URL-form meaning.
kagura setup codex --url-form --oauth --mcp-url https://memory.kagura-ai.com/mcp/w/ The entry Written with Sign in The harness keeps the token in Codex url only (Codex's auth defaults to OAuth) codex mcp add --url , which saves the entry and then starts Codex's browser sign-in, so setup runs it attached to your terminal, and only with a terminal and without -y; otherwise it prints the table and edits nothing (--force: the same add, which signs in again) codex mcp login (--no-browser when the browser cannot reach the callback: it prints the URL and takes the callback URL pasted back) the OS keyring (Codex MCP Credentials; on Windows, Codex's encrypted secrets store in ~/.codex), else ~/.codex/.credentials.json ($CODEX_HOME), keyed on the entry's URL Hermes Agent url + auth: oauth hermes mcp add --url --auth oauth --connect-timeout 315, attached: its probe runs the browser sign-in, which the probe's default 30 s bound would cut short, so setup gives it the bound hermes mcp login uses. Hermes keeps it as the entry's connect_timeout (default 60 s), which also bounds later connects; hermes config set mcp_servers. .connect_timeout 60 lowers it once signed in. An entry Hermes saves without auth: oauth (it offers to continue without authentication when it cannot set up OAuth) counts as not saved, and one it saves disabled (enabled: false, after the sign-in did not finish) stops setup with the command that turns it on hermes mcp login (the browser flow, which also takes the redirect URL pasted at its prompt), or on memory-cloud 0.78.0+ hermes mcp login --flow device (a code entered at the server's /device page; no loopback callback, memory-cloud#1671) ~/.hermes/mcp-tokens/ .json ($HERMES_HOME, or the active Hermes profile's) OpenClaw url, transport: "streamable-http", auth: "oauth" openclaw mcp add --url --transport streamable-http --auth oauth, which saves an OAuth entry without probing (--force: openclaw mcp set) openclaw mcp login (--code when the browser cannot reach the callback), then openclaw mcp doctor --probe its state database, ~/.openclaw/state/openclaw.sqlite ($OPENCLAW_STATE_DIR/state/) Each sign-in redirects the browser to the harness's loopback callback on the harness host (the Sign in column names each harness's way round a browser that cannot reach it), and memory-cloud's consent screen shows the client name the harness sends, which nothing verifies. For Codex, --context-id or --guardrails goes on the URL as ?guardrails=; Codex keys its token on the URL, so changing it later means signing in again. With the plugin's hooks on, an --oauth entry does not get ?guardrails=off (the hooks cannot read it), and setup prints the hooks warning. The --guardrails preview runs on the kagura CLI's own credential: what Codex receives depends on the account it signed in with. Without --profile, it uses the CLI's usual credential only when that is on the --mcp-url server; otherwise it names the stored profiles on that server and runs on the first, or, when there is none, prints the kagura auth login --server to run first and the command on that login.
What has been checked: memory-cloud 0.77.0 accepts these harnesses' client registration on a loopback redirect. On 2026-09-25 each harness signed in end to end on a /mcp/w/ URL against memory-cloud 0.78.0, through entries kagura setup … --url-form --oauth wrote, and reached tools/list: Codex 0.157.0, Hermes Agent v2026.9.24 (the browser sign-in and hermes mcp login --flow device) and OpenClaw 2026.9.6, on a WSL2 host with the browser on Windows (#284). memory-cloud's protected-resource metadata names only /mcp, which the three accept for a /mcp/w/ URL. OpenClaw asks for every scope the server lists, memory:admin and memory:delete included.
stdio or OAuth? The stdio entry stays the default:
Context deletion is a soft delete available via KaguraClient.delete_context() and kagura context delete (the CLI prompts for confirmation). Account erasure (GDPR Art.17 / APPI) is intentionally Web UI only — it is irreversible and requires session authentication and confirmation. kagura sleep rollback runs over the MCP API Key but is itself destructive (reverses edge creation, merges, importance updates, promotions, and archives) and the CLI requires --yes to skip the interactive confirmation. The server commits per-action without a Saga, so a 5xx response after partial success means SOME actions may have been reversed before the error surfaced — re-run kagura sleep report to inspect the post-failure state.
git clone https://github.com/kagura-ai/kagura-memory-python-sdk.git cd kagura-memory-python-sdk uv sync --dev uv run ruff check src/ tests/ # Lint uv run ruff format src/ tests/ # Format uv run pyright src/ # Type check uv run pytest tests/ -v # Test Development with Claude Code This project is developed with Claude Code:
/quality # Run lint, format, type check, tests /simplify # Review for reuse, quality, efficiency /self-review # Pre-PR self-review /self-maint # Audit .claude/ config against codebase /test # Run the test suite /release # Bump version, tag, push, create GitHub Release /kagura-memory:guide # SDK usage reference (kagura-memory plugin) Typical flow: Issue → Branch → Implement → /quality → /simplify → /self-review → PR → Merge → /release
dev ingest ingest-all ingest-audio ingest-browser ingest-docx ingest-epub ingest-html ingest-pdf ingest-pptx ingest-xlsx ingest-youtube secret
agent ai document-ingestion embeddings kagura llm mcp memory pdf rag vector-search
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 26, 2026.




