kg-memory-mcp
Exports all knowledge graph and conversation data to a single SQLite database file for backup.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
kg-memory-mcp
Knowledge graph memory + conversation archival MCP server
A self-hosted Model Context Protocol server backed by PostgreSQL + pgvector. It provides persistent knowledge graph storage (entities, observations, relations) and multi-agent conversation archival with hybrid search -- replacing both mcp-server-memory (JSONL) and cloud-based memory services.
Features
Knowledge Graph -- Create entities with typed observations and directional relations. Automatic deduplication (hash + semantic) and sensitive content filtering.
Conversation Archival -- Collect and store chat transcripts from Claude Code, Codex CLI, Gemini CLI, and OpenCode. Full session history with metadata.
Hybrid Search -- Full-text search (PostgreSQL tsvector) combined with vector similarity (pgvector HNSW), fused via Reciprocal Rank Fusion (RRF) with 1-hop graph expansion.
Hook System -- Automatic post-session archival and knowledge extraction (requires 3+ conversation turns). Optionally uses Gemini API for structured knowledge extraction. Install hooks for supported agents with a single CLI command.
Local Embeddings -- Uses Ollama with bge-m3 (1024-dim) for all vector operations. No data leaves your machine.
Schema Migrations -- Lightweight numbered-SQL migration system. Safely upgrades existing databases without data loss.
Data Export -- Export to JSONL (human-readable, interoperable) or SQLite (single-file backup). Compatible with migration to other tools.
Image Archival -- Extracts base64 images from all agent transcripts to the local filesystem with SHA256 deduplication and metadata tracking. Supports up to 50 MB per image.
Related MCP server: MCP Memory Server
Architecture
+------------------+ stdio +-------------------+
| MCP Client |<-------------->| kg-memory-mcp |
| (Claude Code, | | (FastMCP server) |
| Codex, Gemini, | +--------+----------+
| OpenCode) | |
+------------------+ |
| asyncpg
+--------v----------+
| PostgreSQL 17+ |
| + pgvector |
| |
| kg_entities |
| kg_observations |
| kg_relations |
| chat_sessions |
| chat_messages |
+--------+----------+
|
+------------------+ +--------v----------+
| Agent Hooks | SessionEnd | Ollama |
| (auto-archival |--------------->| bge-m3 |
| + extraction) | | (embeddings) |
+------------------+ +-------------------+Quick Start
Prerequisites
Install
# Via pip
pip install kg-memory-mcp
# Or run directly with uvx (no install needed)
uvx kg-memory-mcp serveInitialize the Database
# Create the knowledge_base database first
createdb knowledge_base
# Pull the embedding model
ollama pull bge-m3
# Run schema migrations
kg-memory-mcp initConfigure Your MCP Client
Add the following to your MCP client configuration:
{
"mcpServers": {
"kg-memory": {
"command": "uvx",
"args": ["kg-memory-mcp", "serve"]
}
}
}Claude Code (~/.claude/settings.json):
{
"mcpServers": {
"kg-memory": {
"command": "uvx",
"args": ["kg-memory-mcp", "serve"]
}
}
}Codex CLI (~/.codex/config.toml):
[mcp_servers.kg-memory]
command = "uvx"
args = ["kg-memory-mcp", "serve"]Gemini CLI (~/.gemini/settings.json):
{
"mcpServers": {
"kg-memory": {
"command": "uvx",
"args": ["kg-memory-mcp", "serve"]
}
}
}MCP Tools
Knowledge Graph
Tool | Description |
| Create entities with name, type, description, and optional observations |
| Add observations to an entity (auto-dedup + sensitive filter) |
| Create directional relations between entities |
| Delete entities (cascades to observations and relations) |
| Delete specific observations from an entity |
| Delete specific relations |
| Hybrid FTS + vector search with 1-hop graph expansion |
| Read the entire knowledge graph |
Conversation Archival
Tool | Description |
| Search chat messages across all agents |
| Get a complete chat session with all messages |
| List chat sessions with optional agent filter |
CLI Reference
kg-memory-mcp [OPTIONS] COMMAND [ARGS]
Commands:
serve Start the MCP server (stdio transport)
init Run schema migrations (create/upgrade tables)
migrate JSONL_PATH Migrate from memory.jsonl (mcp-server-memory format, auto-splits large entities)
collect Collect conversation transcripts from AI agents
--agent TEXT Only collect from: claude-code, codex, gemini-cli, opencode
export jsonl Export all data to JSONL files
--output-dir PATH Output directory (default: ./export)
export sqlite Export all data to a single SQLite file
--output PATH Output file path (default: ./kg-memory-backup.db)
reset Drop all kg-memory-mcp tables (with confirmation)
hooks install AGENT Install hook for a specific agent
hooks uninstall AGENT Remove hook for a specific agent
hooks status Check installation status of all hooks
hooks run AGENT Run a hook directly (called by agent integrations)Examples
# Start the MCP server
kg-memory-mcp serve
# Initialize database schema
kg-memory-mcp init --db-name knowledge_base --db-user postgres
# Migrate from mcp-server-memory
kg-memory-mcp migrate ~/.claude/memory.jsonl
# Collect all agent transcripts
kg-memory-mcp collect
# Collect only Claude Code transcripts
kg-memory-mcp collect --agent claude-code
# Install auto-archival hook for Claude Code
kg-memory-mcp hooks install claude-code
# Uninstall a hook
kg-memory-mcp hooks uninstall claude-code
# Check hook status
kg-memory-mcp hooks status
# Export data to JSONL (for migration to other tools)
kg-memory-mcp export jsonl --output-dir ./my-export
# Export data to SQLite (single-file backup)
kg-memory-mcp export sqlite --output ./backup.dbSupported Agents
Agent | Collector | Hook | Transcript Location |
Claude Code | Yes | SessionEnd |
|
Codex CLI | Yes | notify (agent-turn-complete) |
|
Gemini CLI | Yes | SessionEnd |
|
OpenCode | Yes | session.idle (plugin) |
|
Environment Variables
Variable | Default | Description |
|
| PostgreSQL database name |
|
| PostgreSQL user |
|
| PostgreSQL host |
|
| PostgreSQL port |
| (none) | PostgreSQL password (if required) |
| (disabled) | Set to |
| (disabled) | Set to |
|
| Ollama API base URL |
|
| Ollama embedding model name |
|
| Directory for storing image attachments |
| (none) | Enable automatic knowledge extraction in hooks (opt-in, sends data to Google) |
Privacy & Security
All data stays local by default. The MCP server, database, and embeddings run entirely on your machine. No data is sent to external services unless you explicitly opt in.
Database storage: Conversation transcripts and knowledge graph data are stored in plaintext in your local PostgreSQL database. Ensure your database has appropriate access controls.
Ollama embeddings: Vector embeddings are generated locally via Ollama. No data leaves your machine for embedding generation.
Gemini knowledge extraction (opt-in): If you set the
GEMINI_API_KEYenvironment variable, the SessionEnd hooks will send conversation summaries (up to 15KB) to Google's Gemini API for knowledge extraction. This is disabled by default -- without the API key, no data is sent externally. Conversation content is automatically filtered to remove lines containing API keys, passwords, and tokens before transmission, but project paths and code snippets may still be included.Hook transcript access: Hooks only read transcript files from expected directories (
~/.claude/,~/.codex/,~/.gemini/,~/.local/share/opencode/). Path traversal is validated.Sensitive content filtering: The
quality.pymodule filters out API keys, passwords, and tokens when writing to the knowledge graph via MCP tools and hooks. Note: bulk operations likemigrateandcollectalso apply this filter.
Uninstall
# 1. Remove hooks from all agents
kg-memory-mcp hooks uninstall claude-code
kg-memory-mcp hooks uninstall codex
kg-memory-mcp hooks uninstall gemini
kg-memory-mcp hooks uninstall opencode
# 2. (Optional) Drop all tables from the database
kg-memory-mcp reset
# 3. Remove the MCP server config from your client
# Delete the "kg-memory" entry from mcpServers in your settings
# 4. Uninstall the package
pip uninstall kg-memory-mcp # if installed via pip
uv tool uninstall kg-memory-mcp # if installed via uvDevelopment
# Clone and install dev dependencies
git clone https://github.com/liangquanzhou/kg-memory-mcp.git
cd kg-memory-mcp
pip install -e ".[dev]"
# Run linting
ruff check kg_memory_mcp/
pyright kg_memory_mcp/
# Run tests (requires PostgreSQL with pgvector)
pytest tests/ -vLicense
MIT
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Shared memory for AI agents, as a graph in your own Postgres. Writes never call an LLM.
Universal persistent memory and knowledge retrieval layer for AI agents and LLMs.
Versioned agent memory in your own Postgres: portable context, permissioned, audit trail.
Persistent memory and knowledge graphs for AI agents. Hybrid search, context checkpoints, and more.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to store, retrieve, and manage contextual knowledge across sessions using semantic search with PostgreSQL and vector embeddings. Supports memory relationships, clustering, multi-agent isolation, and intelligent caching for persistent conversational context.21 npm50MIT
- FlicenseNot gradedqualityDmaintenanceEnables AI assistants to store and retrieve long-term memories with semantic search, supporting various memory types and tags via PostgreSQL and pgvector.-
- AlicenseNot gradedqualityBmaintenanceEnables persistent, graph-based memory for AI agents, allowing them to store, traverse, and recall relationships between facts, decisions, and context across sessions for efficient reasoning and reduced token usage.MIT
- FlicenseBqualityBmaintenanceEnables AI agents to read, write, organize, and link persistent long-term memory across model providers using embeddings and pgvector retrieval.21-