Kirok
Kirok is a persistent, searchable memory server for AI agents over MCP, backed by a local SQLite database and Google Gemini AI for embeddings and LLM inference.
Core Memory Operations
Store (
KIROK_retain): Save information with automatic entity/keyword extraction, semantic embedding, and smart deduplication (ADD/UPDATE/NOOP decisions).Smart Store (
KIROK_smart_retain): Score content importance (1–10) via LLM before storing — filters low-value content during bulk ingestion.Search (
KIROK_recall): Hybrid semantic + keyword search using Reciprocal Rank Fusion (RRF), with optional time-range filtering and pagination.Update (
KIROK_update_memory): Edit content or context of existing memories, with automatic re-embedding on content change.Delete (
KIROK_forget): Permanently remove a specific memory by ID.
Insight & Reflection
Reflect (
KIROK_reflect): Analyze accumulated memories with an LLM to generate higher-level insights saved as "mental models", which can be auto-refreshed.Consolidate (
KIROK_consolidate): Manually trigger synthesis of unconsolidated memories into observations (patterns, preferences, durable knowledge).
Mental Model Management
List, view (
KIROK_list_mental_models,KIROK_get_mental_model), refresh (KIROK_refresh_mental_model), or delete (KIROK_delete_mental_model) mental models.
Memory Bank Management
List/Stats (
KIROK_list_banks,KIROK_stats): View all banks and detailed per-bank statistics.Browse/Get (
KIROK_list_memories,KIROK_get_memory): Paginate through or fetch specific memories.Configure (
KIROK_set_bank_config,KIROK_get_bank_config): Define a bank's retain and observations missions.Clear/Delete (
KIROK_clear_bank,KIROK_delete_bank): Remove bank contents or entire banks — both require explicitconfirm=truewith previews as a safeguard.
Reliability & Diagnostics
Atomic writes, soft deletes with audit trails, and startup auto-snapshots ensure data integrity.
Offline CLI for backup, export, and import;
kirok-doctortool checks setup and connectivity.
Provides persistent memory for AI agents using Google Gemini for semantic understanding and search, enabling retention, recall, reflection, and pattern detection across conversations.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Kirok remember that I prefer dark mode in settings"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Kirok
English | 日本語
Persistent memory for AI agents, over MCP. Kirok (記録, "record") is a Model Context Protocol server that gives an agent a durable, searchable memory: Retain what matters, Recall it with hybrid semantic + keyword search, and Reflect to distil accumulated memories into reusable insights. A background consolidation loop turns raw memories into higher-level observations on its own.
Why Kirok
Most "agent memory" is either a flat vector store (recall is a bare cosine top-k, no keyword grounding, no forgetting) or a pile of markdown the agent has to re-read every turn. Kirok is a small, self-hostable server that does the retrieval engineering properly:
Hybrid retrieval, not just vectors. Semantic KNN and FTS5 BM25 are fused with Reciprocal Rank Fusion, so an exact keyword match and a semantic match reinforce each other instead of competing.
A calibrated relevance floor. Naive cosine thresholds don't work on real embedding distributions (see Search quality); Kirok's floor is measured against live data, and there's an evaluation harness to keep it honest.
Autonomous consolidation. Memories are periodically synthesised into observations, and destructive LLM decisions are soft-deleted with an audit trail rather than executed blindly.
Reliability first. Atomic writes, soft deletes, startup auto-snapshots, and a fail-open background pipeline that never loses a
retain.
Not local-first: storage is a local SQLite file you own, but embedding and LLM inference are sent to Google's Gemini API. If everything must stay on-device, Kirok is not for you (yet).
Related MCP server: Memsolus MCP Server
Architecture
flowchart TB
client["MCP Client<br/>(Claude Desktop / Claude Code / Cursor / …)"]
subgraph server["Kirok MCP Server (FastMCP)"]
direction TB
tools["19 MCP tools<br/>Retain · Recall · Reflect · consolidate · CRUD"]
pipeline["Hybrid search (RRF) · Smart dedup<br/>Consolidation · Auto-refresh"]
end
subgraph storage["Local SQLite (WAL)"]
direction LR
fts["FTS5 trigram<br/>(BM25 keyword)"]
vec["sqlite-vec<br/>(KNN, brute-force fallback)"]
tables["memories · observations<br/>mental_models · banks · system_events"]
end
gemini["Google Gemini API<br/>gemini-embedding-001 (3072-d)<br/>gemini-2.5-flash-lite"]
client <-->|"stdio (JSON-RPC 2.0)"| tools
tools --> pipeline
pipeline <--> storage
pipeline <-->|embeddings · entity extraction<br/>reflection · consolidation| geminiStorage is a single SQLite database at ~/.kirok/memory.db. sqlite-vec provides per-bank vector KNN; if the native extension can't load, Kirok falls back to a NumPy brute-force scan with identical results. See docs/architecture.md for the full design.
🚀 Quick start
Requirements: Python 3.12+, uv (for uvx), and a Gemini API key (free tier is plenty).
Kirok ships on PyPI — nothing to clone. Put your key in ~/.kirok/.env (one line: GEMINI_API_KEY=AIza...), then verify the setup:
uvx --from kirok-mcp kirok-doctor # offline sanity checkConnect an MCP client
Claude Code CLI:
claude mcp add kirok -s user -- uvx kirok-mcpClaude Desktop — edit claude_desktop_config.json (macOS: ~/Library/Application Support/Claude/, Windows: %APPDATA%\Claude\):
{
"mcpServers": {
"kirok": { "command": "uvx", "args": ["kirok-mcp"] }
}
}Then restart the client. The server reads GEMINI_API_KEY from ~/.kirok/.env; an env block in the client config also works and takes precedence.
From source (development)
git clone https://github.com/TadFuji/kirok-mcp.git
cd kirok-mcp
uv sync # installs deps, including sqlite-vec
cp .env.example .env # then put your key in it: GEMINI_API_KEY=AIza...
uv run kirok-doctor # offline sanity check of the whole setupPoint your MCP client at the checkout with uv run --directory /absolute/path/to/kirok-mcp kirok-mcp instead of uvx kirok-mcp.
If uv run fails to launch the server (common on Windows or cloud-synced folders — uv run re-syncs on every launch and can hit locked .venv files or an in-use entry-point .exe), invoke the venv's Python directly to skip the sync entirely:
{
"mcpServers": {
"kirok": {
"command": "/absolute/path/to/kirok-mcp/.venv/bin/python",
"args": ["-m", "kirok_mcp.server"],
"env": { "PYTHONPATH": "/absolute/path/to/kirok-mcp/src" }
}
}
}On Windows use .venv\\Scripts\\python.exe and double-backslash paths in JSON.
A bundled agent skill in skills/kirok/ teaches the agent when and how to use the memory tools on its own — point your client at skills/kirok/SKILL.md to enable it.
🛠️ Tools
19 MCP tools. One-line summaries below; full parameter tables in docs/tools-reference.md.
Core
Tool | Purpose |
| Store a memory: entity/keyword extraction + embedding + smart ADD/UPDATE/NOOP dedup |
| Hybrid semantic + keyword search (RRF), observations shown first |
| Synthesise memories into a mental model (insight), optionally auto-refreshing |
| Score importance (1–10) first, then retain only if it clears a threshold |
| Manually run observation consolidation for a bank |
Memory management
Tool | Purpose |
| Fetch one memory / browse a bank with pagination |
| Edit content or context (re-extracts and re-embeds on content change) |
| Delete a single memory (irreversible) |
Mental models
Tool | Purpose |
| List / inspect insights from Reflect |
| Re-analyse against current memories |
| Delete a mental model (irreversible) |
Banks
Tool | Purpose |
| List banks with counts / detailed per-bank stats incl. background failures |
| Delete a bank's memories + observations (requires |
| Delete a bank entirely (requires |
Config
Tool | Purpose |
| Set / view a bank's retain & observation "missions" (what to focus on) |
⚙️ Configuration
Everything is set via environment variables (typically in .env). Only GEMINI_API_KEY is required.
Variable | Default | Description |
| — | Required. Google Gemini API key. |
|
| SQLite database location. |
|
| Cosine similarity above which retain invokes the LLM dedup (ADD/UPDATE/NOOP) decision. |
|
| Similarity floor for semantic memory hits in recall. Keyword/FTS hits are exempt. |
|
| Similarity floor for observation hits in recall. |
|
| Run auto-consolidation only once this many memories are pending ( |
|
| Consolidation timeout, seconds. |
|
| Reflect timeout, seconds. |
|
| Min hours between startup auto-snapshots ( |
|
| Auto-snapshot generations to keep before rotating out the oldest. |
🔍 Search quality
Recall runs semantic KNN and FTS5 BM25 in parallel and fuses them with Reciprocal Rank Fusion (k=60). Short Japanese keyword queries get special handling: 1–2 character kanji/katakana tokens fall below the trigram tokenizer's 3-char window and can never MATCH, so they're rescued by an exact-substring LIKE supplement appended after the BM25 hits (hiragana-only short tokens stay excluded — function words would substring-match half a bank; tokens are OR-joined, matching the MATCH side).
Three details keep the hybrid honest: each source is fetched deeper than the final page (max(limit*3, 30)) so RRF can promote an item ranked just outside the cut in both lists; all FTS text is NFKC-normalized on both the index and query side, so width variants (MCP vs MCP, バグ vs バグ) actually match; and observations get the same hybrid treatment as memories — semantic hits floored, keyword hits floor-exempt — instead of being reachable only through the semantic floor.
The similarity floor is calibrated on real data. A naive cosine threshold doesn't work here: on live gemini-embedding-001 vectors the distribution is narrow — off-topic queries score 0.55–0.62 against unrelated banks while true hits score 0.66–0.73. So the usable floor sits just above the off-topic ceiling, at 0.62. Without it, an unrelated query still returns a full page of memories from any non-empty bank (context pollution); much lower and the floor filters nothing (the old hardcoded 0.4 sat below even off-topic scores). FTS keyword hits bypass the floor entirely — a literal term match is independent evidence, not a weak vector score.
Search parameters aren't tuned by vibes. scripts/search_eval.py runs a golden query set through the exact recall pipeline the server uses (extracted as hybrid_search_memories, so the harness can't drift from production) and reports hit@1/hit@5/hit@k and MRR:
cp scripts/search_eval.example.json my_golden.json # add 30–50 real cases
uv run python scripts/search_eval.py my_golden.json --limit 10🛡️ Reliability
Atomic consolidation. Every create/update embedding is generated before any DB write; all observation changes plus the "consolidated" mark commit in a single transaction. A failure at any step leaves the database exactly as it was, with the source memories still pending for a later retry — never a half-applied batch.
Failures surface, never fake success. A consolidation LLM failure raises and is recorded to
system_events— the batch stays pending for a later retry, instead of being silently marked consolidated with nothing produced. Runs are serialized per bank, so two retains landing together cannot double-process the same batch into duplicate observations.Soft deletes with audit trail. An observation the consolidation LLM decides to remove is stamped
deprecated_at(excluded from search/list/stats) instead of destroyed, and a dedup UPDATE records the pre-merge content in the same transaction as the merge itself — both logged tosystem_eventsso a bad LLM decision is recoverable, not silent data loss.Startup auto-snapshot. On launch, if the newest auto-snapshot is older than
KIROK_AUTO_SNAPSHOT_HOURS, aVACUUM INTO+integrity_checksnapshot is written under~/.kirok/backups/, keeping the newestKIROK_SNAPSHOT_KEEPgenerations. A snapshot that fails partway leaves no broken file behind, and manual backups are never rotated.Concurrency. Connections set
PRAGMA busy_timeout=30000, so a second MCP client waits out a busy writer instead of failing withdatabase is locked.Fail-open background work. Auto-consolidation and mental-model refresh run behind
retainand can never fail it — errors are swallowed, recorded tosystem_events, and surfaced viaKIROK_statsso silent degradation stays visible.
💾 Backup & restore
All state is one SQLite file. The offline kirok-backup CLI needs no API key:
uv run kirok-backup snapshot # byte-level DB copy (safe while server runs)
uv run kirok-backup export # portable JSON of all banks + memories + observations + models
uv run kirok-backup import ~/.kirok/backups/kirok-export-YYYYMMDD-HHMMSS.jsonsnapshot and export write timestamped files under ~/.kirok/backups/ and refuse to overwrite. import runs in one transaction (all-or-nothing), skips existing IDs rather than overwriting, and rebuilds the FTS + vector indexes so search works immediately. Use --db to target a different database file.
🩺 Diagnostics
uv run kirok-doctor # offline: Python version, .env, key presence (never printed),
# required modules, FTS5, sqlite-vec, DB writability
uv run kirok-doctor --json # machine-readable, for automation
uv run kirok-doctor --online # adds one live embedding call to verify Gemini connectivity🧑💻 Development
uv sync
uv run --no-sync pytest # 164 offline tests; no API key or network neededThe suite is fully offline — importing kirok_mcp.server is side-effect-free (the API key is checked at startup, not import) and tests swap in fake Gemini clients. CI runs the same suite on Ubuntu and Windows on every push (.github/workflows/test.yml). See CONTRIBUTING.md before opening a PR.
📚 Documentation
docs/architecture.md — internal design, data model, consolidation engine
docs/tools-reference.md — full parameter reference for all 19 tools
CHANGELOG.md — version history (current: 1.4.2)
📄 License
MIT — see LICENSE.
Acknowledgements
Model Context Protocol and the official MCP Python SDK (FastMCP)
Google Gemini API for embeddings and LLM
Mem0 — inspiration for smart deduplication and the knowledge layer
Reciprocal Rank Fusion (Cormack et al., 2009)
Available Tools
19 toolsKIROK_clear_bankA
Delete ALL memories and observations in a bank, keeping the bank itself. Mental models are preserved. This is destructive and cannot be undone.
Without confirm=true this makes NO changes and returns a preview of what would be deleted. Only pass confirm=true after the user has explicitly approved deleting this specific bank's contents.
Args: bank_id: Bank to clear. confirm: Must be true to actually delete. Defaults to false (preview).
Inputs: bank_id (required), confirm. Returns: result
KIROK_consolidateA
Manually trigger observation consolidation for a bank.
Processes unconsolidated memories and synthesizes them into observations — patterns, preferences, and durable knowledge.
Args: bank_id: Memory bank to consolidate.
Inputs: bank_id (required). Returns: result
KIROK_delete_bankA
Permanently delete a bank and ALL its memories, observations, models, and config. This is destructive and cannot be undone.
Without confirm=true this makes NO changes and returns a preview of what would be deleted. Only pass confirm=true after the user has explicitly approved deleting this specific bank.
Args: bank_id: Bank to delete entirely. confirm: Must be true to actually delete. Defaults to false (preview).
Inputs: bank_id (required), confirm. Returns: result
KIROK_delete_mental_modelA
Delete a specific mental model. This is destructive and cannot be undone.
Args: model_id: ID of the mental model to delete.
Inputs: model_id (required). Returns: result
KIROK_forgetA
Delete a specific memory by its ID. This is destructive and cannot be undone.
Args: memory_id: ID of the memory to delete.
Inputs: memory_id (required). Returns: result
KIROK_get_bank_configA
Get the current configuration for a memory bank.
Args: bank_id: Memory bank to query.
Inputs: bank_id (required). Returns: result
KIROK_get_memoryC
Get full details of a specific memory by its ID.
Args: memory_id: The memory ID to look up.
Inputs: memory_id (required). Returns: result
KIROK_get_mental_modelB
Get full details of a specific mental model.
Args: model_id: The mental model ID to look up.
Inputs: model_id (required). Returns: result
KIROK_list_banksA
List all available memory banks with their memory counts.
Inputs: no named parameters. Returns: result
KIROK_list_memoriesA
List memories in a bank with pagination, ordered by most recent.
Args: bank_id: Memory bank to browse. limit: Maximum number of memories to return (default 20, max 100). offset: Number of memories to skip for pagination (default 0).
Inputs: bank_id (required), limit, offset. Returns: result
KIROK_list_mental_modelsA
List mental models (insights generated by Reflect) for a bank.
Args: bank_id: Memory bank to list mental models from. limit: Maximum number of models to return (default 10).
Inputs: bank_id (required), limit. Returns: result
KIROK_recallA
Search and retrieve relevant memories using semantic similarity and keyword matching, merged with Reciprocal Rank Fusion.
Args: bank_id: Memory bank to search. query: Natural language search query. limit: Maximum number of results (default 10, max 50). time_min: Optional ISO 8601 lower bound for timestamp filtering. time_max: Optional ISO 8601 upper bound for timestamp filtering. verbose: If True, also show relevance scores (RRF/Sim) per item. Default False keeps the output compact (content + ID only) to save context tokens.
Inputs: query (required), bank_id (required), limit, verbose, +2 more. Returns: result
KIROK_reflectA
Reflect on accumulated memories to generate new insights.
Retrieves relevant memories, analyzes them with an LLM, and saves the resulting insight as a 'mental model' for future reference.
Args: bank_id: Memory bank to reflect on. query: What to reflect on (question, topic, or open-ended prompt). limit: Max memories to consider (default 20, max 100). auto_refresh: Whether to refresh this model after future consolidations. source_query: Optional query to use for future refreshes. Defaults to query.
Inputs: query (required), bank_id (required), limit, auto_refresh, +1 more. Returns: result
KIROK_refresh_mental_modelA
Refresh an existing mental model by re-analyzing current memories. Updates the insight based on the latest data in the bank.
Args: model_id: ID of the mental model to refresh. limit: Max memories to consider (default 20, max 100).
Inputs: model_id (required), limit. Returns: result
KIROK_retainA
Store new information in agent memory.
Automatically extracts entities and keywords, generates a semantic embedding, and indexes for later retrieval.
Smart Deduplication (inspired by Mem0): If the new content is highly similar to existing memories (cosine > 0.85), the system will decide whether to ADD (new info), UPDATE (enrich existing), or NOOP (skip).
Args: bank_id: Memory bank identifier (e.g. 'antigravity', 'user-prefs'). content: The information to remember. context: Optional context about the source (e.g. 'project meeting'). timestamp: Optional ISO 8601 timestamp. Defaults to now.
Inputs: bank_id (required), content (required), context, timestamp. Returns: result
KIROK_set_bank_configA
Configure a memory bank's retain and observations missions.
The retain_mission guides what entities/keywords to extract (and what to ignore). The observations_mission guides what patterns to consolidate into observations.
Args: bank_id: Memory bank to configure. retain_mission: Plain-language description of what this bank should focus on. observations_mission: Plain-language description of what observations to synthesize.
Inputs: bank_id (required), retain_mission, observations_mission. Returns: result
KIROK_smart_retainA
Evaluate content importance before retaining. Uses LLM to score the content from 1-10 and only retains if score >= threshold.
Use this for bulk/automatic ingestion where you want the system to decide what's worth remembering.
Args: bank_id: Memory bank identifier. content: The information to potentially remember. context: Optional context about the source. timestamp: Optional ISO 8601 timestamp. threshold: Minimum importance score to retain (1-10, default 5).
Inputs: bank_id (required), content (required), context, threshold, +1 more. Returns: result
KIROK_statsC
Get statistics for a specific memory bank.
Args: bank_id: Memory bank identifier.
Inputs: bank_id (required). Returns: result
KIROK_update_memoryA
Update an existing memory's content. Re-extracts entities/keywords and regenerates the embedding if content changes.
Args: memory_id: ID of the memory to update. content: New content text (leave empty to keep current). context: New context string (leave empty to keep current).
Inputs: memory_id (required), content, context. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 19 tools
Most tools have distinct purposes (e.g., list, get, delete). However, retain and smart_retain are very similar, differing only in an importance threshold. Reflect and refresh_mental_model both deal with mental models but have different actions; still, they could be confused. Overall, the set is mostly clear.
All tools follow a consistent verb_noun pattern with 'KIROK_' prefix and snake_case. No mixing of conventions (e.g., clear_bank, list_banks, get_memory). The naming is predictable and systematic.
With 19 tools, the server covers the full memory management lifecycle (CRUD, search, configuration, consolidation). This is a reasonable scope for a memory bank system, not too many or too few.
The tool set covers most operations for banks, memories, and mental models. However, there is no explicit tool to create a bank (banks seem to be created implicitly or via set_bank_config), and there is no direct way to update a mental model's content (only refresh). These are notable gaps for full lifecycle coverage.
Maintenance
Related MCP Connectors
Persistent memory for AI agents. Search and store durable facts, preferences and decisions.
Persistent memory for AI agents. Search, store, and recall across sessions.
Persistent memory for AI agents: save, search and connect context across tools and sessions.
Universal persistent memory and knowledge retrieval layer for AI agents and LLMs.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceProvides AI agents with persistent, searchable memory that survives across conversations using semantic search, temporal versioning, and smart organization. Enables long-term context retention and cross-session continuity for AI assistants.14-

Memsolus MCP Serverofficial
AlicenseAqualityDmaintenanceProvides persistent long-term memory for AI agents through semantic search and automated knowledge graph extraction. It enables agents to store, recall, and reason over facts, preferences, and relationships across multiple conversations and sessions.146 npmMIT- AlicenseNot gradedqualityBmaintenanceProvides persistent, cross-session memory for AI agents, allowing them to store and automatically retrieve information across different conversations and sessions without repeating context.54 npm179MIT
- FlicenseNot gradedqualityBmaintenanceProvides persistent memory for LLM applications, enabling AI assistants to remember user preferences, facts, and conversation history across sessions.2-