{
  "canonical_name": "Rumblingb/agent-memory-mcp",
  "compilation_id": "pack_7b4a1e00d30c425fba206c2830e0ccaa",
  "created_at": "2026-05-24T13:33:30.921975+00:00",
  "created_by": "project-pack-compiler",
  "feedback": {
    "carrier_selection_notes": [
      "viable_asset_types=mcp_config, recipe, host_instruction, eval, preflight",
      "recommended_asset_types=mcp_config, recipe, host_instruction, eval, preflight"
    ],
    "evidence_delta": {
      "confirmed_claims": [
        "identity_anchor_present",
        "capability_and_host_targets_present",
        "install_path_declared_or_better"
      ],
      "missing_required_fields": [],
      "must_verify_forwarded": [
        "Run or inspect `pip install mcp` in an isolated environment.",
        "Confirm the project exposes the claimed capability to at least one target host."
      ],
      "quickstart_execution_scope": "allowlisted_sandbox_smoke",
      "sandbox_command": "pip install mcp",
      "sandbox_container_image": "python:3.12-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "llm_execute_isolated_install",
      "sandbox_validation_id": "sbx_866de3c86e604e87886b6109f0d01aa1"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_4b441f8b15d440b26bfe53b2e92c741a",
    "canonical_name": "Rumblingb/agent-memory-mcp",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/Rumblingb/agent-memory-mcp",
    "slug": "agent-memory-mcp",
    "source_packet_id": "phit_9bf0c6cf00994e4f8051c8066f2130bf",
    "source_validation_id": "dval_040c2cda697b48e08165081bce8e4198"
  },
  "merchandising": {
    "best_for": "需要工具连接与集成能力，并使用 mcp_host的用户",
    "github_forks": 0,
    "github_stars": 0,
    "one_liner_en": "MCP server providing persistent key-value memory for AI agents with TTL and search",
    "one_liner_zh": "MCP server providing persistent key-value memory for AI agents with TTL and search",
    "primary_category": {
      "category_id": "tool-integrations",
      "confidence": "high",
      "name_en": "Tool Integrations",
      "name_zh": "工具连接与集成",
      "reason": "matched_keywords:mcp, server, github"
    },
    "target_user": "使用 mcp_host 等宿主 AI 的用户",
    "title_en": "agent-memory-mcp",
    "title_zh": "agent-memory-mcp 能力包",
    "visible_tags": [
      {
        "label_en": "MCP Tools",
        "label_zh": "MCP 工具",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-mcp-tools",
        "type": "product_domain"
      },
      {
        "label_en": "Knowledge Base Q&A",
        "label_zh": "知识库问答",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "user_job-knowledge-base-q-a",
        "type": "user_job"
      },
      {
        "label_en": "Multi-agent Collaboration",
        "label_zh": "多 Agent 协作",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-multi-agent-collaboration",
        "type": "core_capability"
      },
      {
        "label_en": "Multi-role Workflow",
        "label_zh": "多角色协作流程",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-multi-role-workflow",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Evaluation Suite",
        "label_zh": "评测体系",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-evaluation-suite",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_9bf0c6cf00994e4f8051c8066f2130bf",
  "page_model": {
    "artifacts": {
      "artifact_slug": "agent-memory-mcp",
      "files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json",
        "REPO_INSPECTION.md",
        "CAPABILITY_CONTRACT.json",
        "EVIDENCE_INDEX.json",
        "CLAIM_GRAPH.json"
      ],
      "required_files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json"
      ]
    },
    "detail": {
      "capability_source": "Project Hit Packet + DownstreamValidationResult",
      "commands": [
        {
          "command": "pip install mcp",
          "label": "Python / pip · 官方安装入口",
          "source": "https://github.com/Rumblingb/agent-memory-mcp#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "MCP 工具",
        "知识库问答",
        "多 Agent 协作",
        "多角色协作流程",
        "评测体系"
      ],
      "eyebrow": "工具连接与集成",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要工具连接与集成能力，并使用 mcp_host的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "MCP server providing persistent key-value memory for AI agents with TTL and search"
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "mcp_host",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "mcp_config, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "仓库名 `agent-memory-mcp` 与安装入口 `mcp` 不完全一致。",
            "category": "身份坑",
            "evidence": [
              "identity.distribution | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | repo=agent-memory-mcp; install=mcp"
            ],
            "severity": "medium",
            "suggested_check": "在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。",
            "title": "仓库名和安装名不一致",
            "user_impact": "用户照着仓库名搜索包或照着包名找仓库时容易走错入口。"
          },
          {
            "body": "README/documentation is current enough for a first validation pass.",
            "category": "能力坑",
            "evidence": [
              "capability.assumptions | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | README/documentation is current enough for a first validation pass."
            ],
            "severity": "medium",
            "suggested_check": "将假设转成下游验证清单。",
            "title": "能力判断依赖假设",
            "user_impact": "假设不成立时，用户拿不到承诺的能力。"
          },
          {
            "body": "未记录 last_activity_observed。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | last_activity_observed missing"
            ],
            "severity": "medium",
            "suggested_check": "补 GitHub 最近 commit、release、issue/PR 响应信号。",
            "title": "维护活跃度未知",
            "user_impact": "新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "downstream_validation.risk_items | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "进入安全/权限治理复核队列。",
            "title": "下游验证发现风险项",
            "user_impact": "下游已经要求复核，不能在页面中弱化。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "risks.scoring_risks | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "把风险写入边界卡，并确认是否需要人工复核。",
            "title": "存在评分风险",
            "user_impact": "风险会影响是否适合普通用户安装。"
          },
          {
            "body": "issue_or_pr_quality=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | issue_or_pr_quality=unknown"
            ],
            "severity": "low",
            "suggested_check": "抽样最近 issue/PR，判断是否长期无人处理。",
            "title": "issue/PR 响应质量未知",
            "user_impact": "用户无法判断遇到问题后是否有人维护。"
          },
          {
            "body": "release_recency=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | release_recency=unknown"
            ],
            "severity": "low",
            "suggested_check": "确认最近 release/tag 和 README 安装命令是否一致。",
            "title": "发布节奏不明确",
            "user_impact": "安装命令和文档可能落后于代码，用户踩坑概率升高。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：身份坑 - 仓库名和安装名不一致。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 1,
        "forks": 0,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 0
      },
      "source_url": "https://github.com/Rumblingb/agent-memory-mcp",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "MCP server providing persistent key-value memory for AI agents with TTL and search",
      "title": "agent-memory-mcp 能力包",
      "trial_prompt": "# agent-memory-mcp - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for Rumblingb/agent-memory-mcp.\n\nProject:\n- Name: agent-memory-mcp\n- Repository: https://github.com/Rumblingb/agent-memory-mcp\n- Summary: MCP server providing persistent key-value memory for AI agents with TTL and search\n- Host target: mcp_host\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: MCP server providing persistent key-value memory for AI agents with TTL and search\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCapabilities that require post-install verification:\n- Runtime installation or host integration must be verified after installation.\n\nCore service flow:\n1. overview: Overview. Produce one small intermediate artifact and wait for confirmation.\n2. quick-start: Quick Start Guide. Produce one small intermediate artifact and wait for confirmation.\n3. namespaces: Namespaces. Produce one small intermediate artifact and wait for confirmation.\n4. ttl-management: TTL Management. Produce one small intermediate artifact and wait for confirmation.\n5. memory-remember: memory_remember Tool. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/Rumblingb/agent-memory-mcp\n- https://github.com/Rumblingb/agent-memory-mcp#readme\n- README.md\n- LICENSE\n- glama.json\n- .gitignore\n- .nojekyll\n- server.py\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "voices": [
        {
          "body": "当前没有项目级社区来源；不会把未抓取讨论包装成社会证明。",
          "items": [],
          "status": "待发现 Agent 补证",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "工具连接与集成",
      "desc": "MCP server providing persistent key-value memory for AI agents with TTL and search",
      "effort": "安装已验证",
      "forks": 0,
      "icon": "link",
      "name": "agent-memory-mcp 能力包",
      "risk": "需复核",
      "slug": "agent-memory-mcp",
      "stars": 0,
      "tags": [
        "MCP 工具",
        "知识库问答",
        "多 Agent 协作",
        "多角色协作流程",
        "评测体系"
      ],
      "thumb": "gray",
      "type": "MCP 配置"
    },
    "manual": {
      "markdown": "# https://github.com/Rumblingb/agent-memory-mcp 项目说明书\n\n生成时间：2026-05-15 22:52:32 UTC\n\n## 目录\n\n- [Overview](#overview)\n- [Installation](#installation)\n- [Quick Start Guide](#quick-start)\n- [Namespaces](#namespaces)\n- [TTL Management](#ttl-management)\n- [Data Storage](#data-storage)\n- [memory_remember Tool](#memory-remember)\n- [memory_recall Tool](#memory-recall)\n- [memory_forget Tool](#memory-forget)\n- [memory_search Tool](#memory-search)\n\n<a id='overview'></a>\n\n## Overview\n\n### 相关页面\n\n相关主题：[Installation](#installation), [Quick Start Guide](#quick-start)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/Rumblingb/agent-memory-mcp/blob/main/README.md)\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n- [requirements.txt](https://github.com/Rumblingb/agent-memory-mcp/blob/main/requirements.txt)\n- [smithery.yaml](https://github.com/Rumblingb/agent-memory-mcp/blob/main/smithery.yaml)\n- [glama.json](https://github.com/Rumblingb/agent-memory-mcp/blob/main/glama.json)\n- [index.html](https://github.com/Rumblingb/agent-memory-mcp/blob/main/index.html)\n</details>\n\n# Overview\n\nAgent Memory MCP is a persistent key-value memory store designed specifically for AI agents. It solves the fundamental problem of context loss between sessions by providing a durable, searchable storage layer that survives restarts, crashes, and context-window limitations.\n\n## Purpose and Scope\n\nAI agents typically lose all context between sessions. Every conversation starts from zero, requiring users to re-explain preferences, history, and requirements repeatedly. Agent Memory MCP addresses this by implementing a persistent memory system with the following capabilities:\n\n- **Persistent Storage**: Data survives agent restarts and system reboots\n- **TTL Support**: Auto-expiring memories with second-level precision\n- **Namespace Isolation**: Organize memories by project, user, or domain\n- **Fuzzy Search**: Case-insensitive keyword search across all namespaces\n- **Access Tracking**: Monitor memory usage patterns and entry activity\n\n资料来源：[README.md](https://github.com/Rumblingb/agent-memory-mcp/blob/main/README.md)\n\n## Architecture\n\nAgent Memory MCP is built on the Model Context Protocol (MCP) Python SDK and operates as a stdio-based server. The architecture follows a simple but effective layered design:\n\n```mermaid\ngraph TD\n    subgraph \"Client Layer\"\n        A[AI Agent / Claude Desktop]\n    end\n    \n    subgraph \"MCP Protocol Layer\"\n        B[MCP Server]\n    end\n    \n    subgraph \"Storage Layer\"\n        C[~/.agent-memory/]\n        D[namespace1.json]\n        E[namespace2.json]\n        F[_meta.json]\n    end\n    \n    A -->|MCP Protocol| B\n    B -->|Read/Write| C\n    C --> D\n    C --> E\n    C --> F\n```\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Storage Model\n\nThe system stores data as JSON files in `~/.agent-memory/`, with one file per namespace plus a metadata file:\n\n| File Pattern | Purpose |\n|--------------|---------|\n| `{namespace}.json` | Key-value entries for a specific namespace |\n| `_meta.json` | Global statistics and metadata |\n\nNamespace filenames are sanitized to prevent directory traversal attacks. Characters outside `[a-zA-Z0-9_.-]` are replaced with underscores.\n\n资料来源：[server.py:42-49](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Core Components\n\n### Tool Handlers\n\nThe MCP server exposes seven tools for memory management:\n\n| Tool | Description | Read-Only | Destructive |\n|------|-------------|-----------|-------------|\n| `memory_remember` | Store a value with optional TTL | No | No |\n| `memory_recall` | Retrieve a value + metadata | Yes | No |\n| `memory_forget` | Delete a key permanently | No | Yes |\n| `memory_search` | Search all namespaces by keyword | Yes | No |\n| `memory_list_namespaces` | List namespaces with counts | Yes | No |\n| `memory_clear_namespace` | Wipe a namespace | No | Yes |\n| `memory_stats` | Global storage statistics | Yes | No |\n\n资料来源：[server.py:206-298](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Memory Entry Schema\n\nEach memory entry contains the following fields:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `key` | string | Unique identifier within namespace |\n| `value` | string | Stored content (max ~25,000 characters) |\n| `namespace` | string | Storage partition identifier |\n| `created_at` | ISO timestamp | Creation timestamp |\n| `accessed_at` | ISO timestamp | Last access timestamp |\n| `expires_at` | ISO timestamp or null | TTL expiration time |\n| `access_count` | integer | Number of times accessed |\n\n资料来源：[server.py:350-358](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Concurrency and Safety\n\nThe system implements POSIX file locking via `fcntl.flock` to ensure thread-safe concurrent access from multiple agents:\n\n```python\n@contextmanager\ndef _locked_file(path: Path, mode: str = \"r+\"):\n    fh = open(path, mode)\n    try:\n        fcntl.flock(fh, fcntl.LOCK_EX)\n        yield fh\n    finally:\n        fcntl.flock(fh, fcntl.LOCK_UN)\n        fh.close()\n```\n\nThe lock gracefully degrades on platforms without `fcntl` support (e.g., Windows without WSL).\n\n资料来源：[server.py:67-83](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Tier System\n\n| Tier | Entries | Price | Features |\n|------|---------|-------|----------|\n| Free | 1,000 | Free | All 7 tools |\n| Pro | Unlimited | $19/month | Unlimited storage |\n\n资料来源：[smithery.yaml](https://github.com/Rumblingb/agent-memory-mcp/blob/main/smithery.yaml)\n\n## Installation\n\n```bash\npip install agent-memory-mcp\n```\n\n**Requirements:**\n\n- Python 3.10+\n- `mcp >= 1.0.0`\n\n资料来源：[requirements.txt](https://github.com/Rumblingb/agent-memory-mcp/blob/main/requirements.txt)\n\n## Entry Point\n\nThe server runs as an async stdio server:\n\n```python\nasync def main() -> None:\n    _ensure_storage()\n    async with stdio_server() as (read_stream, write_stream):\n        await server.run(\n            read_stream,\n            write_stream,\n            server.create_initialization_options(),\n        )\n```\n\n资料来源：[server.py:318-326](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## License and Attribution\n\n| Attribute | Value |\n|-----------|-------|\n| License | MIT |\n| Author | Nous Research |\n| Repository | [github.com/nousresearch/agent-memory-mcp](https://github.com/nousresearch/agent-memory-mcp) |\n\n资料来源：[README.md](https://github.com/Rumblingb/agent-memory-mcp/blob/main/README.md)\n\n---\n\n<a id='installation'></a>\n\n## Installation\n\n### 相关页面\n\n相关主题：[Overview](#overview), [Quick Start Guide](#quick-start)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n- [requirements.txt](https://github.com/Rumblingb/agent-memory-mcp/blob/main/requirements.txt)\n- [smithery.yaml](https://github.com/Rumblingb/agent-memory-mcp/blob/main/smithery.yaml)\n- [README.md](https://github.com/Rumblingb/agent-memory-mcp/blob/main/README.md)\n- [index.html](https://github.com/Rumblingb/agent-memory-mcp/blob/main/index.html)\n- [glama.json](https://github.com/Rumblingb/agent-memory-mcp/blob/main/glama.json)\n</details>\n\n# Installation\n\nThis guide covers all methods for installing and configuring the **Agent Memory MCP** server. The server provides persistent key-value memory storage for AI agents with TTL support, namespaces, fuzzy search, and access tracking.\n\n## Prerequisites\n\nBefore installing Agent Memory MCP, ensure your environment meets the following requirements:\n\n| Requirement | Version | Notes |\n|-------------|---------|-------|\n| Python | 3.10+ | Core runtime requirement |\n| pip | Latest | For package installation |\n| POSIX-compatible OS | Linux/macOS | Required for file locking via `fcntl` |\n| MCP Client | Compatible version | Any MCP 1.0.0+ compatible client |\n\n### System Dependencies\n\nThe server relies on POSIX file locking (`fcntl`) for thread-safe concurrent access:\n\n```python\n# From server.py:34-41\ntry:\n    fcntl.flock(fh, fcntl.LOCK_EX)\nexcept (NameError, OSError):\n    pass  # platform without fcntl support\n```\n\nOn Windows without WSL, file locking falls back gracefully as a no-op.\n\n资料来源：[server.py:34-41]()\n\n## Installation Methods\n\n### Method 1: pip (Recommended)\n\nThe simplest installation method uses pip directly from PyPI:\n\n```bash\npip install agent-memory-mcp\n```\n\nThis command installs the package and its dependencies, including the MCP SDK.\n\n资料来源：[index.html:1]()\n\n### Method 2: From Source\n\nTo install the latest development version from the repository:\n\n```bash\n# Clone the repository\ngit clone https://github.com/nousresearch/agent-memory-mcp.git\ncd agent-memory-mcp\n\n# Install in development mode\npip install -e .\n\n# Or install production dependencies\npip install -r requirements.txt\n```\n\n### Method 3: Using Smithery.ai\n\nFor deployment via Smithery.ai marketplace, the server is pre-configured:\n\n```yaml\n# From smithery.yaml\nruntime:\n  type: python\n  entrypoint: server.py\n  requirements: requirements.txt\n```\n\n资料来源：[smithery.yaml:1-6]()\n\n## Dependencies\n\nAgent Memory MCP has a minimal dependency footprint:\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| mcp | ≥1.0.0 | Model Context Protocol SDK |\n\n资料来源：[requirements.txt:1]()\n\nThe MCP SDK provides:\n\n- Server implementation via `mcp.server.Server`\n- Stdio transport via `mcp.server.stdio.stdio_server`\n- Tool definitions via `mcp.types`\n\n资料来源：[server.py:17-25]()\n\n## Server Entry Point\n\nAfter installation, the server can be run directly:\n\n```bash\npython server.py\n```\n\nThe server uses stdio transport for communication with MCP clients:\n\n```python\n# From server.py:267-272\nasync def main() -> None:\n    _ensure_storage()\n    async with stdio_server() as (read_stream, write_stream):\n        await server.run(\n            read_stream,\n            write_stream,\n            server.create_initialization_options(),\n        )\n```\n\n资料来源：[server.py:267-272]()\n\n## Storage Initialization\n\nOn first run, the server automatically creates the storage directory:\n\n```python\n# From server.py:47-49\ndef _ensure_storage() -> None:\n    \"\"\"Create the storage directory if it doesn't exist.\"\"\"\n    STORAGE_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nThe default storage location is `~/.agent-memory/`:\n\n```python\n# From server.py:38\nSTORAGE_DIR = Path.home() / \".agent-memory\"\n```\n\n资料来源：[server.py:38,47-49]()\n\n### Storage Structure\n\nThe storage directory contains one JSON file per namespace plus a metadata file:\n\n```\n~/.agent-memory/\n├── default.json          # Default namespace\n├── project_a.json        # Custom namespace\n├── user_prefs.json       # Another namespace\n└── _meta.json            # Global metadata\n```\n\n## Configuration Options\n\n### Environment Variables\n\nThe server supports runtime configuration via environment variables:\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `AGENT_MEMORY_PATH` | `~/.agent-memory/` | Custom storage directory path |\n\n### Server Configuration\n\nThe MCP server is configured with metadata:\n\n```python\n# From server.py:238-242\nserver = Server(\n    name=\"agent-memory\",\n    version=\"1.0.0\",\n    instructions=\"Agent Memory MCP — Persistent key-value memory for AI agents with TTL, namespaces, and search.\",\n    website_url=\"https://github.com/nousresearch/agent-memory-mcp\",\n)\n```\n\n资料来源：[server.py:238-242]()\n\n## MCP Client Integration\n\n### Registering the Server\n\nConfigure your MCP client to use the Agent Memory server:\n\n#### For Claude Desktop\n\nAdd to your configuration file:\n\n```json\n{\n  \"mcpServers\": {\n    \"agent-memory\": {\n      \"command\": \"python\",\n      \"args\": [\"-m\", \"agent_memory_mcp\"]\n    }\n  }\n}\n```\n\n#### For Smithery.ai\n\nThe server is automatically available through the Smithery marketplace configuration:\n\n```yaml\n# From smithery.yaml\ncapabilities:\n  tools:\n    - memory_remember\n    - memory_recall\n    - memory_forget\n    - memory_search\n    - memory_list_namespaces\n    - memory_clear_namespace\n    - memory_stats\n```\n\n资料来源：[smithery.yaml:8-15]()\n\n## Available Tools\n\nOnce installed, the following tools are available:\n\n| Tool | Description |\n|------|-------------|\n| `memory_remember` | Store a value with optional TTL |\n| `memory_recall` | Retrieve a value + metadata |\n| `memory_forget` | Delete a key permanently |\n| `memory_search` | Search all namespaces by keyword |\n| `memory_list_namespaces` | List namespaces with counts |\n| `memory_clear_namespace` | Wipe a namespace |\n| `memory_stats` | Global storage statistics |\n\n资料来源：[index.html:1]()\n\n## Verification\n\nVerify the installation by checking the server version:\n\n```bash\npython server.py --version\n```\n\nOr by calling the `memory_stats` tool:\n\n```json\n{\n  \"name\": \"memory_stats\",\n  \"arguments\": {\n    \"format\": \"json\"\n  }\n}\n```\n\nExpected response:\n\n```json\n{\n  \"total_entries\": 0,\n  \"total_size_bytes\": 0,\n  \"namespace_count\": 0,\n  \"storage_path\": \"/home/user/.agent-memory\",\n  \"free_tier_limit\": 1000,\n  \"pro_tier_limit\": \"unlimited\"\n}\n```\n\n## Deployment Architecture\n\n```mermaid\ngraph TD\n    A[MCP Client] -->|stdio| B[Agent Memory MCP Server]\n    B -->|fcntl lock| C[Storage Directory]\n    C -->|JSON per NS| D[default.json]\n    C -->|JSON per NS| E[custom.json]\n    C -->|Metadata| F[_meta.json]\n    \n    G[Python Runtime] -->|mcp≥1.0.0| B\n```\n\n## Licensing\n\nAgent Memory MCP is distributed under the MIT License:\n\n资料来源：[README.md:1]()\n\n| Item | Value |\n|------|-------|\n| License | MIT |\n| Version | 1.0.0 |\n| Author | Nous Research |\n\n资料来源：[smithery.yaml:17-21]()\n资料来源：[glama.json:1-4]()\n\n## Troubleshooting\n\n### Windows without WSL\n\nOn Windows without WSL, file locking is disabled but the server remains functional. For production use on Windows, run via WSL.\n\n### Permission Errors\n\nEnsure the user running the server has write access to `~/.agent-memory/`:\n\n```bash\nmkdir -p ~/.agent-memory\nchmod 755 ~/.agent-memory\n```\n\n### MCP Connection Issues\n\nVerify the MCP SDK is properly installed:\n\n```bash\npython -c \"from mcp.server import Server; print('MCP SDK OK')\"\n\n---\n\n<a id='quick-start'></a>\n\n## Quick Start Guide\n\n### 相关页面\n\n相关主题：[Overview](#overview), [Installation](#installation), [memory_remember Tool](#memory-remember), [memory_recall Tool](#memory-recall)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n- [requirements.txt](https://github.com/Rumblingb/agent-memory-mcp/blob/main/requirements.txt)\n- [smithery.yaml](https://github.com/Rumblingb/agent-memory-mcp/blob/main/smithery.yaml)\n</details>\n\n# Quick Start Guide\n\n## Overview\n\nThe **Agent Memory MCP** server provides a persistent key-value memory system for AI agents. It enables agents to retain context across sessions, solve context-window limitations, and maintain searchable long-term memory. This guide walks you through installation, configuration, and usage of all available tools.\n\n## System Architecture\n\n```mermaid\ngraph TD\n    A[AI Agent] -->|MCP Protocol| B[Agent Memory MCP Server]\n    B --> C[~/.agent-memory/]\n    C --> D[namespace1.json]\n    C --> E[namespace2.json]\n    C --> F[_meta.json]\n    \n    G[memory_remember] -->|Store| C\n    H[memory_recall] -->|Retrieve| C\n    I[memory_search] -->|Query| C\n    J[memory_forget] -->|Delete| C\n```\n\n## Installation\n\n### Prerequisites\n\n| Requirement | Version |\n|-------------|---------|\n| Python | 3.10+ |\n| MCP SDK | ≥1.0.0 |\n\n### Install via pip\n\n```bash\npip install agent-memory-mcp\n```\n\n资料来源：[requirements.txt:1]()\n\n### Verify Installation\n\nAfter installation, the server runs as a stdio-based MCP server. No additional daemon setup is required.\n\n## Core Concepts\n\n### Namespaces\n\nNamespaces provide isolated storage compartments for organizing memories by project, user, or domain. Each namespace stores entries as a separate JSON file in `~/.agent-memory/`.\n\n| Default Namespace | Purpose |\n|-------------------|---------|\n| `default` | General-purpose storage when no namespace is specified |\n\n资料来源：[server.py:44]()\n\n### Entry Structure\n\nEach memory entry contains:\n\n```json\n{\n  \"key\": \"unique_identifier\",\n  \"value\": \"stored_content\",\n  \"created_at\": \"2024-01-01T00:00:00.000Z\",\n  \"accessed_at\": \"2024-01-01T00:00:00.000Z\",\n  \"expires_at\": null,\n  \"access_count\": 0\n}\n```\n\n### TTL (Time-To-Live)\n\nEntries can auto-expire after a specified duration. TTL is set in seconds with second-level precision using lazy expiry—the entry is removed on the next access after expiration.\n\n资料来源：[server.py:200-215]()\n\n### Thread Safety\n\nThe server uses POSIX file locking (`fcntl`) to ensure safe concurrent access from multiple agents.\n\n资料来源：[index.html]()\n\n## Available Tools\n\n| Tool | Purpose | Destructive | Read-Only |\n|------|---------|-------------|-----------|\n| `memory_remember` | Store a value | No | No |\n| `memory_recall` | Retrieve a value | No | Yes |\n| `memory_forget` | Delete a key | Yes | No |\n| `memory_search` | Search by keyword | No | Yes |\n| `memory_list_namespaces` | List all namespaces | No | Yes |\n| `memory_clear_namespace` | Wipe a namespace | Yes | No |\n| `memory_stats` | Get storage statistics | No | Yes |\n\n## Usage Examples\n\n### 1. Store a Memory\n\n**Tool:** `memory_remember`\n\nStore a value under a key in a persistent namespace:\n\n```json\n{\n  \"key\": \"user_preferences\",\n  \"value\": \"dark_mode_enabled: true, language: en\",\n  \"namespace\": \"settings\",\n  \"ttl_seconds\": 86400\n}\n```\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `key` | string | Yes | Unique identifier for this memory entry |\n| `value` | string | Yes | Content to store |\n| `namespace` | string | No | Namespace name (default: `default`) |\n| `ttl_seconds` | integer | No | Auto-expiry duration in seconds |\n| `format` | string | No | `markdown` or `json` (default: `markdown`) |\n\n资料来源：[server.py:130-175]()\n\n**Success Response:**\n\n```markdown\n## ✅ Success\n\n**message:** Stored 'user_preferences' in namespace 'settings'\n**key:** user_preferences\n**namespace:** settings\n**expires_in:** 86400s\n**expires_at:** 2024-01-02T00:00:00.000Z\n```\n\n### 2. Retrieve a Memory\n\n**Tool:** `memory_recall`\n\nFetch a stored value by key from a namespace:\n\n```json\n{\n  \"key\": \"user_preferences\",\n  \"namespace\": \"settings\"\n}\n```\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `key` | string | Yes | The key to retrieve |\n| `namespace` | string | No | Namespace to look in (default: `default`) |\n| `format` | string | No | `markdown` or `json` (default: `markdown`) |\n\n资料来源：[server.py:177-220]()\n\n**Response includes:**\n\n- Current value\n- Creation timestamp\n- Last access timestamp\n- Access count\n- Expiry status\n\n### 3. Delete a Memory\n\n**Tool:** `memory_forget`\n\nPermanently delete a specific key:\n\n```json\n{\n  \"key\": \"user_preferences\",\n  \"namespace\": \"settings\"\n}\n```\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `key` | string | Yes | The key to delete |\n| `namespace` | string | No | Namespace to delete from (default: `default`) |\n| `format` | string | No | `markdown` or `json` (default: `markdown`) |\n\n资料来源：[server.py:222-258]()\n\n### 4. Search Memories\n\n**Tool:** `memory_search`\n\nFind memories across namespaces by keyword (case-insensitive substring match):\n\n```json\n{\n  \"query\": \"preferences\",\n  \"namespace\": null,\n  \"limit\": 10\n}\n```\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `query` | string | Yes | Search keyword or substring |\n| `namespace` | string | No | Limit search to specific namespace |\n| `limit` | integer | No | Maximum results (default: 10) |\n| `format` | string | No | `markdown` or `json` (default: `markdown`) |\n\nSearch matches against both keys and values. Results are sorted by access count (highest first).\n\n资料来源：[server.py:260-320]()\n\n### 5. List All Namespaces\n\n**Tool:** `memory_list_namespaces`\n\nDisplay all namespaces with entry counts:\n\n```json\n{\n  \"format\": \"markdown\"\n}\n```\n\n**Response:**\n\n```markdown\n## ✅ Success\n\n**namespace_count:** 3\n**namespaces:** [3 items]\n  - **namespace:** project_a\n    - **active_entries:** 15\n    - **expired_entries:** 2\n  - **namespace:** project_b\n    - **active_entries:** 8\n    - **expired_entries:** 0\n  - **namespace:** default\n    - **active_entries:** 42\n    - **expired_entries:** 5\n```\n\n资料来源：[server.py:322-360]()\n\n### 6. Clear a Namespace\n\n**Tool:** `memory_clear_namespace`\n\nDelete ALL entries in a namespace permanently:\n\n```json\n{\n  \"namespace\": \"project_a\"\n}\n```\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `namespace` | string | Yes | Namespace to clear |\n\n**Warning:** This action cannot be undone.\n\n资料来源：[server.py:362-395]()\n\n### 7. View Storage Statistics\n\n**Tool:** `memory_stats`\n\nGet comprehensive storage metrics:\n\n```json\n{\n  \"format\": \"markdown\"\n}\n```\n\n**Response includes:**\n\n| Metric | Description |\n|--------|-------------|\n| `total_entries` | Total active memory entries |\n| `total_size_bytes` | Storage size in bytes |\n| `total_size_human` | Human-readable size |\n| `namespace_count` | Number of namespaces |\n| `oldest_entry` | Timestamp of oldest entry |\n| `newest_entry` | Timestamp of newest entry |\n| `storage_path` | Directory path (`~/.agent-memory/`) |\n| `free_tier_limit` | Free tier entry limit (1000) |\n\n资料来源：[server.py:397-440]()\n\n## Storage Layout\n\n```\n~/.agent-memory/\n├── _meta.json           # Global metadata\n├── default.json         # Default namespace\n├── project_a.json       # Custom namespace\n├── project_b.json       # Custom namespace\n└── ...\n```\n\nEach namespace file is a JSON array of entries:\n\n```json\n[\n  {\n    \"key\": \"example_key\",\n    \"value\": \"example_value\",\n    \"created_at\": \"2024-01-01T00:00:00.000Z\",\n    \"accessed_at\": \"2024-01-01T00:00:00.000Z\",\n    \"expires_at\": null,\n    \"access_count\": 5\n  }\n]\n```\n\n资料来源：[server.py:50-75]()\n\n## Response Formats\n\nAll tools support two response formats:\n\n| Format | Use Case |\n|--------|----------|\n| `markdown` | Human-readable output (default) |\n| `json` | Programmatic parsing |\n\nSpecify format via the `format` parameter in each tool call.\n\n## Workflow Diagram\n\n```mermaid\ngraph LR\n    A[Start] --> B{memory_remember?}\n    B -->|Yes| C[Store Entry]\n    B -->|No| D{memory_recall?}\n    D -->|Yes| E[Retrieve + Update Access]\n    D -->|No| F{memory_forget?}\n    F -->|Yes| G[Delete Entry]\n    F -->|No| H{memory_search?}\n    H -->|Yes| I[Search All Namespaces]\n    H -->|No| J{memory_list_namespaces?}\n    J -->|Yes| K[List with Counts]\n    J -->|No| L{memory_clear_namespace?}\n    L -->|Yes| M[Delete All in Namespace]\n    L -->|No| N{memory_stats?}\n    N -->|Yes| O[Return Statistics]\n    \n    C --> P[Success]\n    E --> P\n    G --> P\n    I --> P\n    K --> P\n    M --> P\n    O --> P\n```\n\n## Common Use Cases\n\n### Session Persistence\n\n```python\n# Remember conversation context\nmemory_remember(\n    key=\"session_123_context\",\n    value=\"User prefers technical explanations\",\n    namespace=\"sessions\"\n)\n\n# Recall on next session\ncontext = memory_recall(\n    key=\"session_123_context\",\n    namespace=\"sessions\"\n)\n```\n\n### Project-Scoped Memory\n\n```python\n# Store project-specific data\nmemory_remember(\n    key=\"api_endpoints\",\n    value=\"https://api.example.com/v1\",\n    namespace=\"project_alpha\"\n)\n\n# Search across all projects\nresults = memory_search(query=\"api_endpoints\")\n```\n\n### Temporary Caching with TTL\n\n```python\n# Cache with 1-hour expiry\nmemory_remember(\n    key=\"rate_limit_status\",\n    value=\"{'requests': 450, 'limit': 500}\",\n    namespace=\"cache\",\n    ttl_seconds=3600\n)\n```\n\n## Error Handling\n\n| Error Condition | Response |\n|-----------------|----------|\n| Empty key | `Key must not be empty` |\n| Expired entry | `Key 'X' has expired` |\n| Key not found | `Key 'X' not found in namespace 'Y'` |\n| Internal error | `Internal error in {tool}: {exception}` |\n\nAll errors return a response with `isError: true`.\n\n资料来源：[server.py:95-105]()\n\n## Configuration Options\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `STORAGE_DIR` | `~/.agent-memory/` | Storage directory location |\n| `DEFAULT_NAMESPACE` | `default` | Fallback namespace |\n| `CHARACTER_LIMIT` | 25,000 | Max response truncation |\n\n资料来源：[server.py:42-46]()\n\n## Next Steps\n\n- Explore [Advanced Search Patterns](#) for fuzzy matching techniques\n- Learn about [Namespace Organization](#) best practices\n- Set up [Monitoring](#) with `memory_stats` for capacity planning\n- Configure [Stripe Integration](#) for Pro tier upgrades\n\n---\n\n<a id='namespaces'></a>\n\n## Namespaces\n\n### 相关页面\n\n相关主题：[TTL Management](#ttl-management)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n</details>\n\n# Namespaces\n\n## Overview\n\nNamespaces in Agent Memory MCP provide **isolated storage containers** for memory entries, enabling logical separation of data across projects, users, domains, or any organizational scheme that fits an agent's workflow.\n\nEach namespace functions as an independent key-value store backed by a separate JSON file in the filesystem, with POSIX file locking ensuring safe concurrent access.\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Agent Memory MCP] --> B[Namespace Router]\n    B --> C[Namespace: default]\n    B --> D[Namespace: project-a]\n    B --> E[Namespace: user-123]\n    B --> N[...more namespaces]\n    \n    C --> F[\"default.json<br/>(in ~/.agent-memory/)\"]\n    D --> G[\"project-a.json\"]\n    E --> H[\"user-123.json\"]\n    N --> I[\"namespace.json\"]\n    \n    F --> J[_meta.json]\n    G --> J\n    H --> J\n    I --> J\n    \n    style F fill:#e1f5fe\n    style G fill:#e1f5fe\n    style H fill:#e1f5fe\n    style I fill:#e1f5fe\n    style J fill:#fff9c4\n```\n\n## Storage Model\n\n### File Structure\n\nNamespaces are persisted as individual JSON files in the `~/.agent-memory/` directory:\n\n| Element | Path | Purpose |\n|---------|------|---------|\n| Namespace files | `~/.agent-memory/{namespace}.json` | Individual key-value stores |\n| Metadata file | `~/.agent-memory/_meta.json` | Global statistics and entry counts |\n\n**资料来源:** [server.py:49-58](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Namespace Path Resolution\n\n```python\ndef _namespace_path(namespace: str) -> Path:\n    \"\"\"Return the full path for a namespace JSON file.\"\"\"\n    # Sanitize the namespace so it can't escape the directory.\n    safe = re.sub(r\"[^a-zA-Z0-9_.\\-]\", \"_\", namespace)\n    if not safe:\n        safe = DEFAULT_NAMESPACE\n    return STORAGE_DIR / f\"{safe}.json\"\n```\n\nThe namespace is sanitized to prevent directory traversal attacks—only alphanumeric characters, underscores, dots, and hyphens are permitted. Invalid names default to `\"default\"`.\n\n**资料来源:** [server.py:63-72](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Namespace Operations\n\n### Memory Remember\n\nStores a value under a key within a specified namespace.\n\n```python\ndef memory_remember(\n    key: str,\n    value: str,\n    namespace: str = \"default\",\n    ttl_seconds: Optional[int] = None,\n    fmt: Optional[str] = None,\n) -> str:\n```\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `key` | string | *required* | Unique identifier for the memory entry |\n| `value` | string | *required* | Content to store |\n| `namespace` | string | `\"default\"` | Target namespace |\n| `ttl_seconds` | integer | `null` | Time-to-live in seconds (optional) |\n| `format` | string | `\"markdown\"` | Response format (`markdown` or `json`) |\n\n**资料来源:** [server.py:163-210](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Memory Recall\n\nRetrieves a value and its metadata from a namespace.\n\n```python\ndef memory_recall(\n    key: str,\n    namespace: str = \"default\",\n    fmt: Optional[str] = None,\n) -> str:\n```\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `key` | string | *required* | Key to retrieve |\n| `namespace` | string | `\"default\"` | Namespace to search |\n| `format` | string | `\"markdown\"` | Response format |\n\n**资料来源:** [server.py:212-261](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Memory Forget\n\nPermanently deletes a key from a namespace.\n\n```python\ndef memory_forget(\n    key: str,\n    namespace: str = \"default\",\n    fmt: Optional[str] = None,\n) -> str:\n```\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `key` | string | *required* | Key to delete |\n| `namespace` | string | `\"default\"` | Namespace to delete from |\n| `format` | string | `\"markdown\"` | Response format |\n\n**资料来源:** [server.py:263-303](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Memory Search\n\nSearches within a specific namespace or across all namespaces.\n\n```python\ndef memory_search(\n    query: str,\n    namespace: Optional[str] = None,\n    limit: int = 10,\n    fmt: Optional[str] = None,\n) -> str:\n```\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `query` | string | *required* | Search keyword (case-insensitive) |\n| `namespace` | string | `null` | Limit search to one namespace (searches all if omitted) |\n| `limit` | integer | `10` | Maximum results to return |\n| `format` | string | `\"markdown\"` | Response format |\n\n**资料来源:** [server.py:305-365](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Memory List Namespaces\n\nLists all namespaces with active and expired entry counts.\n\n```python\ndef memory_list_namespaces(fmt: Optional[str] = None) -> str:\n```\n\nReturns a table of all namespaces containing:\n\n| Field | Description |\n|-------|-------------|\n| `namespace` | Namespace name |\n| `active_entries` | Non-expired entries |\n| `expired_entries` | Entries past TTL |\n\n**资料来源:** [server.py:367-400](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Memory Clear Namespace\n\nWipes all entries from a namespace permanently.\n\n```python\ndef memory_clear_namespace(\n    namespace: str,\n    fmt: Optional[str] = None,\n) -> str:\n```\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `namespace` | string | *required* | Namespace to clear |\n| `format` | string | `\"markdown\"` | Response format |\n\n**资料来源:** [server.py:402-427](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Data Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Server\n    participant FileSystem\n    \n    Client->>Server: memory_remember(key, value, namespace)\n    Server->>Server: _namespace_path(namespace)\n    Server->>Server: Sanitize namespace name\n    Server->>Server: _read_namespace(namespace)\n    Server->>Server: Append/update entry with metadata\n    Server->>Server: _write_namespace(namespace, entries)\n    Server->>Server: _recalc_meta()\n    Server->>Client: Success response\n    \n    Client->>Server: memory_recall(key, namespace)\n    Server->>Server: _read_namespace(namespace)\n    Server->>Server: Check TTL expiration\n    Server->>Server: Update access metadata\n    Server->>Server: _write_namespace(namespace, entries)\n    Server->>Client: Value + metadata\n```\n\n## Thread Safety\n\nNamespace operations use POSIX file locking via `fcntl.flock` to ensure safe concurrent access:\n\n```python\n@contextmanager\ndef _locked_file(path: Path, mode: str = \"r+\"):\n    \"\"\"Open a file with an exclusive POSIX lock (fcntl.flock).\"\"\"\n    _ensure_storage()\n    file_exists = path.exists()\n    if not file_exists and \"w\" in mode or \"+\" in mode:\n        path.touch(exist_ok=True)\n    fh = open(path, mode)\n    try:\n        try:\n            fcntl.flock(fh, fcntl.LOCK_EX)\n        except (NameError, OSError):\n            pass  # platform without fcntl support\n        yield fh\n    finally:\n        try:\n            fcntl.flock(fh, fcntl.LOCK_UN)\n        except (NameError, OSError):\n            pass\n        fh.close()\n```\n\nOn platforms without `fcntl` support (e.g., Windows without WSL), the lock gracefully degrades to a no-op.\n\n**资料来源:** [server.py:74-97](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Metadata Tracking\n\nGlobal metadata is recalculated by scanning all namespace files:\n\n```python\ndef _recalc_meta() -> None:\n    \"\"\"Recompute global metadata by scanning all namespaces.\"\"\"\n    total = 0\n    namespace_count = 0\n    for p in STORAGE_DIR.glob(\"*.json\"):\n        if p.stem == \"_meta\":\n            continue\n        namespace_count += 1\n        entries = _read_namespace(p.stem)\n        total += len([e for e in entries if not _is_expired(e)])\n    _write_meta({\"total_entries\": total, \"namespace_count\": namespace_count})\n```\n\n**资料来源:** [server.py:446-457](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Usage Examples\n\n### Storing Project-Specific Memories\n\n```python\n# Store project configuration\nmemory_remember(\n    key=\"config\",\n    value=\"debug_mode=true, max_connections=100\",\n    namespace=\"project-alpha\"\n)\n\n# Store user preferences\nmemory_remember(\n    key=\"theme\",\n    value=\"dark_mode\",\n    namespace=\"user-session-42\"\n)\n```\n\n### Cross-Namespace Search\n\n```python\n# Search all namespaces for \"config\"\nmemory_search(query=\"config\")\n\n# Search only project-alpha namespace\nmemory_search(query=\"config\", namespace=\"project-alpha\")\n```\n\n### Namespace Statistics\n\n```python\n# Get overview of all namespaces\nmemory_list_namespaces()\n```\n\n## Tool Annotations\n\nEach namespace operation is annotated with MCP metadata indicating its behavior:\n\n| Tool | readOnlyHint | destructiveHint | idempotentHint |\n|------|--------------|-----------------|----------------|\n| `memory_remember` | `false` | `false` | `true` |\n| `memory_recall` | `true` | `false` | `true` |\n| `memory_forget` | `false` | `true` | `true` |\n| `memory_search` | `true` | `false` | `true` |\n| `memory_list_namespaces` | `true` | `false` | `true` |\n| `memory_clear_namespace` | `false` | `true` | `true` |\n\n**资料来源:** [server.py:113-430](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Constants\n\n| Constant | Value | Description |\n|----------|-------|-------------|\n| `DEFAULT_NAMESPACE` | `\"default\"` | Fallback namespace when none specified |\n| `STORAGE_DIR` | `Path.home() / \".agent-memory\"` | Base directory for all data |\n| `CHARACTER_LIMIT` | `25,000` | Maximum response size before truncation |\n\n**资料来源:** [server.py:44-49](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n---\n\n<a id='ttl-management'></a>\n\n## TTL Management\n\n### 相关页面\n\n相关主题：[Namespaces](#namespaces), [memory_remember Tool](#memory-remember), [memory_recall Tool](#memory-recall)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n</details>\n\n# TTL Management\n\n## Overview\n\nTTL (Time-To-Live) Management provides automatic expiration for memory entries in the agent-memory-mcp system. This feature enables AI agents to store temporary information that self-destructs after a specified duration, making it ideal for caching, session data, and temporary context that becomes stale over time.\n\nThe TTL implementation uses a lazy expiry pattern where entries are checked and removed only when accessed, avoiding the overhead of background cleanup processes.\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[memory_remember] --> B[Calculate expires_at]\n    B --> C[Store entry with expires_at]\n    C --> D[Write to JSON file]\n    \n    E[memory_recall] --> F[Find entry by key]\n    F --> G{Is expired?}\n    G -->|Yes| H[Delete entry]\n    H --> I[Return Error]\n    G -->|No| J[Update access metadata]\n    J --> K[Return value]\n    \n    L[Background reads] --> M[_is_expired check]\n    M --> N[Filter expired entries]\n    N --> O[memory_list_namespaces]\n    N --> P[memory_stats]\n```\n\n## TTL Implementation Details\n\n### Core Expiry Detection\n\nThe `_is_expired()` function is the central mechanism for TTL validation:\n\n```python\ndef _is_expired(entry: Dict[str, Any]) -> bool:\n    expires_at = entry.get(\"expires_at\")\n    if expires_at is None:\n        return False\n    return _now_unix() > expires_at\n```\n\n| Component | Description |\n|-----------|-------------|\n| `entry.get(\"expires_at\")` | Retrieves the Unix timestamp when entry expires |\n| `None` return | No TTL set, entry never expires |\n| `True` result | Current time exceeds expiry time |\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### TTL Storage on Entry Creation\n\nWhen `memory_remember` is called with a `ttl_seconds` parameter, the expiry timestamp is calculated:\n\n```python\nentry = {\n    \"key\": key,\n    \"value\": value,\n    \"namespace\": namespace,\n    \"created_at\": _now_iso(),\n    \"accessed_at\": _now_iso(),\n    \"expires_at\": (now + ttl_seconds) if ttl_seconds else None,\n    \"access_count\": 0,\n}\n```\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `ttl_seconds` | integer | Duration in seconds before auto-expiry |\n| `expires_at` | float or None | Unix timestamp for expiry, None for permanent |\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## TTL Workflow\n\n### Lazy Expiry Pattern\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Server\n    participant Storage\n    \n    Client->>Server: memory_recall(key)\n    Server->>Storage: Read namespace file\n    Storage-->>Server: Entry found\n    \n    alt Entry is expired\n        Server->>Storage: Delete expired entry\n        Server-->>Client: Error: Key expired\n    else Entry is valid\n        Server->>Server: Update accessed_at\n        Server->>Server: Increment access_count\n        Server->>Storage: Write updated entry\n        Server-->>Client: Return value + metadata\n    end\n```\n\nThe lazy expiry approach offers several advantages:\n\n1. **No background processes** - Expiry is handled during normal operations\n2. **Immediate cleanup** - Expired entries are removed on next access\n3. **Minimal overhead** - No periodic scanning of all entries\n\n### Expiry During Namespace Operations\n\nExpired entries are filtered out when gathering statistics or listing namespaces:\n\n```python\nactive = [e for e in entries if not _is_expired(e)]\ntotal_entries += len(active)\n```\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## API Parameters\n\n### memory_remember\n\n| Parameter | Required | Type | Default | Description |\n|-----------|----------|------|---------|-------------|\n| `key` | Yes | string | - | Unique identifier for the memory entry |\n| `value` | Yes | string | - | Content to store |\n| `namespace` | No | string | `\"default\"` | Storage partition |\n| `ttl_seconds` | No | integer | `None` | Seconds until auto-expiry |\n| `format` | No | string | `\"markdown\"` | Response format (`markdown` or `json`) |\n\n### memory_recall\n\n| Parameter | Required | Type | Default | Description |\n|-----------|----------|------|---------|-------------|\n| `key` | Yes | string | - | Key to retrieve |\n| `namespace` | No | string | `\"default\"` | Namespace to search |\n| `format` | No | string | `\"markdown\"` | Response format |\n\n## Data Model\n\n### Memory Entry Schema\n\n```json\n{\n  \"key\": \"session_token\",\n  \"value\": \"abc123xyz\",\n  \"namespace\": \"user_sessions\",\n  \"created_at\": \"2024-01-15T10:30:00Z\",\n  \"accessed_at\": \"2024-01-15T11:45:00Z\",\n  \"expires_at\": 1705322700,\n  \"access_count\": 42\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `key` | string | Unique identifier within namespace |\n| `value` | string | Stored content |\n| `namespace` | string | Logical partition identifier |\n| `created_at` | ISO8601 string | Creation timestamp |\n| `accessed_at` | ISO8601 string | Last access timestamp |\n| `expires_at` | Unix timestamp or null | Expiry time (null = never expires) |\n| `access_count` | integer | Number of times accessed |\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Usage Examples\n\n### Storing Temporary Data with TTL\n\n```\nTool: memory_remember\nArguments: {\n  \"key\": \"oauth_token\",\n  \"value\": \"eyJhbGciOiJIUzI1NiIs...\",\n  \"namespace\": \"auth\",\n  \"ttl_seconds\": 3600\n}\n```\n\nThis stores an OAuth token that automatically expires after 1 hour.\n\n### Retrieving and Extending TTL\n\nThere is no built-in TTL extension mechanism. To extend an entry's lifetime:\n\n1. Use `memory_recall` to retrieve the current value\n2. Use `memory_remember` with a new `ttl_seconds` value\n\n```mermaid\ngraph LR\n    A[Recall entry] --> B[Get current value]\n    B --> C[Forget old entry]\n    C --> D[Remember with new TTL]\n```\n\n## Performance Considerations\n\n### Expired Entry Handling\n\n| Operation | Expired Entry Behavior |\n|-----------|----------------------|\n| `memory_remember` | Ignored (new key/value) |\n| `memory_recall` | Deleted, returns error |\n| `memory_forget` | Not found (already cleaned) |\n| `memory_search` | Excluded from results |\n| `memory_list_namespaces` | Counted in `expired_entries` |\n| `memory_stats` | Excluded from totals |\n\n### Storage File Structure\n\n```\n~/.agent-memory/\n├── default.json      # Default namespace\n├── auth.json         # Auth-related entries\n├── projects.json     # Project-specific entries\n└── _meta.json        # Global metadata\n```\n\nEach namespace is stored as a separate JSON file. Expired entries remain in the file until accessed, at which point they are removed during lazy expiry.\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Limitations\n\n1. **No automatic background cleanup** - Expired entries persist in storage files until accessed\n2. **No TTL modification** - Existing entries cannot have their TTL updated; must recreate\n3. **Second-level precision** - TTL is calculated in seconds, not milliseconds\n4. **No push notifications** - No mechanism to alert when entries are about to expire\n\n---\n\n<a id='data-storage'></a>\n\n## Data Storage\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n</details>\n\n# Data Storage\n\nThe **Data Storage** subsystem is the persistent layer of the Agent Memory MCP server. It handles all read/write operations to the filesystem, manages namespace isolation, enforces TTL (Time-To-Live) expiry, and provides thread-safe concurrent access using POSIX file locking.\n\n## Overview\n\nAgent Memory MCP uses a **file-based JSON storage model** where each namespace is stored as a separate JSON file. This design provides simplicity, portability, and easy inspection while maintaining isolation between different data domains.\n\n| Property | Value |\n|----------|-------|\n| Storage Location | `~/.agent-memory/` |\n| File Format | JSON (one file per namespace) |\n| Metadata File | `_meta.json` |\n| Concurrency Model | POSIX file locking (`fcntl`) |\n| Thread Safety | Yes (via `LOCK_EX` exclusive locks) |\n\n资料来源：[server.py:36-38](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Storage Architecture\n\n### Directory Structure\n\n```\n~/.agent-memory/\n├── default.json          # Default namespace\n├── project_a.json        # Custom namespace\n├── project_b.json        # Custom namespace\n└── _meta.json             # Global statistics metadata\n```\n\n### Namespace Files\n\nEach namespace is stored as a standalone JSON array containing memory entries. The filename is derived from the namespace name with character sanitization applied.\n\n```python\ndef _namespace_path(namespace: str) -> Path:\n    \"\"\"Return the full path for a namespace JSON file.\"\"\"\n    # Sanitize the namespace so it can't escape the directory.\n    safe = re.sub(r\"[^a-zA-Z0-9_.\\-]\", \"_\", namespace)\n    if not safe:\n        safe = DEFAULT_NAMESPACE\n    return STORAGE_DIR / f\"{safe}.json\"\n```\n\n资料来源：[server.py:54-61](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Sanitization Rules\n\n| Character Class | Action | Result |\n|-----------------|--------|--------|\n| `[a-zA-Z0-9_.\\-]` | Allowed | Preserved |\n| All others | Replaced | `_` (underscore) |\n| Empty after sanitization | Fallback | `default` namespace |\n\nThis prevents directory traversal attacks and ensures safe filesystem operations.\n\n## Data Models\n\n### Memory Entry Structure\n\n```json\n{\n  \"key\": \"user_preference_theme\",\n  \"value\": \"dark_mode\",\n  \"created_at\": \"2024-01-15T10:30:00.000Z\",\n  \"accessed_at\": \"2024-01-15T14:22:00.000Z\",\n  \"expires_at\": \"2024-02-15T10:30:00.000Z\",\n  \"access_count\": 42\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `key` | string | Unique identifier within namespace |\n| `value` | string | Stored content (any text) |\n| `created_at` | ISO 8601 string | Creation timestamp |\n| `accessed_at` | ISO 8601 string | Last access timestamp |\n| `expires_at` | ISO 8601 string or null | TTL expiry timestamp (null = never) |\n| `access_count` | integer | Number of times accessed |\n\n资料来源：[server.py:189-195](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Metadata File Structure (`_meta.json`)\n\n```json\n{\n  \"total_entries\": 150,\n  \"namespace_count\": 5\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `total_entries` | integer | Total active (non-expired) entries |\n| `namespace_count` | integer | Number of namespace files |\n\n## Storage Operations\n\n### Read Flow\n\n```mermaid\ngraph TD\n    A[memory_recall] --> B[Validate key not empty]\n    B --> C[_read_namespace namespace]\n    C --> D[Find entry by key]\n    D --> E{Entry exists?}\n    E -->|Yes| F{Is expired?}\n    E -->|No| G[Return error: key not found]\n    F -->|Yes| H[Remove expired entry]\n    F -->|No| I[Update access metadata]\n    H --> G\n    I --> J[Increment access_count]\n    J --> K[Update accessed_at]\n    K --> L[Return value + metadata]\n```\n\n### Write Flow\n\n```mermaid\ngraph TD\n    A[memory_remember] --> B[Validate key and value]\n    B --> C[_read_namespace namespace]\n    C --> D[Check for existing key]\n    D --> E{Key exists?}\n    E -->|Yes| F[Update existing entry]\n    E -->|No| G[Create new entry]\n    F --> H[_write_namespace]\n    G --> H\n    H --> I[_recalc_meta]\n    I --> J[Return success]\n```\n\n## Core Storage Functions\n\n### File Locking\n\nThread-safety is achieved through POSIX file locking using `fcntl`:\n\n```python\n@contextmanager\ndef _locked_file(path: Path, mode: str):\n    \"\"\"Open a file with exclusive locking (POSIX fcntl).\"\"\"\n    _ensure_storage()\n    fh = open(path, mode)\n    try:\n        fcntl.flock(fh.fileno(), fcntl.LOCK_EX)\n        yield fh\n    finally:\n        try:\n            os.fsync(fh.fileno())\n        except OSError:\n            pass\n        fh.close()\n```\n\n| Operation | Lock Type | Reason |\n|-----------|-----------|--------|\n| Read | `LOCK_EX` (exclusive) | Ensures consistent read after write |\n| Write | `LOCK_EX` (exclusive) | Prevents concurrent modifications |\n| `os.fsync` | After write | Guarantees durability |\n\n资料来源：[server.py:88-102](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Read Namespace\n\n```python\ndef _read_namespace(namespace: str) -> List[Dict[str, Any]]:\n    \"\"\"Read all entries for a namespace (returns list, never None).\"\"\"\n    path = _namespace_path(namespace)\n    if not path.exists():\n        return []\n    with _locked_file(path, \"r\") as fh:\n        try:\n            fh.seek(0)\n            raw = fh.read()\n            if not raw.strip():\n                return []\n            return json.loads(raw)\n        except (json.JSONDecodeError, OSError):\n            return []\n```\n\n**Key behaviors:**\n- Returns empty list for non-existent namespaces\n- Handles malformed JSON gracefully (returns empty list)\n- Handles empty files gracefully\n\n### Write Namespace\n\n```python\ndef _write_namespace(namespace: str, entries: List[Dict[str, Any]]) -> None:\n    \"\"\"Atomically write all entries for a namespace.\"\"\"\n    _ensure_storage()\n    path = _namespace_path(namespace)\n    with _locked_file(path, \"w\") as fh:\n        fh.seek(0)\n        fh.truncate()\n        json.dump(entries, fh, indent=2)\n        fh.flush()\n```\n\n**Atomicity guarantees:**\n1. Truncate file first (removes old data)\n2. Write complete JSON array\n3. Flush to kernel buffer\n4. Release lock (triggers `fsync`)\n\n## TTL (Time-To-Live) Management\n\n### Expiry Detection\n\n```python\ndef _is_expired(entry: Dict[str, Any]) -> bool:\n    \"\"\"Check if an entry has expired based on its TTL.\"\"\"\n    if entry.get(\"expires_at\") is None:\n        return False\n    return _now_unix() > entry[\"expires_at\"]\n```\n\n### Lazy Expiry Strategy\n\nTTL enforcement uses a **lazy deletion** approach:\n\n| Event | Action |\n|-------|--------|\n| `memory_recall` | Check expiry, delete if expired |\n| `memory_search` | Skip expired entries (no deletion) |\n| `memory_forget` | No expiry check needed |\n| Background cleanup | None (relies on lazy deletion) |\n\nThis design:\n- Avoids expensive background processes\n- Ensures expired entries are never returned\n- Accepts slight disk usage increase from expired entries until next access\n\n### TTL Entry Lifecycle\n\n```mermaid\ngraph LR\n    A[Created] --> B[Active]\n    B -->|TTL reached| C[Expired]\n    C -->|Next recall| D[Deleted]\n    C -->|Next search| E[Skipped]\n```\n\n## Metadata Management\n\n### Global Metadata Recalculation\n\n```python\ndef _recalc_meta() -> None:\n    \"\"\"Recompute global metadata by scanning all namespaces.\"\"\"\n    total = 0\n    namespace_count = 0\n    for p in STORAGE_DIR.glob(\"*.json\"):\n        if p.stem == \"_meta\":\n            continue\n        namespace_count += 1\n        entries = _read_namespace(p.stem)\n        total += len([e for e in entries if not _is_expired(e)])\n    _write_meta({\"total_entries\": total, \"namespace_count\": namespace_count})\n```\n\n`recalc_meta()` is called after:\n- `memory_remember` (new entry added)\n- `memory_forget` (entry deleted)\n- `memory_clear_namespace` (namespace wiped)\n- `memory_recall` (lazy expiry cleanup)\n\n资料来源：[server.py:152-164](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Storage Statistics\n\nThe `memory_stats` function aggregates information from all namespace files:\n\n```python\ndef memory_stats(fmt: Optional[str] = None) -> str:\n    \"\"\"Get storage statistics.\"\"\"\n    total_entries = 0\n    total_size = 0\n    namespace_count = 0\n    oldest: Optional[str] = None\n    newest: Optional[str] = None\n\n    for p in STORAGE_DIR.glob(\"*.json\"):\n        if p.stem == \"_meta\":\n            continue\n        namespace_count += 1\n        try:\n            file_size = p.stat().st_size\n            total_size += file_size\n        except OSError:\n            pass\n        entries = _read_namespace(p.stem)\n        active = [e for e in entries if not _is_expired(e)]\n        total_entries += len(active)\n        for e in active:\n            created = e.get(\"created_at\")\n            if created:\n                if oldest is None or created < oldest:\n                    oldest = created\n                if newest is None or created > newest:\n                    newest = created\n```\n\n**Stats returned:**\n\n| Stat | Description |\n|------|-------------|\n| `total_entries` | Sum of active entries across all namespaces |\n| `total_size_bytes` | Disk usage in bytes |\n| `total_size_human` | Human-readable size (B, KB, MB, GB, TB) |\n| `namespace_count` | Number of namespace files |\n| `oldest_entry` | ISO timestamp of earliest entry |\n| `newest_entry` | ISO timestamp of most recent entry |\n| `storage_path` | Filesystem path to storage directory |\n| `free_tier_limit` | 1000 entries |\n| `pro_tier_limit` | unlimited |\n\n资料来源：[server.py:271-307](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Access Tracking\n\nEvery memory entry maintains access metadata:\n\n| Field | Purpose | Updated When |\n|-------|---------|--------------|\n| `created_at` | Creation timestamp | Entry creation |\n| `accessed_at` | Last access timestamp | `memory_recall` |\n| `access_count` | Total access count | `memory_recall` |\n\n```python\n# In memory_recall\nentry[\"accessed_at\"] = _now_iso()\nentry[\"access_count\"] = entry.get(\"access_count\", 0) + 1\n_write_namespace(namespace, entries)\n```\n\nAccess count is used by `memory_search` to rank results by relevance.\n\n## Namespace Isolation\n\nNamespaces provide logical separation of memory entries:\n\n| Feature | Behavior |\n|---------|----------|\n| Separate files | Each namespace has its own `.json` file |\n| Independent entries | Keys only unique within namespace |\n| Independent TTLs | Each entry has its own expiry |\n| Independent access | Separate metadata per entry |\n\n**Search behavior by namespace:**\n\n| Parameter | Search Scope |\n|-----------|--------------|\n| `namespace` omitted | All namespaces |\n| `namespace` specified | Single namespace only |\n\n```python\nif namespace:\n    namespaces_to_search = [namespace]\nelse:\n    namespaces_to_search = [\n        p.stem\n        for p in STORAGE_DIR.glob(\"*.json\")\n        if p.stem != \"_meta\"\n    ]\n```\n\n## Error Handling\n\n| Error Condition | Handling |\n|-----------------|----------|\n| Malformed JSON file | Return empty list, log error |\n| Empty file | Return empty list |\n| Missing namespace | Create empty file on write |\n| Lock acquisition failure | Block until lock available |\n| Disk full | OS-level error propagated |\n\n## Performance Characteristics\n\n| Aspect | Value/Note |\n|--------|------------|\n| File I/O | Blocking (synchronous) |\n| Lock scope | Per-operation (not transaction) |\n| Search complexity | O(n) across namespaces |\n| Memory per namespace | Proportional to entries |\n| Disk I/O per access | 1 read + 1 write |\n\n## Configuration Constants\n\n```python\nCHARACTER_LIMIT = 25_000      # Maximum output truncation\nDEFAULT_NAMESPACE = \"default\" # Fallback namespace\nSTORAGE_DIR = Path.home() / \".agent-memory\"\nMETA_FILE = \"_meta.json\"\n```\n\n资料来源：[server.py:30-35](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n---\n\n<a id='memory-remember'></a>\n\n## memory_remember Tool\n\n### 相关页面\n\n相关主题：[memory_recall Tool](#memory-recall), [TTL Management](#ttl-management), [Quick Start Guide](#quick-start)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n</details>\n\n# memory_remember Tool\n\nThe `memory_remember` tool is the primary data ingestion function in the Agent Memory MCP server, enabling AI agents to persistently store key-value pairs with optional time-to-live (TTL) expiration. It serves as the foundation for creating durable memory entries that survive session restarts, context window limits, and agent crashes.\n\n## Overview\n\n`memory_remember` provides a mechanism for AI agents to store arbitrary string values under unique keys within isolated namespace containers. Each entry captures rich metadata including creation timestamps, access tracking, and optional expiration timers.\n\n**Core Responsibilities:**\n\n- Accept key-value pairs for persistent storage\n- Support optional TTL-based automatic expiration\n- Organize entries within user-defined namespaces\n- Track access statistics (count, timestamps)\n- Enforce atomic writes with POSIX file locking\n- Update global metadata counters\n\n资料来源：[server.py:1-50](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Function Signature\n\n```python\ndef memory_remember(\n    key: str,\n    value: str,\n    namespace: str = DEFAULT_NAMESPACE,\n    ttl_seconds: Optional[int] = None,\n    fmt: Optional[str] = None,\n) -> str\n```\n\n### Parameters\n\n| Parameter | Type | Required | Default | Description |\n|-----------|------|----------|---------|-------------|\n| `key` | `string` | Yes | — | Unique identifier for the memory entry |\n| `value` | `string` | Yes | — | The content/value to store persistently |\n| `namespace` | `string` | No | `\"default\"` | Logical container for organizing entries |\n| `ttl_seconds` | `integer` | No | `null` | Time-to-live in seconds; entry auto-expires after this duration |\n| `format` | `string` | No | `\"markdown\"` | Response format: `\"markdown\"` or `\"json\"` |\n\n资料来源：[server.py:180-230](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Data Model\n\nEach stored entry maintains the following schema:\n\n```python\n{\n    \"key\": str,           # User-provided unique identifier\n    \"value\": str,         # Stored content\n    \"namespace\": str,     # Container identifier\n    \"created_at\": str,    # ISO 8601 timestamp (UTC)\n    \"accessed_at\": str,   # ISO 8601 timestamp, updated on each retrieval\n    \"expires_at\": Optional[str],  # ISO 8601 timestamp or None\n    \"access_count\": int   # Cumulative retrieval count\n}\n```\n\n资料来源：[server.py:200-220](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Storage Architecture\n\nEntries are persisted to the filesystem using a namespace-per-file approach:\n\n```\n~/.agent-memory/\n├── default.json       # Default namespace\n├── project_a.json     # Custom namespace\n├── project_b.json     # Custom namespace\n└── _meta.json         # Global statistics\n```\n\n**Storage Details:**\n\n| Aspect | Specification |\n|--------|---------------|\n| Storage Location | `~/.agent-memory/` |\n| File Format | One JSON file per namespace |\n| Namespace File Naming | Sanitized: `[^a-zA-Z0-9_.\\-]` → `_` |\n| Locking Mechanism | POSIX `fcntl.flock()` |\n| Atomic Writes | Truncate-then-write pattern |\n\n资料来源：[server.py:60-80](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Execution Flow\n\n```mermaid\ngraph TD\n    A[memory_remember Called] --> B{Validate Inputs}\n    B -->|Empty Key| C[Return Error]\n    B -->|Valid Key| D[Acquire File Lock]\n    D --> E[Read Namespace File]\n    E --> F[Check for Duplicate Key]\n    F -->|Key Exists| G[Update Existing Entry]\n    F -->|New Key| H[Append New Entry]\n    G --> I[Write Namespace File]\n    H --> I\n    I --> J[Release File Lock]\n    J --> K[Recalculate Global Metadata]\n    K --> L[Return Success Response]\n    C --> L2[Return Error Response]\n```\n\n### Step-by-Step Process\n\n1. **Input Validation**: Reject empty or whitespace-only keys\n2. **Lock Acquisition**: Obtain exclusive POSIX file lock on namespace file\n3. **Entry Creation**: Build entry dict with timestamps and TTL calculation\n4. **File Write**: Atomically write updated entries array\n5. **Metadata Update**: Recalculate global entry counts via `_recalc_meta()`\n6. **Response Generation**: Format success data as markdown or JSON\n\n资料来源：[server.py:195-230](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## TTL (Time-to-Live) Mechanism\n\nThe TTL feature enables automatic expiration of entries after a specified duration:\n\n```python\nentry = {\n    \"key\": key,\n    \"value\": value,\n    \"namespace\": namespace,\n    \"created_at\": _now_iso(),\n    \"accessed_at\": _now_iso(),\n    \"expires_at\": (now + ttl_seconds) if ttl_seconds else None,\n    \"access_count\": 0,\n}\n```\n\n**TTL Behavior:**\n\n- TTL is calculated as `current_time + ttl_seconds` at write time\n- Expired entries are lazily deleted during `memory_recall` operations\n- TTL precision is second-level (not millisecond)\n- A value of `null` or omitting `ttl_seconds` creates a never-expiring entry\n\n资料来源：[server.py:205-215](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Response Format\n\n### Success Response (Markdown)\n\n```\n## ✅ Success\n\n**message:** Stored 'user_preference' in namespace 'default'\n**key:** user_preference\n**namespace:** default\n**expires_in:** 3600s\n**expires_at:** 2024-01-15T10:30:00Z\n```\n\n### Success Response (JSON)\n\n```json\n{\n  \"status\": \"ok\",\n  \"message\": \"Stored 'user_preference' in namespace 'default'\",\n  \"key\": \"user_preference\",\n  \"namespace\": \"default\",\n  \"expires_in\": \"3600s\",\n  \"expires_at\": \"2024-01-15T10:30:00Z\"\n}\n```\n\n### Error Response\n\n```json\n{\n  \"status\": \"error\",\n  \"error\": \"Key must not be empty\",\n  \"isError\": true\n}\n```\n\n资料来源：[server.py:300-350](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Namespace Handling\n\nNamespaces provide logical isolation for memory entries:\n\n```mermaid\ngraph LR\n    subgraph Storage Layer\n        NA[Namespace A<br/>namespace_a.json]\n        NB[Namespace B<br/>namespace_b.json]\n        NC[Default<br/>default.json]\n    end\n    \n    A1[Entry 1] --> NA\n    A2[Entry 2] --> NA\n    B1[Entry 3] --> NB\n    C1[Entry 4] --> NC\n```\n\n**Namespace Rules:**\n\n- Default namespace is `\"default\"` when unspecified\n- Names are sanitized to prevent directory traversal attacks\n- Each namespace persists independently\n- Cross-namespace search available via `memory_search`\n\n资料来源：[server.py:65-75](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Thread Safety\n\nThe implementation ensures safe concurrent access through POSIX file locking:\n\n```python\n@contextmanager\ndef _locked_file(path: Path, mode: str):\n    fh = open(path, mode)\n    fcntl.flock(fh.fileno(), fcntl.LOCK_EX)\n    try:\n        yield fh\n    finally:\n        fcntl.flock(fh.fileno(), fcntl.LOCK_UN)\n        fh.close()\n```\n\n- **Lock Type**: Exclusive (`LOCK_EX`) for both reads and writes\n- **Scope**: Per-file locks prevent corruption during concurrent access\n- **Guarantee**: Prevents race conditions from multiple agents\n\n资料来源：[server.py:85-100](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## MCP Tool Definition\n\nThe tool is registered with the MCP server as follows:\n\n```python\nTool(\n    name=\"memory_remember\",\n    description=\"Store a value under a key in a persistent memory namespace. Optionally set a TTL (time-to-live) in seconds for automatic expiry.\",\n    inputSchema={\n        \"type\": \"object\",\n        \"properties\": {\n            \"key\": {\"type\": \"string\", \"description\": \"Unique key for this memory entry.\"},\n            \"value\": {\"type\": \"string\", \"description\": \"The value/content to store.\"},\n            \"namespace\": {\n                \"type\": \"string\",\n                \"description\": \"Namespace to store the entry in (default: 'default').\",\n                \"default\": \"default\",\n            },\n            \"ttl_seconds\": {\n                \"type\": \"integer\",\n                \"description\": \"Optional TTL in seconds. Entry auto-expires after this duration.\",\n            },\n            \"format\": {\n                \"type\": \"string\",\n                \"enum\": [\"markdown\", \"json\"],\n                \"description\": \"Response format (default: markdown).\",\n                \"default\": \"markdown\",\n            },\n        },\n        \"required\": [\"key\", \"value\"],\n    },\n    annotations=ToolAnnotations(\n        readOnlyHint=False,\n        destructiveHint=False,\n        idempotentHint=True,\n        openWorldHint=False,\n    ),\n)\n```\n\n**Tool Annotations:**\n\n| Annotation | Value | Meaning |\n|------------|-------|---------|\n| `readOnlyHint` | `false` | Modifies server state |\n| `destructiveHint` | `false` | Does not delete existing data |\n| `idempotentHint` | `true` | Safe to retry |\n| `openWorldHint` | `false` | Operates on local storage only |\n\n资料来源：[server.py:280-320](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Usage Examples\n\n### Basic Storage\n\n```\nTool: memory_remember\nArguments: {\n    \"key\": \"user_name\",\n    \"value\": \"Alice\",\n    \"namespace\": \"users\"\n}\n```\n\n### Storage with TTL (1 hour)\n\n```\nTool: memory_remember\nArguments: {\n    \"key\": \"session_token\",\n    \"value\": \"abc123xyz\",\n    \"namespace\": \"sessions\",\n    \"ttl_seconds\": 3600\n}\n```\n\n### JSON Response Format\n\n```\nTool: memory_remember\nArguments: {\n    \"key\": \"config\",\n    \"value\": \"{\\\"theme\\\": \\\"dark\\\", \\\"lang\\\": \\\"en\\\"}\",\n    \"namespace\": \"settings\",\n    \"format\": \"json\"\n}\n```\n\n## Related Tools\n\n| Tool | Purpose | Relationship |\n|------|---------|--------------|\n| `memory_recall` | Retrieve stored values by key | Complements write with read |\n| `memory_forget` | Delete a specific entry | Inverse operation |\n| `memory_search` | Find entries by keyword | Discovery of stored data |\n| `memory_list_namespaces` | List all namespaces | Namespace enumeration |\n| `memory_stats` | View storage statistics | Global monitoring |\n\n资料来源：[server.py:320-380](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Limitations\n\n- **Character Limit**: Stored values are truncated at 25,000 characters via `_truncate()` helper\n- **Key Constraints**: Empty keys are rejected; keys are case-sensitive\n- **Storage Backend**: Filesystem-based (not suitable for high-frequency write workloads)\n- **Free Tier**: Limited to 1,000 total entries across all namespaces\n- **No Batch Operations**: Single key-value pair per call only\n\n资料来源：[server.py:55](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py) and [smithery.yaml](https://github.com/Rumblingb/agent-memory-mcp/blob/main/smithery.yaml)\n\n---\n\n<a id='memory-recall'></a>\n\n## memory_recall Tool\n\n### 相关页面\n\n相关主题：[memory_remember Tool](#memory-remember), [memory_forget Tool](#memory-forget), [TTL Management](#ttl-management)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n</details>\n\n# memory_recall Tool\n\n## Overview\n\nThe `memory_recall` tool is a core retrieval function in the Agent Memory MCP server that enables AI agents to fetch previously stored values from persistent memory. It provides lazy TTL (Time-To-Live) expiry checking, automatic access tracking, and metadata enrichment on every retrieval operation.\n\n**Key Characteristics:**\n\n| Attribute | Value |\n|-----------|-------|\n| Tool Name | `memory_recall` |\n| Category | Read operation |\n| Destructive | No |\n| Idempotent | Yes |\n| Default Namespace | `default` |\n| Response Formats | `markdown`, `json` |\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Function Signature\n\n```python\ndef memory_recall(\n    key: str,\n    namespace: str = DEFAULT_NAMESPACE,\n    fmt: Optional[str] = None,\n) -> str:\n```\n\n### Parameters\n\n| Parameter | Type | Required | Default | Description |\n|-----------|------|----------|---------|-------------|\n| `key` | `string` | Yes | — | The unique key identifying the memory entry to retrieve |\n| `namespace` | `string` | No | `\"default\"` | The namespace to search within |\n| `fmt` | `string` | No | `\"markdown\"` | Response format: `\"markdown\"` or `\"json\"` |\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Tool Schema Definition\n\n```json\n{\n  \"name\": \"memory_recall\",\n  \"description\": \"Retrieve a stored value by key from a namespace. Returns full metadata including creation time, last access, and expiry. Automatically expires TTL'd entries.\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"properties\": {\n      \"key\": {\n        \"type\": \"string\",\n        \"description\": \"The key to retrieve.\"\n      },\n      \"namespace\": {\n        \"type\": \"string\",\n        \"description\": \"Namespace to look in (default: 'default').\",\n        \"default\": \"default\"\n      },\n      \"format\": {\n        \"type\": \"string\",\n        \"enum\": [\"markdown\", \"json\"],\n        \"description\": \"Response format (default: markdown).\",\n        \"default\": \"markdown\"\n      }\n    },\n    \"required\": [\"key\"]\n  },\n  \"annotations\": {\n    \"readOnlyHint\": false,\n    \"destructiveHint\": false,\n    \"idempotentHint\": true,\n    \"openWorldHint\": false\n  }\n}\n```\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Workflow\n\n```mermaid\ngraph TD\n    A[Start: memory_recall called] --> B{Key provided?}\n    B -->|No| C[Return Error: Key must not be empty]\n    B -->|Yes| D[Read namespace file]\n    E[Find entry by key] --> F{Entry found?}\n    F -->|No| G[Return Error: Key not found]\n    F -->|Yes| H{Entry expired?}\n    D --> E\n    H -->|Yes| I[Remove expired entry from file]\n    I --> J[Recalculate metadata]\n    J --> K[Return Error: Key has expired]\n    H -->|No| L[Update access metadata]\n    L --> M[Increment access_count]\n    M --> N[Update accessed_at timestamp]\n    N --> O[Write updated namespace file]\n    O --> P[Return Success with value and metadata]\n```\n\n## Lazy TTL Expiry Mechanism\n\nOne of the key features of `memory_recall` is its **lazy expiry** behavior. Rather than running a background cleanup task, expired entries are detected and removed when they are accessed:\n\n```python\nfor i, entry in enumerate(entries):\n    if entry[\"key\"] == key:\n        if _is_expired(entry):\n            # Lazy expiry – remove and return not-found\n            entries.pop(i)\n            _write_namespace(namespace, entries)\n            _recalc_meta()\n            return _error(f\"Key '{key}' has expired\", fmt)\n```\n\n**Expiry Detection Logic:**\n\n| Field | Purpose |\n|-------|---------|\n| `expires_at` | ISO timestamp when entry expires |\n| `_is_expired(entry)` | Returns `True` if current time > `expires_at` |\n\nWhen an entry expires:\n1. The entry is removed from the namespace file immediately\n2. Global metadata is recalculated\n3. An error response is returned indicating expiration\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Access Tracking\n\nEvery successful recall operation automatically updates metadata:\n\n```python\n# Update access metadata\nentry[\"accessed_at\"] = _now_iso()\nentry[\"access_count\"] = entry.get(\"access_count\", 0) + 1\n_write_namespace(namespace, entries)\n```\n\n**Tracked Metadata:**\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `accessed_at` | ISO string | Timestamp of most recent access |\n| `access_count` | integer | Total number of times this entry has been accessed |\n\nThis data powers the search ranking algorithm, which sorts results by `access_count` in descending order.\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Response Format\n\n### Success Response (Markdown)\n\n```markdown\n## ✅ Success\n\n**key:** example_key\n**namespace:** default\n**value:** The stored value content\n**created_at:** 2024-01-15T10:30:00\n**accessed_at:** 2024-01-15T14:22:00\n**access_count:** 5\n**expires_at:** 2024-01-16T10:30:00 or Never\n```\n\n### Success Response (JSON)\n\n```json\n{\n  \"status\": \"ok\",\n  \"key\": \"example_key\",\n  \"namespace\": \"default\",\n  \"value\": \"The stored value content\",\n  \"created_at\": \"2024-01-15T10:30:00\",\n  \"accessed_at\": \"2024-01-15T14:22:00\",\n  \"access_count\": 5,\n  \"expires_at\": \"2024-01-16T10:30:00\"\n}\n```\n\n### Error Responses\n\n| Error Condition | Message |\n|-----------------|---------|\n| Empty key | `Key must not be empty` |\n| Key not found | `Key 'example_key' not found in namespace 'default'` |\n| Entry expired | `Key 'example_key' has expired` |\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Data Storage Model\n\nEntries are stored in JSON files within the storage directory:\n\n```\n~/.agent-memory/\n├── _meta.json\n├── default.json\n├── project_a.json\n└── user_b.json\n```\n\n### Entry Schema\n\n```json\n{\n  \"key\": \"string\",\n  \"value\": \"string\",\n  \"created_at\": \"ISO8601 timestamp\",\n  \"accessed_at\": \"ISO8601 timestamp\",\n  \"expires_at\": \"ISO8601 timestamp or null\",\n  \"access_count\": 0\n}\n```\n\n### Thread Safety\n\nFile operations use POSIX file locking (`fcntl`) to ensure safe concurrent access:\n\n```python\n@contextmanager\ndef _locked_file(path: Path, mode: str):\n    fh = open(path, mode)\n    try:\n        fcntl.flock(fh.fileno(), fcntl.LOCK_EX)\n        yield fh\n    finally:\n        fcntl.flock(fh.fileno(), fcntl.LOCK_UN)\n        fh.close()\n```\n\nThis ensures that multiple agents can safely read and write to the memory store simultaneously without data corruption.\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Usage Examples\n\n### Basic Recall\n\n```\nTool: memory_recall\nArguments: {\"key\": \"user_preference\", \"namespace\": \"default\"}\n```\n\n### Recalling from Specific Namespace\n\n```\nTool: memory_recall\nArguments: {\"key\": \"session_state\", \"namespace\": \"user_123\"}\n```\n\n### JSON Response Format\n\n```\nTool: memory_recall\nArguments: {\"key\": \"config\", \"namespace\": \"settings\", \"format\": \"json\"}\n```\n\n## Integration with Other Tools\n\n| Related Tool | Interaction |\n|--------------|-------------|\n| `memory_remember` | Stores data that `memory_recall` retrieves |\n| `memory_search` | Uses `access_count` to rank search results |\n| `memory_forget` | Permanently deletes entries |\n| `memory_stats` | Tracks global `total_entries` count |\n\nThe search functionality prioritizes frequently accessed entries:\n\n```python\n# Sort by access count desc, then created_at desc\nresults.sort(key=lambda x: (-x.get(\"access_count\", 0), x.get(\"created_at\", \"\")))\n```\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Error Handling\n\n| Scenario | Handling |\n|----------|----------|\n| Empty key | Returns error immediately before file I/O |\n| Non-existent namespace | Returns empty array; treated as \"key not found\" |\n| Corrupted JSON file | Returns empty array, log error |\n| Expired entry | Removes from file, returns expiration error |\n| File permission errors | Caught by try/except, returns error |\n\nThe tool handles exceptions gracefully at the server level:\n\n```python\nexcept Exception as exc:\n    err_text = _error(f\"Internal error in {name}: {exc}\", fmt)\n    return CallToolResult(\n        content=[TextContent(type=\"text\", text=err_text)],\n        isError=True,\n    )\n```\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n---\n\n<a id='memory-forget'></a>\n\n## memory_forget Tool\n\n### 相关页面\n\n相关主题：[memory_recall Tool](#memory-recall)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n- [smithery.yaml](https://github.com/Rumblingb/agent-memory-mcp/blob/main/smithery.yaml)\n- [index.html](https://github.com/Rumblingb/agent-memory-mcp/blob/main/index.html)\n- [README.md](https://github.com/Rumblingb/agent-memory-mcp/blob/main/README.md)\n- [requirements.txt](https://github.com/Rumblingb/agent-memory-mcp/blob/main/requirements.txt)\n</details>\n\n# memory_forget Tool\n\nThe `memory_forget` tool is a destructive operation within the Agent Memory MCP server that permanently removes a specific key-value entry from a designated memory namespace. It is one of seven tools exposed by the MCP server and represents the deletion capability in the persistent key-value storage system.\n\n## Overview\n\nAgent Memory MCP provides AI agents with persistent memory across sessions. The system stores data as JSON files in `~/.agent-memory/`, with one file per namespace plus a `_meta.json` statistics file. The `memory_forget` tool enables agents to selectively remove entries when they are no longer needed, helping manage storage and maintain relevant data.\n\n| Tool Name | Purpose | Destructive | Read-Only |\n|-----------|---------|-------------|-----------|\n| memory_remember | Store a key-value pair | No | No |\n| memory_recall | Retrieve a value by key | No | Yes |\n| memory_forget | Delete a key permanently | Yes | No |\n| memory_search | Search across namespaces | No | Yes |\n| memory_list_namespaces | List all namespaces | No | Yes |\n| memory_clear_namespace | Wipe entire namespace | Yes | No |\n| memory_stats | Get storage statistics | No | Yes |\n\n## Function Signature\n\nThe `memory_forget` function is defined in `server.py` and accepts the following parameters:\n\n```python\ndef memory_forget(\n    key: str,\n    namespace: str = DEFAULT_NAMESPACE,\n    fmt: Optional[str] = None,\n) -> str:\n```\n\n| Parameter | Type | Required | Default | Description |\n|-----------|------|----------|---------|-------------|\n| key | string | Yes | — | Unique key identifying the memory entry to delete |\n| namespace | string | No | \"default\" | Namespace containing the entry |\n| format | string | No | \"markdown\" | Response format: \"markdown\" or \"json\" |\n\n## Tool Definition\n\nThe MCP server exposes `memory_forget` with the following schema definition:\n\n```python\nTool(\n    name=\"memory_forget\",\n    description=\"Permanently delete a key from a memory namespace.\",\n    inputSchema={\n        \"type\": \"object\",\n        \"properties\": {\n            \"key\": {\n                \"type\": \"string\",\n                \"description\": \"Unique key for this memory entry.\",\n            },\n            \"namespace\": {\n                \"type\": \"string\",\n                \"description\": \"Namespace to delete from (default: 'default').\",\n                \"default\": \"default\",\n            },\n            \"format\": {\n                \"type\": \"string\",\n                \"enum\": [\"markdown\", \"json\"],\n                \"description\": \"Response format (default: markdown).\",\n                \"default\": \"markdown\",\n            },\n        },\n        \"required\": [\"key\"],\n    },\n    annotations=ToolAnnotations(\n        readOnlyHint=False,\n        destructiveHint=True,\n        idempotentHint=True,\n        openWorldHint=False,\n    ),\n),\n```\n\n## Tool Annotations\n\nThe tool is annotated with specific behavioral hints that inform MCP clients about its characteristics:\n\n| Annotation | Value | Implication |\n|------------|-------|-------------|\n| readOnlyHint | false | This tool modifies state |\n| destructiveHint | true | This operation permanently removes data |\n| idempotentHint | true | Multiple calls with same key produce same result (success or not-found) |\n| openWorldHint | false | Only affects local storage, no external world interaction |\n\n## Execution Flow\n\nThe following diagram illustrates the execution flow when `memory_forget` is invoked:\n\n```mermaid\ngraph TD\n    A[Call memory_forget with key and namespace] --> B{Key is empty?}\n    B -->|Yes| C[Return error: Key must not be empty]\n    B -->|No| D[Read namespace file from ~/.agent-memory/]\n    D --> E{Namespace file exists?}\n    E -->|No| F[Return error: Key not found]\n    E -->|Yes| G[Parse JSON entries list]\n    G --> H{Entry with matching key exists?}\n    H -->|No| I[Return error: Key not found]\n    H -->|Yes| J[Remove entry from list]\n    J --> K[Write updated entries back to namespace file]\n    K --> L[Recalculate global metadata]\n    L --> M[Return success response]\n```\n\n## Implementation Details\n\nThe core implementation of `memory_forget` performs the following operations:\n\n```python\ndef memory_forget(\n    key: str,\n    namespace: str = DEFAULT_NAMESPACE,\n    fmt: Optional[str] = None,\n) -> str:\n    \"\"\"Delete a key permanently from a namespace.\"\"\"\n    if not key.strip():\n        return _error(\"Key must not be empty\", fmt)\n\n    entries = _read_namespace(namespace)\n\n    for i, entry in enumerate(entries):\n        if entry[\"key\"] == key:\n            entries.pop(i)\n            _write_namespace(namespace, entries)\n            _recalc_meta()\n\n            return _success(\n                {\n                    \"message\": f\"Deleted '{key}' from namespace '{namespace}'\",\n                    \"key\": key,\n                    \"namespace\": namespace,\n                },\n                fmt,\n            )\n\n    return _error(f\"Key '{key}' not found in namespace '{namespace}'\", fmt)\n```\n\n### Step-by-Step Breakdown\n\n1. **Input Validation**: Checks that the key is not empty or whitespace-only. Empty keys return an error immediately.\n\n2. **Read Namespace**: Loads all entries from the namespace's JSON file using the thread-safe `_read_namespace()` helper.\n\n3. **Search for Entry**: Iterates through entries to find a matching key.\n\n4. **Remove Entry**: If found, removes the entry from the list using `pop(i)`.\n\n5. **Write Back**: Persists the modified entries list to the namespace file using `_write_namespace()`.\n\n6. **Update Metadata**: Calls `_recalc_meta()` to update global statistics reflecting the entry count change.\n\n7. **Return Response**: Returns a formatted success or error message.\n\n## File Operations\n\nThe tool relies on two critical helper functions for file I/O:\n\n### _read_namespace()\n\n```python\ndef _read_namespace(namespace: str) -> List[Dict[str, Any]]:\n    \"\"\"Read all entries for a namespace (returns list, never None).\"\"\"\n    path = _namespace_path(namespace)\n    if not path.exists():\n        return []\n    with _locked_file(path, \"r\") as fh:\n        try:\n            fh.seek(0)\n            raw = fh.read()\n            if not raw.strip():\n                return []\n            return json.loads(raw)\n        except (json.JSONDecodeError, OSError):\n            return []\n```\n\n### _write_namespace()\n\n```python\ndef _write_namespace(namespace: str, entries: List[Dict[str, Any]]) -> None:\n    \"\"\"Atomically write all entries for a namespace.\"\"\"\n    _ensure_storage()\n    path = _namespace_path(namespace)\n    with _locked_file(path, \"w\") as fh:\n        fh.seek(0)\n        fh.truncate()\n        json.dump(entries, fh, indent=2)\n        fh.flush()\n```\n\nBoth operations use POSIX file locking via `_locked_file()` context manager to ensure thread-safe concurrent access.\n\n## Namespace Path Resolution\n\nNamespace names are sanitized to prevent directory escape attacks:\n\n```python\ndef _namespace_path(namespace: str) -> Path:\n    \"\"\"Return the full path for a namespace JSON file.\"\"\"\n    safe = re.sub(r\"[^a-zA-Z0-9_.\\-]\", \"_\", namespace)\n    if not safe:\n        safe = DEFAULT_NAMESPACE\n    return STORAGE_DIR / f\"{safe}.json\"\n```\n\nThis ensures all namespace files remain within `~/.agent-memory/` directory. 资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Metadata Recalculation\n\nAfter successful deletion, global metadata is updated:\n\n```python\ndef _recalc_meta() -> None:\n    \"\"\"Recompute global metadata by scanning all namespaces.\"\"\"\n    total = 0\n    namespace_count = 0\n    for p in STORAGE_DIR.glob(\"*.json\"):\n        if p.stem == \"_meta\":\n            continue\n        namespace_count += 1\n        entries = _read_namespace(p.stem)\n        total += len([e for e in entries if not _is_expired(e)])\n    _write_meta({\"total_entries\": total, \"namespace_count\": namespace_count})\n```\n\nThe function scans all namespace files to count active (non-expired) entries and updates the `_meta.json` file accordingly.\n\n## Response Formats\n\n### Success Response (Markdown)\n\n```markdown\n## ✅ Success\n**message:** Deleted 'user_preference' from namespace 'default'\n**key:** user_preference\n**namespace:** default\n```\n\n### Success Response (JSON)\n\n```json\n{\n  \"status\": \"ok\",\n  \"message\": \"Deleted 'user_preference' from namespace 'default'\",\n  \"key\": \"user_preference\",\n  \"namespace\": \"default\"\n}\n```\n\n### Error Response (Key Not Found)\n\n```markdown\n## ❌ Error\n**Key 'nonexistent_key' not found in namespace 'default'**\n```\n\n## Error Handling\n\n| Scenario | Error Message | HTTP-like Status |\n|----------|---------------|------------------|\n| Empty key | \"Key must not be empty\" | Validation Error |\n| Key not in namespace | \"Key '{key}' not found in namespace '{namespace}'\" | Not Found |\n\nErrors are formatted consistently via `_error()` helper and returned with `isError=True` in JSON mode.\n\n## Routing in MCP Server\n\nThe MCP server routes tool calls through the `call_tool` handler:\n\n```python\n@server.call_tool()\nasync def call_tool(name: str, arguments: Dict[str, Any]) -> CallToolResult:\n    \"\"\"Route tool calls to the appropriate implementation.\"\"\"\n    fmt = arguments.pop(\"format\", \"markdown\")\n\n    try:\n        if name == \"memory_remember\":\n            text = memory_remember(**arguments, fmt=fmt)\n        elif name == \"memory_recall\":\n            text = memory_recall(**arguments, fmt=fmt)\n        elif name == \"memory_forget\":\n            text = memory_forget(**arguments, fmt=fmt)\n        # ... other tools\n```\n\nThe format parameter is extracted before forwarding arguments to the implementation function.\n\n## Concurrency and Thread Safety\n\nThe tool is designed for multi-agent environments with the following safety mechanisms:\n\n1. **POSIX File Locking**: All read/write operations use `fcntl.flock()` through the `_locked_file()` context manager.\n\n2. **Atomic Writes**: `_write_namespace()` uses `truncate()` before `json.dump()` to ensure atomic replacement of file contents.\n\n3. **Lazy Expiry**: Expired entries are automatically skipped during read operations but not proactively cleaned unless accessed.\n\n## Storage Structure\n\nData persists in `~/.agent-memory/` with the following structure:\n\n```\n~/.agent-memory/\n├── _meta.json          # Global statistics\n├── default.json        # Default namespace\n├── project_a.json      # Custom namespace\n└── user_sessions.json  # Another namespace\n```\n\nEach namespace file contains a JSON array of entry objects:\n\n```json\n[\n  {\n    \"key\": \"user_preference\",\n    \"value\": \"dark_mode\",\n    \"created_at\": \"2024-01-15T10:30:00Z\",\n    \"accessed_at\": \"2024-01-15T14:22:00Z\",\n    \"expires_at\": null,\n    \"access_count\": 15\n  }\n]\n```\n\n## Usage Examples\n\n### Basic Deletion\n\n```json\n{\n  \"name\": \"memory_forget\",\n  \"arguments\": {\n    \"key\": \"session_token\"\n  }\n}\n```\n\n### Deletion from Specific Namespace\n\n```json\n{\n  \"name\": \"memory_forget\",\n  \"arguments\": {\n    \"key\": \"temp_cache\",\n    \"namespace\": \"user_123\"\n  }\n}\n```\n\n### Deletion with JSON Response\n\n```json\n{\n  \"name\": \"memory_forget\",\n  \"arguments\": {\n    \"key\": \"old_preference\",\n    \"namespace\": \"settings\",\n    \"format\": \"json\"\n  }\n}\n```\n\n## Idempotency\n\nThe tool is idempotent—calling it multiple times with the same key produces consistent results:\n\n- First call with existing key: Success (entry deleted)\n- Subsequent calls with same key: Error (key not found)\n\nThis property makes the tool safe for retry logic in agent workflows.\n\n## Related Tools\n\n| Tool | Relationship | Purpose |\n|------|--------------|---------|\n| memory_remember | Complement | Store new entries |\n| memory_recall | Read counterpart | Retrieve entries before deletion |\n| memory_clear_namespace | Bulk deletion | Remove all entries in namespace |\n| memory_list_namespaces | Discovery | Find available namespaces |\n\n## Configuration Constants\n\nThe tool operates within the constraints defined by these constants:\n\n| Constant | Value | Purpose |\n|----------|-------|---------|\n| DEFAULT_NAMESPACE | \"default\" | Fallback namespace if none specified |\n| STORAGE_DIR | `Path.home() / \".agent-memory\"` | Base storage directory |\n| CHARACTER_LIMIT | 25,000 | Maximum response size before truncation |\n| META_FILE | \"_meta.json\" | Global metadata filename |\n\n---\n\n<a id='memory-search'></a>\n\n## memory_search Tool\n\n### 相关页面\n\n相关主题：[Namespaces](#namespaces), [Quick Start Guide](#quick-start)\n\n<details>\n<summary>Relevant Source Files</summary>\n\nThe following source files were used to generate this page:\n\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n- [smithery.yaml](https://github.com/Rumblingb/agent-memory-mcp/blob/main/smithery.yaml)\n- [requirements.txt](https://github.com/Rumblingb/agent-memory-mcp/blob/main/requirements.txt)\n- [README.md](https://github.com/Rumblingb/agent-memory-mcp/blob/main/README.md)\n</details>\n\n# memory_search Tool\n\nThe `memory_search` tool is a fuzzy keyword search capability within the Agent Memory MCP server that enables AI agents to retrieve stored memory entries across one or all namespaces using case-insensitive substring matching. It serves as the primary discovery mechanism for agents seeking to recall previously stored context, preferences, or state information without requiring exact key names.\n\n## Overview\n\nAgent Memory MCP is a persistent key-value memory store built on the Model Context Protocol (MCP) Python SDK. The `memory_search` tool addresses a fundamental limitation in agent-based systems: the inability to retrieve information when the exact storage key is unknown. Rather than requiring agents to remember precise key names, the search tool accepts natural language queries and matches them against both keys and values stored across all memory namespaces.\n\nThe tool implements substring matching at the byte-string level, converting both the search query and stored content to lowercase before comparison. This design choice prioritizes recall over precision, ensuring that partial matches, typos, and variations in casing do not prevent agents from finding relevant information.\n\n## Architecture\n\n### System Context\n\n```mermaid\ngraph TD\n    A[\"Agent / Client\"] -->|MCP Tool Call| B[\"memory_search\"]\n    B --> C{namespace param?}\n    C -->|Yes| D[Search Single Namespace]\n    C -->|No| E[Discover All Namespaces]\n    E --> F[\"Glob *.json in ~/.agent-memory/\"]\n    F --> G[\"Exclude _meta.json\"]\n    D --> H[\"Read Namespace JSON Files\"]\n    G --> H\n    H --> I[\"Parse entries array\"]\n    I --> J{Entry expired?}\n    J -->|Yes| K[Skip entry]\n    J -->|No| L{Check match conditions}\n    L --> M[\"query ∈ key.lower()\"]\n    L --> N[\"query ∈ value.lower()\"]\n    M -->|OR| O[Add to results]\n    N -->|OR| O\n    O --> P[\"Sort: access_count DESC, created_at DESC\"]\n    P --> Q[\"Apply limit\"]\n    Q --> R[\"Truncate values to 500 chars\"]\n    R --> S[Format response]\n    S --> T[\"Return markdown or JSON\"]\n    K --> P\n```\n\n### Data Model\n\nEach memory entry stored in the Agent Memory system follows a consistent schema:\n\n```json\n{\n  \"key\": \"string\",\n  \"value\": \"string\",\n  \"created_at\": \"ISO 8601 timestamp\",\n  \"accessed_at\": \"ISO 8601 timestamp\",\n  \"expires_at\": \"ISO 8601 timestamp | null\",\n  \"access_count\": \"integer\"\n}\n```\n\nThe `memory_search` tool operates on this entry structure, examining both `key` and `value` fields for substring matches while respecting the `expires_at` field for TTL-based entries. 资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Function Signature\n\n```python\ndef memory_search(\n    query: str,\n    namespace: Optional[str] = None,\n    limit: int = 10,\n    fmt: Optional[str] = None,\n) -> str:\n```\n\nThe function returns a formatted string response rather than a structured object, supporting both markdown and JSON output formats through the `fmt` parameter.\n\n## Parameters\n\n| Parameter | Type | Required | Default | Description |\n|-----------|------|----------|---------|-------------|\n| `query` | `string` | Yes | — | Search keyword or substring to match against keys and values |\n| `namespace` | `string \\| null` | No | `null` | Optional namespace to limit search scope. When `null`, searches all namespaces |\n| `limit` | `integer` | No | `10` | Maximum number of results to return |\n| `fmt` | `string \\| null` | No | `null` | Response format: `\"markdown\"` or `\"json\"`. Defaults to markdown when `null` |\n\n## Search Algorithm\n\n### Step 1: Input Validation\n\nThe search immediately rejects empty queries to prevent unnecessary filesystem operations:\n\n```python\nif not query.strip():\n    return _error(\"Query must not be empty\", fmt)\n```\n\nThis validation ensures that whitespace-only strings and empty inputs are rejected before any namespace discovery occurs. 资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Step 2: Query Normalization\n\nThe search query is normalized to lowercase for case-insensitive matching:\n\n```python\nq = query.lower()\n```\n\nThis single transformation enables matching against both `key.lower()` and `value.lower()` without additional case-handling logic.\n\n### Step 3: Namespace Discovery\n\nWhen no namespace is specified, the tool discovers all available namespaces by globbing the storage directory:\n\n```python\nnamespaces_to_search = [\n    p.stem\n    for p in STORAGE_DIR.glob(\"*.json\")\n    if p.stem != \"_meta\"\n]\n```\n\nThe `_meta.json` file is explicitly excluded from search results as it contains internal metadata rather than user data. Each discovered namespace corresponds to a `namespace.json` file in `~/.agent-memory/`. 资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Step 4: Entry Matching\n\nFor each namespace and entry, the matching logic follows this flow:\n\n```mermaid\ngraph LR\n    A[entry.key.lower()] --> C{query in key?}\n    B[entry.value.lower()] --> D{query in value?}\n    C -->|Yes| E[Include result]\n    D -->|Yes| E\n    C -->|No| F[Skip]\n    D -->|No| F\n```\n\nThe `OR` condition means an entry is included if the query appears in **either** the key or the value. Expired entries are automatically skipped:\n\n```python\nif _is_expired(entry):\n    continue\n```\n\n### Step 5: Result Truncation\n\nTo prevent oversized responses, value fields are truncated to 500 characters before inclusion in results:\n\n```python\nresults.append(\n    {\n        \"namespace\": ns,\n        \"key\": entry[\"key\"],\n        \"value\": _truncate(entry[\"value\"], 500),\n        \"created_at\": entry[\"created_at\"],\n        \"access_count\": entry.get(\"access_count\", 0),\n    }\n)\n```\n\nThe full value remains intact in storage; truncation occurs only in search results.\n\n### Step 6: Result Ordering\n\nResults are sorted by two criteria in descending order:\n\n1. `access_count` — More frequently accessed entries rank higher\n2. `created_at` — More recently created entries rank higher within equal access counts\n\nThis ordering heuristic surfaces the most relevant and useful memories based on historical access patterns. 资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## MCP Tool Definition\n\nThe `memory_search` tool is registered with the MCP server with the following schema definition:\n\n```python\nTool(\n    name=\"memory_search\",\n    description=\"Search memories across namespaces by keyword substring. Case-insensitive match on both keys and values. Returns results sorted by access count.\",\n    inputSchema={\n        \"type\": \"object\",\n        \"properties\": {\n            \"query\": {\n                \"type\": \"string\",\n                \"description\": \"Search keyword or substring.\",\n            },\n            \"namespace\": {\n                \"type\": \"string\",\n                \"description\": \"Optional namespace to limit search. Searches ALL namespaces if omitted.\",\n            },\n            \"limit\": {\n                \"type\": \"integer\",\n                \"description\": \"Maximum results to return (default: 10).\",\n                \"default\": 10,\n            },\n            \"format\": {\n                \"type\": \"string\",\n                \"enum\": [\"markdown\", \"json\"],\n                \"description\": \"Response format (default: markdown).\",\n                \"default\": \"markdown\",\n            },\n        },\n        \"required\": [\"query\"],\n    },\n    annotations=ToolAnnotations(\n        readOnlyHint=True,\n        destructiveHint=False,\n        idempotentHint=True,\n        openWorldHint=True,\n    ),\n),\n```\n\n### Tool Annotations\n\n| Annotation | Value | Implication |\n|------------|-------|-------------|\n| `readOnlyHint` | `True` | The tool does not modify stored data |\n| `destructiveHint` | `False` | No permanent deletion occurs during search |\n| `idempotentHint` | `True` | Multiple identical calls produce identical results |\n| `openWorldHint` | `True` | Search may cross namespace boundaries |\n\nThese annotations inform client applications about the nature of the operation, enabling appropriate caching, undo handling, and UI behavior.\n\n## Response Formats\n\n### Markdown Output (Default)\n\nWhen `fmt=\"markdown\"` or `fmt` is `None`:\n\n```\n## ✅ Success\n\n**query:** search_term\n\n**results:** 3 items\n\n  - **namespace:** project-alpha\n    **key:** api_credentials\n    **value:** sk-... (truncated to 500 chars)\n    **created_at:** 2025-01-15T10:30:00\n    **access_count:** 42\n\n  - **namespace:** project-alpha\n    **key:** user_preferences\n    **value:** dark_mode: true, language:...\n    **created_at:** 2025-01-14T08:15:00\n    **access_count:** 38\n\n  - **namespace:** default\n    **key:** search_history\n    **value:** previous queries stored here...\n    **created_at:** 2025-01-10T14:22:00\n    **access_count:** 12\n```\n\n### JSON Output\n\nWhen `fmt=\"json\"`:\n\n```json\n{\n  \"status\": \"ok\",\n  \"query\": \"search_term\",\n  \"results\": [\n    {\n      \"namespace\": \"project-alpha\",\n      \"key\": \"api_credentials\",\n      \"value\": \"sk-... (truncated)\",\n      \"created_at\": \"2025-01-15T10:30:00\",\n      \"access_count\": 42\n    }\n  ],\n  \"total_found\": 3,\n  \"returned\": 3\n}\n```\n\n## Usage Examples\n\n### Basic Search Across All Namespaces\n\n```python\nresult = memory_search(query=\"api_key\", limit=5)\n```\n\nThis searches all namespaces for entries containing \"api_key\" in either the key or value field, returning the top 5 matches sorted by access frequency.\n\n### Namespace-Scoped Search\n\n```python\nresult = memory_search(\n    query=\"user\",\n    namespace=\"session_2024\",\n    limit=20\n)\n```\n\nLimiting search to a specific namespace reduces I/O and improves response time when the agent knows the relevant context domain.\n\n### Integration with MCP Client\n\n```python\nfrom mcp import ClientSession\n\nasync def search_memories(session: ClientSession, query: str):\n    result = await session.call_tool(\n        \"memory_search\",\n        arguments={\n            \"query\": query,\n            \"namespace\": None,\n            \"limit\": 10,\n            \"format\": \"markdown\"\n        }\n    )\n    return result.content[0].text\n```\n\n## Error Handling\n\n### Empty Query Error\n\n```python\nif not query.strip():\n    return _error(\"Query must not be empty\", fmt)\n```\n\nReturns:\n\n```\n## ❌ Error\n**Query must not be empty**\n```\n\n### Internal Error Handling\n\nThe `call_tool` wrapper catches exceptions and formats them as error responses:\n\n```python\nexcept Exception as exc:\n    err_text = _error(f\"Internal error in {name}: {exc}\", fmt)\n    return CallToolResult(\n        content=[TextContent(type=\"text\", text=err_text)],\n        isError=True,\n    )\n```\n\nThis ensures that filesystem errors, JSON parsing failures, or unexpected exceptions return structured error responses rather than crashes.\n\n## Performance Considerations\n\n| Factor | Impact |\n|--------|--------|\n| Namespace count | Linear increase in filesystem reads |\n| Entries per namespace | Linear scan through all entries |\n| Value size | Truncation mitigates large value impact |\n| Default limit (10) | Bounds result set size |\n\nThe tool does not implement indexing; every search performs a full scan of matching entries. For deployments with thousands of entries across many namespaces, consider:\n\n- Using namespace-scoped searches when context is known\n- Increasing the `limit` parameter to reduce missed relevant results\n- Partitioning memories into task-specific namespaces\n\n## Related Tools\n\n| Tool | Purpose |\n|------|---------|\n| `memory_remember` | Store new key-value entries |\n| `memory_recall` | Retrieve entry by exact key name |\n| `memory_forget` | Delete entry by key |\n| `memory_list_namespaces` | Enumerate available namespaces |\n| `memory_clear_namespace` | Delete all entries in a namespace |\n| `memory_stats` | View storage statistics |\n\n## Conclusion\n\nThe `memory_search` tool provides essential discovery capabilities for AI agents using Agent Memory MCP. By supporting fuzzy substring matching across both keys and values, it enables agents to find relevant context without requiring perfect recall of storage locations. The tool's design balances functionality with simplicity: case-insensitive matching, configurable result limits, and output formatting options make it adaptable to diverse agent architectures while maintaining predictable behavior through filesystem-based storage.\n\n---\n\n---\n\n## Doramagic Pitfall Log\n\nProject: Rumblingb/agent-memory-mcp\n\nSummary: Found 7 potential pitfall items; 0 are high/blocking. Highest priority: identity - 仓库名和安装名不一致.\n\n## 1. identity · 仓库名和安装名不一致\n\n- Severity: medium\n- Evidence strength: runtime_trace\n- Finding: 仓库名 `agent-memory-mcp` 与安装入口 `mcp` 不完全一致。\n- User impact: 用户照着仓库名搜索包或照着包名找仓库时容易走错入口。\n- Suggested check: 在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。\n- Reproduction command: `pip install mcp`\n- Guardrail action: 页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。\n- Evidence: identity.distribution | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | repo=agent-memory-mcp; install=mcp\n\n## 2. capability · 能力判断依赖假设\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: README/documentation is current enough for a first validation pass.\n- User impact: 假设不成立时，用户拿不到承诺的能力。\n- Suggested check: 将假设转成下游验证清单。\n- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。\n- Evidence: capability.assumptions | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | README/documentation is current enough for a first validation pass.\n\n## 3. maintenance · 维护活跃度未知\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 未记录 last_activity_observed。\n- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。\n- Evidence: evidence.maintainer_signals | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | last_activity_observed missing\n\n## 4. security_permissions · 下游验证发现风险项\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 下游已经要求复核，不能在页面中弱化。\n- Suggested check: 进入安全/权限治理复核队列。\n- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。\n- Evidence: downstream_validation.risk_items | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | no_demo; severity=medium\n\n## 5. security_permissions · 存在评分风险\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 风险会影响是否适合普通用户安装。\n- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。\n- Evidence: risks.scoring_risks | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | no_demo; severity=medium\n\n## 6. maintenance · issue/PR 响应质量未知\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: issue_or_pr_quality=unknown。\n- User impact: 用户无法判断遇到问题后是否有人维护。\n- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。\n- Guardrail action: issue/PR 响应未知时，必须提示维护风险。\n- Evidence: evidence.maintainer_signals | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | issue_or_pr_quality=unknown\n\n## 7. maintenance · 发布节奏不明确\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: release_recency=unknown。\n- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。\n- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- Evidence: evidence.maintainer_signals | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | release_recency=unknown\n\n<!-- canonical_name: Rumblingb/agent-memory-mcp; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "agent-memory-mcp",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:1236240815",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/Rumblingb/agent-memory-mcp"
        },
        {
          "evidence_id": "art_4f1584cdb6d643c099ec7e025683da6e",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/Rumblingb/agent-memory-mcp#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki output with a Doramagic pitfall appendix.",
      "title": "agent-memory-mcp 说明书",
      "toc": [
        "https://github.com/Rumblingb/agent-memory-mcp 项目说明书",
        "目录",
        "Overview",
        "Purpose and Scope",
        "Architecture",
        "Core Components",
        "Concurrency and Safety",
        "Tier System",
        "Doramagic 踩坑日志"
      ]
    }
  },
  "quality_gate": {
    "blocking_gaps": [],
    "category_confidence": "medium",
    "compile_status": "ready_for_review",
    "five_assets_present": true,
    "install_sandbox_verified": true,
    "missing_evidence": [],
    "next_action": "publish to Doramagic.ai project surfaces",
    "prompt_preview_boundary_ok": true,
    "publish_status": "publishable",
    "quick_start_verified": true,
    "repo_clone_verified": true,
    "repo_commit": "b6142b50dcf7d6b901620b6fc7553a8fb2235b23",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "pyproject.toml",
      "package.json",
      "README.md",
      "requirements.txt"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [
      "community_discussion_evidence_below_public_threshold"
    ],
    "tag_count_ok": true,
    "unsupported_claims": []
  },
  "schema_version": "0.1",
  "user_assets": {
    "ai_context_pack": {
      "asset_id": "ai_context_pack",
      "filename": "AI_CONTEXT_PACK.md",
      "markdown": "# agent-memory-mcp - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 agent-memory-mcp 编译的 AI Context Pack。请把它当作开工前上下文：帮助用户理解适合谁、能做什么、如何开始、哪些必须安装后验证、风险在哪里。不要声称你已经安装、运行或执行了目标项目。\n\n## Claim 消费规则\n\n- **事实来源**：Repo Evidence + Claim/Evidence Graph；Human Wiki 只提供显著性、术语和叙事结构。\n- **事实最低状态**：`supported`\n- `supported`：可以作为项目事实使用，但回答中必须引用 claim_id 和证据路径。\n- `weak`：只能作为低置信度线索，必须要求用户继续核实。\n- `inferred`：只能用于风险提示或待确认问题，不能包装成项目事实。\n- `unverified`：不得作为事实使用，应明确说证据不足。\n- `contradicted`：必须展示冲突来源，不得替用户强行选择一个版本。\n\n## 它最适合谁\n\n- **想在安装前理解开源项目价值和边界的用户**：当前证据主要来自项目文档。 证据：`README.md` Claim：`clm_0002` supported 0.86\n\n## 它能做什么\n\n- **项目知识预览**（可做安装前预览）：项目可被阅读和解释，但当前证据不足以确认可安装能力或运行入口。 证据：`README.md`, `LICENSE`, `glama.json`, `.gitignore` 等 Claim：`clm_0001` supported 0.86\n\n## 怎么开始\n\n- 项目证据中没有稳定 Quick Start 命令；此项应留空，而不是由 Doramagic 编造。\n\n## 继续前判断卡\n\n- **当前建议**：先做 Prompt Preview\n- **为什么**：当前信息足以做安装前体验，但真实兼容性、输出质量或风险边界还不能直接相信。\n\n### 30 秒判断\n\n- **现在怎么做**：先做 Prompt Preview\n- **最小安全下一步**：先跑 Prompt Preview\n- **先别相信**：工具权限边界不能在安装前相信。\n- **继续会触碰**：宿主 AI 上下文\n\n### 现在可以相信\n\n- **适合人群线索：想在安装前理解开源项目价值和边界的用户**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0002` supported 0.86\n- **能力存在：项目知识预览**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md`, `LICENSE`, `glama.json`, `.gitignore` 等 Claim：`clm_0001` supported 0.86\n\n### 现在还不能相信\n\n- **工具权限边界不能在安装前相信。**（unverified）：MCP/tool 类项目通常会触碰文件、网络、浏览器或外部 API，必须真实检查权限和日志。\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n\n### 继续会触碰什么\n\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：用安装前交互式试用判断工作方式是否匹配，不需要授权或改环境。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。\n\n## 哪些只能预览\n\n- 解释项目适合谁和能做什么\n- 基于项目文档演示典型对话流程\n- 帮助用户判断是否值得安装或继续研究\n\n## 哪些必须安装后验证\n\n- 真实安装 Skill、插件或 CLI\n- 执行脚本、修改本地文件或访问外部服务\n- 验证真实输出质量、性能和兼容性\n\n## 边界与风险判断卡\n\n- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0003` inferred 0.45\n- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。\n- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。\n\n## 开工前工作上下文\n\n### 加载顺序\n\n- 先读取 how_to_use.host_ai_instruction，建立安装前判断资产的边界。\n- 读取 claim_graph_summary，确认事实来自 Claim/Evidence Graph，而不是 Human Wiki 叙事。\n- 再读取 intended_users、capabilities 和 quick_start_candidates，判断用户是否匹配。\n- 需要执行具体任务时，优先查 role_skill_index，再查 evidence_index。\n- 遇到真实安装、文件修改、网络访问、性能或兼容性问题时，转入 risk_card 和 boundaries.runtime_required。\n\n### 任务路由\n\n- **项目知识预览**：先基于 role_skill_index / evidence_index 帮用户挑选可用角色、Skill 或工作流。 边界：可做安装前 Prompt 体验。 证据：`README.md`, `LICENSE`, `glama.json`, `.gitignore` 等 Claim：`clm_0001` supported 0.86\n\n### 上下文规模\n\n- 文件总数：10\n- 重要文件覆盖：10/10\n- 证据索引条目：9\n- 角色 / Skill 条目：1\n\n### 证据不足时的处理\n\n- **missing_evidence**：说明证据不足，要求用户提供目标文件、README 段落或安装后验证记录；不要补全事实。\n- **out_of_scope_request**：说明该任务超出当前 AI Context Pack 证据范围，并建议用户先查看 Human Manual 或真实安装后验证。\n- **runtime_request**：给出安装前检查清单和命令来源，但不要替用户执行命令或声称已执行。\n- **source_conflict**：同时展示冲突来源，标记为待核实，不要强行选择一个版本。\n\n## Prompt Recipes\n\n### 适配判断\n\n- 目标：判断这个项目是否适合用户当前任务。\n- 预期输出：适配结论、关键理由、证据引用、安装前可预览内容、必须安装后验证内容、下一步建议。\n\n```text\n请基于 agent-memory-mcp 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 agent-memory-mcp 当作安装前体验资产，而不是已安装工具或真实运行环境。\n\n请严格输出四段：\n1. 先问我 3 个必要问题。\n2. 给出一段“体验剧本”：用 [安装前可预览]、[必须安装后验证]、[证据不足] 三种标签展示它可能如何引导工作流。\n3. 给出安装后验证清单：列出哪些能力只有真实安装、真实宿主加载、真实项目运行后才能确认。\n4. 给出谨慎建议：只能说“值得继续研究/试装”“先补充信息后再判断”或“不建议继续”，不得替项目背书。\n\n硬性边界：\n- 不要声称已经安装、运行、执行测试、修改文件或产生真实结果。\n- 不要写“自动适配”“确保通过”“完美适配”“强烈建议安装”等承诺性表达。\n- 如果描述安装后的工作方式，必须使用“如果安装成功且宿主正确加载 Skill，它可能会……”这种条件句。\n- 体验剧本只能写成“示例台词/假设流程”：使用“可能会询问/可能会建议/可能会展示”，不要写“已写入、已生成、已通过、正在运行、正在生成”。\n- Prompt Preview 不负责给安装命令；如用户准备试装，只能提示先阅读 Quick Start 和 Risk Card，并在隔离环境验证。\n- 所有项目事实必须来自 supported claim、evidence_refs 或 source_paths；inferred/unverified 只能作风险或待确认项。\n\n```\n\n### 角色 / Skill 选择\n\n- 目标：从项目里的角色或 Skill 中挑选最匹配的资产。\n- 预期输出：候选角色或 Skill 列表，每项包含适用场景、证据路径、风险边界和是否需要安装后验证。\n\n```text\n请读取 role_skill_index，根据我的目标任务推荐 3-5 个最相关的角色或 Skill。每个推荐都要说明适用场景、可能输出、风险边界和 evidence_refs。\n```\n\n### 风险预检\n\n- 目标：安装或引入前识别环境、权限、规则冲突和质量风险。\n- 预期输出：环境、权限、依赖、许可、宿主冲突、质量风险和未知项的检查清单。\n\n```text\n请基于 risk_card、boundaries 和 quick_start_candidates，给我一份安装前风险预检清单。不要替我执行命令，只说明我应该检查什么、为什么检查、失败会有什么影响。\n```\n\n### 宿主 AI 开工指令\n\n- 目标：把项目上下文转成一次对话开始前的宿主 AI 指令。\n- 预期输出：一段边界明确、证据引用明确、适合复制给宿主 AI 的开工前指令。\n\n```text\n请基于 agent-memory-mcp 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 1 个角色 / Skill / 项目文档条目。\n\n- **Agent Memory MCP Pro**（project_doc）：Persistent memory storage for AI agents across conversations. Remember user preferences, session state, and context. $19/month. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`\n\n## 证据索引\n\n- 共索引 9 条证据。\n\n- **Agent Memory MCP Pro**（documentation）：Persistent memory storage for AI agents across conversations. Remember user preferences, session state, and context. $19/month. 证据：`README.md`\n- **License**（source_file）：Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files the \"Software\" , to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 证据：`LICENSE`\n- **Glama**（structured_config）：{ \"$schema\": \"https://glama.ai/mcp/schemas/server.json\", \"maintainers\": \"Rumblingb\" } 证据：`glama.json`\n- **Python**（source_file）：Python pycache / .py cod $py.class .so .egg-info/ dist/ build/ .egg 证据：`.gitignore`\n- **Index**（source_file）：Agent Memory MCP — Persistent Memory for AI Agents { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: 0d1117; color: c9d1d9; line-height: 1.6; } .container { max-width: 800px; margin: 0 auto; padding: 60px 20px; } h1 { font-size: 2.5rem; margin-bottom: 0.5rem; background: linear-gradient 135deg, 58a6ff, bc8cff ; -webkit-background-clip: text; -webkit-text-fill-color: transparent; } .subtitle { font-size: 1.2rem; color: 8b949e; margin-bottom: 2rem; } .badges { margin: 1rem 0 2rem; display: flex; gap: 0.5rem; flex-wrap: wrap; } .badge { background: 21262d; border: 1px solid 30363d; border-radius… 证据：`index.html`\n- **Pyproject**（source_file）：build-system requires = \"setuptools =68.0\", \"wheel\" build-backend = \"setuptools.backends. legacy: Backend\" 证据：`pyproject.toml`\n- **Requirements**（source_file）：mcp =1.0.0 证据：`requirements.txt`\n- **!/usr/bin/env python3**（source_file）：!/usr/bin/env python3 \"\"\" Agent Memory MCP Server ======================== A persistent key-value memory store for AI agents with TTL, namespaces, fuzzy search, and access counting. Data lives in ~/.agent-memory/ as one JSON file per namespace plus a meta.json stats file. 证据：`server.py`\n- **Smithery.ai deployment configuration for Agent Memory MCP**（source_file）：Smithery.ai deployment configuration for Agent Memory MCP name: agent-memory-mcp version: 1.0.0 description: Persistent key-value memory for AI agents with TTL, namespaces, and search. 证据：`smithery.yaml`\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`README.md`, `LICENSE`, `glama.json`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`README.md`, `LICENSE`, `glama.json`\n\n## 用户开工前应该回答的问题\n\n- 你准备在哪个宿主 AI 或本地环境中使用它？\n- 你只是想先体验工作流，还是准备真实安装？\n- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？\n\n## 验收标准\n\n- 所有能力声明都能回指到 evidence_refs 中的文件路径。\n- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。\n- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。\n\n---\n\n## Doramagic Context Augmentation\n\nThe following material strengthens the Repomix/AI Context Pack body. Human Manual is only a reading skeleton; pitfall logs become hard operating constraints for the host AI.\n\n## Human Manual Skeleton\n\nUsage rule: this is only a reading path and salience signal, not factual authority. Concrete facts must still come from repo evidence / Claim Graph.\n\nHard rules for the host AI:\n- Do not treat page titles, order, summaries, or importance as project facts.\n- When explaining the Human Manual skeleton, state that it is only a reading path / salience signal.\n- Capability, installation, compatibility, runtime status, and risk judgments must cite repo evidence, source paths, or Claim Graph.\n\n- **Overview**：importance `high`\n  - source_paths: README.md, server.py\n- **Installation**：importance `high`\n  - source_paths: requirements.txt, pyproject.toml\n- **Quick Start Guide**：importance `high`\n  - source_paths: server.py\n- **Namespaces**：importance `high`\n  - source_paths: server.py\n- **TTL Management**：importance `high`\n  - source_paths: server.py\n- **Data Storage**：importance `medium`\n  - source_paths: server.py\n- **memory_remember Tool**：importance `high`\n  - source_paths: server.py\n- **memory_recall Tool**：importance `high`\n  - source_paths: server.py\n\n## Repo Inspection Evidence\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `b6142b50dcf7d6b901620b6fc7553a8fb2235b23`\n- inspected_files: `pyproject.toml`, `package.json`, `README.md`, `requirements.txt`\n\nHard rules for the host AI:\n- Without repo_clone_verified=true, do not claim the source code has been read.\n- Without repo_inspection_verified=true, do not turn README/docs/package observations into facts.\n- Without quick_start_verified=true, do not claim the Quick Start has been successfully run.\n\n## Doramagic Pitfall Constraints\n\nThese rules come from Doramagic discovery, validation, or compilation pitfalls. The host AI must treat them as operating constraints, not general background notes.\n\n### Constraint 1: 仓库名和安装名不一致\n\n- Trigger: 仓库名 `agent-memory-mcp` 与安装入口 `mcp` 不完全一致。\n- Host AI rule: 在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。\n- Why it matters: 用户照着仓库名搜索包或照着包名找仓库时容易走错入口。\n- Evidence: identity.distribution | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | repo=agent-memory-mcp; install=mcp\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 2: 能力判断依赖假设\n\n- Trigger: README/documentation is current enough for a first validation pass.\n- Host AI rule: 将假设转成下游验证清单。\n- Why it matters: 假设不成立时，用户拿不到承诺的能力。\n- Evidence: capability.assumptions | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | README/documentation is current enough for a first validation pass.\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 3: 维护活跃度未知\n\n- Trigger: 未记录 last_activity_observed。\n- Host AI rule: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Why it matters: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Evidence: evidence.maintainer_signals | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | last_activity_observed missing\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 4: 下游验证发现风险项\n\n- Trigger: no_demo\n- Host AI rule: 进入安全/权限治理复核队列。\n- Why it matters: 下游已经要求复核，不能在页面中弱化。\n- Evidence: downstream_validation.risk_items | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | no_demo; severity=medium\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 5: 存在评分风险\n\n- Trigger: no_demo\n- Host AI rule: 把风险写入边界卡，并确认是否需要人工复核。\n- Why it matters: 风险会影响是否适合普通用户安装。\n- Evidence: risks.scoring_risks | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | no_demo; severity=medium\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 6: issue/PR 响应质量未知\n\n- Trigger: issue_or_pr_quality=unknown。\n- Host AI rule: 抽样最近 issue/PR，判断是否长期无人处理。\n- Why it matters: 用户无法判断遇到问题后是否有人维护。\n- Evidence: evidence.maintainer_signals | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | issue_or_pr_quality=unknown\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 7: 发布节奏不明确\n\n- Trigger: release_recency=unknown。\n- Host AI rule: 确认最近 release/tag 和 README 安装命令是否一致。\n- Why it matters: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Evidence: evidence.maintainer_signals | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | release_recency=unknown\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n",
      "summary": "Context and operating boundaries for host AI agents.",
      "title": "AI Context Pack"
    },
    "boundary_risk_card": {
      "asset_id": "boundary_risk_card",
      "filename": "BOUNDARY_RISK_CARD.md",
      "markdown": "# Boundary & Risk Card\n\nProject: Rumblingb/agent-memory-mcp\n\n## Doramagic Trial Decision\n\nCurrent decision: it can enter pre-publication recommendation checks. First use should still start with least privilege, a temporary directory, and reversible configuration.\n\n## What The User Can Do Now\n\n- Read the Human Manual first to understand the project purpose and main workflows.\n- Use Prompt Preview for pre-install exploration; it validates interaction shape, not real execution.\n- Run official Quick Start commands only inside an isolated environment, not a primary setup.\n\n## Do Not Do Yet\n\n- Do not treat Prompt Preview as a real project execution result.\n- Do not treat metadata-only validation as sandbox installation validation.\n- Do not describe unverified capabilities as supported, working, or safe to install.\n- Do not provide production data, private files, real secrets, or primary host configuration on first trial.\n\n## Pre-Install Checklist\n\n- Host AI match: mcp_host\n- Official installation entry status: official entry point found\n- Isolated temporary directory, temporary host, or container validation: required\n- Configuration rollback path: required\n- API keys, network access, file access, or host configuration changes: treat as high risk until confirmed\n- Installation command, actual output, and failure logs: must be recorded\n\n## Current Blockers\n\n- review_required: community_discussion_evidence_below_public_threshold\n\n## Project-Specific Pitfalls\n\n- 仓库名和安装名不一致 (medium): 用户照着仓库名搜索包或照着包名找仓库时容易走错入口。 Suggested check: 在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。\n- 能力判断依赖假设 (medium): 假设不成立时，用户拿不到承诺的能力。 Suggested check: 将假设转成下游验证清单。\n- 维护活跃度未知 (medium): 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。 Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 下游验证发现风险项 (medium): 下游已经要求复核，不能在页面中弱化。 Suggested check: 进入安全/权限治理复核队列。\n- 存在评分风险 (medium): 风险会影响是否适合普通用户安装。 Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n\n## Risk And Permission Notes\n\n- no_demo: medium\n\n## Evidence Gaps\n\n- No structured evidence gaps are currently visible.\n",
      "summary": "Installation, permission, validation, and pre-recommendation risks.",
      "title": "Boundary & Risk Card"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/Rumblingb/agent-memory-mcp 项目说明书\n\n生成时间：2026-05-15 22:52:32 UTC\n\n## 目录\n\n- [Overview](#overview)\n- [Installation](#installation)\n- [Quick Start Guide](#quick-start)\n- [Namespaces](#namespaces)\n- [TTL Management](#ttl-management)\n- [Data Storage](#data-storage)\n- [memory_remember Tool](#memory-remember)\n- [memory_recall Tool](#memory-recall)\n- [memory_forget Tool](#memory-forget)\n- [memory_search Tool](#memory-search)\n\n<a id='overview'></a>\n\n## Overview\n\n### 相关页面\n\n相关主题：[Installation](#installation), [Quick Start Guide](#quick-start)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/Rumblingb/agent-memory-mcp/blob/main/README.md)\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n- [requirements.txt](https://github.com/Rumblingb/agent-memory-mcp/blob/main/requirements.txt)\n- [smithery.yaml](https://github.com/Rumblingb/agent-memory-mcp/blob/main/smithery.yaml)\n- [glama.json](https://github.com/Rumblingb/agent-memory-mcp/blob/main/glama.json)\n- [index.html](https://github.com/Rumblingb/agent-memory-mcp/blob/main/index.html)\n</details>\n\n# Overview\n\nAgent Memory MCP is a persistent key-value memory store designed specifically for AI agents. It solves the fundamental problem of context loss between sessions by providing a durable, searchable storage layer that survives restarts, crashes, and context-window limitations.\n\n## Purpose and Scope\n\nAI agents typically lose all context between sessions. Every conversation starts from zero, requiring users to re-explain preferences, history, and requirements repeatedly. Agent Memory MCP addresses this by implementing a persistent memory system with the following capabilities:\n\n- **Persistent Storage**: Data survives agent restarts and system reboots\n- **TTL Support**: Auto-expiring memories with second-level precision\n- **Namespace Isolation**: Organize memories by project, user, or domain\n- **Fuzzy Search**: Case-insensitive keyword search across all namespaces\n- **Access Tracking**: Monitor memory usage patterns and entry activity\n\n资料来源：[README.md](https://github.com/Rumblingb/agent-memory-mcp/blob/main/README.md)\n\n## Architecture\n\nAgent Memory MCP is built on the Model Context Protocol (MCP) Python SDK and operates as a stdio-based server. The architecture follows a simple but effective layered design:\n\n```mermaid\ngraph TD\n    subgraph \"Client Layer\"\n        A[AI Agent / Claude Desktop]\n    end\n    \n    subgraph \"MCP Protocol Layer\"\n        B[MCP Server]\n    end\n    \n    subgraph \"Storage Layer\"\n        C[~/.agent-memory/]\n        D[namespace1.json]\n        E[namespace2.json]\n        F[_meta.json]\n    end\n    \n    A -->|MCP Protocol| B\n    B -->|Read/Write| C\n    C --> D\n    C --> E\n    C --> F\n```\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Storage Model\n\nThe system stores data as JSON files in `~/.agent-memory/`, with one file per namespace plus a metadata file:\n\n| File Pattern | Purpose |\n|--------------|---------|\n| `{namespace}.json` | Key-value entries for a specific namespace |\n| `_meta.json` | Global statistics and metadata |\n\nNamespace filenames are sanitized to prevent directory traversal attacks. Characters outside `[a-zA-Z0-9_.-]` are replaced with underscores.\n\n资料来源：[server.py:42-49](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Core Components\n\n### Tool Handlers\n\nThe MCP server exposes seven tools for memory management:\n\n| Tool | Description | Read-Only | Destructive |\n|------|-------------|-----------|-------------|\n| `memory_remember` | Store a value with optional TTL | No | No |\n| `memory_recall` | Retrieve a value + metadata | Yes | No |\n| `memory_forget` | Delete a key permanently | No | Yes |\n| `memory_search` | Search all namespaces by keyword | Yes | No |\n| `memory_list_namespaces` | List namespaces with counts | Yes | No |\n| `memory_clear_namespace` | Wipe a namespace | No | Yes |\n| `memory_stats` | Global storage statistics | Yes | No |\n\n资料来源：[server.py:206-298](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Memory Entry Schema\n\nEach memory entry contains the following fields:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `key` | string | Unique identifier within namespace |\n| `value` | string | Stored content (max ~25,000 characters) |\n| `namespace` | string | Storage partition identifier |\n| `created_at` | ISO timestamp | Creation timestamp |\n| `accessed_at` | ISO timestamp | Last access timestamp |\n| `expires_at` | ISO timestamp or null | TTL expiration time |\n| `access_count` | integer | Number of times accessed |\n\n资料来源：[server.py:350-358](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Concurrency and Safety\n\nThe system implements POSIX file locking via `fcntl.flock` to ensure thread-safe concurrent access from multiple agents:\n\n```python\n@contextmanager\ndef _locked_file(path: Path, mode: str = \"r+\"):\n    fh = open(path, mode)\n    try:\n        fcntl.flock(fh, fcntl.LOCK_EX)\n        yield fh\n    finally:\n        fcntl.flock(fh, fcntl.LOCK_UN)\n        fh.close()\n```\n\nThe lock gracefully degrades on platforms without `fcntl` support (e.g., Windows without WSL).\n\n资料来源：[server.py:67-83](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Tier System\n\n| Tier | Entries | Price | Features |\n|------|---------|-------|----------|\n| Free | 1,000 | Free | All 7 tools |\n| Pro | Unlimited | $19/month | Unlimited storage |\n\n资料来源：[smithery.yaml](https://github.com/Rumblingb/agent-memory-mcp/blob/main/smithery.yaml)\n\n## Installation\n\n```bash\npip install agent-memory-mcp\n```\n\n**Requirements:**\n\n- Python 3.10+\n- `mcp >= 1.0.0`\n\n资料来源：[requirements.txt](https://github.com/Rumblingb/agent-memory-mcp/blob/main/requirements.txt)\n\n## Entry Point\n\nThe server runs as an async stdio server:\n\n```python\nasync def main() -> None:\n    _ensure_storage()\n    async with stdio_server() as (read_stream, write_stream):\n        await server.run(\n            read_stream,\n            write_stream,\n            server.create_initialization_options(),\n        )\n```\n\n资料来源：[server.py:318-326](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## License and Attribution\n\n| Attribute | Value |\n|-----------|-------|\n| License | MIT |\n| Author | Nous Research |\n| Repository | [github.com/nousresearch/agent-memory-mcp](https://github.com/nousresearch/agent-memory-mcp) |\n\n资料来源：[README.md](https://github.com/Rumblingb/agent-memory-mcp/blob/main/README.md)\n\n---\n\n<a id='installation'></a>\n\n## Installation\n\n### 相关页面\n\n相关主题：[Overview](#overview), [Quick Start Guide](#quick-start)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n- [requirements.txt](https://github.com/Rumblingb/agent-memory-mcp/blob/main/requirements.txt)\n- [smithery.yaml](https://github.com/Rumblingb/agent-memory-mcp/blob/main/smithery.yaml)\n- [README.md](https://github.com/Rumblingb/agent-memory-mcp/blob/main/README.md)\n- [index.html](https://github.com/Rumblingb/agent-memory-mcp/blob/main/index.html)\n- [glama.json](https://github.com/Rumblingb/agent-memory-mcp/blob/main/glama.json)\n</details>\n\n# Installation\n\nThis guide covers all methods for installing and configuring the **Agent Memory MCP** server. The server provides persistent key-value memory storage for AI agents with TTL support, namespaces, fuzzy search, and access tracking.\n\n## Prerequisites\n\nBefore installing Agent Memory MCP, ensure your environment meets the following requirements:\n\n| Requirement | Version | Notes |\n|-------------|---------|-------|\n| Python | 3.10+ | Core runtime requirement |\n| pip | Latest | For package installation |\n| POSIX-compatible OS | Linux/macOS | Required for file locking via `fcntl` |\n| MCP Client | Compatible version | Any MCP 1.0.0+ compatible client |\n\n### System Dependencies\n\nThe server relies on POSIX file locking (`fcntl`) for thread-safe concurrent access:\n\n```python\n# From server.py:34-41\ntry:\n    fcntl.flock(fh, fcntl.LOCK_EX)\nexcept (NameError, OSError):\n    pass  # platform without fcntl support\n```\n\nOn Windows without WSL, file locking falls back gracefully as a no-op.\n\n资料来源：[server.py:34-41]()\n\n## Installation Methods\n\n### Method 1: pip (Recommended)\n\nThe simplest installation method uses pip directly from PyPI:\n\n```bash\npip install agent-memory-mcp\n```\n\nThis command installs the package and its dependencies, including the MCP SDK.\n\n资料来源：[index.html:1]()\n\n### Method 2: From Source\n\nTo install the latest development version from the repository:\n\n```bash\n# Clone the repository\ngit clone https://github.com/nousresearch/agent-memory-mcp.git\ncd agent-memory-mcp\n\n# Install in development mode\npip install -e .\n\n# Or install production dependencies\npip install -r requirements.txt\n```\n\n### Method 3: Using Smithery.ai\n\nFor deployment via Smithery.ai marketplace, the server is pre-configured:\n\n```yaml\n# From smithery.yaml\nruntime:\n  type: python\n  entrypoint: server.py\n  requirements: requirements.txt\n```\n\n资料来源：[smithery.yaml:1-6]()\n\n## Dependencies\n\nAgent Memory MCP has a minimal dependency footprint:\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| mcp | ≥1.0.0 | Model Context Protocol SDK |\n\n资料来源：[requirements.txt:1]()\n\nThe MCP SDK provides:\n\n- Server implementation via `mcp.server.Server`\n- Stdio transport via `mcp.server.stdio.stdio_server`\n- Tool definitions via `mcp.types`\n\n资料来源：[server.py:17-25]()\n\n## Server Entry Point\n\nAfter installation, the server can be run directly:\n\n```bash\npython server.py\n```\n\nThe server uses stdio transport for communication with MCP clients:\n\n```python\n# From server.py:267-272\nasync def main() -> None:\n    _ensure_storage()\n    async with stdio_server() as (read_stream, write_stream):\n        await server.run(\n            read_stream,\n            write_stream,\n            server.create_initialization_options(),\n        )\n```\n\n资料来源：[server.py:267-272]()\n\n## Storage Initialization\n\nOn first run, the server automatically creates the storage directory:\n\n```python\n# From server.py:47-49\ndef _ensure_storage() -> None:\n    \"\"\"Create the storage directory if it doesn't exist.\"\"\"\n    STORAGE_DIR.mkdir(parents=True, exist_ok=True)\n```\n\nThe default storage location is `~/.agent-memory/`:\n\n```python\n# From server.py:38\nSTORAGE_DIR = Path.home() / \".agent-memory\"\n```\n\n资料来源：[server.py:38,47-49]()\n\n### Storage Structure\n\nThe storage directory contains one JSON file per namespace plus a metadata file:\n\n```\n~/.agent-memory/\n├── default.json          # Default namespace\n├── project_a.json        # Custom namespace\n├── user_prefs.json       # Another namespace\n└── _meta.json            # Global metadata\n```\n\n## Configuration Options\n\n### Environment Variables\n\nThe server supports runtime configuration via environment variables:\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `AGENT_MEMORY_PATH` | `~/.agent-memory/` | Custom storage directory path |\n\n### Server Configuration\n\nThe MCP server is configured with metadata:\n\n```python\n# From server.py:238-242\nserver = Server(\n    name=\"agent-memory\",\n    version=\"1.0.0\",\n    instructions=\"Agent Memory MCP — Persistent key-value memory for AI agents with TTL, namespaces, and search.\",\n    website_url=\"https://github.com/nousresearch/agent-memory-mcp\",\n)\n```\n\n资料来源：[server.py:238-242]()\n\n## MCP Client Integration\n\n### Registering the Server\n\nConfigure your MCP client to use the Agent Memory server:\n\n#### For Claude Desktop\n\nAdd to your configuration file:\n\n```json\n{\n  \"mcpServers\": {\n    \"agent-memory\": {\n      \"command\": \"python\",\n      \"args\": [\"-m\", \"agent_memory_mcp\"]\n    }\n  }\n}\n```\n\n#### For Smithery.ai\n\nThe server is automatically available through the Smithery marketplace configuration:\n\n```yaml\n# From smithery.yaml\ncapabilities:\n  tools:\n    - memory_remember\n    - memory_recall\n    - memory_forget\n    - memory_search\n    - memory_list_namespaces\n    - memory_clear_namespace\n    - memory_stats\n```\n\n资料来源：[smithery.yaml:8-15]()\n\n## Available Tools\n\nOnce installed, the following tools are available:\n\n| Tool | Description |\n|------|-------------|\n| `memory_remember` | Store a value with optional TTL |\n| `memory_recall` | Retrieve a value + metadata |\n| `memory_forget` | Delete a key permanently |\n| `memory_search` | Search all namespaces by keyword |\n| `memory_list_namespaces` | List namespaces with counts |\n| `memory_clear_namespace` | Wipe a namespace |\n| `memory_stats` | Global storage statistics |\n\n资料来源：[index.html:1]()\n\n## Verification\n\nVerify the installation by checking the server version:\n\n```bash\npython server.py --version\n```\n\nOr by calling the `memory_stats` tool:\n\n```json\n{\n  \"name\": \"memory_stats\",\n  \"arguments\": {\n    \"format\": \"json\"\n  }\n}\n```\n\nExpected response:\n\n```json\n{\n  \"total_entries\": 0,\n  \"total_size_bytes\": 0,\n  \"namespace_count\": 0,\n  \"storage_path\": \"/home/user/.agent-memory\",\n  \"free_tier_limit\": 1000,\n  \"pro_tier_limit\": \"unlimited\"\n}\n```\n\n## Deployment Architecture\n\n```mermaid\ngraph TD\n    A[MCP Client] -->|stdio| B[Agent Memory MCP Server]\n    B -->|fcntl lock| C[Storage Directory]\n    C -->|JSON per NS| D[default.json]\n    C -->|JSON per NS| E[custom.json]\n    C -->|Metadata| F[_meta.json]\n    \n    G[Python Runtime] -->|mcp≥1.0.0| B\n```\n\n## Licensing\n\nAgent Memory MCP is distributed under the MIT License:\n\n资料来源：[README.md:1]()\n\n| Item | Value |\n|------|-------|\n| License | MIT |\n| Version | 1.0.0 |\n| Author | Nous Research |\n\n资料来源：[smithery.yaml:17-21]()\n资料来源：[glama.json:1-4]()\n\n## Troubleshooting\n\n### Windows without WSL\n\nOn Windows without WSL, file locking is disabled but the server remains functional. For production use on Windows, run via WSL.\n\n### Permission Errors\n\nEnsure the user running the server has write access to `~/.agent-memory/`:\n\n```bash\nmkdir -p ~/.agent-memory\nchmod 755 ~/.agent-memory\n```\n\n### MCP Connection Issues\n\nVerify the MCP SDK is properly installed:\n\n```bash\npython -c \"from mcp.server import Server; print('MCP SDK OK')\"\n\n---\n\n<a id='quick-start'></a>\n\n## Quick Start Guide\n\n### 相关页面\n\n相关主题：[Overview](#overview), [Installation](#installation), [memory_remember Tool](#memory-remember), [memory_recall Tool](#memory-recall)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n- [requirements.txt](https://github.com/Rumblingb/agent-memory-mcp/blob/main/requirements.txt)\n- [smithery.yaml](https://github.com/Rumblingb/agent-memory-mcp/blob/main/smithery.yaml)\n</details>\n\n# Quick Start Guide\n\n## Overview\n\nThe **Agent Memory MCP** server provides a persistent key-value memory system for AI agents. It enables agents to retain context across sessions, solve context-window limitations, and maintain searchable long-term memory. This guide walks you through installation, configuration, and usage of all available tools.\n\n## System Architecture\n\n```mermaid\ngraph TD\n    A[AI Agent] -->|MCP Protocol| B[Agent Memory MCP Server]\n    B --> C[~/.agent-memory/]\n    C --> D[namespace1.json]\n    C --> E[namespace2.json]\n    C --> F[_meta.json]\n    \n    G[memory_remember] -->|Store| C\n    H[memory_recall] -->|Retrieve| C\n    I[memory_search] -->|Query| C\n    J[memory_forget] -->|Delete| C\n```\n\n## Installation\n\n### Prerequisites\n\n| Requirement | Version |\n|-------------|---------|\n| Python | 3.10+ |\n| MCP SDK | ≥1.0.0 |\n\n### Install via pip\n\n```bash\npip install agent-memory-mcp\n```\n\n资料来源：[requirements.txt:1]()\n\n### Verify Installation\n\nAfter installation, the server runs as a stdio-based MCP server. No additional daemon setup is required.\n\n## Core Concepts\n\n### Namespaces\n\nNamespaces provide isolated storage compartments for organizing memories by project, user, or domain. Each namespace stores entries as a separate JSON file in `~/.agent-memory/`.\n\n| Default Namespace | Purpose |\n|-------------------|---------|\n| `default` | General-purpose storage when no namespace is specified |\n\n资料来源：[server.py:44]()\n\n### Entry Structure\n\nEach memory entry contains:\n\n```json\n{\n  \"key\": \"unique_identifier\",\n  \"value\": \"stored_content\",\n  \"created_at\": \"2024-01-01T00:00:00.000Z\",\n  \"accessed_at\": \"2024-01-01T00:00:00.000Z\",\n  \"expires_at\": null,\n  \"access_count\": 0\n}\n```\n\n### TTL (Time-To-Live)\n\nEntries can auto-expire after a specified duration. TTL is set in seconds with second-level precision using lazy expiry—the entry is removed on the next access after expiration.\n\n资料来源：[server.py:200-215]()\n\n### Thread Safety\n\nThe server uses POSIX file locking (`fcntl`) to ensure safe concurrent access from multiple agents.\n\n资料来源：[index.html]()\n\n## Available Tools\n\n| Tool | Purpose | Destructive | Read-Only |\n|------|---------|-------------|-----------|\n| `memory_remember` | Store a value | No | No |\n| `memory_recall` | Retrieve a value | No | Yes |\n| `memory_forget` | Delete a key | Yes | No |\n| `memory_search` | Search by keyword | No | Yes |\n| `memory_list_namespaces` | List all namespaces | No | Yes |\n| `memory_clear_namespace` | Wipe a namespace | Yes | No |\n| `memory_stats` | Get storage statistics | No | Yes |\n\n## Usage Examples\n\n### 1. Store a Memory\n\n**Tool:** `memory_remember`\n\nStore a value under a key in a persistent namespace:\n\n```json\n{\n  \"key\": \"user_preferences\",\n  \"value\": \"dark_mode_enabled: true, language: en\",\n  \"namespace\": \"settings\",\n  \"ttl_seconds\": 86400\n}\n```\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `key` | string | Yes | Unique identifier for this memory entry |\n| `value` | string | Yes | Content to store |\n| `namespace` | string | No | Namespace name (default: `default`) |\n| `ttl_seconds` | integer | No | Auto-expiry duration in seconds |\n| `format` | string | No | `markdown` or `json` (default: `markdown`) |\n\n资料来源：[server.py:130-175]()\n\n**Success Response:**\n\n```markdown\n## ✅ Success\n\n**message:** Stored 'user_preferences' in namespace 'settings'\n**key:** user_preferences\n**namespace:** settings\n**expires_in:** 86400s\n**expires_at:** 2024-01-02T00:00:00.000Z\n```\n\n### 2. Retrieve a Memory\n\n**Tool:** `memory_recall`\n\nFetch a stored value by key from a namespace:\n\n```json\n{\n  \"key\": \"user_preferences\",\n  \"namespace\": \"settings\"\n}\n```\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `key` | string | Yes | The key to retrieve |\n| `namespace` | string | No | Namespace to look in (default: `default`) |\n| `format` | string | No | `markdown` or `json` (default: `markdown`) |\n\n资料来源：[server.py:177-220]()\n\n**Response includes:**\n\n- Current value\n- Creation timestamp\n- Last access timestamp\n- Access count\n- Expiry status\n\n### 3. Delete a Memory\n\n**Tool:** `memory_forget`\n\nPermanently delete a specific key:\n\n```json\n{\n  \"key\": \"user_preferences\",\n  \"namespace\": \"settings\"\n}\n```\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `key` | string | Yes | The key to delete |\n| `namespace` | string | No | Namespace to delete from (default: `default`) |\n| `format` | string | No | `markdown` or `json` (default: `markdown`) |\n\n资料来源：[server.py:222-258]()\n\n### 4. Search Memories\n\n**Tool:** `memory_search`\n\nFind memories across namespaces by keyword (case-insensitive substring match):\n\n```json\n{\n  \"query\": \"preferences\",\n  \"namespace\": null,\n  \"limit\": 10\n}\n```\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `query` | string | Yes | Search keyword or substring |\n| `namespace` | string | No | Limit search to specific namespace |\n| `limit` | integer | No | Maximum results (default: 10) |\n| `format` | string | No | `markdown` or `json` (default: `markdown`) |\n\nSearch matches against both keys and values. Results are sorted by access count (highest first).\n\n资料来源：[server.py:260-320]()\n\n### 5. List All Namespaces\n\n**Tool:** `memory_list_namespaces`\n\nDisplay all namespaces with entry counts:\n\n```json\n{\n  \"format\": \"markdown\"\n}\n```\n\n**Response:**\n\n```markdown\n## ✅ Success\n\n**namespace_count:** 3\n**namespaces:** [3 items]\n  - **namespace:** project_a\n    - **active_entries:** 15\n    - **expired_entries:** 2\n  - **namespace:** project_b\n    - **active_entries:** 8\n    - **expired_entries:** 0\n  - **namespace:** default\n    - **active_entries:** 42\n    - **expired_entries:** 5\n```\n\n资料来源：[server.py:322-360]()\n\n### 6. Clear a Namespace\n\n**Tool:** `memory_clear_namespace`\n\nDelete ALL entries in a namespace permanently:\n\n```json\n{\n  \"namespace\": \"project_a\"\n}\n```\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `namespace` | string | Yes | Namespace to clear |\n\n**Warning:** This action cannot be undone.\n\n资料来源：[server.py:362-395]()\n\n### 7. View Storage Statistics\n\n**Tool:** `memory_stats`\n\nGet comprehensive storage metrics:\n\n```json\n{\n  \"format\": \"markdown\"\n}\n```\n\n**Response includes:**\n\n| Metric | Description |\n|--------|-------------|\n| `total_entries` | Total active memory entries |\n| `total_size_bytes` | Storage size in bytes |\n| `total_size_human` | Human-readable size |\n| `namespace_count` | Number of namespaces |\n| `oldest_entry` | Timestamp of oldest entry |\n| `newest_entry` | Timestamp of newest entry |\n| `storage_path` | Directory path (`~/.agent-memory/`) |\n| `free_tier_limit` | Free tier entry limit (1000) |\n\n资料来源：[server.py:397-440]()\n\n## Storage Layout\n\n```\n~/.agent-memory/\n├── _meta.json           # Global metadata\n├── default.json         # Default namespace\n├── project_a.json       # Custom namespace\n├── project_b.json       # Custom namespace\n└── ...\n```\n\nEach namespace file is a JSON array of entries:\n\n```json\n[\n  {\n    \"key\": \"example_key\",\n    \"value\": \"example_value\",\n    \"created_at\": \"2024-01-01T00:00:00.000Z\",\n    \"accessed_at\": \"2024-01-01T00:00:00.000Z\",\n    \"expires_at\": null,\n    \"access_count\": 5\n  }\n]\n```\n\n资料来源：[server.py:50-75]()\n\n## Response Formats\n\nAll tools support two response formats:\n\n| Format | Use Case |\n|--------|----------|\n| `markdown` | Human-readable output (default) |\n| `json` | Programmatic parsing |\n\nSpecify format via the `format` parameter in each tool call.\n\n## Workflow Diagram\n\n```mermaid\ngraph LR\n    A[Start] --> B{memory_remember?}\n    B -->|Yes| C[Store Entry]\n    B -->|No| D{memory_recall?}\n    D -->|Yes| E[Retrieve + Update Access]\n    D -->|No| F{memory_forget?}\n    F -->|Yes| G[Delete Entry]\n    F -->|No| H{memory_search?}\n    H -->|Yes| I[Search All Namespaces]\n    H -->|No| J{memory_list_namespaces?}\n    J -->|Yes| K[List with Counts]\n    J -->|No| L{memory_clear_namespace?}\n    L -->|Yes| M[Delete All in Namespace]\n    L -->|No| N{memory_stats?}\n    N -->|Yes| O[Return Statistics]\n    \n    C --> P[Success]\n    E --> P\n    G --> P\n    I --> P\n    K --> P\n    M --> P\n    O --> P\n```\n\n## Common Use Cases\n\n### Session Persistence\n\n```python\n# Remember conversation context\nmemory_remember(\n    key=\"session_123_context\",\n    value=\"User prefers technical explanations\",\n    namespace=\"sessions\"\n)\n\n# Recall on next session\ncontext = memory_recall(\n    key=\"session_123_context\",\n    namespace=\"sessions\"\n)\n```\n\n### Project-Scoped Memory\n\n```python\n# Store project-specific data\nmemory_remember(\n    key=\"api_endpoints\",\n    value=\"https://api.example.com/v1\",\n    namespace=\"project_alpha\"\n)\n\n# Search across all projects\nresults = memory_search(query=\"api_endpoints\")\n```\n\n### Temporary Caching with TTL\n\n```python\n# Cache with 1-hour expiry\nmemory_remember(\n    key=\"rate_limit_status\",\n    value=\"{'requests': 450, 'limit': 500}\",\n    namespace=\"cache\",\n    ttl_seconds=3600\n)\n```\n\n## Error Handling\n\n| Error Condition | Response |\n|-----------------|----------|\n| Empty key | `Key must not be empty` |\n| Expired entry | `Key 'X' has expired` |\n| Key not found | `Key 'X' not found in namespace 'Y'` |\n| Internal error | `Internal error in {tool}: {exception}` |\n\nAll errors return a response with `isError: true`.\n\n资料来源：[server.py:95-105]()\n\n## Configuration Options\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `STORAGE_DIR` | `~/.agent-memory/` | Storage directory location |\n| `DEFAULT_NAMESPACE` | `default` | Fallback namespace |\n| `CHARACTER_LIMIT` | 25,000 | Max response truncation |\n\n资料来源：[server.py:42-46]()\n\n## Next Steps\n\n- Explore [Advanced Search Patterns](#) for fuzzy matching techniques\n- Learn about [Namespace Organization](#) best practices\n- Set up [Monitoring](#) with `memory_stats` for capacity planning\n- Configure [Stripe Integration](#) for Pro tier upgrades\n\n---\n\n<a id='namespaces'></a>\n\n## Namespaces\n\n### 相关页面\n\n相关主题：[TTL Management](#ttl-management)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n</details>\n\n# Namespaces\n\n## Overview\n\nNamespaces in Agent Memory MCP provide **isolated storage containers** for memory entries, enabling logical separation of data across projects, users, domains, or any organizational scheme that fits an agent's workflow.\n\nEach namespace functions as an independent key-value store backed by a separate JSON file in the filesystem, with POSIX file locking ensuring safe concurrent access.\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Agent Memory MCP] --> B[Namespace Router]\n    B --> C[Namespace: default]\n    B --> D[Namespace: project-a]\n    B --> E[Namespace: user-123]\n    B --> N[...more namespaces]\n    \n    C --> F[\"default.json<br/>(in ~/.agent-memory/)\"]\n    D --> G[\"project-a.json\"]\n    E --> H[\"user-123.json\"]\n    N --> I[\"namespace.json\"]\n    \n    F --> J[_meta.json]\n    G --> J\n    H --> J\n    I --> J\n    \n    style F fill:#e1f5fe\n    style G fill:#e1f5fe\n    style H fill:#e1f5fe\n    style I fill:#e1f5fe\n    style J fill:#fff9c4\n```\n\n## Storage Model\n\n### File Structure\n\nNamespaces are persisted as individual JSON files in the `~/.agent-memory/` directory:\n\n| Element | Path | Purpose |\n|---------|------|---------|\n| Namespace files | `~/.agent-memory/{namespace}.json` | Individual key-value stores |\n| Metadata file | `~/.agent-memory/_meta.json` | Global statistics and entry counts |\n\n**资料来源:** [server.py:49-58](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Namespace Path Resolution\n\n```python\ndef _namespace_path(namespace: str) -> Path:\n    \"\"\"Return the full path for a namespace JSON file.\"\"\"\n    # Sanitize the namespace so it can't escape the directory.\n    safe = re.sub(r\"[^a-zA-Z0-9_.\\-]\", \"_\", namespace)\n    if not safe:\n        safe = DEFAULT_NAMESPACE\n    return STORAGE_DIR / f\"{safe}.json\"\n```\n\nThe namespace is sanitized to prevent directory traversal attacks—only alphanumeric characters, underscores, dots, and hyphens are permitted. Invalid names default to `\"default\"`.\n\n**资料来源:** [server.py:63-72](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Namespace Operations\n\n### Memory Remember\n\nStores a value under a key within a specified namespace.\n\n```python\ndef memory_remember(\n    key: str,\n    value: str,\n    namespace: str = \"default\",\n    ttl_seconds: Optional[int] = None,\n    fmt: Optional[str] = None,\n) -> str:\n```\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `key` | string | *required* | Unique identifier for the memory entry |\n| `value` | string | *required* | Content to store |\n| `namespace` | string | `\"default\"` | Target namespace |\n| `ttl_seconds` | integer | `null` | Time-to-live in seconds (optional) |\n| `format` | string | `\"markdown\"` | Response format (`markdown` or `json`) |\n\n**资料来源:** [server.py:163-210](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Memory Recall\n\nRetrieves a value and its metadata from a namespace.\n\n```python\ndef memory_recall(\n    key: str,\n    namespace: str = \"default\",\n    fmt: Optional[str] = None,\n) -> str:\n```\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `key` | string | *required* | Key to retrieve |\n| `namespace` | string | `\"default\"` | Namespace to search |\n| `format` | string | `\"markdown\"` | Response format |\n\n**资料来源:** [server.py:212-261](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Memory Forget\n\nPermanently deletes a key from a namespace.\n\n```python\ndef memory_forget(\n    key: str,\n    namespace: str = \"default\",\n    fmt: Optional[str] = None,\n) -> str:\n```\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `key` | string | *required* | Key to delete |\n| `namespace` | string | `\"default\"` | Namespace to delete from |\n| `format` | string | `\"markdown\"` | Response format |\n\n**资料来源:** [server.py:263-303](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Memory Search\n\nSearches within a specific namespace or across all namespaces.\n\n```python\ndef memory_search(\n    query: str,\n    namespace: Optional[str] = None,\n    limit: int = 10,\n    fmt: Optional[str] = None,\n) -> str:\n```\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `query` | string | *required* | Search keyword (case-insensitive) |\n| `namespace` | string | `null` | Limit search to one namespace (searches all if omitted) |\n| `limit` | integer | `10` | Maximum results to return |\n| `format` | string | `\"markdown\"` | Response format |\n\n**资料来源:** [server.py:305-365](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Memory List Namespaces\n\nLists all namespaces with active and expired entry counts.\n\n```python\ndef memory_list_namespaces(fmt: Optional[str] = None) -> str:\n```\n\nReturns a table of all namespaces containing:\n\n| Field | Description |\n|-------|-------------|\n| `namespace` | Namespace name |\n| `active_entries` | Non-expired entries |\n| `expired_entries` | Entries past TTL |\n\n**资料来源:** [server.py:367-400](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Memory Clear Namespace\n\nWipes all entries from a namespace permanently.\n\n```python\ndef memory_clear_namespace(\n    namespace: str,\n    fmt: Optional[str] = None,\n) -> str:\n```\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `namespace` | string | *required* | Namespace to clear |\n| `format` | string | `\"markdown\"` | Response format |\n\n**资料来源:** [server.py:402-427](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Data Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Server\n    participant FileSystem\n    \n    Client->>Server: memory_remember(key, value, namespace)\n    Server->>Server: _namespace_path(namespace)\n    Server->>Server: Sanitize namespace name\n    Server->>Server: _read_namespace(namespace)\n    Server->>Server: Append/update entry with metadata\n    Server->>Server: _write_namespace(namespace, entries)\n    Server->>Server: _recalc_meta()\n    Server->>Client: Success response\n    \n    Client->>Server: memory_recall(key, namespace)\n    Server->>Server: _read_namespace(namespace)\n    Server->>Server: Check TTL expiration\n    Server->>Server: Update access metadata\n    Server->>Server: _write_namespace(namespace, entries)\n    Server->>Client: Value + metadata\n```\n\n## Thread Safety\n\nNamespace operations use POSIX file locking via `fcntl.flock` to ensure safe concurrent access:\n\n```python\n@contextmanager\ndef _locked_file(path: Path, mode: str = \"r+\"):\n    \"\"\"Open a file with an exclusive POSIX lock (fcntl.flock).\"\"\"\n    _ensure_storage()\n    file_exists = path.exists()\n    if not file_exists and \"w\" in mode or \"+\" in mode:\n        path.touch(exist_ok=True)\n    fh = open(path, mode)\n    try:\n        try:\n            fcntl.flock(fh, fcntl.LOCK_EX)\n        except (NameError, OSError):\n            pass  # platform without fcntl support\n        yield fh\n    finally:\n        try:\n            fcntl.flock(fh, fcntl.LOCK_UN)\n        except (NameError, OSError):\n            pass\n        fh.close()\n```\n\nOn platforms without `fcntl` support (e.g., Windows without WSL), the lock gracefully degrades to a no-op.\n\n**资料来源:** [server.py:74-97](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Metadata Tracking\n\nGlobal metadata is recalculated by scanning all namespace files:\n\n```python\ndef _recalc_meta() -> None:\n    \"\"\"Recompute global metadata by scanning all namespaces.\"\"\"\n    total = 0\n    namespace_count = 0\n    for p in STORAGE_DIR.glob(\"*.json\"):\n        if p.stem == \"_meta\":\n            continue\n        namespace_count += 1\n        entries = _read_namespace(p.stem)\n        total += len([e for e in entries if not _is_expired(e)])\n    _write_meta({\"total_entries\": total, \"namespace_count\": namespace_count})\n```\n\n**资料来源:** [server.py:446-457](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Usage Examples\n\n### Storing Project-Specific Memories\n\n```python\n# Store project configuration\nmemory_remember(\n    key=\"config\",\n    value=\"debug_mode=true, max_connections=100\",\n    namespace=\"project-alpha\"\n)\n\n# Store user preferences\nmemory_remember(\n    key=\"theme\",\n    value=\"dark_mode\",\n    namespace=\"user-session-42\"\n)\n```\n\n### Cross-Namespace Search\n\n```python\n# Search all namespaces for \"config\"\nmemory_search(query=\"config\")\n\n# Search only project-alpha namespace\nmemory_search(query=\"config\", namespace=\"project-alpha\")\n```\n\n### Namespace Statistics\n\n```python\n# Get overview of all namespaces\nmemory_list_namespaces()\n```\n\n## Tool Annotations\n\nEach namespace operation is annotated with MCP metadata indicating its behavior:\n\n| Tool | readOnlyHint | destructiveHint | idempotentHint |\n|------|--------------|-----------------|----------------|\n| `memory_remember` | `false` | `false` | `true` |\n| `memory_recall` | `true` | `false` | `true` |\n| `memory_forget` | `false` | `true` | `true` |\n| `memory_search` | `true` | `false` | `true` |\n| `memory_list_namespaces` | `true` | `false` | `true` |\n| `memory_clear_namespace` | `false` | `true` | `true` |\n\n**资料来源:** [server.py:113-430](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Constants\n\n| Constant | Value | Description |\n|----------|-------|-------------|\n| `DEFAULT_NAMESPACE` | `\"default\"` | Fallback namespace when none specified |\n| `STORAGE_DIR` | `Path.home() / \".agent-memory\"` | Base directory for all data |\n| `CHARACTER_LIMIT` | `25,000` | Maximum response size before truncation |\n\n**资料来源:** [server.py:44-49](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n---\n\n<a id='ttl-management'></a>\n\n## TTL Management\n\n### 相关页面\n\n相关主题：[Namespaces](#namespaces), [memory_remember Tool](#memory-remember), [memory_recall Tool](#memory-recall)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n</details>\n\n# TTL Management\n\n## Overview\n\nTTL (Time-To-Live) Management provides automatic expiration for memory entries in the agent-memory-mcp system. This feature enables AI agents to store temporary information that self-destructs after a specified duration, making it ideal for caching, session data, and temporary context that becomes stale over time.\n\nThe TTL implementation uses a lazy expiry pattern where entries are checked and removed only when accessed, avoiding the overhead of background cleanup processes.\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[memory_remember] --> B[Calculate expires_at]\n    B --> C[Store entry with expires_at]\n    C --> D[Write to JSON file]\n    \n    E[memory_recall] --> F[Find entry by key]\n    F --> G{Is expired?}\n    G -->|Yes| H[Delete entry]\n    H --> I[Return Error]\n    G -->|No| J[Update access metadata]\n    J --> K[Return value]\n    \n    L[Background reads] --> M[_is_expired check]\n    M --> N[Filter expired entries]\n    N --> O[memory_list_namespaces]\n    N --> P[memory_stats]\n```\n\n## TTL Implementation Details\n\n### Core Expiry Detection\n\nThe `_is_expired()` function is the central mechanism for TTL validation:\n\n```python\ndef _is_expired(entry: Dict[str, Any]) -> bool:\n    expires_at = entry.get(\"expires_at\")\n    if expires_at is None:\n        return False\n    return _now_unix() > expires_at\n```\n\n| Component | Description |\n|-----------|-------------|\n| `entry.get(\"expires_at\")` | Retrieves the Unix timestamp when entry expires |\n| `None` return | No TTL set, entry never expires |\n| `True` result | Current time exceeds expiry time |\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### TTL Storage on Entry Creation\n\nWhen `memory_remember` is called with a `ttl_seconds` parameter, the expiry timestamp is calculated:\n\n```python\nentry = {\n    \"key\": key,\n    \"value\": value,\n    \"namespace\": namespace,\n    \"created_at\": _now_iso(),\n    \"accessed_at\": _now_iso(),\n    \"expires_at\": (now + ttl_seconds) if ttl_seconds else None,\n    \"access_count\": 0,\n}\n```\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `ttl_seconds` | integer | Duration in seconds before auto-expiry |\n| `expires_at` | float or None | Unix timestamp for expiry, None for permanent |\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## TTL Workflow\n\n### Lazy Expiry Pattern\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Server\n    participant Storage\n    \n    Client->>Server: memory_recall(key)\n    Server->>Storage: Read namespace file\n    Storage-->>Server: Entry found\n    \n    alt Entry is expired\n        Server->>Storage: Delete expired entry\n        Server-->>Client: Error: Key expired\n    else Entry is valid\n        Server->>Server: Update accessed_at\n        Server->>Server: Increment access_count\n        Server->>Storage: Write updated entry\n        Server-->>Client: Return value + metadata\n    end\n```\n\nThe lazy expiry approach offers several advantages:\n\n1. **No background processes** - Expiry is handled during normal operations\n2. **Immediate cleanup** - Expired entries are removed on next access\n3. **Minimal overhead** - No periodic scanning of all entries\n\n### Expiry During Namespace Operations\n\nExpired entries are filtered out when gathering statistics or listing namespaces:\n\n```python\nactive = [e for e in entries if not _is_expired(e)]\ntotal_entries += len(active)\n```\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## API Parameters\n\n### memory_remember\n\n| Parameter | Required | Type | Default | Description |\n|-----------|----------|------|---------|-------------|\n| `key` | Yes | string | - | Unique identifier for the memory entry |\n| `value` | Yes | string | - | Content to store |\n| `namespace` | No | string | `\"default\"` | Storage partition |\n| `ttl_seconds` | No | integer | `None` | Seconds until auto-expiry |\n| `format` | No | string | `\"markdown\"` | Response format (`markdown` or `json`) |\n\n### memory_recall\n\n| Parameter | Required | Type | Default | Description |\n|-----------|----------|------|---------|-------------|\n| `key` | Yes | string | - | Key to retrieve |\n| `namespace` | No | string | `\"default\"` | Namespace to search |\n| `format` | No | string | `\"markdown\"` | Response format |\n\n## Data Model\n\n### Memory Entry Schema\n\n```json\n{\n  \"key\": \"session_token\",\n  \"value\": \"abc123xyz\",\n  \"namespace\": \"user_sessions\",\n  \"created_at\": \"2024-01-15T10:30:00Z\",\n  \"accessed_at\": \"2024-01-15T11:45:00Z\",\n  \"expires_at\": 1705322700,\n  \"access_count\": 42\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `key` | string | Unique identifier within namespace |\n| `value` | string | Stored content |\n| `namespace` | string | Logical partition identifier |\n| `created_at` | ISO8601 string | Creation timestamp |\n| `accessed_at` | ISO8601 string | Last access timestamp |\n| `expires_at` | Unix timestamp or null | Expiry time (null = never expires) |\n| `access_count` | integer | Number of times accessed |\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Usage Examples\n\n### Storing Temporary Data with TTL\n\n```\nTool: memory_remember\nArguments: {\n  \"key\": \"oauth_token\",\n  \"value\": \"eyJhbGciOiJIUzI1NiIs...\",\n  \"namespace\": \"auth\",\n  \"ttl_seconds\": 3600\n}\n```\n\nThis stores an OAuth token that automatically expires after 1 hour.\n\n### Retrieving and Extending TTL\n\nThere is no built-in TTL extension mechanism. To extend an entry's lifetime:\n\n1. Use `memory_recall` to retrieve the current value\n2. Use `memory_remember` with a new `ttl_seconds` value\n\n```mermaid\ngraph LR\n    A[Recall entry] --> B[Get current value]\n    B --> C[Forget old entry]\n    C --> D[Remember with new TTL]\n```\n\n## Performance Considerations\n\n### Expired Entry Handling\n\n| Operation | Expired Entry Behavior |\n|-----------|----------------------|\n| `memory_remember` | Ignored (new key/value) |\n| `memory_recall` | Deleted, returns error |\n| `memory_forget` | Not found (already cleaned) |\n| `memory_search` | Excluded from results |\n| `memory_list_namespaces` | Counted in `expired_entries` |\n| `memory_stats` | Excluded from totals |\n\n### Storage File Structure\n\n```\n~/.agent-memory/\n├── default.json      # Default namespace\n├── auth.json         # Auth-related entries\n├── projects.json     # Project-specific entries\n└── _meta.json        # Global metadata\n```\n\nEach namespace is stored as a separate JSON file. Expired entries remain in the file until accessed, at which point they are removed during lazy expiry.\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Limitations\n\n1. **No automatic background cleanup** - Expired entries persist in storage files until accessed\n2. **No TTL modification** - Existing entries cannot have their TTL updated; must recreate\n3. **Second-level precision** - TTL is calculated in seconds, not milliseconds\n4. **No push notifications** - No mechanism to alert when entries are about to expire\n\n---\n\n<a id='data-storage'></a>\n\n## Data Storage\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n</details>\n\n# Data Storage\n\nThe **Data Storage** subsystem is the persistent layer of the Agent Memory MCP server. It handles all read/write operations to the filesystem, manages namespace isolation, enforces TTL (Time-To-Live) expiry, and provides thread-safe concurrent access using POSIX file locking.\n\n## Overview\n\nAgent Memory MCP uses a **file-based JSON storage model** where each namespace is stored as a separate JSON file. This design provides simplicity, portability, and easy inspection while maintaining isolation between different data domains.\n\n| Property | Value |\n|----------|-------|\n| Storage Location | `~/.agent-memory/` |\n| File Format | JSON (one file per namespace) |\n| Metadata File | `_meta.json` |\n| Concurrency Model | POSIX file locking (`fcntl`) |\n| Thread Safety | Yes (via `LOCK_EX` exclusive locks) |\n\n资料来源：[server.py:36-38](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Storage Architecture\n\n### Directory Structure\n\n```\n~/.agent-memory/\n├── default.json          # Default namespace\n├── project_a.json        # Custom namespace\n├── project_b.json        # Custom namespace\n└── _meta.json             # Global statistics metadata\n```\n\n### Namespace Files\n\nEach namespace is stored as a standalone JSON array containing memory entries. The filename is derived from the namespace name with character sanitization applied.\n\n```python\ndef _namespace_path(namespace: str) -> Path:\n    \"\"\"Return the full path for a namespace JSON file.\"\"\"\n    # Sanitize the namespace so it can't escape the directory.\n    safe = re.sub(r\"[^a-zA-Z0-9_.\\-]\", \"_\", namespace)\n    if not safe:\n        safe = DEFAULT_NAMESPACE\n    return STORAGE_DIR / f\"{safe}.json\"\n```\n\n资料来源：[server.py:54-61](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Sanitization Rules\n\n| Character Class | Action | Result |\n|-----------------|--------|--------|\n| `[a-zA-Z0-9_.\\-]` | Allowed | Preserved |\n| All others | Replaced | `_` (underscore) |\n| Empty after sanitization | Fallback | `default` namespace |\n\nThis prevents directory traversal attacks and ensures safe filesystem operations.\n\n## Data Models\n\n### Memory Entry Structure\n\n```json\n{\n  \"key\": \"user_preference_theme\",\n  \"value\": \"dark_mode\",\n  \"created_at\": \"2024-01-15T10:30:00.000Z\",\n  \"accessed_at\": \"2024-01-15T14:22:00.000Z\",\n  \"expires_at\": \"2024-02-15T10:30:00.000Z\",\n  \"access_count\": 42\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `key` | string | Unique identifier within namespace |\n| `value` | string | Stored content (any text) |\n| `created_at` | ISO 8601 string | Creation timestamp |\n| `accessed_at` | ISO 8601 string | Last access timestamp |\n| `expires_at` | ISO 8601 string or null | TTL expiry timestamp (null = never) |\n| `access_count` | integer | Number of times accessed |\n\n资料来源：[server.py:189-195](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Metadata File Structure (`_meta.json`)\n\n```json\n{\n  \"total_entries\": 150,\n  \"namespace_count\": 5\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `total_entries` | integer | Total active (non-expired) entries |\n| `namespace_count` | integer | Number of namespace files |\n\n## Storage Operations\n\n### Read Flow\n\n```mermaid\ngraph TD\n    A[memory_recall] --> B[Validate key not empty]\n    B --> C[_read_namespace namespace]\n    C --> D[Find entry by key]\n    D --> E{Entry exists?}\n    E -->|Yes| F{Is expired?}\n    E -->|No| G[Return error: key not found]\n    F -->|Yes| H[Remove expired entry]\n    F -->|No| I[Update access metadata]\n    H --> G\n    I --> J[Increment access_count]\n    J --> K[Update accessed_at]\n    K --> L[Return value + metadata]\n```\n\n### Write Flow\n\n```mermaid\ngraph TD\n    A[memory_remember] --> B[Validate key and value]\n    B --> C[_read_namespace namespace]\n    C --> D[Check for existing key]\n    D --> E{Key exists?}\n    E -->|Yes| F[Update existing entry]\n    E -->|No| G[Create new entry]\n    F --> H[_write_namespace]\n    G --> H\n    H --> I[_recalc_meta]\n    I --> J[Return success]\n```\n\n## Core Storage Functions\n\n### File Locking\n\nThread-safety is achieved through POSIX file locking using `fcntl`:\n\n```python\n@contextmanager\ndef _locked_file(path: Path, mode: str):\n    \"\"\"Open a file with exclusive locking (POSIX fcntl).\"\"\"\n    _ensure_storage()\n    fh = open(path, mode)\n    try:\n        fcntl.flock(fh.fileno(), fcntl.LOCK_EX)\n        yield fh\n    finally:\n        try:\n            os.fsync(fh.fileno())\n        except OSError:\n            pass\n        fh.close()\n```\n\n| Operation | Lock Type | Reason |\n|-----------|-----------|--------|\n| Read | `LOCK_EX` (exclusive) | Ensures consistent read after write |\n| Write | `LOCK_EX` (exclusive) | Prevents concurrent modifications |\n| `os.fsync` | After write | Guarantees durability |\n\n资料来源：[server.py:88-102](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Read Namespace\n\n```python\ndef _read_namespace(namespace: str) -> List[Dict[str, Any]]:\n    \"\"\"Read all entries for a namespace (returns list, never None).\"\"\"\n    path = _namespace_path(namespace)\n    if not path.exists():\n        return []\n    with _locked_file(path, \"r\") as fh:\n        try:\n            fh.seek(0)\n            raw = fh.read()\n            if not raw.strip():\n                return []\n            return json.loads(raw)\n        except (json.JSONDecodeError, OSError):\n            return []\n```\n\n**Key behaviors:**\n- Returns empty list for non-existent namespaces\n- Handles malformed JSON gracefully (returns empty list)\n- Handles empty files gracefully\n\n### Write Namespace\n\n```python\ndef _write_namespace(namespace: str, entries: List[Dict[str, Any]]) -> None:\n    \"\"\"Atomically write all entries for a namespace.\"\"\"\n    _ensure_storage()\n    path = _namespace_path(namespace)\n    with _locked_file(path, \"w\") as fh:\n        fh.seek(0)\n        fh.truncate()\n        json.dump(entries, fh, indent=2)\n        fh.flush()\n```\n\n**Atomicity guarantees:**\n1. Truncate file first (removes old data)\n2. Write complete JSON array\n3. Flush to kernel buffer\n4. Release lock (triggers `fsync`)\n\n## TTL (Time-To-Live) Management\n\n### Expiry Detection\n\n```python\ndef _is_expired(entry: Dict[str, Any]) -> bool:\n    \"\"\"Check if an entry has expired based on its TTL.\"\"\"\n    if entry.get(\"expires_at\") is None:\n        return False\n    return _now_unix() > entry[\"expires_at\"]\n```\n\n### Lazy Expiry Strategy\n\nTTL enforcement uses a **lazy deletion** approach:\n\n| Event | Action |\n|-------|--------|\n| `memory_recall` | Check expiry, delete if expired |\n| `memory_search` | Skip expired entries (no deletion) |\n| `memory_forget` | No expiry check needed |\n| Background cleanup | None (relies on lazy deletion) |\n\nThis design:\n- Avoids expensive background processes\n- Ensures expired entries are never returned\n- Accepts slight disk usage increase from expired entries until next access\n\n### TTL Entry Lifecycle\n\n```mermaid\ngraph LR\n    A[Created] --> B[Active]\n    B -->|TTL reached| C[Expired]\n    C -->|Next recall| D[Deleted]\n    C -->|Next search| E[Skipped]\n```\n\n## Metadata Management\n\n### Global Metadata Recalculation\n\n```python\ndef _recalc_meta() -> None:\n    \"\"\"Recompute global metadata by scanning all namespaces.\"\"\"\n    total = 0\n    namespace_count = 0\n    for p in STORAGE_DIR.glob(\"*.json\"):\n        if p.stem == \"_meta\":\n            continue\n        namespace_count += 1\n        entries = _read_namespace(p.stem)\n        total += len([e for e in entries if not _is_expired(e)])\n    _write_meta({\"total_entries\": total, \"namespace_count\": namespace_count})\n```\n\n`recalc_meta()` is called after:\n- `memory_remember` (new entry added)\n- `memory_forget` (entry deleted)\n- `memory_clear_namespace` (namespace wiped)\n- `memory_recall` (lazy expiry cleanup)\n\n资料来源：[server.py:152-164](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Storage Statistics\n\nThe `memory_stats` function aggregates information from all namespace files:\n\n```python\ndef memory_stats(fmt: Optional[str] = None) -> str:\n    \"\"\"Get storage statistics.\"\"\"\n    total_entries = 0\n    total_size = 0\n    namespace_count = 0\n    oldest: Optional[str] = None\n    newest: Optional[str] = None\n\n    for p in STORAGE_DIR.glob(\"*.json\"):\n        if p.stem == \"_meta\":\n            continue\n        namespace_count += 1\n        try:\n            file_size = p.stat().st_size\n            total_size += file_size\n        except OSError:\n            pass\n        entries = _read_namespace(p.stem)\n        active = [e for e in entries if not _is_expired(e)]\n        total_entries += len(active)\n        for e in active:\n            created = e.get(\"created_at\")\n            if created:\n                if oldest is None or created < oldest:\n                    oldest = created\n                if newest is None or created > newest:\n                    newest = created\n```\n\n**Stats returned:**\n\n| Stat | Description |\n|------|-------------|\n| `total_entries` | Sum of active entries across all namespaces |\n| `total_size_bytes` | Disk usage in bytes |\n| `total_size_human` | Human-readable size (B, KB, MB, GB, TB) |\n| `namespace_count` | Number of namespace files |\n| `oldest_entry` | ISO timestamp of earliest entry |\n| `newest_entry` | ISO timestamp of most recent entry |\n| `storage_path` | Filesystem path to storage directory |\n| `free_tier_limit` | 1000 entries |\n| `pro_tier_limit` | unlimited |\n\n资料来源：[server.py:271-307](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Access Tracking\n\nEvery memory entry maintains access metadata:\n\n| Field | Purpose | Updated When |\n|-------|---------|--------------|\n| `created_at` | Creation timestamp | Entry creation |\n| `accessed_at` | Last access timestamp | `memory_recall` |\n| `access_count` | Total access count | `memory_recall` |\n\n```python\n# In memory_recall\nentry[\"accessed_at\"] = _now_iso()\nentry[\"access_count\"] = entry.get(\"access_count\", 0) + 1\n_write_namespace(namespace, entries)\n```\n\nAccess count is used by `memory_search` to rank results by relevance.\n\n## Namespace Isolation\n\nNamespaces provide logical separation of memory entries:\n\n| Feature | Behavior |\n|---------|----------|\n| Separate files | Each namespace has its own `.json` file |\n| Independent entries | Keys only unique within namespace |\n| Independent TTLs | Each entry has its own expiry |\n| Independent access | Separate metadata per entry |\n\n**Search behavior by namespace:**\n\n| Parameter | Search Scope |\n|-----------|--------------|\n| `namespace` omitted | All namespaces |\n| `namespace` specified | Single namespace only |\n\n```python\nif namespace:\n    namespaces_to_search = [namespace]\nelse:\n    namespaces_to_search = [\n        p.stem\n        for p in STORAGE_DIR.glob(\"*.json\")\n        if p.stem != \"_meta\"\n    ]\n```\n\n## Error Handling\n\n| Error Condition | Handling |\n|-----------------|----------|\n| Malformed JSON file | Return empty list, log error |\n| Empty file | Return empty list |\n| Missing namespace | Create empty file on write |\n| Lock acquisition failure | Block until lock available |\n| Disk full | OS-level error propagated |\n\n## Performance Characteristics\n\n| Aspect | Value/Note |\n|--------|------------|\n| File I/O | Blocking (synchronous) |\n| Lock scope | Per-operation (not transaction) |\n| Search complexity | O(n) across namespaces |\n| Memory per namespace | Proportional to entries |\n| Disk I/O per access | 1 read + 1 write |\n\n## Configuration Constants\n\n```python\nCHARACTER_LIMIT = 25_000      # Maximum output truncation\nDEFAULT_NAMESPACE = \"default\" # Fallback namespace\nSTORAGE_DIR = Path.home() / \".agent-memory\"\nMETA_FILE = \"_meta.json\"\n```\n\n资料来源：[server.py:30-35](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n---\n\n<a id='memory-remember'></a>\n\n## memory_remember Tool\n\n### 相关页面\n\n相关主题：[memory_recall Tool](#memory-recall), [TTL Management](#ttl-management), [Quick Start Guide](#quick-start)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n</details>\n\n# memory_remember Tool\n\nThe `memory_remember` tool is the primary data ingestion function in the Agent Memory MCP server, enabling AI agents to persistently store key-value pairs with optional time-to-live (TTL) expiration. It serves as the foundation for creating durable memory entries that survive session restarts, context window limits, and agent crashes.\n\n## Overview\n\n`memory_remember` provides a mechanism for AI agents to store arbitrary string values under unique keys within isolated namespace containers. Each entry captures rich metadata including creation timestamps, access tracking, and optional expiration timers.\n\n**Core Responsibilities:**\n\n- Accept key-value pairs for persistent storage\n- Support optional TTL-based automatic expiration\n- Organize entries within user-defined namespaces\n- Track access statistics (count, timestamps)\n- Enforce atomic writes with POSIX file locking\n- Update global metadata counters\n\n资料来源：[server.py:1-50](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Function Signature\n\n```python\ndef memory_remember(\n    key: str,\n    value: str,\n    namespace: str = DEFAULT_NAMESPACE,\n    ttl_seconds: Optional[int] = None,\n    fmt: Optional[str] = None,\n) -> str\n```\n\n### Parameters\n\n| Parameter | Type | Required | Default | Description |\n|-----------|------|----------|---------|-------------|\n| `key` | `string` | Yes | — | Unique identifier for the memory entry |\n| `value` | `string` | Yes | — | The content/value to store persistently |\n| `namespace` | `string` | No | `\"default\"` | Logical container for organizing entries |\n| `ttl_seconds` | `integer` | No | `null` | Time-to-live in seconds; entry auto-expires after this duration |\n| `format` | `string` | No | `\"markdown\"` | Response format: `\"markdown\"` or `\"json\"` |\n\n资料来源：[server.py:180-230](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Data Model\n\nEach stored entry maintains the following schema:\n\n```python\n{\n    \"key\": str,           # User-provided unique identifier\n    \"value\": str,         # Stored content\n    \"namespace\": str,     # Container identifier\n    \"created_at\": str,    # ISO 8601 timestamp (UTC)\n    \"accessed_at\": str,   # ISO 8601 timestamp, updated on each retrieval\n    \"expires_at\": Optional[str],  # ISO 8601 timestamp or None\n    \"access_count\": int   # Cumulative retrieval count\n}\n```\n\n资料来源：[server.py:200-220](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Storage Architecture\n\nEntries are persisted to the filesystem using a namespace-per-file approach:\n\n```\n~/.agent-memory/\n├── default.json       # Default namespace\n├── project_a.json     # Custom namespace\n├── project_b.json     # Custom namespace\n└── _meta.json         # Global statistics\n```\n\n**Storage Details:**\n\n| Aspect | Specification |\n|--------|---------------|\n| Storage Location | `~/.agent-memory/` |\n| File Format | One JSON file per namespace |\n| Namespace File Naming | Sanitized: `[^a-zA-Z0-9_.\\-]` → `_` |\n| Locking Mechanism | POSIX `fcntl.flock()` |\n| Atomic Writes | Truncate-then-write pattern |\n\n资料来源：[server.py:60-80](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Execution Flow\n\n```mermaid\ngraph TD\n    A[memory_remember Called] --> B{Validate Inputs}\n    B -->|Empty Key| C[Return Error]\n    B -->|Valid Key| D[Acquire File Lock]\n    D --> E[Read Namespace File]\n    E --> F[Check for Duplicate Key]\n    F -->|Key Exists| G[Update Existing Entry]\n    F -->|New Key| H[Append New Entry]\n    G --> I[Write Namespace File]\n    H --> I\n    I --> J[Release File Lock]\n    J --> K[Recalculate Global Metadata]\n    K --> L[Return Success Response]\n    C --> L2[Return Error Response]\n```\n\n### Step-by-Step Process\n\n1. **Input Validation**: Reject empty or whitespace-only keys\n2. **Lock Acquisition**: Obtain exclusive POSIX file lock on namespace file\n3. **Entry Creation**: Build entry dict with timestamps and TTL calculation\n4. **File Write**: Atomically write updated entries array\n5. **Metadata Update**: Recalculate global entry counts via `_recalc_meta()`\n6. **Response Generation**: Format success data as markdown or JSON\n\n资料来源：[server.py:195-230](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## TTL (Time-to-Live) Mechanism\n\nThe TTL feature enables automatic expiration of entries after a specified duration:\n\n```python\nentry = {\n    \"key\": key,\n    \"value\": value,\n    \"namespace\": namespace,\n    \"created_at\": _now_iso(),\n    \"accessed_at\": _now_iso(),\n    \"expires_at\": (now + ttl_seconds) if ttl_seconds else None,\n    \"access_count\": 0,\n}\n```\n\n**TTL Behavior:**\n\n- TTL is calculated as `current_time + ttl_seconds` at write time\n- Expired entries are lazily deleted during `memory_recall` operations\n- TTL precision is second-level (not millisecond)\n- A value of `null` or omitting `ttl_seconds` creates a never-expiring entry\n\n资料来源：[server.py:205-215](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Response Format\n\n### Success Response (Markdown)\n\n```\n## ✅ Success\n\n**message:** Stored 'user_preference' in namespace 'default'\n**key:** user_preference\n**namespace:** default\n**expires_in:** 3600s\n**expires_at:** 2024-01-15T10:30:00Z\n```\n\n### Success Response (JSON)\n\n```json\n{\n  \"status\": \"ok\",\n  \"message\": \"Stored 'user_preference' in namespace 'default'\",\n  \"key\": \"user_preference\",\n  \"namespace\": \"default\",\n  \"expires_in\": \"3600s\",\n  \"expires_at\": \"2024-01-15T10:30:00Z\"\n}\n```\n\n### Error Response\n\n```json\n{\n  \"status\": \"error\",\n  \"error\": \"Key must not be empty\",\n  \"isError\": true\n}\n```\n\n资料来源：[server.py:300-350](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Namespace Handling\n\nNamespaces provide logical isolation for memory entries:\n\n```mermaid\ngraph LR\n    subgraph Storage Layer\n        NA[Namespace A<br/>namespace_a.json]\n        NB[Namespace B<br/>namespace_b.json]\n        NC[Default<br/>default.json]\n    end\n    \n    A1[Entry 1] --> NA\n    A2[Entry 2] --> NA\n    B1[Entry 3] --> NB\n    C1[Entry 4] --> NC\n```\n\n**Namespace Rules:**\n\n- Default namespace is `\"default\"` when unspecified\n- Names are sanitized to prevent directory traversal attacks\n- Each namespace persists independently\n- Cross-namespace search available via `memory_search`\n\n资料来源：[server.py:65-75](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Thread Safety\n\nThe implementation ensures safe concurrent access through POSIX file locking:\n\n```python\n@contextmanager\ndef _locked_file(path: Path, mode: str):\n    fh = open(path, mode)\n    fcntl.flock(fh.fileno(), fcntl.LOCK_EX)\n    try:\n        yield fh\n    finally:\n        fcntl.flock(fh.fileno(), fcntl.LOCK_UN)\n        fh.close()\n```\n\n- **Lock Type**: Exclusive (`LOCK_EX`) for both reads and writes\n- **Scope**: Per-file locks prevent corruption during concurrent access\n- **Guarantee**: Prevents race conditions from multiple agents\n\n资料来源：[server.py:85-100](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## MCP Tool Definition\n\nThe tool is registered with the MCP server as follows:\n\n```python\nTool(\n    name=\"memory_remember\",\n    description=\"Store a value under a key in a persistent memory namespace. Optionally set a TTL (time-to-live) in seconds for automatic expiry.\",\n    inputSchema={\n        \"type\": \"object\",\n        \"properties\": {\n            \"key\": {\"type\": \"string\", \"description\": \"Unique key for this memory entry.\"},\n            \"value\": {\"type\": \"string\", \"description\": \"The value/content to store.\"},\n            \"namespace\": {\n                \"type\": \"string\",\n                \"description\": \"Namespace to store the entry in (default: 'default').\",\n                \"default\": \"default\",\n            },\n            \"ttl_seconds\": {\n                \"type\": \"integer\",\n                \"description\": \"Optional TTL in seconds. Entry auto-expires after this duration.\",\n            },\n            \"format\": {\n                \"type\": \"string\",\n                \"enum\": [\"markdown\", \"json\"],\n                \"description\": \"Response format (default: markdown).\",\n                \"default\": \"markdown\",\n            },\n        },\n        \"required\": [\"key\", \"value\"],\n    },\n    annotations=ToolAnnotations(\n        readOnlyHint=False,\n        destructiveHint=False,\n        idempotentHint=True,\n        openWorldHint=False,\n    ),\n)\n```\n\n**Tool Annotations:**\n\n| Annotation | Value | Meaning |\n|------------|-------|---------|\n| `readOnlyHint` | `false` | Modifies server state |\n| `destructiveHint` | `false` | Does not delete existing data |\n| `idempotentHint` | `true` | Safe to retry |\n| `openWorldHint` | `false` | Operates on local storage only |\n\n资料来源：[server.py:280-320](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Usage Examples\n\n### Basic Storage\n\n```\nTool: memory_remember\nArguments: {\n    \"key\": \"user_name\",\n    \"value\": \"Alice\",\n    \"namespace\": \"users\"\n}\n```\n\n### Storage with TTL (1 hour)\n\n```\nTool: memory_remember\nArguments: {\n    \"key\": \"session_token\",\n    \"value\": \"abc123xyz\",\n    \"namespace\": \"sessions\",\n    \"ttl_seconds\": 3600\n}\n```\n\n### JSON Response Format\n\n```\nTool: memory_remember\nArguments: {\n    \"key\": \"config\",\n    \"value\": \"{\\\"theme\\\": \\\"dark\\\", \\\"lang\\\": \\\"en\\\"}\",\n    \"namespace\": \"settings\",\n    \"format\": \"json\"\n}\n```\n\n## Related Tools\n\n| Tool | Purpose | Relationship |\n|------|---------|--------------|\n| `memory_recall` | Retrieve stored values by key | Complements write with read |\n| `memory_forget` | Delete a specific entry | Inverse operation |\n| `memory_search` | Find entries by keyword | Discovery of stored data |\n| `memory_list_namespaces` | List all namespaces | Namespace enumeration |\n| `memory_stats` | View storage statistics | Global monitoring |\n\n资料来源：[server.py:320-380](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Limitations\n\n- **Character Limit**: Stored values are truncated at 25,000 characters via `_truncate()` helper\n- **Key Constraints**: Empty keys are rejected; keys are case-sensitive\n- **Storage Backend**: Filesystem-based (not suitable for high-frequency write workloads)\n- **Free Tier**: Limited to 1,000 total entries across all namespaces\n- **No Batch Operations**: Single key-value pair per call only\n\n资料来源：[server.py:55](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py) and [smithery.yaml](https://github.com/Rumblingb/agent-memory-mcp/blob/main/smithery.yaml)\n\n---\n\n<a id='memory-recall'></a>\n\n## memory_recall Tool\n\n### 相关页面\n\n相关主题：[memory_remember Tool](#memory-remember), [memory_forget Tool](#memory-forget), [TTL Management](#ttl-management)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n</details>\n\n# memory_recall Tool\n\n## Overview\n\nThe `memory_recall` tool is a core retrieval function in the Agent Memory MCP server that enables AI agents to fetch previously stored values from persistent memory. It provides lazy TTL (Time-To-Live) expiry checking, automatic access tracking, and metadata enrichment on every retrieval operation.\n\n**Key Characteristics:**\n\n| Attribute | Value |\n|-----------|-------|\n| Tool Name | `memory_recall` |\n| Category | Read operation |\n| Destructive | No |\n| Idempotent | Yes |\n| Default Namespace | `default` |\n| Response Formats | `markdown`, `json` |\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Function Signature\n\n```python\ndef memory_recall(\n    key: str,\n    namespace: str = DEFAULT_NAMESPACE,\n    fmt: Optional[str] = None,\n) -> str:\n```\n\n### Parameters\n\n| Parameter | Type | Required | Default | Description |\n|-----------|------|----------|---------|-------------|\n| `key` | `string` | Yes | — | The unique key identifying the memory entry to retrieve |\n| `namespace` | `string` | No | `\"default\"` | The namespace to search within |\n| `fmt` | `string` | No | `\"markdown\"` | Response format: `\"markdown\"` or `\"json\"` |\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Tool Schema Definition\n\n```json\n{\n  \"name\": \"memory_recall\",\n  \"description\": \"Retrieve a stored value by key from a namespace. Returns full metadata including creation time, last access, and expiry. Automatically expires TTL'd entries.\",\n  \"inputSchema\": {\n    \"type\": \"object\",\n    \"properties\": {\n      \"key\": {\n        \"type\": \"string\",\n        \"description\": \"The key to retrieve.\"\n      },\n      \"namespace\": {\n        \"type\": \"string\",\n        \"description\": \"Namespace to look in (default: 'default').\",\n        \"default\": \"default\"\n      },\n      \"format\": {\n        \"type\": \"string\",\n        \"enum\": [\"markdown\", \"json\"],\n        \"description\": \"Response format (default: markdown).\",\n        \"default\": \"markdown\"\n      }\n    },\n    \"required\": [\"key\"]\n  },\n  \"annotations\": {\n    \"readOnlyHint\": false,\n    \"destructiveHint\": false,\n    \"idempotentHint\": true,\n    \"openWorldHint\": false\n  }\n}\n```\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Workflow\n\n```mermaid\ngraph TD\n    A[Start: memory_recall called] --> B{Key provided?}\n    B -->|No| C[Return Error: Key must not be empty]\n    B -->|Yes| D[Read namespace file]\n    E[Find entry by key] --> F{Entry found?}\n    F -->|No| G[Return Error: Key not found]\n    F -->|Yes| H{Entry expired?}\n    D --> E\n    H -->|Yes| I[Remove expired entry from file]\n    I --> J[Recalculate metadata]\n    J --> K[Return Error: Key has expired]\n    H -->|No| L[Update access metadata]\n    L --> M[Increment access_count]\n    M --> N[Update accessed_at timestamp]\n    N --> O[Write updated namespace file]\n    O --> P[Return Success with value and metadata]\n```\n\n## Lazy TTL Expiry Mechanism\n\nOne of the key features of `memory_recall` is its **lazy expiry** behavior. Rather than running a background cleanup task, expired entries are detected and removed when they are accessed:\n\n```python\nfor i, entry in enumerate(entries):\n    if entry[\"key\"] == key:\n        if _is_expired(entry):\n            # Lazy expiry – remove and return not-found\n            entries.pop(i)\n            _write_namespace(namespace, entries)\n            _recalc_meta()\n            return _error(f\"Key '{key}' has expired\", fmt)\n```\n\n**Expiry Detection Logic:**\n\n| Field | Purpose |\n|-------|---------|\n| `expires_at` | ISO timestamp when entry expires |\n| `_is_expired(entry)` | Returns `True` if current time > `expires_at` |\n\nWhen an entry expires:\n1. The entry is removed from the namespace file immediately\n2. Global metadata is recalculated\n3. An error response is returned indicating expiration\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Access Tracking\n\nEvery successful recall operation automatically updates metadata:\n\n```python\n# Update access metadata\nentry[\"accessed_at\"] = _now_iso()\nentry[\"access_count\"] = entry.get(\"access_count\", 0) + 1\n_write_namespace(namespace, entries)\n```\n\n**Tracked Metadata:**\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `accessed_at` | ISO string | Timestamp of most recent access |\n| `access_count` | integer | Total number of times this entry has been accessed |\n\nThis data powers the search ranking algorithm, which sorts results by `access_count` in descending order.\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Response Format\n\n### Success Response (Markdown)\n\n```markdown\n## ✅ Success\n\n**key:** example_key\n**namespace:** default\n**value:** The stored value content\n**created_at:** 2024-01-15T10:30:00\n**accessed_at:** 2024-01-15T14:22:00\n**access_count:** 5\n**expires_at:** 2024-01-16T10:30:00 or Never\n```\n\n### Success Response (JSON)\n\n```json\n{\n  \"status\": \"ok\",\n  \"key\": \"example_key\",\n  \"namespace\": \"default\",\n  \"value\": \"The stored value content\",\n  \"created_at\": \"2024-01-15T10:30:00\",\n  \"accessed_at\": \"2024-01-15T14:22:00\",\n  \"access_count\": 5,\n  \"expires_at\": \"2024-01-16T10:30:00\"\n}\n```\n\n### Error Responses\n\n| Error Condition | Message |\n|-----------------|---------|\n| Empty key | `Key must not be empty` |\n| Key not found | `Key 'example_key' not found in namespace 'default'` |\n| Entry expired | `Key 'example_key' has expired` |\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Data Storage Model\n\nEntries are stored in JSON files within the storage directory:\n\n```\n~/.agent-memory/\n├── _meta.json\n├── default.json\n├── project_a.json\n└── user_b.json\n```\n\n### Entry Schema\n\n```json\n{\n  \"key\": \"string\",\n  \"value\": \"string\",\n  \"created_at\": \"ISO8601 timestamp\",\n  \"accessed_at\": \"ISO8601 timestamp\",\n  \"expires_at\": \"ISO8601 timestamp or null\",\n  \"access_count\": 0\n}\n```\n\n### Thread Safety\n\nFile operations use POSIX file locking (`fcntl`) to ensure safe concurrent access:\n\n```python\n@contextmanager\ndef _locked_file(path: Path, mode: str):\n    fh = open(path, mode)\n    try:\n        fcntl.flock(fh.fileno(), fcntl.LOCK_EX)\n        yield fh\n    finally:\n        fcntl.flock(fh.fileno(), fcntl.LOCK_UN)\n        fh.close()\n```\n\nThis ensures that multiple agents can safely read and write to the memory store simultaneously without data corruption.\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Usage Examples\n\n### Basic Recall\n\n```\nTool: memory_recall\nArguments: {\"key\": \"user_preference\", \"namespace\": \"default\"}\n```\n\n### Recalling from Specific Namespace\n\n```\nTool: memory_recall\nArguments: {\"key\": \"session_state\", \"namespace\": \"user_123\"}\n```\n\n### JSON Response Format\n\n```\nTool: memory_recall\nArguments: {\"key\": \"config\", \"namespace\": \"settings\", \"format\": \"json\"}\n```\n\n## Integration with Other Tools\n\n| Related Tool | Interaction |\n|--------------|-------------|\n| `memory_remember` | Stores data that `memory_recall` retrieves |\n| `memory_search` | Uses `access_count` to rank search results |\n| `memory_forget` | Permanently deletes entries |\n| `memory_stats` | Tracks global `total_entries` count |\n\nThe search functionality prioritizes frequently accessed entries:\n\n```python\n# Sort by access count desc, then created_at desc\nresults.sort(key=lambda x: (-x.get(\"access_count\", 0), x.get(\"created_at\", \"\")))\n```\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Error Handling\n\n| Scenario | Handling |\n|----------|----------|\n| Empty key | Returns error immediately before file I/O |\n| Non-existent namespace | Returns empty array; treated as \"key not found\" |\n| Corrupted JSON file | Returns empty array, log error |\n| Expired entry | Removes from file, returns expiration error |\n| File permission errors | Caught by try/except, returns error |\n\nThe tool handles exceptions gracefully at the server level:\n\n```python\nexcept Exception as exc:\n    err_text = _error(f\"Internal error in {name}: {exc}\", fmt)\n    return CallToolResult(\n        content=[TextContent(type=\"text\", text=err_text)],\n        isError=True,\n    )\n```\n\n资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n---\n\n<a id='memory-forget'></a>\n\n## memory_forget Tool\n\n### 相关页面\n\n相关主题：[memory_recall Tool](#memory-recall)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n- [smithery.yaml](https://github.com/Rumblingb/agent-memory-mcp/blob/main/smithery.yaml)\n- [index.html](https://github.com/Rumblingb/agent-memory-mcp/blob/main/index.html)\n- [README.md](https://github.com/Rumblingb/agent-memory-mcp/blob/main/README.md)\n- [requirements.txt](https://github.com/Rumblingb/agent-memory-mcp/blob/main/requirements.txt)\n</details>\n\n# memory_forget Tool\n\nThe `memory_forget` tool is a destructive operation within the Agent Memory MCP server that permanently removes a specific key-value entry from a designated memory namespace. It is one of seven tools exposed by the MCP server and represents the deletion capability in the persistent key-value storage system.\n\n## Overview\n\nAgent Memory MCP provides AI agents with persistent memory across sessions. The system stores data as JSON files in `~/.agent-memory/`, with one file per namespace plus a `_meta.json` statistics file. The `memory_forget` tool enables agents to selectively remove entries when they are no longer needed, helping manage storage and maintain relevant data.\n\n| Tool Name | Purpose | Destructive | Read-Only |\n|-----------|---------|-------------|-----------|\n| memory_remember | Store a key-value pair | No | No |\n| memory_recall | Retrieve a value by key | No | Yes |\n| memory_forget | Delete a key permanently | Yes | No |\n| memory_search | Search across namespaces | No | Yes |\n| memory_list_namespaces | List all namespaces | No | Yes |\n| memory_clear_namespace | Wipe entire namespace | Yes | No |\n| memory_stats | Get storage statistics | No | Yes |\n\n## Function Signature\n\nThe `memory_forget` function is defined in `server.py` and accepts the following parameters:\n\n```python\ndef memory_forget(\n    key: str,\n    namespace: str = DEFAULT_NAMESPACE,\n    fmt: Optional[str] = None,\n) -> str:\n```\n\n| Parameter | Type | Required | Default | Description |\n|-----------|------|----------|---------|-------------|\n| key | string | Yes | — | Unique key identifying the memory entry to delete |\n| namespace | string | No | \"default\" | Namespace containing the entry |\n| format | string | No | \"markdown\" | Response format: \"markdown\" or \"json\" |\n\n## Tool Definition\n\nThe MCP server exposes `memory_forget` with the following schema definition:\n\n```python\nTool(\n    name=\"memory_forget\",\n    description=\"Permanently delete a key from a memory namespace.\",\n    inputSchema={\n        \"type\": \"object\",\n        \"properties\": {\n            \"key\": {\n                \"type\": \"string\",\n                \"description\": \"Unique key for this memory entry.\",\n            },\n            \"namespace\": {\n                \"type\": \"string\",\n                \"description\": \"Namespace to delete from (default: 'default').\",\n                \"default\": \"default\",\n            },\n            \"format\": {\n                \"type\": \"string\",\n                \"enum\": [\"markdown\", \"json\"],\n                \"description\": \"Response format (default: markdown).\",\n                \"default\": \"markdown\",\n            },\n        },\n        \"required\": [\"key\"],\n    },\n    annotations=ToolAnnotations(\n        readOnlyHint=False,\n        destructiveHint=True,\n        idempotentHint=True,\n        openWorldHint=False,\n    ),\n),\n```\n\n## Tool Annotations\n\nThe tool is annotated with specific behavioral hints that inform MCP clients about its characteristics:\n\n| Annotation | Value | Implication |\n|------------|-------|-------------|\n| readOnlyHint | false | This tool modifies state |\n| destructiveHint | true | This operation permanently removes data |\n| idempotentHint | true | Multiple calls with same key produce same result (success or not-found) |\n| openWorldHint | false | Only affects local storage, no external world interaction |\n\n## Execution Flow\n\nThe following diagram illustrates the execution flow when `memory_forget` is invoked:\n\n```mermaid\ngraph TD\n    A[Call memory_forget with key and namespace] --> B{Key is empty?}\n    B -->|Yes| C[Return error: Key must not be empty]\n    B -->|No| D[Read namespace file from ~/.agent-memory/]\n    D --> E{Namespace file exists?}\n    E -->|No| F[Return error: Key not found]\n    E -->|Yes| G[Parse JSON entries list]\n    G --> H{Entry with matching key exists?}\n    H -->|No| I[Return error: Key not found]\n    H -->|Yes| J[Remove entry from list]\n    J --> K[Write updated entries back to namespace file]\n    K --> L[Recalculate global metadata]\n    L --> M[Return success response]\n```\n\n## Implementation Details\n\nThe core implementation of `memory_forget` performs the following operations:\n\n```python\ndef memory_forget(\n    key: str,\n    namespace: str = DEFAULT_NAMESPACE,\n    fmt: Optional[str] = None,\n) -> str:\n    \"\"\"Delete a key permanently from a namespace.\"\"\"\n    if not key.strip():\n        return _error(\"Key must not be empty\", fmt)\n\n    entries = _read_namespace(namespace)\n\n    for i, entry in enumerate(entries):\n        if entry[\"key\"] == key:\n            entries.pop(i)\n            _write_namespace(namespace, entries)\n            _recalc_meta()\n\n            return _success(\n                {\n                    \"message\": f\"Deleted '{key}' from namespace '{namespace}'\",\n                    \"key\": key,\n                    \"namespace\": namespace,\n                },\n                fmt,\n            )\n\n    return _error(f\"Key '{key}' not found in namespace '{namespace}'\", fmt)\n```\n\n### Step-by-Step Breakdown\n\n1. **Input Validation**: Checks that the key is not empty or whitespace-only. Empty keys return an error immediately.\n\n2. **Read Namespace**: Loads all entries from the namespace's JSON file using the thread-safe `_read_namespace()` helper.\n\n3. **Search for Entry**: Iterates through entries to find a matching key.\n\n4. **Remove Entry**: If found, removes the entry from the list using `pop(i)`.\n\n5. **Write Back**: Persists the modified entries list to the namespace file using `_write_namespace()`.\n\n6. **Update Metadata**: Calls `_recalc_meta()` to update global statistics reflecting the entry count change.\n\n7. **Return Response**: Returns a formatted success or error message.\n\n## File Operations\n\nThe tool relies on two critical helper functions for file I/O:\n\n### _read_namespace()\n\n```python\ndef _read_namespace(namespace: str) -> List[Dict[str, Any]]:\n    \"\"\"Read all entries for a namespace (returns list, never None).\"\"\"\n    path = _namespace_path(namespace)\n    if not path.exists():\n        return []\n    with _locked_file(path, \"r\") as fh:\n        try:\n            fh.seek(0)\n            raw = fh.read()\n            if not raw.strip():\n                return []\n            return json.loads(raw)\n        except (json.JSONDecodeError, OSError):\n            return []\n```\n\n### _write_namespace()\n\n```python\ndef _write_namespace(namespace: str, entries: List[Dict[str, Any]]) -> None:\n    \"\"\"Atomically write all entries for a namespace.\"\"\"\n    _ensure_storage()\n    path = _namespace_path(namespace)\n    with _locked_file(path, \"w\") as fh:\n        fh.seek(0)\n        fh.truncate()\n        json.dump(entries, fh, indent=2)\n        fh.flush()\n```\n\nBoth operations use POSIX file locking via `_locked_file()` context manager to ensure thread-safe concurrent access.\n\n## Namespace Path Resolution\n\nNamespace names are sanitized to prevent directory escape attacks:\n\n```python\ndef _namespace_path(namespace: str) -> Path:\n    \"\"\"Return the full path for a namespace JSON file.\"\"\"\n    safe = re.sub(r\"[^a-zA-Z0-9_.\\-]\", \"_\", namespace)\n    if not safe:\n        safe = DEFAULT_NAMESPACE\n    return STORAGE_DIR / f\"{safe}.json\"\n```\n\nThis ensures all namespace files remain within `~/.agent-memory/` directory. 资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Metadata Recalculation\n\nAfter successful deletion, global metadata is updated:\n\n```python\ndef _recalc_meta() -> None:\n    \"\"\"Recompute global metadata by scanning all namespaces.\"\"\"\n    total = 0\n    namespace_count = 0\n    for p in STORAGE_DIR.glob(\"*.json\"):\n        if p.stem == \"_meta\":\n            continue\n        namespace_count += 1\n        entries = _read_namespace(p.stem)\n        total += len([e for e in entries if not _is_expired(e)])\n    _write_meta({\"total_entries\": total, \"namespace_count\": namespace_count})\n```\n\nThe function scans all namespace files to count active (non-expired) entries and updates the `_meta.json` file accordingly.\n\n## Response Formats\n\n### Success Response (Markdown)\n\n```markdown\n## ✅ Success\n**message:** Deleted 'user_preference' from namespace 'default'\n**key:** user_preference\n**namespace:** default\n```\n\n### Success Response (JSON)\n\n```json\n{\n  \"status\": \"ok\",\n  \"message\": \"Deleted 'user_preference' from namespace 'default'\",\n  \"key\": \"user_preference\",\n  \"namespace\": \"default\"\n}\n```\n\n### Error Response (Key Not Found)\n\n```markdown\n## ❌ Error\n**Key 'nonexistent_key' not found in namespace 'default'**\n```\n\n## Error Handling\n\n| Scenario | Error Message | HTTP-like Status |\n|----------|---------------|------------------|\n| Empty key | \"Key must not be empty\" | Validation Error |\n| Key not in namespace | \"Key '{key}' not found in namespace '{namespace}'\" | Not Found |\n\nErrors are formatted consistently via `_error()` helper and returned with `isError=True` in JSON mode.\n\n## Routing in MCP Server\n\nThe MCP server routes tool calls through the `call_tool` handler:\n\n```python\n@server.call_tool()\nasync def call_tool(name: str, arguments: Dict[str, Any]) -> CallToolResult:\n    \"\"\"Route tool calls to the appropriate implementation.\"\"\"\n    fmt = arguments.pop(\"format\", \"markdown\")\n\n    try:\n        if name == \"memory_remember\":\n            text = memory_remember(**arguments, fmt=fmt)\n        elif name == \"memory_recall\":\n            text = memory_recall(**arguments, fmt=fmt)\n        elif name == \"memory_forget\":\n            text = memory_forget(**arguments, fmt=fmt)\n        # ... other tools\n```\n\nThe format parameter is extracted before forwarding arguments to the implementation function.\n\n## Concurrency and Thread Safety\n\nThe tool is designed for multi-agent environments with the following safety mechanisms:\n\n1. **POSIX File Locking**: All read/write operations use `fcntl.flock()` through the `_locked_file()` context manager.\n\n2. **Atomic Writes**: `_write_namespace()` uses `truncate()` before `json.dump()` to ensure atomic replacement of file contents.\n\n3. **Lazy Expiry**: Expired entries are automatically skipped during read operations but not proactively cleaned unless accessed.\n\n## Storage Structure\n\nData persists in `~/.agent-memory/` with the following structure:\n\n```\n~/.agent-memory/\n├── _meta.json          # Global statistics\n├── default.json        # Default namespace\n├── project_a.json      # Custom namespace\n└── user_sessions.json  # Another namespace\n```\n\nEach namespace file contains a JSON array of entry objects:\n\n```json\n[\n  {\n    \"key\": \"user_preference\",\n    \"value\": \"dark_mode\",\n    \"created_at\": \"2024-01-15T10:30:00Z\",\n    \"accessed_at\": \"2024-01-15T14:22:00Z\",\n    \"expires_at\": null,\n    \"access_count\": 15\n  }\n]\n```\n\n## Usage Examples\n\n### Basic Deletion\n\n```json\n{\n  \"name\": \"memory_forget\",\n  \"arguments\": {\n    \"key\": \"session_token\"\n  }\n}\n```\n\n### Deletion from Specific Namespace\n\n```json\n{\n  \"name\": \"memory_forget\",\n  \"arguments\": {\n    \"key\": \"temp_cache\",\n    \"namespace\": \"user_123\"\n  }\n}\n```\n\n### Deletion with JSON Response\n\n```json\n{\n  \"name\": \"memory_forget\",\n  \"arguments\": {\n    \"key\": \"old_preference\",\n    \"namespace\": \"settings\",\n    \"format\": \"json\"\n  }\n}\n```\n\n## Idempotency\n\nThe tool is idempotent—calling it multiple times with the same key produces consistent results:\n\n- First call with existing key: Success (entry deleted)\n- Subsequent calls with same key: Error (key not found)\n\nThis property makes the tool safe for retry logic in agent workflows.\n\n## Related Tools\n\n| Tool | Relationship | Purpose |\n|------|--------------|---------|\n| memory_remember | Complement | Store new entries |\n| memory_recall | Read counterpart | Retrieve entries before deletion |\n| memory_clear_namespace | Bulk deletion | Remove all entries in namespace |\n| memory_list_namespaces | Discovery | Find available namespaces |\n\n## Configuration Constants\n\nThe tool operates within the constraints defined by these constants:\n\n| Constant | Value | Purpose |\n|----------|-------|---------|\n| DEFAULT_NAMESPACE | \"default\" | Fallback namespace if none specified |\n| STORAGE_DIR | `Path.home() / \".agent-memory\"` | Base storage directory |\n| CHARACTER_LIMIT | 25,000 | Maximum response size before truncation |\n| META_FILE | \"_meta.json\" | Global metadata filename |\n\n---\n\n<a id='memory-search'></a>\n\n## memory_search Tool\n\n### 相关页面\n\n相关主题：[Namespaces](#namespaces), [Quick Start Guide](#quick-start)\n\n<details>\n<summary>Relevant Source Files</summary>\n\nThe following source files were used to generate this page:\n\n- [server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n- [smithery.yaml](https://github.com/Rumblingb/agent-memory-mcp/blob/main/smithery.yaml)\n- [requirements.txt](https://github.com/Rumblingb/agent-memory-mcp/blob/main/requirements.txt)\n- [README.md](https://github.com/Rumblingb/agent-memory-mcp/blob/main/README.md)\n</details>\n\n# memory_search Tool\n\nThe `memory_search` tool is a fuzzy keyword search capability within the Agent Memory MCP server that enables AI agents to retrieve stored memory entries across one or all namespaces using case-insensitive substring matching. It serves as the primary discovery mechanism for agents seeking to recall previously stored context, preferences, or state information without requiring exact key names.\n\n## Overview\n\nAgent Memory MCP is a persistent key-value memory store built on the Model Context Protocol (MCP) Python SDK. The `memory_search` tool addresses a fundamental limitation in agent-based systems: the inability to retrieve information when the exact storage key is unknown. Rather than requiring agents to remember precise key names, the search tool accepts natural language queries and matches them against both keys and values stored across all memory namespaces.\n\nThe tool implements substring matching at the byte-string level, converting both the search query and stored content to lowercase before comparison. This design choice prioritizes recall over precision, ensuring that partial matches, typos, and variations in casing do not prevent agents from finding relevant information.\n\n## Architecture\n\n### System Context\n\n```mermaid\ngraph TD\n    A[\"Agent / Client\"] -->|MCP Tool Call| B[\"memory_search\"]\n    B --> C{namespace param?}\n    C -->|Yes| D[Search Single Namespace]\n    C -->|No| E[Discover All Namespaces]\n    E --> F[\"Glob *.json in ~/.agent-memory/\"]\n    F --> G[\"Exclude _meta.json\"]\n    D --> H[\"Read Namespace JSON Files\"]\n    G --> H\n    H --> I[\"Parse entries array\"]\n    I --> J{Entry expired?}\n    J -->|Yes| K[Skip entry]\n    J -->|No| L{Check match conditions}\n    L --> M[\"query ∈ key.lower()\"]\n    L --> N[\"query ∈ value.lower()\"]\n    M -->|OR| O[Add to results]\n    N -->|OR| O\n    O --> P[\"Sort: access_count DESC, created_at DESC\"]\n    P --> Q[\"Apply limit\"]\n    Q --> R[\"Truncate values to 500 chars\"]\n    R --> S[Format response]\n    S --> T[\"Return markdown or JSON\"]\n    K --> P\n```\n\n### Data Model\n\nEach memory entry stored in the Agent Memory system follows a consistent schema:\n\n```json\n{\n  \"key\": \"string\",\n  \"value\": \"string\",\n  \"created_at\": \"ISO 8601 timestamp\",\n  \"accessed_at\": \"ISO 8601 timestamp\",\n  \"expires_at\": \"ISO 8601 timestamp | null\",\n  \"access_count\": \"integer\"\n}\n```\n\nThe `memory_search` tool operates on this entry structure, examining both `key` and `value` fields for substring matches while respecting the `expires_at` field for TTL-based entries. 资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## Function Signature\n\n```python\ndef memory_search(\n    query: str,\n    namespace: Optional[str] = None,\n    limit: int = 10,\n    fmt: Optional[str] = None,\n) -> str:\n```\n\nThe function returns a formatted string response rather than a structured object, supporting both markdown and JSON output formats through the `fmt` parameter.\n\n## Parameters\n\n| Parameter | Type | Required | Default | Description |\n|-----------|------|----------|---------|-------------|\n| `query` | `string` | Yes | — | Search keyword or substring to match against keys and values |\n| `namespace` | `string \\| null` | No | `null` | Optional namespace to limit search scope. When `null`, searches all namespaces |\n| `limit` | `integer` | No | `10` | Maximum number of results to return |\n| `fmt` | `string \\| null` | No | `null` | Response format: `\"markdown\"` or `\"json\"`. Defaults to markdown when `null` |\n\n## Search Algorithm\n\n### Step 1: Input Validation\n\nThe search immediately rejects empty queries to prevent unnecessary filesystem operations:\n\n```python\nif not query.strip():\n    return _error(\"Query must not be empty\", fmt)\n```\n\nThis validation ensures that whitespace-only strings and empty inputs are rejected before any namespace discovery occurs. 资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Step 2: Query Normalization\n\nThe search query is normalized to lowercase for case-insensitive matching:\n\n```python\nq = query.lower()\n```\n\nThis single transformation enables matching against both `key.lower()` and `value.lower()` without additional case-handling logic.\n\n### Step 3: Namespace Discovery\n\nWhen no namespace is specified, the tool discovers all available namespaces by globbing the storage directory:\n\n```python\nnamespaces_to_search = [\n    p.stem\n    for p in STORAGE_DIR.glob(\"*.json\")\n    if p.stem != \"_meta\"\n]\n```\n\nThe `_meta.json` file is explicitly excluded from search results as it contains internal metadata rather than user data. Each discovered namespace corresponds to a `namespace.json` file in `~/.agent-memory/`. 资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n### Step 4: Entry Matching\n\nFor each namespace and entry, the matching logic follows this flow:\n\n```mermaid\ngraph LR\n    A[entry.key.lower()] --> C{query in key?}\n    B[entry.value.lower()] --> D{query in value?}\n    C -->|Yes| E[Include result]\n    D -->|Yes| E\n    C -->|No| F[Skip]\n    D -->|No| F\n```\n\nThe `OR` condition means an entry is included if the query appears in **either** the key or the value. Expired entries are automatically skipped:\n\n```python\nif _is_expired(entry):\n    continue\n```\n\n### Step 5: Result Truncation\n\nTo prevent oversized responses, value fields are truncated to 500 characters before inclusion in results:\n\n```python\nresults.append(\n    {\n        \"namespace\": ns,\n        \"key\": entry[\"key\"],\n        \"value\": _truncate(entry[\"value\"], 500),\n        \"created_at\": entry[\"created_at\"],\n        \"access_count\": entry.get(\"access_count\", 0),\n    }\n)\n```\n\nThe full value remains intact in storage; truncation occurs only in search results.\n\n### Step 6: Result Ordering\n\nResults are sorted by two criteria in descending order:\n\n1. `access_count` — More frequently accessed entries rank higher\n2. `created_at` — More recently created entries rank higher within equal access counts\n\nThis ordering heuristic surfaces the most relevant and useful memories based on historical access patterns. 资料来源：[server.py](https://github.com/Rumblingb/agent-memory-mcp/blob/main/server.py)\n\n## MCP Tool Definition\n\nThe `memory_search` tool is registered with the MCP server with the following schema definition:\n\n```python\nTool(\n    name=\"memory_search\",\n    description=\"Search memories across namespaces by keyword substring. Case-insensitive match on both keys and values. Returns results sorted by access count.\",\n    inputSchema={\n        \"type\": \"object\",\n        \"properties\": {\n            \"query\": {\n                \"type\": \"string\",\n                \"description\": \"Search keyword or substring.\",\n            },\n            \"namespace\": {\n                \"type\": \"string\",\n                \"description\": \"Optional namespace to limit search. Searches ALL namespaces if omitted.\",\n            },\n            \"limit\": {\n                \"type\": \"integer\",\n                \"description\": \"Maximum results to return (default: 10).\",\n                \"default\": 10,\n            },\n            \"format\": {\n                \"type\": \"string\",\n                \"enum\": [\"markdown\", \"json\"],\n                \"description\": \"Response format (default: markdown).\",\n                \"default\": \"markdown\",\n            },\n        },\n        \"required\": [\"query\"],\n    },\n    annotations=ToolAnnotations(\n        readOnlyHint=True,\n        destructiveHint=False,\n        idempotentHint=True,\n        openWorldHint=True,\n    ),\n),\n```\n\n### Tool Annotations\n\n| Annotation | Value | Implication |\n|------------|-------|-------------|\n| `readOnlyHint` | `True` | The tool does not modify stored data |\n| `destructiveHint` | `False` | No permanent deletion occurs during search |\n| `idempotentHint` | `True` | Multiple identical calls produce identical results |\n| `openWorldHint` | `True` | Search may cross namespace boundaries |\n\nThese annotations inform client applications about the nature of the operation, enabling appropriate caching, undo handling, and UI behavior.\n\n## Response Formats\n\n### Markdown Output (Default)\n\nWhen `fmt=\"markdown\"` or `fmt` is `None`:\n\n```\n## ✅ Success\n\n**query:** search_term\n\n**results:** 3 items\n\n  - **namespace:** project-alpha\n    **key:** api_credentials\n    **value:** sk-... (truncated to 500 chars)\n    **created_at:** 2025-01-15T10:30:00\n    **access_count:** 42\n\n  - **namespace:** project-alpha\n    **key:** user_preferences\n    **value:** dark_mode: true, language:...\n    **created_at:** 2025-01-14T08:15:00\n    **access_count:** 38\n\n  - **namespace:** default\n    **key:** search_history\n    **value:** previous queries stored here...\n    **created_at:** 2025-01-10T14:22:00\n    **access_count:** 12\n```\n\n### JSON Output\n\nWhen `fmt=\"json\"`:\n\n```json\n{\n  \"status\": \"ok\",\n  \"query\": \"search_term\",\n  \"results\": [\n    {\n      \"namespace\": \"project-alpha\",\n      \"key\": \"api_credentials\",\n      \"value\": \"sk-... (truncated)\",\n      \"created_at\": \"2025-01-15T10:30:00\",\n      \"access_count\": 42\n    }\n  ],\n  \"total_found\": 3,\n  \"returned\": 3\n}\n```\n\n## Usage Examples\n\n### Basic Search Across All Namespaces\n\n```python\nresult = memory_search(query=\"api_key\", limit=5)\n```\n\nThis searches all namespaces for entries containing \"api_key\" in either the key or value field, returning the top 5 matches sorted by access frequency.\n\n### Namespace-Scoped Search\n\n```python\nresult = memory_search(\n    query=\"user\",\n    namespace=\"session_2024\",\n    limit=20\n)\n```\n\nLimiting search to a specific namespace reduces I/O and improves response time when the agent knows the relevant context domain.\n\n### Integration with MCP Client\n\n```python\nfrom mcp import ClientSession\n\nasync def search_memories(session: ClientSession, query: str):\n    result = await session.call_tool(\n        \"memory_search\",\n        arguments={\n            \"query\": query,\n            \"namespace\": None,\n            \"limit\": 10,\n            \"format\": \"markdown\"\n        }\n    )\n    return result.content[0].text\n```\n\n## Error Handling\n\n### Empty Query Error\n\n```python\nif not query.strip():\n    return _error(\"Query must not be empty\", fmt)\n```\n\nReturns:\n\n```\n## ❌ Error\n**Query must not be empty**\n```\n\n### Internal Error Handling\n\nThe `call_tool` wrapper catches exceptions and formats them as error responses:\n\n```python\nexcept Exception as exc:\n    err_text = _error(f\"Internal error in {name}: {exc}\", fmt)\n    return CallToolResult(\n        content=[TextContent(type=\"text\", text=err_text)],\n        isError=True,\n    )\n```\n\nThis ensures that filesystem errors, JSON parsing failures, or unexpected exceptions return structured error responses rather than crashes.\n\n## Performance Considerations\n\n| Factor | Impact |\n|--------|--------|\n| Namespace count | Linear increase in filesystem reads |\n| Entries per namespace | Linear scan through all entries |\n| Value size | Truncation mitigates large value impact |\n| Default limit (10) | Bounds result set size |\n\nThe tool does not implement indexing; every search performs a full scan of matching entries. For deployments with thousands of entries across many namespaces, consider:\n\n- Using namespace-scoped searches when context is known\n- Increasing the `limit` parameter to reduce missed relevant results\n- Partitioning memories into task-specific namespaces\n\n## Related Tools\n\n| Tool | Purpose |\n|------|---------|\n| `memory_remember` | Store new key-value entries |\n| `memory_recall` | Retrieve entry by exact key name |\n| `memory_forget` | Delete entry by key |\n| `memory_list_namespaces` | Enumerate available namespaces |\n| `memory_clear_namespace` | Delete all entries in a namespace |\n| `memory_stats` | View storage statistics |\n\n## Conclusion\n\nThe `memory_search` tool provides essential discovery capabilities for AI agents using Agent Memory MCP. By supporting fuzzy substring matching across both keys and values, it enables agents to find relevant context without requiring perfect recall of storage locations. The tool's design balances functionality with simplicity: case-insensitive matching, configurable result limits, and output formatting options make it adaptable to diverse agent architectures while maintaining predictable behavior through filesystem-based storage.\n\n---\n\n---\n\n## Doramagic Pitfall Log\n\nProject: Rumblingb/agent-memory-mcp\n\nSummary: Found 7 potential pitfall items; 0 are high/blocking. Highest priority: identity - 仓库名和安装名不一致.\n\n## 1. identity · 仓库名和安装名不一致\n\n- Severity: medium\n- Evidence strength: runtime_trace\n- Finding: 仓库名 `agent-memory-mcp` 与安装入口 `mcp` 不完全一致。\n- User impact: 用户照着仓库名搜索包或照着包名找仓库时容易走错入口。\n- Suggested check: 在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。\n- Reproduction command: `pip install mcp`\n- Guardrail action: 页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。\n- Evidence: identity.distribution | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | repo=agent-memory-mcp; install=mcp\n\n## 2. capability · 能力判断依赖假设\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: README/documentation is current enough for a first validation pass.\n- User impact: 假设不成立时，用户拿不到承诺的能力。\n- Suggested check: 将假设转成下游验证清单。\n- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。\n- Evidence: capability.assumptions | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | README/documentation is current enough for a first validation pass.\n\n## 3. maintenance · 维护活跃度未知\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 未记录 last_activity_observed。\n- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。\n- Evidence: evidence.maintainer_signals | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | last_activity_observed missing\n\n## 4. security_permissions · 下游验证发现风险项\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 下游已经要求复核，不能在页面中弱化。\n- Suggested check: 进入安全/权限治理复核队列。\n- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。\n- Evidence: downstream_validation.risk_items | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | no_demo; severity=medium\n\n## 5. security_permissions · 存在评分风险\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 风险会影响是否适合普通用户安装。\n- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。\n- Evidence: risks.scoring_risks | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | no_demo; severity=medium\n\n## 6. maintenance · issue/PR 响应质量未知\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: issue_or_pr_quality=unknown。\n- User impact: 用户无法判断遇到问题后是否有人维护。\n- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。\n- Guardrail action: issue/PR 响应未知时，必须提示维护风险。\n- Evidence: evidence.maintainer_signals | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | issue_or_pr_quality=unknown\n\n## 7. maintenance · 发布节奏不明确\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: release_recency=unknown。\n- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。\n- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- Evidence: evidence.maintainer_signals | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | release_recency=unknown\n\n<!-- canonical_name: Rumblingb/agent-memory-mcp; human_manual_source: deepwiki_human_wiki -->\n",
      "summary": "DeepWiki/Human Wiki output with a Doramagic pitfall appendix.",
      "title": "Human Manual"
    },
    "pitfall_log": {
      "asset_id": "pitfall_log",
      "filename": "PITFALL_LOG.md",
      "markdown": "# Pitfall Log\n\nProject: Rumblingb/agent-memory-mcp\n\nSummary: Found 7 potential pitfall items; 0 are high/blocking. Highest priority: identity - 仓库名和安装名不一致.\n\n## 1. identity · 仓库名和安装名不一致\n\n- Severity: medium\n- Evidence strength: runtime_trace\n- Finding: 仓库名 `agent-memory-mcp` 与安装入口 `mcp` 不完全一致。\n- User impact: 用户照着仓库名搜索包或照着包名找仓库时容易走错入口。\n- Suggested check: 在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。\n- Reproduction command: `pip install mcp`\n- Guardrail action: 页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。\n- Evidence: identity.distribution | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | repo=agent-memory-mcp; install=mcp\n\n## 2. capability · 能力判断依赖假设\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: README/documentation is current enough for a first validation pass.\n- User impact: 假设不成立时，用户拿不到承诺的能力。\n- Suggested check: 将假设转成下游验证清单。\n- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。\n- Evidence: capability.assumptions | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | README/documentation is current enough for a first validation pass.\n\n## 3. maintenance · 维护活跃度未知\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 未记录 last_activity_observed。\n- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。\n- Evidence: evidence.maintainer_signals | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | last_activity_observed missing\n\n## 4. security_permissions · 下游验证发现风险项\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 下游已经要求复核，不能在页面中弱化。\n- Suggested check: 进入安全/权限治理复核队列。\n- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。\n- Evidence: downstream_validation.risk_items | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | no_demo; severity=medium\n\n## 5. security_permissions · 存在评分风险\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 风险会影响是否适合普通用户安装。\n- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。\n- Evidence: risks.scoring_risks | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | no_demo; severity=medium\n\n## 6. maintenance · issue/PR 响应质量未知\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: issue_or_pr_quality=unknown。\n- User impact: 用户无法判断遇到问题后是否有人维护。\n- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。\n- Guardrail action: issue/PR 响应未知时，必须提示维护风险。\n- Evidence: evidence.maintainer_signals | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | issue_or_pr_quality=unknown\n\n## 7. maintenance · 发布节奏不明确\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: release_recency=unknown。\n- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。\n- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- Evidence: evidence.maintainer_signals | github_repo:1236240815 | https://github.com/Rumblingb/agent-memory-mcp | release_recency=unknown\n",
      "summary": "Identity, installation, configuration, runtime, and safety pitfalls before user trial.",
      "title": "Pitfall Log"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# agent-memory-mcp - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for Rumblingb/agent-memory-mcp.\n\nProject:\n- Name: agent-memory-mcp\n- Repository: https://github.com/Rumblingb/agent-memory-mcp\n- Summary: MCP server providing persistent key-value memory for AI agents with TTL and search\n- Host target: mcp_host\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: MCP server providing persistent key-value memory for AI agents with TTL and search\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCapabilities that require post-install verification:\n- Runtime installation or host integration must be verified after installation.\n\nCore service flow:\n1. overview: Overview. Produce one small intermediate artifact and wait for confirmation.\n2. quick-start: Quick Start Guide. Produce one small intermediate artifact and wait for confirmation.\n3. namespaces: Namespaces. Produce one small intermediate artifact and wait for confirmation.\n4. ttl-management: TTL Management. Produce one small intermediate artifact and wait for confirmation.\n5. memory-remember: memory_remember Tool. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/Rumblingb/agent-memory-mcp\n- https://github.com/Rumblingb/agent-memory-mcp#readme\n- README.md\n- LICENSE\n- glama.json\n- .gitignore\n- .nojekyll\n- server.py\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "summary": "不安装项目也能感受能力节奏的安全试用 Prompt。",
      "title": "Prompt Preview / 安装前试用 Prompt"
    },
    "quick_start": {
      "asset_id": "quick_start",
      "filename": "QUICK_START.md",
      "markdown": "# Quick Start\n\nProject: Rumblingb/agent-memory-mcp\n\n## Official Entry Points\n\n### Python / pip · 官方安装入口\n\n```bash\npip install mcp\n```\n\nSource：https://github.com/Rumblingb/agent-memory-mcp#readme\n\n## Sources\n\n- repo: https://github.com/Rumblingb/agent-memory-mcp\n- docs: https://github.com/Rumblingb/agent-memory-mcp#readme\n",
      "summary": "Entry points extracted from official README or installation documentation.",
      "title": "Quick Start"
    }
  },
  "validation_id": "dval_040c2cda697b48e08165081bce8e4198"
}
