6. claude-mem 实现
6.1 架构
typescript
// claude-mem: 开源的 Claude Code 记忆系统
class ClaudeMem {
private compressor: MemoryCompressor;
private store: VectorMemoryStore;
private retriever: HybridMemoryRetriever;
// 监听工具调用
async onToolCall(tool: string, input: any, output: any) {
// 1. 判断是否值得记忆
if (!this.shouldRemember(tool, output)) {
return;
}
// 2. 压缩输出
const compressed = await this.compressor.compress(output);
// 3. 生成记忆条目
const memory = {
tool,
input: this.sanitizeInput(input),
output: compressed,
timestamp: new Date(),
context: this.getCurrentContext()
};
// 4. 存储
await this.store.add(
this.formatMemory(memory),
{
tool,
timestamp: memory.timestamp
}
);
}
// 判断是否值得记忆
private shouldRemember(tool: string, output: any): boolean {
// 跳过简单的读操作
if (tool === 'read_file' && output.length < 100) {
return false;
}
// 跳过失败的操作
if (output.error) {
return false;
}
// 记住重要操作
const importantTools = [
'write_file',
'edit_file',
'run_command',
'git_commit'
];
return importantTools.includes(tool);
}
// 检索相关记忆
async recall(query: string): Promise<string> {
const memories = await this.retriever.retrieve(query, 5);
if (memories.length === 0) {
return '';
}
return `
## Relevant Past Experience
${memories.map((m, i) => `
### ${i + 1}. ${m.metadata.topic}
${m.content}
`).join('\n')}
`;
}
}6.2 MCP 集成
typescript
// 作为 MCP Server 运行
class ClaudeMemMCPServer {
private mem: ClaudeMem;
async initialize() {
this.mem = new ClaudeMem();
// 注册工具
this.registerTools([
{
name: 'remember',
description: 'Store information in long-term memory',
inputSchema: {
type: 'object',
properties: {
content: { type: 'string' },
topic: { type: 'string' }
}
},
handler: async (input) => {
await this.mem.store(input.content, input.topic);
return { success: true };
}
},
{
name: 'recall',
description: 'Retrieve relevant information from memory',
inputSchema: {
type: 'object',
properties: {
query: { type: 'string' }
}
},
handler: async (input) => {
const memories = await this.mem.recall(input.query);
return { memories };
}
}
]);
}
// 监听所有工具调用
async onToolExecuted(tool: string, input: any, output: any) {
await this.mem.onToolCall(tool, input, output);
}
}