Integrate Long-Term Memory with Claude Code via MCP

更新时间:
复制 MD 格式

Overview

AnalyticDB for PostgreSQLLong-Term Memory MCP Server is a self-hosted service based on the Model Context Protocol (MCP) that gives Claude Code persistent memory across sessions. MCP is a standard protocol defined by Anthropic that lets Claude Code call external services through a unified tool interface. After you register the AnalyticDB for PostgreSQL Long-Term Memory MCP Server, Claude can proactively call memory tools during conversations to create, retrieve, update, and delete knowledge.

How It Works

The adbpgmem MCP Server communicates with Claude Code over stdio (standard input/output). The workflow is as follows:

  1. Register: Register the adbpgmem MCP Server to Claude Code via the claude mcp add command.

  2. On-demand startup: Claude Code starts the MCP Server subprocess on demand through uvx (uv package manager), so no pre-installation is required.

  3. Tool invocation: Claude proactively calls MCP tools such as add_memory, search_memories based on the conversation context.

  4. API forwarding: The MCP Server converts tool calls into adbpgmem REST API requests to perform the actual memory operations.

All MCP tool calls are autonomously decided by Claude. No manual triggering is required.

Six MCP Tools

Tool

Function

Description

add_memory

Save memory to the memory store

Supports infer=true to let the server automatically extract atomic facts

search_memories

Semantic search for historical memories

Matches by meaning rather than keywords to find relevant past experience

list_memories

List all memories with pagination

Browse all memories in the memory store

update_memory

Update specified memory content

Modifies an existing memory by memory_id

delete_memory

Delete single memory

Removes expired or unused memories by memory_id

delete_all_memories

Bulk delete all memories

As a safety measure, requires confirm=true for confirmation

Use Cases

MCP tool integration is suitable for the following scenarios:

  • Manual memory control: You want precise control over what knowledge is recorded instead of relying on fully automatic background saving.

  • On-demand history query: Claude proactively searches for relevant knowledge in the memory store when needed.

  • Memory CRUD operations: You need fine-grained management of memories such as updating and deleting.

  • Team-shared configuration: Register the adbpgmem MCP Server to Claude Code through a project-level .mcp.json file.

Install MCP Server

Prerequisites

  • Claude Code CLI is installed and functional.

  • Python >= 3.10.

  • uv package manager (for on-demand startup via uvx, recommended).

  • Obtained the AnalyticDB for PostgreSQLlong-term memory service API URL and token. For details, seeContext service.

  • Obtained the adbpgmem_mcp_selfhosted project source code adbpgmem-mcp-server-0.2.0.tar.gz.

    Extract the archive to a directory named adbpgmem_mcp_selfhosted. All paths in the following steps refer to this extracted directory.

Installation

No pre-installation is required for MCP Server. uvx creates a temporary virtual environment from the local project path on demand and starts the service. You only need to ensure that the source path is accessible.

# Verify the source path is accessible
ls /path/to/adbpgmem_mcp_selfhosted/pyproject.toml
# The file info should be displayed, confirming the path is correct

Configure MCP Server

The MCP Server obtains AnalyticDB for PostgreSQL long-term memory service connection parameters through environment variables or configuration files. The following table lists the parameter sources in descending order of priority:

Priority

Source

Description

1

--env environment variable

Injected through claude mcp add --env during registration. This source has the highest priority.

2

$ADBPGMEM_CONFIG_DIR

Environment variable pointing to the configuration file directory

3

./.claude/adbpgmem.conf

Project-level configuration file

4

~/.claude/adbpgmem.conf

Global-level configuration file

Parameters

Parameter

Type

Required

Description

ADBPGMEM_API_URL

String

Yes

API URL of the long-term memory service

ADBPGMEM_API_TOKEN

String

Yes

Service authentication token

ADBPGMEM_USER_ID

String

No

User identifier. Defaults to the system username

Method 1: Inject via --env During Registration (Recommended)

You can inject environment variables directly through the --env parameter when registering the MCP Server, without creating additional configuration files. For more information, see the Register MCP Server section below.

Method 2: Manually Create a Configuration File

Global configuration (applies to all projects):

mkdir -p ~/.claude
cat > ~/.claude/adbpgmem.conf << 'EOF'
ADBPGMEM_API_URL="https://api-longmemory-cn-chengdu.opentrust.net"
ADBPGMEM_API_TOKEN="sk-your-token-here"
ADBPGMEM_USER_ID="your.username"
EOF

Project-level configuration (applies to the current project only):

mkdir -p .claude
cat > .claude/adbpgmem.conf << 'EOF'
ADBPGMEM_API_URL="https://api-longmemory-cn-chengdu.opentrust.net"
ADBPGMEM_API_TOKEN="sk-your-token-here"
ADBPGMEM_USER_ID="your.username"
EOF

adbpgmem.conf contains the API token. Do not commit it to Git. We recommend adding .claude/adbpgmem.conf to .gitignore.

Configuration File Description

The configuration file uses the KEY="VALUE" format, with one entry per line. If the configuration is missing, MCP Server logs a warning and continues to start, but API calls will fail.

Register MCP Server

You can register the MCP Server globally or at the project level.

Global Registration (Recommended)

Writes to ~/.claude.json and takes effect for all projects:

claude mcp add --scope user --transport stdio adbpgmem \
  --env ADBPGMEM_API_URL=https://api-longmemory-cn-chengdu.opentrust.net \
  --env ADBPGMEM_API_TOKEN=sk-your-token-here \
  --env ADBPGMEM_USER_ID=your.username \
  -- uvx --from /path/to/adbpgmem_mcp_selfhosted adbpgmem-mcp-server

The following table describes each parameter in the command:

Parameter

Description

claude mcp add

Registers a new MCP Server with the Claude Code client

--scope user

Registers as a global (user-level) configuration that takes effect for all projects

--transport stdio

Communicates over standard I/O. Claude Code communicates bidirectionally with the MCP Server through subprocess stdin/stdout

adbpgmem

The alias for this MCP Server. You can manage or remove it by this name later

-- uvx --from ...

-- Everything after -- is the actual startup command. uvx creates a temporary virtual environment from the local project path and runs the entry function.

Project-Level Registration

You can also register the MCP Server through the .mcp.json file in the project root directory. This method takes effect only for the current project and can be committed to version control for team sharing:

{
  "mcpServers": {
    "adbpgmem": {
      "command": "uvx",
      "args": ["--from", "/path/to/adbpgmem_mcp_selfhosted", "adbpgmem-mcp-server"],
      "env": {
        "ADBPGMEM_API_URL": "https://api-longmemory-cn-chengdu.opentrust.net",
        "ADBPGMEM_API_TOKEN": "sk-your-token-here",
        "ADBPGMEM_USER_ID": "your.username"
      }
    }
  }
}

You can commit the project-level .mcp.json to the Git repository so that team members can share the configuration after cloning. Do not include real API tokens.

Configure CLAUDE.md Behavior Instructions (Optional)

You can add the following content to ~/.claude/CLAUDE.md (global) or CLAUDE.md (project-level) in the project root directory to guide Claude to proactively use memory tools. If you do not configure this, MCP tool functionality is not affected, but Claude will not proactively call the tools.

# MCP Servers

- **adbpgmem**: Persistent memory service. At the start of each session, use `search_memories`
  to search for relevant context. Use `add_memory` to save architectural decisions,
  debugging experience, and coding patterns. Use `update_memory` when memory content
  changes. Better to save too much than to miss something.

How to Use MCP Tools

Verify Registration

Check if the MCP Server is registered successfully:

# Check if the MCP Server is registered successfully
claude mcp list
# The output should include adbpgmem

# After starting Claude Code, type /mcp to check if the status shows ✓ Connected

Invocation

Claude autonomously calls MCP tools based on the conversation context. You trigger them through natural language:

What You Say

Tool Called by Claude

Remember: the project uses PostgreSQL 15

add_memory

Search for previous memories about database configuration

search_memories

List all memories

list_memories

Update the content of this memory

update_memory

Delete this memory

delete_memory

Detailed Tool Usage

add_memory (Save Memory)

Saves development knowledge to the adbpgmem memory store for cross-session retrieval.

Parameters:

Parameter

Type

Default

Description

content

String

-

Memory content to save (required)

user_id

String

Config value

User identifier. Defaults to the configured user_id

Usage example:

You: Remember: this project uses Go 1.22 + Gin framework, ORM uses GORM v2, database is PostgreSQL 15

Claude calls add_memory → Server stores the memory

search_memories (Semantic Memory Search)

Performs a semantic search for relevant historical memories in the memory store, matching by meaning rather than keywords.

Parameters:

Parameter

Type

Default

Description

query

String

-

Search query text (required)

user_id

String

Config value

User identifier

top_k

Int

5

Number of results to return

Usage example:

You: Search for previous memories about database selection

Claude calls search_memories → Returns semantically matched historical memories

list_memories (List Memories)

Lists all memories in the memory store with pagination.

Parameters:

Parameter

Type

Default

Description

user_id

String

Config value

User identifier

page

Int

1

Page number

page_size

Int

50

Items per page

update_memory (Update Memory)

Updates the content of a specified memory by memory_id.

Parameters:

Parameter

Type

Description

memory_id

String

UUID of the memory (required)

text

String

New memory content (required)

delete_memory (Delete Single Memory)

Deletes a specified memory by memory_id.

Parameters:

Parameter

Type

Description

memory_id

String

UUID of the memory (required)

delete_all_memories (Bulk Delete)

Safely deletes all memories of the specified user in bulk. Memories are deleted one by one instead of clearing the entire collection.

Parameters:

Parameter

Type

Default

Description

user_id

String

Config value

User identifier

confirm

Bool

false

Confirms deletion. Must be set to true

Typical Usage Scenarios

Scenario 1: Search Historical Debugging Experience

You encounter a Docker container out-of-memory issue and want to check whether there is any previous experience.

Operation:

You: Search if we've encountered Docker container OOM issues before

Claude behavior:

  1. Recognizes the search intent.

  2. Calls search_memories(query="Docker container OOM out of memory").

  3. Returns matching historical memories.

Example output:

Found 1 relevant memory:

1. [score: 0.91] Java applications in Docker containers require -XX:MaxRAMPercentage=75.0
   and -XX:+UseContainerSupport, otherwise JVM cannot correctly recognize container
   memory limits, causing it to exceed the container limit and get killed.

Scenario 2: Cross-Session Knowledge Reuse

In a previous session, you established API design conventions. This session requires developing new API endpoints.

Session 1:

You: Remember: our APIs uniformly use RESTful style, pagination uses page/page_size,
    sorting uses sort=field:asc|desc, error responses include type/title/status/detail fields

Session 2 (days later, a new session):

You: Help me design a new user management API endpoint

Claude: Based on the API design conventions saved earlier, I'll design the user management endpoint:
       - List API supports pagination and sorting
       - Error responses use the unified four-field format
       - Follows RESTful naming conventions

       [Automatically outputs design following team conventions without needing repeated instructions]

Claude automatically retrieves the conventions established in the previous session from the memory store. New sessions can directly reuse team consensus without repeated communication.