Memory

MCP文档知识

提供方 未标注

文档知识 HTTP · 远程 API Key 社区 / 第三方 Claude DesktopClaudeCursorVS Code
查看接入方式

为你的AI代理提供持久记忆。Memory-MCP存储、检索并语义搜索AI代理的“记忆”,这些记忆被组织在由API密钥保护的隔离多租户空间中——因此上下文能在对话间延续,且不浪费令牌。

一句话选型结论

按资料字段整理

Memory 属于文档知识类 MCP 服务器,HTTP · 远程,API Key,可直接接入 Claude Desktop、Claude、Cursor 等,有可直接复制的远程端点配置。接入前先确认权限范围;涉及写入、删除或付款的操作,建议先在测试环境验证。

分类文档知识 传输方式HTTP · 远程 鉴权API Key 部署方式远程部署
GitHub 星标 未标注 仓库热度,无公开仓库时显示未标注
工具数 未标注 暴露给模型的工具数量
资源 / 提示词 0 / 0 资源与提示词模板数量
维护方 社区 / 第三方 核验等级 仅资料核对

工具与能力

文档知识
数量来自来源目录的标注,具体工具清单以官方文档为准
工具数量未标注暴露给模型可调用的工具个数
资源数量0可读取的资源条目
提示词数量0内置提示词模板数量

能力标签

支持客户端

适用场景

记忆

安装与配置

HTTP · 远程 API Key
连远程 HTTPS 端点,通常为 Streamable HTTP
{ "mcpServers": { "memory-mcp": { "url": "http://localhost:5004/mcp", "headers": { "X-Api-Key": "mmcp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } }, "memory-mcp-stdio": { "command": "dotnet", "args": ["C:\\path\\to\\Memory-MCP\\src\\MemoryMcp.Api\\bin\\Release\\net10.0\\MemoryMcp.Api.dll", "--", "--stdio"], "env": { "ConnectionStrings__Default": "Host=localhost;Port=5432;Username=<user>;Password=<password

这条命令只是入口,具体启动参数请按官方文档补齐,不要直接照搬到别的服务器。

  1. 1
    准备运行环境

    确认你的客户端支持远程端点,并拿到服务地址。

  2. 2
    安装服务

    复制上面的安装命令执行;命令里带占位符的位置,换成自己的密钥或路径。

  3. 3
    写入客户端配置

    在客户端的 MCP 配置里填好启动命令和参数,保存后完全退出客户端再打开,让新配置生效。

  4. 4
    验证是否可用

    连接成功后随便调一个只读工具,确认能返回结果,再接入正式流程。

典型使用场景

3 类
按分类与标签整理的常见用法,具体以官方文档为准
文档检索问答

在你的文档库里按问题找答案。

知识库读写

把新资料写进知识库,随用随取。

内容整理

把零散资料归纳成结构化笔记。

选择建议

选之前先看这几条
按条目字段给出的判断,不替你决定用不用

值得选的地方

  • 有现成的安装命令,不用自己找入口,照着跑就能起服务。
  • 已适配 Claude Desktop、Claude、Cursor,换客户端不用重新研究配置。

先想清楚的地方

  • 远程端点依赖网络与服务方可用性,注意密钥与调用额度。
  • 使用前要准备好API Key对应的凭据,并按最小权限配置。
  • 资料没标注工具数量,实际能力要装好后确认。
  • 版本更新与行为细节以官方仓库为准。

更适合

  • 需要在文档知识场景里让模型直接调用外部能力的人。
  • 已经在用 Claude Desktop、Claude 的用户,接入路径最短。
  • 想先快速试一下、能接受在本地或自有环境跑服务的人。

不太适合

  • 不方便管理密钥或第三方授权的人。
  • 需要厂商级 SLA 和技术支持的生产环境。

同类对比

6 个同类
同分类里挑最接近的几条,字段以各自详情页为准
MCP 服务器工具数传输方式部署方式安装命令最后核验
Memory当前 未标注 HTTP · 远程 远程部署 有 未标注
dify 未标注 stdio · 本地进程 本地部署 有 2026-04-11
open-webui 未标注 stdio · 本地进程 本地部署 有 2026-04-11
JeecgBoot 未标注 stdio · 本地进程 本地部署 有 2026-04-11
Cherry Studio 未标注 未标注 未标注 无 2026-05-17
mempalace 未标注 stdio · 本地进程 本地部署 有 2026-04-11

服务器档案

文档知识
字段来自项目仓库与公开索引,中文说明由本站标注
提供方未标注上游标注的维护方 未标注
分类文档知识本站按上游分类展示
连接方式HTTP · 远程连远程 HTTPS 端点,通常为 Streamable HTTP
鉴权方式API Key远程服务建议用最小权限凭据
维护方社区 / 第三方核验等级 仅资料核对
包名 / 运行时未标注 · 未标注本地安装时用到的包标识与运行时
部署类型远程部署上游给出的部署形态
最近核验未标注上游最后核验时间

详细介绍

44.8 KB
来自项目仓库与上游目录的原文,未做删改

Memory-MCP

Remote MCP (Model Context Protocol) server for storing, retrieving, and semantically searching
"memories" on behalf of AI agents, organized into multi-tenant spaces and protected by API Key.
A space can be shared by several users — each a Writer or a Reader, each attributed on what
they write.

Full functional specification: CLAUDE.md.

Table of contents

  • Architecture
  • Technology
  • Data model
  • Available MCP tools
  • Available MCP resources and prompts
  • MCP Apps widgets
  • Project phases
  • Setup and startup
  • Tests
  • Docker
  • Deploy to Fly.io

Architecture

4-layer Clean Architecture, with dependencies flowing in a single direction (Api → Infrastructure/Application → Domain):```
Memory-MCP/
├── src/
│ ├── MemoryMcp.Domain/ # Pure entities (Space, ApiKey, ApiKeySpaceGrant, Document, Memory)
│ │ # No dependency on EF/HTTP/external libraries.
│ ├── MemoryMcp.Application/ # Use cases: interfaces (IMemoryService, IDocumentService,
│ │ # ISpaceService, IEmbeddingProvider, repositories, ICurrentAccessContext)
│ │ # + application service implementations + DTOs.
│ ├── MemoryMcp.Infrastructure/ # EF Core (MemoryDbContext, migrations, repositories), embedding
│ │ # provider (OpenAI/Azure OpenAI/Gemini) and fact extractor for graph memory.
│ └── MemoryMcp.Api/ # ASP.NET Core host: MCP hosting, API Key authentication,
│ # MCP tools/resources/prompts (thin adapters) and the MCP Apps widgets (Apps/).
└── tests/
├── MemoryMcp.Application.Tests/ # Unit tests for the application services (mock/NSubstitute)
├── MemoryMcp.Infrastructure.Tests/ # Integration tests for the repositories against a real Postgres
└── MemoryMcp.Api.Tests/ # End-to-end tests for tools/resources/prompts/widgets via an MCP client + WebApplicationFactory


**Why Clean Architecture and not Vertical Slice**: all tools share the same data model
(Space/ApiKey/Memory/Document) and the same per-space authorization rules; isolating EF persistence
and the embedding provider behind interfaces in `Application` let the project be extended in later
phases (resources, prompts, MCP Apps widgets) with at most small, additive `Application` service
methods and no changes to `Domain`.

Every class in `Api/Tools` is a **thin adapter**: it resolves the access context (`ICurrentAccessContext`),
calls the application service, and formats the output — no business logic in the Api layer.

### Authentication and multi-tenancy

See docs/multi-user-spaces.md for the full design of users, roles, and
write attribution.

- Every **API Key** belongs to exactly one **user** and is granted one or more **spaces**, with an access
  level (`Read` or `ReadWrite`) per space and one space marked as &quot;active&quot; (`IsDefault`).
- A **user** is either a **`Writer`** (read/write) or a **`Reader`** (read only). The role is a ceiling
  that applies everywhere; the grant is what was given on one space. The **effective** access level is
  the lower of the two, so a Reader holding a `ReadWrite` grant is still read-only, and demoting someone
  to Reader removes write access on every space at once without touching a grant row.
- The capping is applied once, where the access snapshot is built (`ApiKeyRepository`), so every
  consumer — tool checks, `listSpaces`, `whoAmI`, the write-capable widgets — reads the same effective
  level and none of them can disagree about it.
- `ApiKeyAuthenticationHandler` (`src/MemoryMcp.Api/Auth`) reads the key from the `X-Api-Key` header (or
  `Authorization: Bearer `), validates it against the database (SHA-256 hash, never the plaintext key), and
  populates `CurrentAccessContext`, a scoped service injected into the application services.
- Deactivating a user (`users.IsActive`) stops **all** of their keys from authenticating, without having
  to find each credential they minted. Their display name is still resolved, so what they wrote while
  active does not become anonymous.
- The tools&#x27; `containerTag` parameter corresponds to the `spaces.key` column; if omitted, the current
  key&#x27;s &quot;active&quot; space is used.
- **Isolation is per space**: every read resolves exactly one space and filters on it, so no search or
  listing crosses a space boundary. A space the key holds no grant on is indistinguishable from one that
  does not exist. **Within** a space nothing is filtered by author — every member reads the whole
  space&#x27;s knowledge.
- Authorization/space-not-found errors are translated into MCP tool results with `isError=true`
  (never unhandled exceptions or 500s).

### Write attribution

- `memories` and `documents` both carry `CreatedByUserId` and `UpdatedByUserId`, exposed on the tool
  results as ids **and** resolved display names (`createdBy`, `updatedBy`), so a model reading a search
  result can cite who wrote each fact without a second call.
- The two are kept apart because in a shared space they frequently differ: `UpdatedByUserId` is the
  record of who *deactivated* a memory, whether by an explicit `forget` or by a save whose extracted
  fact superseded it, while `CreatedByUserId` keeps naming the original author.
- **A save never deactivates a colleague&#x27;s memory.** When extraction classifies a new fact as `Updates`
  an existing memory of someone else (and similarity clears the forget threshold), the `Updates` edge is
  still recorded but both memories stay active; `add_memory` returns the other memories in
  `contestedMemoryIds` and says so in its message. Superseding your own memory, or one written before
  authorship was recorded, works as before. An explicit `forget` is unchanged.
- Names are resolved in one batched lookup per call, so a page of results costs one extra query rather
  than one per row — and none at all when nothing in the result set is attributed.
- Rows written before users existed keep NULL authorship and are reported as unattributed rather than
  guessed at.

### Semantic search

`IEmbeddingProvider` is pluggable (OpenAI, Azure OpenAI, or Gemini — the same OpenAI SDK
`EmbeddingClient` under all three, pointed at a different base URL for Gemini, since its API is
OpenAI-compatible). Embeddings are stored in a **`pgvector`** column and ranked **in the database** by
cosine distance (`&lt;=&gt;`), served by an HNSW index — see
docs/pgvector-halfvec-search.md for the full design.

The column type is `halfvec(3072)`, not `vector(3072)`, and that choice is load-bearing: pgvector&#x27;s HNSW
and IVFFlat indexes cap the `vector` type at **2000 dimensions**, so a `vector(3072)` column would accept
the data and then fail at index creation. `halfvec` indexes up to 4000 dimensions and halves storage
(2 bytes per component instead of 4); the half-precision rounding is immaterial for cosine *ranking*.

`MemoryRepository.SearchAsync` runs the KNN as parameterized SQL that projects only ids and distances —
embeddings never cross the wire — then loads just the top-k rows as tracked entities, so `ForgetAsync`
can still soft-delete through change tracking without the read path tracking the whole space.

The embedding width is **schema-bound**, not a configuration knob: EF migrations are generated at design
time, so `VectorSettings.Dimensions` (3072) is the single source of truth, and startup fails if
`Embeddings:Dimensions` disagrees with it. Changing the width means a migration plus a re-embed of every
stored memory. This is what makes mixed-width embeddings — which previously produced silently
meaningless similarity scores — unrepresentable.

Besides semantic search, `search_memory` also supports literal keyword search
(`keyword`, matched in `MemoryRepository.SearchByKeywordAsync` without generating an embedding). A memory
matches if its text contains the keyword as a case-insensitive substring (`ILIKE`) **or** is a close
fuzzy/typo match per Postgres&#x27;s `pg_trgm` word similarity (`word_similarity(keyword, text) &gt;=
pg_trgm.word_similarity_threshold`, the extension&#x27;s default of `0.6`); matches are ranked by that
similarity score. Both paths are backed by a single GIN trigram index on `memories.text`
(`gin_trgm_ops`, see `MemoryConfiguration`). The default threshold is intentional rather than an
oversight: for short keywords (3-5 letters) trigram similarity is noisy — e.g. `word_similarity(&#x27;plan&#x27;,
&#x27;plant&#x27;)` is `0.8` and `word_similarity(&#x27;sky&#x27;, &#x27;skip&#x27;)` is `0.5` — so lowering it below the default to
catch more typos (e.g. `word_similarity(&#x27;recieve&#x27;, &#x27;receive&#x27;)` is only `0.375`) trades a small amount of
typo recall for a much larger amount of unrelated-word noise. `pg_trgm` needs no admin-restricted native
extension (unlike `pgvector`, see below), so it works in this environment.

`search_memory` also supports filtering/listing by category (`category`, an optional column on
`memories`, assignable in `add_memory`). The three criteria can be combined: `query`/`keyword` can be further restricted by
`category`; if only `category` is given, `MemoryRepository.ListByCategoryAsync` lists the memories in that
category ordered by creation date. At least one of `query`, `keyword`, and `category` must be provided.

&gt; **Requires `pgvector` ≥ 0.7.0** (the version that introduced `halfvec`), on a **stable** PostgreSQL
&gt; release. Earlier phases ran without the extension and scored cosine similarity in-app; that path has
&gt; been removed. Two environment notes worth knowing before setting this up elsewhere:
&gt;
&gt; - A PostgreSQL *release candidate* will reject the extension (`The specified procedure could not be
&gt;   found`) — pgvector binaries are built against the released ABI, so a pre-GA server fails to load them.
&gt; - `CREATE EXTENSION vector` needs **superuser**, because pgvector is not a *trusted* extension. The
&gt;   migration runs it, so verify the permission on managed Postgres before the first deploy.

### Graph memory

Saved content isn&#x27;t stored verbatim as a single memory: `MemoryService.SaveAsync` first asks
`IFactExtractor` to split it into atomic facts and classify each fact&#x27;s relation — `Updates`,
`Extends`, or `Derives` — to a handful of similar existing memories (fetched the same way
`ForgetAsync` finds candidates, via `IMemoryRepository.SearchAsync`). Each fact becomes its own
`Memory`, and each relation becomes a `MemoryEdge` row; an `Updates` relation also calls the existing
`Memory.Forget(supersededBy:)`, so `SupersededBy`/`IsActive` stay in sync with the edge that
generalizes them. `LlmFactExtractor` asks its chat model for this via JSON Schema structured output
(strict mode) rather than parsing free text, and relations pointing at memory ids outside the supplied
candidates are dropped defensively (a hallucinated id would otherwise violate the edge&#x27;s foreign key).
Every relation also carries a short rationale, stored on `MemoryEdge.Note` (clamped to the column width
by the entity) — the only record of *why* an `Updates` deactivated an existing memory.

There&#x27;s no dedicated graph database in this environment either (same constraint as above) — traversal
(`MemoryEdgeRepository.GetRelatedAsync`) is a `WITH RECURSIVE` CTE over the plain `memory_edges`
table, parameterized through EF Core&#x27;s `Database.SqlQuery`, bounded by a hop count and a
visited-node path array to guarantee termination on cycles. `search_memory` attaches each top match&#x27;s
related memories (text + relation type + hop count, plus the edge&#x27;s rationale for direct relations) via
`MemoryGraphService`, additive to the existing `MemorySearchResultDto` shape.

If `Extraction:ApiKey` is left unconfigured, `IFactExtractor` throws `ExtractorNotConfiguredException`
and `add_memory` transparently falls back to saving the whole content as a single memory with zero
edges — exactly Phase 1&#x27;s behavior, so nothing breaks for callers who never configure extraction.
`IFactExtractor` is pluggable the same way as `IEmbeddingProvider` (OpenAI, Azure OpenAI, Gemini, or
any other OpenAI-compatible chat endpoint such as a self-hosted Ollama/vLLM/LM Studio model) by
configuration alone.

## Technology

| Layer | Technology |
| --- | --- |
| Runtime | .NET 10 (pinned in global.json) |
| MCP Server | `ModelContextProtocol` / `ModelContextProtocol.AspNetCore` 2.1.0 + `ModelContextProtocol.Extensions.Apps` (MCP Apps widgets) |
| Web host | ASP.NET Core Minimal API |
| Persistence | PostgreSQL + EF Core 10 (`Npgsql.EntityFrameworkCore.PostgreSQL`) |
| Vector search | `pgvector` ≥ 0.7.0 (`halfvec` + HNSW), via `Pgvector.EntityFrameworkCore` |
| Embedding | `OpenAI` / `Azure.AI.OpenAI` (same `EmbeddingClient`, selected via configuration; also backs Gemini&#x27;s OpenAI-compatible endpoint) |
| Fact extraction | Same `OpenAI` SDK&#x27;s `ChatClient`, JSON Schema structured output (OpenAI / Azure OpenAI / Gemini / self-hosted OpenAI-compatible) |
| PDF text extraction | `PdfPig` + its document layout analysis for reading order (pure managed, no native dependencies or external service) |
| Authentication | Custom `AuthenticationHandler` scheme based on API Key (SHA-256 hash) |
| Tests | xUnit, NSubstitute, AwesomeAssertions (MIT fork of FluentAssertions), `Microsoft.AspNetCore.Mvc.Testing` |
| Container | Multi-stage Dockerfile + docker-compose (for environments where Docker is available) |

## Data model

| Table | Description |
| --- | --- |
| `spaces` | Logical space (`key` unique = `containerTag`, `name`, `description`) |
| `users` | Person (`email` unique, display name, `role` = `Writer`/`Reader` stored as text, `is_active`) |
| `api_keys` | API key belonging to one user (only the hash is stored, never the plaintext value; `label` says *which* credential — laptop, CI — not whose) |
| `api_key_space_grants` | `Read`/`ReadWrite` permission of an API Key on a space + &quot;active space&quot; flag; capped at read time by the owning user&#x27;s role |
| `documents` | Source document (title, type, status, summary, raw content, `created_by_user_id`/`updated_by_user_id`) |
| `memories` | Extracted memory (text, optional category, `halfvec(3072)` embedding with an HNSW cosine index, version, `is_active` for soft-delete/&quot;forget&quot;, `created_by_user_id`/`updated_by_user_id`) |
| `memory_edges` | Typed, directed graph edge between two memories (`Updates`/`Extends`/`Derives`), scoped to a space, with the extractor&#x27;s rationale in `note` |

## Available MCP tools

The 7 tools required by the specification are implemented in `src/MemoryMcp.Api/Tools`. `search_memory`
and `add_memory` are enriched by graph memory (related memories on search results, multi-fact
extraction on save) without any change to their tool contract — no new tool was added for this.
Phase 3 additionally introduced two small, additive tools (`setActiveSpace`, `create_document`) that
back the MCP Apps widgets below, plus four `*_ui` tools whose only job is to open a widget (see
&quot;MCP Apps widgets&quot;). &quot;Access required&quot; is the **effective** level — the space grant already capped by
the caller&#x27;s role — so every `ReadWrite` row below is refused to a `Reader`:

| Tool | File | Access required | Description |
| --- | --- | --- | --- |
| `search_memory` | `MemoryTools.cs` | Read | Searches a space&#x27;s memories by semantic similarity (`query`), literal keyword (`keyword`), and/or category (`category`), with optional profile; top matches include `relatedMemories` from the graph |
| `add_memory` | `MemoryTools.cs` | ReadWrite | Saves (`action=save`, with optional `category`) or removes (`action=forget`) a memory; saving extracts atomic facts and links them to related existing memories as graph edges |
| `listDocuments` | `DocumentTools.cs` | Read | Paginated list of a space&#x27;s source documents |
| `getDocument` | `DocumentTools.cs` | Read | Metadata and content of a document |
| `create_document` | `DocumentTools.cs` | ReadWrite | Stores content as a new document (text/Markdown/CSV/PDF in this version — PDF content is base64 bytes, extracted to text server-side) — source-of-truth storage only, does not run fact extraction |
| `listMemories` | `MemoryTools.cs` | Read | Paginated list of extracted memories |
| `listSpaces` | `AccessTools.cs` | — | Spaces accessible with the current API Key, with the effective access level and counts |
| `whoAmI` | `AccessTools.cs` | — | Authenticated user (id, email, display name, `Writer`/`Reader` role), the key in use, accessible spaces, active space |
| `setActiveSpace` | `AccessTools.cs` | — | Sets which of the current API key&#x27;s accessible spaces is active (default) |

## Available MCP resources and prompts

For clients that support them — implemented in `src/MemoryMcp.Api/Resources` and
`src/MemoryMcp.Api/Prompts`, both thin adapters over the same `Application` services the tools use:

| Kind | URI / Name | File | Description |
| --- | --- | --- | --- |
| Resource | `memory-mcp://profile` | `MemoryResources.cs` | Recent-active-memories profile context for the active space (the same set `search_memory`&#x27;s `includeProfile` attaches) |
| Resource | `memory-mcp://spaces` | `AccessResources.cs` | The same compact space list as `listSpaces`, with the active space marked |
| Resource | `memory-mcp://memories` | `MemoryResources.cs` | First page of the active space&#x27;s memories (any status), same shape as `listMemories` |
| Resource | `memory-mcp://graph` | `MemoryResources.cs` | Nodes (memories, any status) and typed edges for the active space, for the `memory-graph` widget |
| Prompt | `context` | `ContextPrompt.cs` | A ready-to-attach text message: the active space&#x27;s profile, plus up to 3 other spaces ranked by their most recent memory |

These four resources are fixed (non-templated) URIs scoped to the API key&#x27;s active space; none take
arguments. `IMemoryService.GetProfileAsync`/`GetSpaceGraphAsync` are small additive `Application`
methods — the profile one is the fetch logic already used by `search_memory`, extracted so it can be
called on its own instead of only alongside a search; the graph one wraps
`IMemoryGraphService.GetSpaceGraphAsync` behind the same `RequireAccess` check every other method uses.

See docs/resources-and-prompt-usage.md for how to read the
resources at the protocol level, and docs/mcp-prompt-usage.md for the
`context` prompt in detail — what it contains, how the space ranking works, and when to prefer it
over `search_memory`.

## MCP Apps widgets

See docs/mcp-apps-widgets-usage.md for a protocol-level walkthrough
of each widget with request/response examples.

Phase 3 also adds four interactive widgets via the `ModelContextProtocol.Extensions.Apps` package
(an `[Experimental]` API, `MCPEXP003` suppressed in `MemoryMcp.Api.csproj`, same as the SDK&#x27;s own
`samples/WeatherAppServer`): `[McpAppUi(ResourceUri = &quot;ui://...&quot;)]` on a tool
(`src/MemoryMcp.Api/Apps/AppUiTools.cs`) links it to an HTML resource served with
`MimeType = McpApps.HtmlMimeType` (`src/MemoryMcp.Api/Apps/AppUiResources.cs`, markup under
`Apps/ui/*.html`); `.WithMcpApps()` is wired into both the HTTP and stdio server registrations in
`Program.cs`. Inside the iframe, each widget bootstraps a small `window.postMessage` JSON-RPC bridge
(`ui/initialize` handshake, then ordinary `tools/call`/`resources/read`) to drive real tools/resources
— no widget-specific business logic lives in the HTML beyond that bridge.

| Widget | Opens via tool | Backing UI resource | What it does |
| --- | --- | --- | --- |
| `select-space` | `select_space_ui` | `ui://select-space` | Lists accessible spaces (`memory-mcp://spaces`) and switches the active one (`setActiveSpace`) |
| `guided-save` | `guided_save_ui` | `ui://guided-save` | Editable content/category/space form that calls `add_memory` |
| `upload-file` | `upload_file_ui` | `ui://upload-file` | Local file picker that calls `create_document`, then optionally `add_memory` with the extracted text |
| `memory-graph` | `memory_graph_ui` | `ui://memory-graph` | Reads `memory-mcp://graph` and renders it with a small hand-rolled force-directed layout (no CDN dependency) |

`upload-file` fully ingests text-like formats (`.txt`/`.md`/`.csv`, read client-side via
`FileReader.readAsText`) and PDF: for PDF the widget instead reads the file as base64
(`FileReader.readAsDataURL`) and sends it to `create_document` with `docType: &quot;pdf&quot;`, which decodes it
server-side and extracts the text via `IPdfTextExtractor` (`PdfPig`, pure managed, no native
dependencies or external service — see `src/MemoryMcp.Infrastructure/Documents/PdfTextExtractor.cs`)
before storing it as the document&#x27;s `RawContent`; the widget then fetches that extracted text back via
`getDocument` if &quot;also extract memories&quot; is checked, since the plain text only exists server-side for
PDFs. A malformed/corrupt PDF surfaces as a normal tool error (`DocumentExtractionException`), not an
unhandled exception.

Extraction runs PdfPig&#x27;s document layout analysis (letters → words → paragraph blocks → reading order)
rather than the raw `Page.Text`, which concatenates glyphs in content-stream order and interleaves
columns, tables and running headers. Since the extracted text is what gets embedded and fed to the fact
extractor, reading order is a correctness concern rather than a cosmetic one. Layout analysis is
heuristic, so a page it cannot segment falls back to `Page.Text` for that page alone. Scanned
(image-only) PDFs have no text layer to recover and still extract as empty — OCR is not in scope.

&gt; **Note:** other formats the wider spec mentions (Word, images, MP3/WAV/M4A, MP4/WebM) can still be
&gt; picked in the file dialog but disable upload with an inline explanation — Word text extraction and
&gt; image OCR/audio transcription are deferred to a future phase, the same way the pgvector/Docker
&gt; constraints above are called out rather than worked around.

Full interactive rendering (the widget actually showing up and working inside an iframe) requires an
MCP Apps-capable host (e.g. Claude Desktop/VS Code with Apps support) — same caveat the SDK&#x27;s own
`WeatherAppServer` sample calls out. Any MCP client can still list/call the four `*_ui` tools and read
the `ui://*` resources to confirm they&#x27;re registered and serving HTML.

## Project phases

### Phase 1 — Completed

- [x] Domain entities and the relational data model (Space, ApiKey, ApiKeySpaceGrant, Document, Memory)
- [x] EF Core persistence + initial migration
- [x] API Key authentication with per-space permissions
- [x] Pluggable `IEmbeddingProvider` (OpenAI / Azure OpenAI)
- [x] The 7 core MCP tools, exposed via `ModelContextProtocol.AspNetCore` on the `/mcp` HTTP endpoint
- [x] Test suite (unit, integration, end-to-end)

### Phase 2 — Graph memory — Completed

See docs/graph-memory-plan.md for the full design.

- [x] `MemoryEdge`/`RelationType` domain model, generalizing the existing `SupersededBy`/`IsActive`/`Version` fields
- [x] Pluggable `IFactExtractor` (OpenAI / Azure OpenAI / Gemini / self-hosted OpenAI-compatible), with a
      strictly-additive fallback to Phase 1&#x27;s single-memory save when unconfigured
- [x] `memory_edges` table + `WITH RECURSIVE` CTE traversal (`MemoryEdgeRepository`, no graph DB extension)
- [x] `search_memory` enriched with `relatedMemories`; `add_memory` extracts and links multiple facts per save
- [x] `Embeddings:Dimensions` made configurable (Gemini&#x27;s native embedding width differs from OpenAI&#x27;s)
- [x] Test suite extended (unit, integration, end-to-end)

### Phase 3 — Resources, prompt, and MCP Apps widgets — Completed

- [x] MCP Resources: `memory-mcp://profile`, `memory-mcp://spaces`, `memory-mcp://memories`, `memory-mcp://graph`
- [x] MCP Prompt: `context`
- [x] Interactive MCP Apps widgets: `select-space`, `guided-save`, `upload-file`, `memory-graph`
      (via the `ModelContextProtocol.Extensions.Apps` package; see &quot;MCP Apps widgets&quot; above —
      `upload-file` ingests text-like formats and PDF (via `PdfPig`); Word/image/audio parsing deferred)
- [x] Test suite extended (end-to-end, via the MCP client&#x27;s resource/prompt/tool calls)

### Phase 4 — Native vector index — Completed

See docs/pgvector-halfvec-search.md for the full design and rationale.

- [x] `pgvector` adopted with a **native HNSW index**, replacing in-app cosine scoring — the original
      specification&#x27;s intent, reached with pgvector rather than the separate `Qdrant` service originally
      sketched, since it keeps memories and their vectors in one transactional store
- [x] `halfvec(3072)` column, working around pgvector&#x27;s 2000-dimension index limit on the `vector` type
- [x] KNN pushed into SQL: embeddings no longer cross the wire, and change tracking is confined to `topK`
      rows instead of the whole space
- [x] Embedding width made schema-bound and validated at startup, making mixed-width embeddings
      (previously a silent source of meaningless similarity scores) unrepresentable
- [x] Npgsql provider configuration centralized so `UseVector()` can&#x27;t be omitted by a second call site

### Phase 5 — Multi-user spaces — Completed

See docs/multi-user-spaces.md for the full design.

- [x] `User` + `UserRole` (`Writer`/`Reader`) domain model; `ApiKey` becomes a credential *of* a user
      (`ApiKey.OwnerEmail` dropped — the owner&#x27;s identity lives on `users.email`)
- [x] Role used as a ceiling over the per-space grant, capped once where the access snapshot is built,
      so no service, tool, or widget has to combine the two itself
- [x] Deactivating a user invalidates every key they hold, in the authentication query
- [x] `CreatedByUserId`/`UpdatedByUserId` on memories and documents, exposed as ids and resolved display
      names on every search/list/detail result, with the &quot;who forgot whose memory&quot; case kept distinct
      from authorship
- [x] Per-space isolation pinned end-to-end (an ungranted space is unreachable by semantic search,
      keyword search, and by naming its key), and reads left unfiltered by author *within* a space
- [x] `--seed` provisions two users and two spaces; `guided-save`/`upload-file` offer only writable
      spaces and `select-space` shows the effective level
- [x] Test suite extended (domain, application, integration, end-to-end)

### Phase 6 — Not implemented (evolution)
- [ ] Review project for introducing a real graphDB (Neo4j)
- [ ] Full-precision re-ranking of HNSW candidates, if measured recall proves insufficient
- [ ] pgvector iterative index scans (0.8.0+) for highly selective filtered searches
- [ ] Word text extraction and image OCR/audio transcription for `upload-file`

## Setup and startup

### Prerequisites

- .NET SDK 10 (version pinned in global.json)
- A reachable PostgreSQL instance (local or remote) on a **stable** release, with the **`pgvector`
  extension ≥ 0.7.0** available and a database user allowed to `CREATE EXTENSION` (superuser — pgvector
  is not a trusted extension). The migration installs the extension itself; see
  docs/pgvector-halfvec-search.md
- (Optional) an OpenAI, Azure OpenAI, or Gemini API Key, needed only for the `add_memory` and `search_memory` tools
- (Optional) a second API Key (OpenAI / Azure OpenAI / Gemini / self-hosted) for fact extraction —
  without it, `add_memory` still works but saves whole content as a single memory with no graph edges

### 1. Configure the connection string

Create/update `src/MemoryMcp.Api/appsettings.Development.json` (file **not versioned**, see
.gitignore) with your Postgres connection string:```json
{
  &quot;ConnectionStrings&quot;: {
    &quot;Default&quot;: &quot;Host=localhost;Port=5432;Username=&lt;user&gt;;Password=&lt;password&gt;;Database=&lt;database&gt;&quot;
  }
}

Alternatively, you can set the ConnectionStrings__Default environment variable without touching the
configuration files.

2. Apply migrations```bash

dotnet tool restore # if you don't already have dotnet-ef installed: dotnet tool install --global dotnet-ef
dotnet ef database update --project src/MemoryMcp.Infrastructure --startup-project src/MemoryMcp.Api


&gt; To wipe the database and start over from a clean schema (e.g. after accumulating test/throwaway
&gt; spaces), run scripts/reset-db.ps1 — **destructive**, it drops and recreates
&gt; the database pointed at by your current connection string, then re-applies all migrations and
&gt; optionally reseeds a fresh `default` space + API key:
&gt;```powershell
&gt; ./scripts/reset-db.ps1
&gt; ```

### 3. (Optional) Configure the embedding provider

To use `add_memory`/`search_memory`, in `appsettings.Development.json`:```json
{
  &quot;Embeddings&quot;: {
    &quot;Provider&quot;: &quot;OpenAI&quot;,
    &quot;ApiKey&quot;: &quot;sk-...&quot;,
    &quot;Model&quot;: &quot;text-embedding-3-small&quot;
  }
}

For Azure OpenAI: &quot;Provider&quot;: &quot;AzureOpenAI&quot;, &quot;Endpoint&quot;: &quot;https://.openai.azure.com&quot;,
&quot;Model&quot; = deployment name. For Gemini (its API is OpenAI-compatible):```json
{
"Embeddings": {
"Provider": "Gemini",
"ApiKey": "AIza...",
"Model": "gemini-embedding-001",
"Dimensions": 3072
}
}


`Dimensions` is forwarded as the OpenAI &quot;dimensions&quot; request parameter and **must equal
`VectorSettings.Dimensions` (3072)**, the width baked into the `halfvec` column — the server refuses to
start otherwise, with a message naming both values. Changing it is a schema migration plus a re-embed of
every stored memory, not a configuration edit; `3072` is `gemini-embedding-001`&#x27;s native width, and that
model needs manual re-normalization for truncated widths anyway.

Provider and endpoint are validated at startup too: an unrecognized `Provider` is rejected rather than
silently falling through to `api.openai.com`, and `AzureOpenAI` without an `Endpoint` fails immediately
instead of at the first tool call.

**Keep provider API keys out of `appsettings.Development.json`.** Store them with
user secrets, which the app loads
automatically in the Development environment (the project already has a `UserSecretsId`):```bash
dotnet user-secrets set &quot;Embeddings:ApiKey&quot; &quot;&lt;key&gt;&quot; --project src/MemoryMcp.Api
dotnet user-secrets set &quot;Extraction:ApiKey&quot; &quot;&lt;key&gt;&quot; --project src/MemoryMcp.Api

Rate limiting and tool-call logs

…(正文过长,页面只展示前面部分,完整内容见仓库)

常见问题

8 问
答案由本站依据条目字段整理,不引用上游原文
Memory 怎么安装?

在客户端按下面的安装命令接入:{ "mcpServers": { "memory-mcp": { "url": "http://localhost:5004/mcp", "headers": { "X-Api-Key": "mmcp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } }, "memory-mcp-stdio": { "command": "dotnet", "args": ["C:\\path\\to\\Memory-MCP\\src\\MemoryMcp.Api\\bin\\Release\\net10.0\\MemoryMcp.Api.dll", "--", "--stdio"], "env": { "ConnectionStrings__Default": "Host=localhost;Port=5432;Username=<user>;Password=<password。装完在客户端配置里引用同一个包或端点。

Memory 怎么在 Claude Desktop、Claude、Cursor 里配置?

它的传输方式是HTTP · 远程,在客户端的 MCP 配置里填好启动命令和参数,保存后完全退出客户端再打开,配置才会生效。

Memory 收费吗?

本站不代收费用,也没有标注具体价格。是否收费取决于服务本身和背后的接口额度,正式使用前按官方说明确认。

Memory 需要 API Key 吗?

资料标注需要API Key认证,使用前准备好对应凭据,并按最小权限配置。

Memory 支持哪些客户端?

资料标注支持 Claude Desktop、Claude、Cursor、VS Code、Gemini CLI、Codex;其他客户端只要能配置 MCP Server,也能用同样的命令或地址接入。

Memory 能提供哪些能力?

资料显示能力标签包括 记忆。具体工具清单以官方文档为准。

Memory 需要什么运行环境?

属于远程端点,不需要在本地装运行时。

Memory 是本地还是远程?

它是远程端点,连服务地址即可。传输方式为HTTP · 远程。

热门专题

按标签挑服务器
全部专题 →

服务器信息以作者仓库与官方文档为准;分类、传输方式与鉴权方式的中文说明为中文整理,最近核验 未标注。