agentmemory for OpenClaw 集成实战:为 OpenClaw Agent 接入跨会话持久记忆(MCP 工具 + Memory Slot 插件)
【免费下载链接】agentmemory#1 Persistent memory for AI coding agents based on real-world benchmarks项目地址: https://gitcode.com/GitHub_Trending/age/agentmemory
导读
本文基于 integrations/openclaw/README.md 编写,完整讲解如何将 agentmemory 的持久化记忆能力接入 OpenClaw:既可以走零代码的 MCP 工具通道,一步获得 43 个记忆工具;也可以安装深度插件,让 OpenClaw 通过plugins.slots.memory记忆槽在会话开始前自动召回、会话结束后自动捕获,实现真正的"跨会话记忆,不再重复解释"。读完本文,你将掌握两种集成方式的完整配置、插件钩子(hook)的工作原理、全部配置参数的含义,以及常见故障的排查方法。
一、为什么 OpenClaw 需要持久记忆
OpenClaw 是支持扩展(extension)与插件(plugin)机制的 AI 编码/操作 Agent 宿主。默认情况下,每次会话结束时,Agent 的上下文随之清空——下次会话你需要重新解释项目背景、偏好和之前做过的决策。
agentmemory 的定位正是解决这一痛点:它以本地 REST 服务(默认localhost:3111)的形式提供跨会话、跨 Agent 的持久记忆,并在 LongMemEval-S 上取得 95.2% 的召回准确率(R@5)。与 OpenClaw 集成后,你的 Agent 会在每次任务开始前自动"想起"相关的历史记忆,任务结束后自动把这次对话沉淀为记忆,供后续会话使用。
集成后你还可以与其他 Agent 共享同一套记忆后端——项目主 README.md 中列出的 Claude Code、Codex CLI、Gemini CLI、Hermes、pi、OpenCode 等均可连接同一个 agentmemory 服务。
二、30 秒快速安装:把安装提示词直接交给 OpenClaw
原文档提供了一条"零手工操作"的安装路径:把下面这段提示词粘贴给 OpenClaw,它会替你完成整个配置:
Install agentmemory for OpenClaw. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. For zero-code setup, add this MCP server so OpenClaw gets all 43 memory tools: { "mcpServers": { "agentmemory": { "command": "npx", "args": ["-y", "@agentmemory/mcp"] } } } For deeper memory integration, copy `integrations/openclaw` from the agentmemory repo to `~/.openclaw/extensions/agentmemory`, then enable it in `~/.openclaw/openclaw.json`: { "plugins": { "slots": { "memory": "agentmemory" }, "entries": { "agentmemory": { "enabled": true, "config": { "base_url": "http://localhost:3111", "token_budget": 2000, "min_confidence": 0.5, "fallback_on_error": true, "timeout_ms": 5000 } } } } } Restart OpenClaw. Verify with `curl http://localhost:3111/agentmemory/health`. Open http://localhost:3113 for the real-time viewer.这段提示词实际上描述了三个步骤:启动记忆服务、注册 MCP 工具、安装深度插件。如果你希望手动完成,也可以直接按下面的 Option 1 / Option 2 操作。
提示:主 README 的 集成速查表 中提供了一条等价命令
openclaw plugins install ./integrations/openclaw,它会自动认领 OpenClaw 的 memory 槽位(自动从memory-core切换),并提示需在plugins.entries.agentmemory.hooks.allowConversationAccess=true开启对话捕获权限,否则会话捕获会被静默拦截。
三、Option 1:MCP Server(零代码,推荐快速上手)
3.1 启动 agentmemory 记忆服务
在任何终端启动记忆服务:
npx @agentmemory/agentmemory该命令会在本地启动 REST 服务,默认监听http://localhost:3111(REST 端口;流端口为 3112,实时查看器为 3113,参见 src/cli.ts 中关于端口偏移的说明)。
3.2 在 OpenClaw 的 MCP 配置中注册
{ "mcpServers": { "agentmemory": { "command": "npx", "args": ["-y", "@agentmemory/mcp"] } } }重启 OpenClaw 后,它即可访问全部43 个 MCP 工具,其中核心工具包括:
| 工具名 | 作用 |
|---|---|
memory_recall | 按查询召回历史记忆,支持full/compact/narrative三种格式与token_budget预算控制 |
memory_save | 保存一条记忆,可附带type、concepts、files、project、agentId |
memory_smart_search | 混合检索(向量 + 关键词 + 图/关联扩展),支持expandIds与limit |
memory_timeline | 以某个锚点为中心,返回其前后的记忆时间线 |
memory_profile | 生成/刷新某个项目的 Agent 画像 |
memory_sessions | 列出历史会话 |
memory_export | 导出全部记忆与会话 |
memory_audit | 查询审计日志 |
memory_governance_delete | 按memoryIds批量删除记忆(需提供reason) |
这些工具的入参校验与实现集中在 src/mcp/server.ts:例如memory_recall要求query非空、format仅接受full|compact|narrative、token_budget必须为正整数(src/mcp/server.ts);memory_smart_search将limit钳制在 1~100 之间,expandIds最多取前 20 个(src/mcp/server.ts)。
3.3 底层机制:Proxy 代理与本地降级
从源码看,npx @agentmemory/mcp运行的是独立 MCP 服务器(src/mcp/standalone.ts),它并非一个纯代理:
- 当
localhost:3111的 agentmemory 服务可达时,以proxy 模式运行:本地仅内置memory_save、memory_recall、memory_smart_search、memory_sessions、memory_export、memory_audit、memory_governance_delete这 7 个工具的直接实现(src/mcp/standalone.ts),其余全部通过/agentmemory/mcp/call转发给服务端,从而拿到完整工具面; - 当服务不可达时,自动降级为本地紧凑模式(local fallback),仅提供 7 个工具的子集,并在 stderr 打印提示:
Start 'npx @agentmemory/agentmemory' ... to unlock all tools(src/mcp/standalone.ts)。
因此,务必先启动npx @agentmemory/agentmemory,否则 OpenClaw 只能拿到降级后的 7 个工具。
四、Option 2:OpenClaw 记忆插件(深度集成)
如果希望 OpenClaw 在每个会话开始前自动召回记忆、会话结束后自动捕获记忆(而不仅仅是让 Agent 手动调用工具),就需要安装记忆插件。
4.1 安装步骤
把本仓库的integrations/openclaw目录复制到 OpenClaw 的扩展目录:
mkdir -p ~/.openclaw/extensions cp -r integrations/openclaw ~/.openclaw/extensions/agentmemory然后编辑~/.openclaw/openclaw.json启用插件:
{ "plugins": { "slots": { "memory": "agentmemory" }, "entries": { "agentmemory": { "enabled": true, "config": { "base_url": "http://localhost:3111", "token_budget": 2000, "min_confidence": 0.5, "fallback_on_error": true, "timeout_ms": 5000 } } } } }插件目录中应包含
package.json、openclaw.plugin.json与plugin.mjs三个文件(以及声明插件元数据的plugin.yaml),OpenClaw 校验不通过时插件不会加载(详见后文 Troubleshooting)。
4.2 插件做了什么
原文档总结了插件的三个核心行为,下面结合 integrations/openclaw/plugin.mjs 源码逐条展开:
(1)认领记忆槽位
插件启动时通过api.registerMemoryCapability({ promptBuilder })认领plugins.slots.memory = "agentmemory"槽位,让 OpenClaw 识别它是当前生效的记忆插件(plugin.mjs)。注册的promptBuilder向 OpenClaw 注入一段提示词,声明"长期记忆提供方为 agentmemory(外部 REST 服务)",并提示把召回的上下文当作背景信息而非权威结论。
(2)会话开始前自动召回
通过before_agent_start钩子,在 Agent 启动前用用户的 prompt 作为查询,调用 agentmemory 的/agentmemory/smart-search接口做混合检索,取前 5 条结果并格式化为Relevant long-term memory from agentmemory: ...注入到上下文前缀(plugin.mjs):
api.on("before_agent_start", async (event) => { if (!cfg.enabled) return; const prompt = typeof event?.prompt === "string" ? event.prompt.trim() : ""; if (!prompt) return; const result = await client.postJson("/agentmemory/smart-search", { query: prompt, limit: 5, }); const block = formatResults(result?.results || []); if (!block) return; return { prependContext: `Relevant long-term memory from agentmemory:\n${block}` }; });smart-search的后端实现见 src/functions/smart-search.ts,它综合了混合检索与记忆访问追踪(recordAccessBatch),并受AGENTMEMORY_AGENT_SCOPE等隔离配置影响。
(3)会话结束后自动捕获
通过agent_end钩子,在 Agent 成功结束(event.success)后取出本轮最后一条用户消息与助手回复,调用/agentmemory/observe写入记忆(plugin.mjs):
api.on("agent_end", async (event) => { if (!cfg.enabled || !event?.success || !Array.isArray(event.messages)) return; const userText = latestUserText(event.messages); const assistantText = lastAssistantText(event.messages); if (!userText || !assistantText) return; const sessionId = event.sessionId || event.sessionKey || event.runId || `openclaw-${Date.now()}`; await client.postJson("/agentmemory/observe", { hookType: "post_tool_use", sessionId, timestamp: new Date().toISOString(), data: { tool_name: "conversation", tool_input: userText.slice(0, 1000), tool_output: assistantText.slice(0, 4000), }, }); });可以看到捕获时对用户输入截断为 1000 字符、助手输出截断为 4000 字符,避免超大消息撑爆记忆库。
(4)会话读取权限(关键!)
OpenClaw 出于安全考虑,默认禁止非内置插件读取会话内容。因此必须显式放行,否则agent_end拿不到消息,会话捕获会被静默跳过:
{ "plugins": { "allow": ["agentmemory"], "entries": { "agentmemory": { "hooks": { "allowConversationAccess": true } } } } }主 README 的集成速查表也特别标注了这一点:"setplugins.entries.agentmemory.hooks.allowConversationAccess=trueor turn capture is silently blocked"。
(5)共享同一记忆后端
插件只是 OpenClaw 侧的适配层,记忆数据全部由本地 agentmemory 服务统一存储,因此它与 Claude Code、Codex CLI、Gemini CLI、Hermes、pi 等其他 Agent 共享同一份记忆——在 OpenClaw 里学到的经验,其他 Agent 也能"想起"。
4.3 插件配置文件与参数说明
插件元数据声明在 integrations/openclaw/openclaw.plugin.json(当前版本 0.9.29),configSchema同时出现在 plugin.mjs 中。各参数含义如下:
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
enabled | boolean | true | 是否启用插件;为false时两个钩子直接短路返回 |
base_url | string | http://localhost:3111 | agentmemory REST 服务地址(末尾斜杠会被自动去除) |
token_budget | number | 2000 | 会话开始前注入上下文的近似 token 预算(UI 提示"Approximate context budget to inject before the agent starts") |
min_confidence | number | 0.5 | 记忆召回的最低置信度阈值 |
fallback_on_error | boolean | true | 请求出错时是否静默降级:为true时返回null并打 warn 日志;为false时抛出异常 |
timeout_ms | number | 5000 | 单次 HTTP 请求超时(毫秒),通过AbortSignal.timeout实现 |
从源码看(plugin.mjs),token_budget与min_confidence目前已在注册阶段被读取,但before_agent_start钩子当前以固定limit: 5调用 smart-search,预算/置信度字段更多是为后续语义化注入预留的配置位。
4.4 安全机制:明文 Bearer 认证防护
插件内置了"明文 HTTP + Bearer 令牌"防护逻辑(plugin.mjs):
- 当设置了环境变量
AGENTMEMORY_SECRET,且base_url使用http:协议并指向非回环地址(localhost、127.0.0.1、::1之外)时,会判定为"明文传输敏感信息"; - 此时若环境变量
AGENTMEMORY_REQUIRE_HTTPS=1,则直接抛出异常拒绝启动; - 否则打印警告:
Bearer tokens and memory payloads can be observed on the network; use HTTPS or an SSH tunnel.
也就是说,远程部署时请务必使用 HTTPS 或 SSH 隧道,并配合AGENTMEMORY_SECRET(请求会带上Authorization: Bearer <secret>头,服务端在 src/mcp/server.ts 用常数时间比较校验)。
五、Memory Runtime:当前集成范围与边界
原文档明确说明了当前插件的能力边界,这是理解集成深度的重要信息:
插件目前只注册了一个
promptBuilder,并没有注册完整的MemoryPluginRuntime适配器。OpenClaw 的MemoryRuntimeBackendConfig类型目前只有{ backend: "builtin" }或{ backend: "qmd" }两种取值,二者都是 OpenClaw 内置后端,无法匹配 agentmemory 的外部 REST 形态。
因此,当前的可行集成路径就是文档前面介绍的"钩子驱动"(hook-driven)方案:before_agent_start召回 +agent_end捕获。如果你确实需要基于 agentmemory 使用 OpenClaw 进程内的 memory-runtime API(例如getMemorySearchManager),需要先向 OpenClaw 上游提交需求,请求增加"external"后端类型;一旦契约支持,仓库会在此处补齐runtime适配。
在等待上游支持期间,MCP 工具通道(Option 1)已经能覆盖绝大多数记忆读写、检索、时间线、画像等操作,配合钩子自动召回/捕获,实战中已经足够。
六、验证与故障排查(Troubleshooting)
6.1 安装完成后的验证
# 1) 记忆服务健康检查 curl http://localhost:3111/agentmemory/health # 2) 打开实时查看器,确认观测数据正在被捕获 # 浏览器访问 http://localhost:3113服务端的健康探测逻辑在 src/health/monitor.ts 中,会向 KV 写入并读回_probe记录来确认存储可用。查看器端口 3113 与 REST 端口 3111 的固定偏移关系见 src/cli.ts。
6.2 常见问题排查
插件校验通过但未加载检查扩展目录是否包含package.json、openclaw.plugin.json、plugin.mjs三个文件,并且plugins.slots.memory的值必须是agentmemory。
plugins.slots.memory = "agentmemory"显示unavailable升级到 agentmemory v0.9.11 及以上版本。旧版本插件虽然注册了钩子,但从未调用api.registerMemoryCapability(...),因此记忆槽机制不认为槽位已被认领;当前版本在启动时即注册记忆能力(prompt builder),这是 OpenClaw 文档化地占据槽位的 API。
端口 3111 连接被拒绝(Connection refused)agentmemory 服务没有启动。在独立终端运行npx @agentmemory/agentmemory即可。
没有任何记忆返回打开http://localhost:3113查看器,确认观测数据(observations)是否正在被捕获。常见原因是忘了在openclaw.json中开启plugins.entries.agentmemory.hooks.allowConversationAccess = true,导致agent_end拿不到会话消息、捕获被静默跳过。
MCP 工具只有 7 个npx @agentmemory/mcp在没有服务端时会降级为本地紧凑模式。确认已先启动npx @agentmemory/agentmemory,并将AGENTMEMORY_URL指向它(src/mcp/standalone.ts),即可解锁完整工具面。
七、相关集成参考
agentmemory 除了 OpenClaw,还为其他 Agent 提供了对等集成,可互相参照:
- Hermes 集成
- pi 集成
- agentmemory 主 README(含全部 Agent 的集成速查表与 MCP 配置模板)
所有集成共用同一个 REST 后端与数据目录,因此多 Agent 共用一套记忆是完全可行的部署形态。插件与主项目同属 Apache-2.0 协议。
【免费下载链接】agentmemory#1 Persistent memory for AI coding agents based on real-world benchmarks项目地址: https://gitcode.com/GitHub_Trending/age/agentmemory
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考