Skip to main content
Glama

agent-memory-mcp

License: MIT Node.js Version Model Context Protocol Glama M8ven Verified

Persistent, per-project architectural memory, centralized cross-project global knowledge graph, two-tier anti-loop dead-end tracking, and token budgeting middleware for AI coding agents.

Works with Google Antigravity, Claude Code, Cursor, Windsurf, Cline, and any MCP-compatible environment.


โšก The Problem

AI coding agents suffer from session amnesia, debugging loops, and context bloat:

  1. When a chat session terminates or context is compacted, the agent forgets project patterns, architectural decisions, and setup instructions.

  2. When encountering errors, agents repeatedly attempt the same failing fix because past failure context is lost across sessions.

  3. Proven patterns and library workarounds learned in one repository are forgotten when opening another repository.

  4. Unbounded tool responses dump thousands of raw tokens into agent context windows, burning token budgets and degrading model reasoning.


Related MCP server: @renzynx/memory-mcp

โœจ Features

  • ๐Ÿš€ Zero External Database Setup: Built directly on Node.js 22.5+/24+ native node:sqlite in WAL mode. No Docker, no Python, no native compilation dependencies.

  • ๐ŸŒ Centralized Global Knowledge Graph: Store cross-project architectural patterns, library quirks, and conventions in ~/.ag-memory-mcp/global.db. Seamlessly promote project memories via promote_to_global and read with g- prefixed IDs.

  • ๐Ÿ›ก๏ธ Two-Tier Anti-Loop Dead-End Registry: Distinguish between immediate code/test bugs (error_loop) and intentional architectural constraints (architectural). Track active constraints and reopen dead-ends via reopen_dead_end when requirements evolve.

  • ๐Ÿ’ฐ Output Token Budgeting Middleware: Automatically estimates tokens and gracefully caps oversized tool outputs at natural sentence and word boundaries. Configure via AG_MEMORY_MAX_RESPONSE_TOKENS or ~/.ag-memory-mcp/config.json, with emergency full_content: true bypass.

  • ๐Ÿ” Ranked Full-Text Search (FTS5): Weighted BM25 search across titles, summaries, tags, and files with contextual snippets and Porter stemming for both project stores and global knowledge.

  • ๐Ÿ“Œ Code-Anchored Context & Staleness Detection: Links notes to specific workspace files; warns the agent if referenced code was modified on disk after the memory was saved.

  • ๐Ÿ“Š Audit & Token Efficiency Metrics: Query machine-wide token savings and audit logs across projects via get_token_metrics.

  • ๐Ÿ”„ Zero-Data-Loss JIT Migration: Automatically detects, validates, and migrates legacy .ag-memory.json files on first project open, creating verified backup archives.


๐Ÿ—๏ธ Architecture

flowchart LR
    subgraph Clients["AI Clients & Editors"]
        AG["Google Antigravity"]
        CC["Claude Code"]
        CU["Cursor / Windsurf"]
    end

    subgraph MCP["agent-memory-mcp Engine (15 Tools)"]
        Server["MCP Server (JSON-RPC)"]
        Middleware["Token Budgeting Middleware<br/>(Natural Sentence Trimming)"]
        Migrator["Zero-Loss JIT Migrator"]
    end

    subgraph Storage["Central Data Vault (~/.ag-memory-mcp)"]
        ProjectDB[("project-*.db<br/>(Project WAL + FTS5)")]
        GlobalDB[("global.db<br/>(Cross-Project Knowledge & Audit)")]
        Config["config.json"]
        Backups["backups/"]
    end

    Clients <-->|"stdio"| Server
    Server --> Middleware
    Server --> Migrator
    Migrator --> Backups
    Server <--> ProjectDB
    Server <--> GlobalDB
    Server <--> Config

๐Ÿ› ๏ธ MCP Tools (15 Tools)

Project-Scoped Memory Tools (1โ€“10)

Tool

Mode

Description

check_memory_status

Read-only

1-shot check returning initialization state, architecture TOC, dead-end count, and recent session timeline in a single call. Auto-migrates legacy .ag-memory.json.

get_session_timeline

Read-only

Chronological feed filterable by category (session, architecture, decision, note, all), tag, and date.

save_project_memory

Write/Upsert

Single or atomic batch (entries: [...]) save; automatically upserts matching id or canonical slug while archiving prior versions in revisions.

search_project_memory

Read-only

Weighted FTS5 BM25 search across title, tags, files, and summary (plus matching dead-ends) with match snippets.

read_memory_node

Read-only

Reads single id or batch ids: [...] (supports slugs like tech-stack or global g-... IDs), checking files[] disk mtime for staleness warnings.

update_memory_node

Write

In-place partial update to title, summary, tags, category, or files with automatic revision backup.

delete_memory_node

Write

Soft-archives obsolete memories (hard_delete: false default) or permanently deletes (hard_delete: true).

record_dead_end

Write

Logs { error_pattern, attempted_solution, root_cause, files, kind, constraints } to prevent repeating failed debugging paths.

check_dead_ends

Read-only

Searches recorded dead-ends by error message, keyword, or file_path, filterable by kind (all, error_loop, architectural).

get_file_memories

Read-only

Returns all memories and dead-ends anchored to target file_paths (or parent directories) before modifying code.

Global Knowledge & Taxonomy Tools (11โ€“15)

Tool

Mode

Description

save_global_knowledge

Write

Saves or updates a cross-project pattern, convention, or library quirk in ~/.ag-memory-mcp/global.db. Auto-generates g- prefixed IDs.

search_global_knowledge

Read-only

Searches machine-wide patterns and library quirks using BM25 ranking, filterable by tech_stack and category.

promote_to_global

Write

Promotes a proven project-specific memory node to the machine-wide global knowledge graph in global.db.

reopen_dead_end

Write

Reopens a previously recorded dead-end with a justification when external constraints or library versions change.

get_token_metrics

Read-only

Queries machine-wide token savings, budgeting statistics, and audit logs across all projects from global.db.


๐Ÿง  Deep Dives

๐ŸŒ Cross-Project Global Knowledge Graph

When developing across multiple microservices or repositories, agents repeatedly discover common framework quirks (e.g., SQLite lock timeouts in Node.js, Next.js hydration issues, Docker networking gotchas).

  • Global notes are saved to ~/.ag-memory-mcp/global.db.

  • Project memories can be promoted to global status via promote_to_global.

  • Any global node can be read using read_memory_node with its g-... ID prefix.

๐Ÿ›ก๏ธ Two-Tier Anti-Loop Dead-End Taxonomy

Not all failures are code bugs. agent-memory-mcp classifies dead-ends into two distinct tiers:

  1. error_loop: Code errors, compilation failures, and test breaks. Used by the 3-strike circuit breaker to prevent looping.

  2. architectural: Deliberate architectural trade-offs, discarded designs, and rejected patterns (e.g., "Do not use Redux; project uses Zustand"). Stores explicit constraints: [...].

  3. Reopening (reopen_dead_end): When a dependency upgrades or requirements change, an architectural dead-end can be reopened with a clear recorded rationale.

๐Ÿ’ฐ Token Budgeting Middleware

Large tool outputs degrade agent reasoning and exhaust context windows. agent-memory-mcp features transparent budgeting middleware:

  • Inspects response string size using character-to-token heuristics (~4 chars/token).

  • If the response exceeds the budget (default: 3,000 tokens), it trims the content at the nearest natural sentence boundary (. , \n\n, ! , ? ) and appends a truncation notice with instructions to bypass if necessary (full_content: true).

  • Logs token metrics (raw_tokens, capped_tokens, tokens_saved) directly to global.db for inspection via get_token_metrics.


โš™๏ธ Configuration

Create or modify ~/.ag-memory-mcp/config.json:

{
  "max_response_tokens": 3000
}

Or set the environment variable:

export AG_MEMORY_MAX_RESPONSE_TOKENS=4000

๐Ÿš€ Quickstart

1. Claude Code

Add to your Claude Code configuration with one command:

claude mcp add agent-memory-mcp -- npx -y @getsugatension/agent-memory-mcp

2. Cursor / Windsurf / Cline

Add to your mcpServers configuration (e.g. ~/.cursor/mcp.json or cline settings):

{
  "mcpServers": {
    "agent-memory-mcp": {
      "command": "npx",
      "args": ["-y", "@getsugatension/agent-memory-mcp"]
    }
  }
}

3. Google Antigravity (Plugin Bundle)

Install the plugin into your Antigravity plugins directory (~/.gemini/config/plugins/agent-memory/):

git clone https://github.com/msking18/agent-memory-mcp.git ~/.gemini/config/plugins/agent-memory

Restart Antigravity. The plugin enables zero-turn SessionStart context hydration, scoped agent rules, and global memory tools automatically.


๐Ÿ“ฆ MCP Resources

  • memory://projects: Exposes a read-only JSON registry of all workspaces tracked by agent-memory-mcp on your machine.


Add this rule to your agent's system prompt or AGENTS.md / CLAUDE.md:

### Rule: Persistent Project Memory & Anti-Looping (v3.1)
1. Startup: When starting work on a workspace, call `check_memory_status` with the absolute project directory.
2. Bootstrap: If UNINITIALIZED, explore the codebase and save 3 foundational nodes atomically via `save_project_memory`:
   - "Tech Stack & Ecosystem" (slug: "tech-stack", category: "architecture")
   - "Project Structure & Architecture" (slug: "project-structure", category: "architecture")
   - "Build & Run Instructions" (slug: "build-run", category: "architecture")
3. Before Editing Shared Utilities: Call `get_file_memories` with the file paths about to be edited.
4. Error Anti-Looping: Before retrying a failed test, build, or terminal command, call `check_dead_ends`. If a fix fails, record it via `record_dead_end` (specifying `kind: "error_loop"` or `"architectural"`).
5. Global Knowledge: Search machine-wide conventions and quirks with `search_global_knowledge`. Promote reusable solutions with `promote_to_global`.
6. Session Log: At the end of a major task, log changes via `save_project_memory` (category: "session", tags: ["changelog"]).

๐Ÿงช Testing

Run the automated test suite across SQLite transactions, FTS5 queries, JIT migrations, token budgeting, and stdio JSON-RPC:

npm test

๐Ÿ”’ Privacy Policy

agent-memory-mcp is local-first software. All SQLite databases, search indexes, and memory stores reside exclusively on your machine (~/.ag-memory-mcp/ or your workspace directory). It collects zero telemetry and transmits no data over the network. For complete details, see PRIVACY.md.


๐Ÿ“„ License

MIT ยฉ Manveer Singh Kahlon

Available Tools

15 tools
check_dead_endsCheck Recorded Dead-EndsA
Read-onlyIdempotent

Check the anti-loop dead-end registry by error text, keyword, or file path before attempting fixes.

Inputs: project_path (required), kind, limit, query, +1 more.

check_memory_statusCheck Memory Status & Hydrate ContextB
Read-onlyIdempotent

Check if project memory is initialized and retrieve core architecture index, dead-end count, and recent session timeline in one call. Auto-migrates legacy .ag-memory.json if present.

Inputs: project_path (required), timeline_limit, include_timeline.

delete_memory_nodeArchive or Delete Memory NodeA
Destructive

Soft-archives a memory node (default, preserves history) or permanently deletes it along with its revisions.

Inputs: id (required), hard_delete, project_path.

get_file_memoriesGet File-Anchored MemoriesB
Read-onlyIdempotent

Retrieve all architectural invariants, past gotchas, and dead-ends anchored to specific workspace file or directory paths.

Inputs: file_paths (required), project_path (required), include_dead_ends.

get_session_timelineGet Session Timeline FeedA
Read-onlyIdempotent

Retrieve a chronological feed of past work sessions, decisions, and architectural notes for this project workspace.

Inputs: project_path (required), tag, limit, since, +1 more.

get_token_metricsGet Token Efficiency & Audit MetricsB
Read-onlyIdempotent

Query machine-wide token savings, budgeting statistics, and audit logs from ~/.ag-memory-mcp/global.db.

Inputs: limit, timeframe_hours.

promote_to_globalPromote Project Memory to Global GraphB

Promote a proven project-specific memory node to the machine-wide global knowledge graph in ~/.ag-memory-mcp/global.db.

Inputs: memory_id (required), project_path (required), category, tech_stack.

read_memory_nodeRead Memory Node(s) with Staleness Detection & Global RoutingA
Read-onlyIdempotent

Read full markdown content of single or multiple memory nodes by id/slug (or global ID 'g-...'). Warns if referenced workspace files were modified on disk after memory was saved.

Inputs: id, ids, full_content, project_path, +1 more.

record_dead_endRecord Anti-Loop Dead-End or Architectural ConstraintA

Record a failed debugging attempt or intentional architectural constraint so future turns and sessions never repeat the same dead-end.

Inputs: root_cause (required), project_path (required), error_pattern (required), attempted_solution (required), +3 more.

reopen_dead_endReopen Dead-End RecordB
Idempotent

Reopen a previously recorded dead-end when external constraints, dependencies, or requirements change.

Inputs: id (required), reason (required), project_path (required).

save_global_knowledgeSave Global Architecture Pattern or Library QuirkB

Save or update a cross-project architecture pattern or library quirk into the centralized ~/.ag-memory-mcp/global.db.

Inputs: title (required), summary (required), id, tags, +3 more.

save_project_memorySave or Batch-Upsert Project MemoryA

Save a single memory note, session log, or atomic batch of foundational architecture nodes (via entries array). Automatically updates existing nodes matching slug or id, preserving revisions in SQLite.

Inputs: project_path (required), id, slug, tags, +5 more.

search_global_knowledgeSearch Global Knowledge GraphA
Read-onlyIdempotent

Search machine-wide patterns, library quirks, and cross-project invariants in ~/.ag-memory-mcp/global.db using BM25 ranking.

Inputs: limit, query, category, tech_stack.

search_project_memorySearch Project Memory with FTS5 BM25 RankingB
Read-onlyIdempotent

Full-text search across project titles, tags, summaries, anchored files, and active anti-loop dead-ends with contextual match snippets.

Inputs: query (required), project_path (required), limit, category.

update_memory_nodeUpdate Memory Node In-PlaceA

Update title, summary, tags, category, or files of an existing memory node. Automatically saves prior version to revisions history.

Inputs: id (required), tags, files, title, +4 more.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelogโ€ฆ

    TDQS

    A3.6/5.0

    Scored across 15 tools

    Disambiguation4/5

    Most tools have clearly distinct purpose: project CRUD (save/read/update/delete/search), the project-specific dead-end registry, and the machine-wide global graph. The clearest overlaps are check_memory_status vs get_session_timeline (status already returns a 'recent session timeline'), check_dead_ends vs search_project_memory (which also searches active dead-ends), and read_memory_node vs get_file_memories (both surface file-anchored notes via different keys). These are workable given the descriptions but could cause misselection.

    Naming Consistency5/5

    Every tool is snake_case with a leading verb (check_, get_, save_, search_, read_, update_, delete_, record_, reopen_, promote_), which is a fully predictable pattern. Scope is encoded consistently too (project vs global vs dead-end suffixes), so names alone reveal domain and action.

    Tool Count4/5

    15 tools is within a reasonable range for a memory/knowledge server, and each has a stated job. It is slightly heavy because the surface mirrors project tools into global tools (save/search_global_knowledge, promote_to_global) and splits dead-end handling across three dedicated tools, which adds breadth not strictly required.

    Completeness4/5

    Core lifecycle is covered: save, read, update, soft/hard delete, search, status, timeline, plus dead-end tracking and promotion to a global graph. Gaps are minor but present: no delete or read-by-id for global knowledge (only save/search), no bulk export/import or reindex, and no explicit session-boundary tool despite session logs being a first-class concept.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      C
      maintenance
      A local-first MCP server for durable agent memory using SQLite and FTS5, enabling knowledge graph storage, search, and recall for AI agents.
      20
      1
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      Persistent memory MCP server with FTS5 fuzzy search, storing data in SQLite with automatic maintenance and token-efficient TOON output.
      3
      18 npm
      1
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      MCP server for personal and shared memory with full-text search (SQLite FTS5) and outcome tracking, compatible with any MCP agent like Claude Code, Cursor, and Codex CLI.
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      Local MCP server for persistent, searchable agent memory using SQLite FTS5, replacing flat MEMORY.md files with efficient full-text search and workspace context caching.
      GPL 3.0