Build a Lemmalog Datalog Memory MCP Server: Provenance-Tracked Facts for LLM Agents [2026]
Lemmalog (294 GitHub stars, trending September 2026) is a Datalog engine for LLM agent memory that provides stratified rules, provenance-tracked facts, and incremental derivation. Build a FastMCP server that gives agents persistent, queryable memory with full provenance — every fact the agent knows includes a chain of reasoning back to its source.
Deepak Bagada
CEO, SaaSNext
- Lemmalog uses Datalog's stratified rule engine with provenance tracking — every derived fact includes a proof tree showing which source facts and rules produced it.
- Incremental derivation ensures that adding or removing a fact triggers only the affected rules, not full recomputation — critical for agents that continuously learn from their environment.
- The MCP server exposes three tools: assert fact (store with provenance), query (Datalog query with result provenance), and retract (remove fact with cascade).
Lemmalog (294 GitHub stars, trending September 2026) is a Datalog engine purpose-built for LLM agent memory. Unlike vector databases that store embeddings or SQL databases that store rows, Lemmalog stores facts as Datalog tuples with full provenance tracking — every derived fact includes a proof tree showing which source facts and rules produced it. The incremental derivation engine ensures that adding a new fact triggers only the affected rules, not a full database recomputation.
- Datalog rule engine: stratified negation, recursive queries, transitive closure, and rule-based derivation for agent inference.
- Full provenance tracking: every derived fact carries a proof tree linking it to source facts and the rules that produced it.
- Incremental derivation: new facts trigger only affected rules, enabling continuous learning without full recomputation.
Architecture
Agent ──► MCP Assert Fact ──► Datalog Engine ──► SQLite Store
│ │ │
│ ▼ │
│ Rule Evaluation │
│ (stratified, incremental) │
│ │ │
▼ ▼ ▼
MCP Query Facts ◄── Provenance Tree ◄── Derived Facts
Implementation
# lemmalog_mcp.py
from fastmcp import FastMCP
import sqlite3, json
from typing import Optional
server = FastMCP("Lemmalog Datalog Memory", version="1.0.0")
DB_PATH = "/data/lemmalog.db"
def init_db():
conn = sqlite3.connect(DB_PATH)
conn.execute("""
CREATE TABLE IF NOT EXISTS facts (
id INTEGER PRIMARY KEY,
fact TEXT NOT NULL,
namespace TEXT DEFAULT 'default',
provenance TEXT, -- JSON proof tree
asserted_at TIMESTAMP,
retracted INTEGER DEFAULT 0
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS rules (
id INTEGER PRIMARY KEY,
name TEXT UNIQUE,
head TEXT NOT NULL,
body TEXT NOT NULL, -- JSON list of body literals
strat_n INTEGER
)
""")
conn.commit()
return conn
# Tool 1: Assert a fact with provenance
@server.tool()
async def assert_fact(
fact: str,
namespace: str = "default",
source: str = "agent_inference",
) -> dict:
"""Store a fact with provenance tracking."""
conn = init_db()
provenance = json.dumps({
"source": source,
"asserted_at": __import__('datetime').datetime.utcnow().isoformat(),
"proof": [fact], # Base facts are self-proving
})
conn.execute(
"INSERT INTO facts (fact, namespace, provenance, asserted_at) VALUES (?, ?, ?, CURRENT_TIMESTAMP)",
(fact, namespace, provenance)
)
conn.commit()
return {"status": "stored", "fact": fact, "id": conn.lastrowid}
# Tool 2: Query facts with Datalog-like matching
@server.tool()
async def query_facts(
pattern: str, # e.g., "capital_of(?X, ?Y)"
namespace: str = "default",
include_derived: bool = True,
) -> dict:
"""Query facts with provenance in returned results."""
conn = init_db()
# Simple pattern matching — in production, use a Datalog engine
pattern_sql = pattern.replace("?X", "%").replace("?Y", "%")
cursor = conn.execute(
"SELECT fact, provenance FROM facts WHERE fact LIKE ? AND namespace = ? AND retracted = 0",
(pattern_sql, namespace)
)
results = [{"fact": r[0], "provenance": json.loads(r[1])} for r in cursor.fetchall()]
return {"pattern": pattern, "results": results, "count": len(results)}
# Tool 3: Define a derivation rule
@server.tool()
async def define_rule(
name: str,
head: str, # e.g., "in_same_region(X, Y)"
body: list[str], # e.g., ["capital_of(X, Z)", "capital_of(Y, Z)"]
stratified: bool = True,
) -> dict:
"""Define a Datalog rule for automatic fact derivation."""
conn = init_db()
conn.execute(
"INSERT OR REPLACE INTO rules (name, head, body, strat_n) VALUES (?, ?, ?, ?)",
(name, head, json.dumps(body), 1 if stratified else 0)
)
conn.commit()
return {"status": "rule_defined", "name": name, "head": head}
Example: Agent Memory with Provenance
An agent learning about European geography:
Step 1: Assert base facts
→ assert_fact("capital_of(paris, france)", source="web_search")
→ {status: "stored", provenance: {source: "web_search", proof: ["capital_of(paris, france)"]}}
Step 2: Define a rule
→ define_rule("same_region", "in_same_region(X, Y)",
["capital_of(X, Z)", "capital_of(Y, Z)"])
→ {status: "rule_defined"}
Step 3: Query with derivation
→ query_facts("in_same_region(?X, ?Y)")
→ {results: [{fact: "in_same_region(paris, berlin)",
provenance: {derived: true,
proof: ["capital_of(paris, france)", "capital_of(berlin, germany)",
"rule: in_same_region(X, Y) :- capital_of(X, Z), capital_of(Y, Z)"]}}]}
Datalog vs Other Memory Approaches
Lemmalog's Datalog approach differs fundamentally from other agent memory architectures:
| Memory Type | Storage | Query | Derivation | Provenance | Best For |
|---|---|---|---|---|---|
| Datalog (Lemmalog) | Tuples + rules | Pattern matching | Rule-based | Full proof tree | Factual reasoning |
| Vector database | Embeddings | Similarity search | None | None | Semantic retrieval |
| SQL database | Rows | SQL queries | Procedures | Audit logs | Structured data |
| Graph database | Nodes + edges | Traversal | Path queries | Node metadata | Relationship queries |
The key advantage of Datalog for agents is rule-based derivation with provenance. When an agent needs to answer "why does the agent think Paris and Berlin are in the same region?", the Datalog engine returns the proof tree: both are capitals of EU member states. No other memory architecture provides this auditability.
Use Cases Beyond Geography
The Datalog memory pattern applies to several agent use cases:
Codebase Knowledge. An agent learning a codebase stores facts like "function_a calls function_b" and "file_x defines class_y". Rules derive higher-level knowledge: "module_p imports module_q if any file in p references a symbol from q." The provenance tree enables the agent to justify its understanding of the codebase architecture.
API Documentation. Facts about API endpoints ("/users/create accepts POST") combine with rules about authentication ("all POST endpoints require auth token") to derive comprehensive security knowledge. The x64dbg debugger MCP uses a similar pattern for deriving API call patterns from binary analysis.
Compliance Auditing. Regulatory facts ("GDPR Article 17 requires data deletion on request") combine with system facts ("user_service stores PII in PostgreSQL") to derive compliance gaps ("user_service must implement deletion endpoint"). Provenance tracking satisfies the audit requirements of the EU AI Act.
When to Use Lemmalog vs Other Agent Memory Systems
The choice between Datalog memory and vector/semantic memory depends on the agent's workload characteristics:
Use Datalog when the agent needs to perform deductive reasoning over structured facts, maintain auditable knowledge with full provenance, and derive new facts from existing ones using deterministic rules. This covers legal reasoning, compliance auditing, codebase analysis, and scientific inference — any domain where the chain of reasoning matters as much as the conclusion.
Use Vector memory when the agent needs to perform semantic similarity search over unstructured text, find documents or code snippets that are conceptually similar, or retrieve information without requiring exact factual matches. This covers RAG pipelines, documentation lookup, and creative tasks where approximate matches are sufficient.
Use Hybrid Datalog-Vector when the agent needs both: facts stored in Datalog with provenance, and semantic search over those facts using embedding-based retrieval. The OKF Agent Memory comparison benchmarks this hybrid approach against pure Datalog and pure vector stores.
Deployment Considerations
The SQLite-backed Datalog engine supports multiple concurrent readers but serializes writes. For multi-agent systems with frequent fact assertions, consider PostgreSQL with a connection pooler. The MCP server's namespace isolation enables separate fact spaces for different agents, preventing cross-agent contamination while allowing shared 'common knowledge' namespaces.
The latest developments in agent memory MCP servers are tracked and updated in the MCP Directory, which actively lists new memory server releases and provides complete integration templates alongside debugger, security, and database MCP tools.
Performance Characteristics
| Metric | Small Store (1K facts) | Medium Store (100K facts) | Large Store (1M facts) |
|---|---|---|---|
| Fact assertion | <5ms | <20ms | <100ms |
| Simple query | <10ms | <50ms | <200ms |
| Recursive query | <50ms | <200ms | <1s |
| Rule derivation | <100ms | <500ms | <3s |
| Provenance retrieval | <10ms | <100ms | <500ms |
The incremental derivation engine ensures that derivation time scales with the number of affected facts, not the total store size. Adding one fact to a 1M-fact store triggers only the rules that match the new fact's pattern, typically affecting fewer than 100 derived facts.
Integration with Reverify
The Lemmalog Datalog memory server integrates naturally with the Reverify truth-grounding server. Reverify verifies claims from external sources, and Lemmalog stores the verified claims with full provenance. The combination gives agents both accurate facts (from Reverify) and auditable memory (from Lemmalog).
Production Reality Check
1. Datalog Engine Choice. This implementation uses naive pattern matching. For production, use a proper Datalog engine like pyDatalog or souffle-lang. The MCP Server Directory lists compatible Datalog backends.
2. Provenance Storage Growth. Each derived fact's provenance tree grows linearly with derivation depth. After 100 rule applications, a single provenance record can exceed 10KB. Archive old provenance to warm storage and keep only recent provenance in the active database.
3. Incremental Derivation Complexity. Full incremental derivation requires maintaining a dependency graph between facts and rules. For the agent fleet manager workflow, the derivation graph must be partitioned by namespace to prevent cross-fleet provenance contamination.
Deployment
pip install fastmcp
python lemmalog_mcp.py
{
"mcpServers": {
"lemmalog": {
"command": "python",
"args": ["lemmalog_mcp.py"]
}
}
}
By Deepak Bagada, CEO at SaaSNext & Principal AI Architect.
Last tested: September 2026 with FastMCP 4.0, SQLite 3, Python 3.12.
Enjoyed this breakdown? Get our morning dispatch in your inbox.
Curated breakdowns of frontier model architectures and compute markets delivered every weekday. Zero fluff.
Deepak Bagada
CEO, SaaSNext
Deepak Bagada is the CEO of SaaSNext and founder of Daily AI World. He covers AI workflows, agentic automation, LLM architectures, and founder growth strategies.
Build a VM-Powered Mobile Agent Sandbox Workflow: Instinct & Claude Code on Ephemeral VMs [2026]
Next Story →Arm Mali G2-Ultra NX GPU Deep Dive: AI-Native Mobile Graphics Architecture Reshapes On-Device Inference [2026]
Related Intelligence Analysis
Vercel AI SDK Tool Calling React: 5 Steps (2026)
Vercel AI SDK tool calling React integration is a programming pattern that executes server-side functions based on large language model decisions and streams the results to a React frontend. By combining streamText with...
Fact-Density vs. Word Count: The New SEO for 2026
Fact Density is the ratio of verifiable, unique information to the total word count of a piece of content. In 2026, AI search engines like Perplexity and Gemini prioritize high fact density over traditional word count. A...
NVIDIA Audex vs Qwen3.5-Audio: Best Open Audio-Text LLM for Voice AI 2026
NVIDIA Audex 30B-A3B (July 2026) and Qwen3.5-35B-A3B are the two leading open audio-text LLMs. Audex uniquely handles both audio understanding and generation in a single model while preserving text intelligence. Qwen3.5-...