Skip to main content
Glama

Programming Agent Self-Learning Memory Engine

An MCP (Model Context Protocol)-based self-learning memory engine that provides programming agents with a four-layer closed-loop learning capability: "Perceive-Reflect-Consolidate-Apply". It lets agents learn from mistakes and get better with use.

Architecture Overview

┌──────────────────────────────────────────────────────┐
│                    编程智能体                          │
│  (Claude Code / Cursor / 任何支持 MCP 的智能体)       │
└──────────┬───────────────────────┬────────────────────┘
           │ MCP Protocol          │
    ┌──────▼──────┐         ┌──────▼──────┐
    │  应用层      │         │  感知层      │
    │  检索+注入   │         │  错误捕获    │
    └──────┬──────┘         └──────┬──────┘
           │                       │
    ┌──────▼──────┐         ┌──────▼──────┐
    │  沉淀层      │         │  反思层      │
    │  技能+记忆   │◄────────│  根因分析    │
    └──────┬──────┘         └─────────────┘
           │
    ┌──────▼──────┐
    │  存储层      │
    │  SQLite+FTS5 │
    └─────────────┘

Related MCP server: recall-memory-mcp

Four-Layer Closed Loop

Layer

Responsibility

MCP Tools

Perception Observation

Captures tool execution errors, test failures, user corrections, conversation signals

record_observation, capture_conversation_signals, get_pending_observations

Reflection Reflection

Root cause analysis, extracts reusable experience

get_reflection_prompt, reflect_and_save, batch_get_reflection_prompts

Consolidation Consolidation

Distills skills, generates SKILL.md, maintains memory

create_skill, get_skill_prompt, list_skills, get_skill, check_consolidation

Application Application

Retrieves relevant experience, injects into task context

get_context, search_memory, search_skill

Statistics

Views engine status

get_stats

Installation

# 进入项目目录(替换为你本机的实际路径)
cd memory-engine

# 安装依赖(绕过代理)
pip install --no-proxy -e .

# 或手动安装
pip install --no-proxy mcp[cli] jieba

Configuring the MCP Server

ZCode / Claude Code

Add the following to the MCP configuration file:

{
  "mcpServers": {
    "memory-engine": {
      "command": "python",
      "args": ["-m", "memory_engine.server"],
      "cwd": "<项目根目录的绝对路径>"
    }
  }
}

Replace <absolute path to the project root> with the actual path where this project is cloned/stored on your machine (i.e., the directory containing pyproject.toml), for example D:/tools/memory-engine on Windows, or /home/user/tools/memory-engine on macOS/Linux.

Cursor / VS Code

Add the same configuration in .cursor/mcp.json or the MCP settings in VS Code.

Standalone Run (for debugging)

cd memory-engine
python -m memory_engine.server

Core Workflow

0. Capturing Conversation Signals (Perception Enhancement)

During vibe coding, operators often leave explicit signals in the conversation—emphatic instructions such as "please note" or "please remember"—as well as complaints caused by the agent repeatedly making the same mistakes ("why again...", "how many times have I told you..."). These statements are the highest-value learning material and should be captured and incorporated into memory:

capture_conversation_signals(
  conversation_text="用户: 请注意,bat文件必须用ANSI编码
用户: 怎么又是编码问题,我说过多少次了",
  auto_record=true
)

The detector identifies four types of signals and ranks them by priority:

Signal

Recognition Examples

Meaning

complaint

"why again", "still wrong", "how many times have I said"

Complaints from repeated mistakes, indicating previous lessons were not learned (highest priority)

emphasis

"please note", "please remember", "be sure to", "never"

Rules explicitly emphasized by the user

preference

"always use from now on", "I like", "please default to"

User preferences on how to work

frustration

"speechless", "too slow", "wasting time"

Dissatisfaction, signaling efficiency/experience issues

Detection results are automatically recorded as conversation_signal type observations. During reflection, a specially tailored prompt is used (inferring past mistakes + distilling into imperative rules), and the subsequent flow is identical to error reflection.

1. Recording Errors (Perception)

When a tool execution fails, the agent calls:

record_observation(
  obs_type="tool_error",
  tool_name="Bash",
  error_message="bat文件执行报错:编码错误",
  context="在Windows上创建的bat文件包含中文注释",
  tags="encoding,windows,bat"
)

2. Reflection Analysis (Reflection)

Get the analysis prompt:

get_reflection_prompt(obs_id="abc123")

The agent analyzes the root cause based on the returned prompt, then saves the result:

reflect_and_save(
  obs_id="abc123",
  root_cause="Windows的cmd.exe默认使用系统ANSI编码,UTF-8编码的bat文件会导致中文注释被解析错误",
  category="encoding",
  lesson="在Windows上创建bat文件时,文件必须使用ANSI/GBK编码,而非UTF-8",
  solution="将bat文件保存为ANSI编码,或使用chcp 65001切换代码页",
  tags="encoding,windows,bat,cmd",
  generalizable=true
)

3. Distilling Skills (Consolidation)

After accumulating enough experience, check whether a skill can be distilled:

check_consolidation()

Create the skill:

create_skill(
  name="windows-bat-encoding",
  description="Windows bat文件中文编码问题的处理方法",
  trigger_conditions="创建或编辑.bat文件\n在Windows上运行脚本失败且涉及中文",
  steps="将文件保存为ANSI编码\n或使用chcp 65001 + UTF-8 BOM",
  caveats="chcp 65001仅在当前cmd会话有效\n某些旧版Windows不支持UTF-8 BOM",
  category="encoding"
)

4. Retrieval and Application (Application)

Before starting a new task, retrieve relevant experience:

get_context(task_description="需要创建一个Windows批处理脚本来部署应用")

Returns context containing relevant skills and cases, injected directly into the prompt.

Memory Hierarchy

Type

Description

Example

Episodic Memory

Specific "stories", a complete record of a particular fix

"2024-01-15 fixed the bat encoding issue in project XX"

Semantic Memory

Abstracted rules and lessons

"bat files on Windows should use ANSI encoding"

Skill

Standardized executable operation guide

SKILL.md file

Data Storage

  • SQLite database (data/memories.db): structured storage, supports FTS5 full-text search

  • JSONL log (data/observations.jsonl): append-only log of raw observation records

  • Markdown files (data/skills/): generated skill documents, human-readable and version-controllable

Project Structure

memory-engine/
├── 开发思路.md              # 设计文档
├── README.md                # 本文件
├── pyproject.toml           # Python 项目配置
├── requirements.txt         # 依赖列表
├── config/
│   └── settings.json        # 引擎配置
├── src/memory_engine/
│   ├── __init__.py
│   ├── server.py            # MCP 服务器入口(15个工具)
│   ├── models/
│   │   └── schemas.py       # 数据模型
│   ├── observation/
│   │   ├── collector.py     # 感知层:错误收集器
│   │   └── signal_detector.py # 感知层:对话信号检测器
│   ├── reflection/
│   │   └── analyzer.py      # 反思层:根因分析器
│   ├── consolidation/
│   │   ├── memory_store.py  # 存储层:SQLite + FTS5
│   │   └── skill_generator.py # 沉淀层:技能生成器
│   └── application/
│       └── retriever.py     # 应用层:记忆检索器
├── data/
│   ├── memories.db          # SQLite 数据库(运行后生成)
│   ├── observations.jsonl   # 观察日志(运行后生成)
│   └── skills/              # 技能 Markdown(运行后生成)
└── tests/
    └── test_engine.py       # 测试

Error Categories

encoding | build_error | runtime_error | test_failure | dependency | configuration | platform_specific | performance | security | best_practice | api_usage | preference | communication | other

Design Philosophy

  • No external LLM dependency: reflection and skill distillation are done by the caller (the agent itself); the engine only provides the framework and storage

  • MCP-native: runs as a standard MCP server; any MCP-capable agent can connect directly

  • Human-machine collaboration: all memories and skills are stored in human-readable formats (Markdown, JSON) for easy review and maintenance

  • Progressive learning: from single errors → episodic memory → semantic memory → skills, abstracting layer by layer and refining gradually

Available Tools

15 tools
batch_get_reflection_promptsC

批量获取待反思观察的分析提示词。

Inputs: limit.

capture_conversation_signalsA

分析近期对话文本,捕获用户的显式信号并记录为待反思观察。识别四类信号:complaint(重复犯错的埋怨,如"怎么又"、"我说过多少次")、emphasis(显式强调,如"请注意"、"请记住")、preference(偏好表达,如"以后都用")、frustration(不满情绪)。用户话语包含明显纠正/强调语气时应调用。

Inputs: conversation_text (required), auto_record.

check_consolidationC

检查是否有足够的记忆可以提炼为新技能。

Inputs: category.

create_skillC

从经验中创建一个标准化技能。

Inputs: name (required), steps (required), description (required), trigger_conditions (required), +4 more.

get_contextB

根据任务描述获取相关历史经验和技能。在开始新任务前调用此工具。

Inputs: task_description (required), top_k.

get_pending_observationsC

获取所有待反思的观察记录。定期调用检查是否有未处理的错误需要反思分析。

Inputs: limit.

get_reflection_promptA

获取某条观察记录的反思分析提示词。分析完成后用 reflect_and_save 保存结果。

Inputs: obs_id (required).

get_skillC

获取技能的完整内容(含Markdown)。

Inputs: skill_id (required).

get_skill_promptC

根据记忆ID列表生成技能提炼提示词。

Inputs: memory_ids (required).

get_statsB

获取记忆引擎的统计信息。

Inputs: no named parameters.

list_skillsD

列出已学习的技能。

Inputs: limit, status, category.

record_observationA

记录一次错误观察或用户纠正事件。在工具执行失败、测试未通过、或用户纠正你的操作时调用。

Inputs: obs_type (required), error_message (required), tags, context, +2 more.

reflect_and_saveC

保存对某条观察记录的反思分析结果(根因、教训、方案)。

Inputs: lesson (required), obs_id (required), category (required), solution (required), +3 more.

search_memoryD

搜索历史记忆。

Inputs: query (required), top_k, category.

search_skillC

搜索已学习的技能。

Inputs: query (required), top_k.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    B3.2/5.0

    Scored across 15 tools

    Disambiguation5/5

    每个工具都有明确且独特的用途:记录观察、捕获信号、获取待办、获取反思提示、保存反思、批量获取提示、搜索技能、统计、创建技能、获取技能提示、列出技能、获取技能、检查整合、获取上下文、搜索记忆。即使有相似工具(如get_pending_observations与get_reflection_prompt),它们分别针对观察记录和提示生成,边界清晰。

    Naming Consistency5/5

    所有工具名称均采用小写蛇形命名,且遵循动词_名词模式(如record_observation, search_skill, create_skill)。命名风格统一,没有混合约定,动词选择也符合操作语义。

    Tool Count5/5

    15个工具覆盖了记忆引擎的核心功能:记录、分析、反思、技能管理、上下文检索等,每个工具都有明确的存在价值,没有冗余或重叠。数量在合理范围内(接近上限但仍紧凑)。

    Completeness4/5

    工具表面覆盖了记忆引擎的主要生命周期:观察记录->反思->技能创建->检索。缺少明确的删除/更新操作(如删除记忆或技能),但对于该领域并非核心需求,且其他关键步骤齐全。

    Maintenance

    ActivityStale
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI agents to learn from their work by recording tasks, extracting patterns, detecting mistakes, and proactively surfacing insights, all using the agent's own model through a cooperative intelligence pattern.
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides coding agents with durable, cross-session lessons-learned memory, enforcing that success or failure verdicts can only come from human approval, human correction, or objective metrics—never from the agent itself.
      Apache 2.0
    • F
      license
      Not graded
      quality
      C
      maintenance
      Persistent, self-curating memory for coding agents. It enables local, zero-cost context recall through MCP tools with hybrid retrieval and autonomous consolidation.
      -