Skip to main content
Glama

MCP Local RAG

GitHub stars npm version License: MIT MCP Registry

从 MCP 客户端或终端搜索私有文档,无需将其发送到嵌入 API。

mcp-local-rag 为机器上的 PDF、DOCX、Markdown 和文本文件建立索引。搜索将语义相似度与关键词匹配相结合,因此查询既能匹配意图,也能匹配精确的技术术语,如 API 名称、类名和错误代码。

功能特性

  • 本地运行: 文档解析、嵌入、存储和搜索均在您的机器上运行。 初始模型下载完成后,文本摄取和搜索可离线工作。

  • 混合搜索: 语义检索查找相关概念,关键词匹配提升精确技术术语的权重。

  • 可配置嵌入: 选择适合文档语言和领域的 Hugging Face 嵌入模型。

  • 语义分块: 文档按主题边界而非固定字符数进行拆分。Markdown 代码块保持完整。

  • MCP 和 CLI: 从 AI 编码工具或直接通过终端使用同一索引。

无需 API 密钥、Docker、Python 或外部数据库。

Related MCP server: rag-mcp

快速开始

环境要求

  • Node.js 22 或更高版本

  • 首次使用需联网以下载 npm 包和嵌入模型

  • 包含要搜索文档的目录

将 BASE_DIR 设置为该目录。它也是文件操作的安全边界。将下面的 /absolute/path/to/your/documents 替换为该目录的绝对路径。

mcp-local-rag 通过本地 stdio 服务器使用标准 MCP 协议,因此可与支持本地 MCP 服务器的 AI 编码工具和其他 MCP 主机配合使用。

使用以下示例之一,或注册 npx -y mcp-local-rag 并使用客户端的 MCP 配置格式设置 BASE_DIR。

对于 Claude Code: 运行此命令:

claude mcp add local-rag --scope user --env BASE_DIR=/absolute/path/to/your/documents -- npx -y mcp-local-rag

对于 Codex: 添加到 ~/.codex/config.toml:

[mcp_servers.local-rag]
command = "npx"
args = ["-y", "mcp-local-rag"]

[mcp_servers.local-rag.env]
BASE_DIR = "/absolute/path/to/your/documents"

对于 OpenCode: 添加到 ~/.config/opencode/opencode.json(或 opencode.jsonc):

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "local-rag": {
      "type": "local",
      "command": ["npx", "-y", "mcp-local-rag"],
      "environment": {
        "BASE_DIR": "/absolute/path/to/your/documents"
      }
    }
  }
}

对于 Cursor: 添加到 ~/.cursor/mcp.json:

{
  "mcpServers": {
    "local-rag": {
      "command": "npx",
      "args": ["-y", "mcp-local-rag"],
      "env": {
        "BASE_DIR": "/absolute/path/to/your/documents"
      }
    }
  }
}

重启客户端,然后要求其构建索引:

Sync all documents in the configured root and wait until it finishes.

首次同步会下载默认嵌入模型(约 90 MB),摄取开始前可能需要 1–2 分钟。后续运行使用本地缓存。

同步完成后:

What does the API documentation say about authentication?

CLI 快速开始

要在没有 MCP 客户端的情况下使用 CLI:

npx mcp-local-rag ingest ./docs/
npx mcp-local-rag query "authentication API"

CLI 默认使用当前目录作为文档根目录。请从同一目录运行这两个命令,以便它们使用相同的默认索引,或显式设置 BASE_DIR 和 DB_PATH。

为什么需要这个项目

某些文档集因保密性或组织策略而无法发送到托管嵌入服务。将索引保留在本地,即可在不增加每次查询 API 成本的情况下实现可搜索性。

仅靠语义搜索可能会遗漏技术文档中重要的精确标识符。关键词重排序可在不放弃自然语言检索的情况下保持这些术语的可见性。

支持的内容

输入

摄取方式

PDF、DOCX、TXT、Markdown

文件摄取或目录同步

客户端已获取的 HTML

ingest_data;使用 Readability 清理并转换为 Markdown

内存中的纯文本或 Markdown

ingest_data,使用稳定的源标识符

服务器不内置 HTML 抓取功能。MCP 客户端可以抓取页面并将其 HTML 传递给 ingest_data。

文件摄取不支持 Excel、PowerPoint、独立图片和源代码文件扩展名。PDF 可选使用本地视觉模型描述图形,但这并非 OCR 或图像搜索。

MCP 工具

工具

用途

sync_start

将索引与所有配置的根目录或单个路径进行对账

sync_status

轮询正在运行的同步任务

ingest_file

摄取或替换单个文件

ingest_data

摄取客户端已持有的文本、Markdown 或 HTML

query_documents

使用语义匹配和关键词提升进行搜索

read_chunk_neighbors

从搜索结果中读取相邻分块

list_files

显示受支持的文件及其摄取状态

delete_file

删除已索引的文件或 ingest_data 条目

status

显示索引和搜索状态

同步文档根目录

sync_start 摄取新增和变更的文件,跳过字节完全相同的文件,并删除不再存在的文件的索引条目:

Sync everything under the configured document roots and wait for completion.

该工具会立即返回 jobId。客户端应轮询 sync_status,直到其状态变为 succeeded 或 failed。同步不会生成视觉标题。在 MCP 服务器环境中设置 STORE_IMAGES=true,以存储同步所选新增或变更文件中的受支持 PDF 和 DOCX 图片;未变更的文件仍会被跳过。

服务器进程仅保留一个同步任务。较新的任务会替换已完成的记录,重启服务器会将其丢弃。

摄取单个文件

ingest_file 接受 PDF、DOCX、TXT 和 Markdown。MCP 文件路径必须是绝对路径,且必须位于配置的文档根目录内:

Ingest the document at /Users/me/docs/api-spec.pdf.

重新摄取同一路径会替换其现有分块。

搜索和阅读更多上下文

What does the API documentation say about authentication?
Find the documented behavior of ERR_CONNECTION_REFUSED.

结果包含文本、源路径、标题、分块索引、相关性分数以及存储在该分块上的任何图片。MCP 将每张图片作为图片内容块返回,并与其结果标识配对;CLI query 在每个结果中包含 images 数组,格式为 { imageIndex, mimeType, data }。当答案需要更多上下文时,将结果中的 chunkIndex 以及 filePath 或 source 传递给 read_chunk_neighbors:

Read the surrounding chunks for that authentication result.

query_documents 和 list_files 都接受可选的绝对 scope 路径前缀,或前缀列表。前缀匹配精确路径及其后代。

摄取 HTML

在 MCP 客户端抓取页面后使用 ingest_data:

Fetch https://example.com/docs and ingest the HTML.

服务器提取主要文章,将其转换为 Markdown,并存储在提供的源标识符下。重复使用同一源会更新现有内容。

索引外部内容时,请尊重源网站的条款和版权。

PDF 视觉标题和存储的图片

视觉模式为图形较多的 PDF 页面添加生成的标题。该功能为可选启用,正常摄取期间不会加载视觉模型。

Ingest /Users/me/docs/research-paper.pdf with visual: true.
npx mcp-local-rag ingest ./docs/research-paper.pdf --visual

图片存储独立于视觉标题。为 MCP 服务器设置 STORE_IMAGES=true,或为 CLI 摄取和同步传递 --images:

npx mcp-local-rag ingest ./docs/research-paper.pdf --images
npx mcp-local-rag sync ./docs/ --images

PDF 存储使用检测到的图形/表格区域。DOCX 存储仅包含现有 Mammoth 转换以 <img> 形式输出的 PNG/JPEG 图片;图表、SmartArt 和形状不会单独渲染。存储的图片会跟随其周围文本进入最终语义分块,不会改变排序、分数或结果数量。

visual / --visual

STORE_IMAGES / --images

PDF 行为

false

false

仅文本;无视觉标题或返回的图片。

true

false

生成的标题成为可搜索文本;不存储或返回图片。

true

true

生成的标题成为可搜索文本,匹配分块中的图片以内联方式返回。

false

true

图片附加到附近保留的 PDF 文本,并为匹配分块内联返回;不导入、加载或运行 VLM。

配置文件

模型缓存

使用场景

fast(默认)

约 250 MB

轻量级视觉索引

quality

约 2.9 GB

包含标签、注释或其他图像内文字的图形

通过 MCP 使用 visualQuality: "quality" 或通过 CLI 使用 --visual-quality quality 选择更大的模型。实测 CPU 推理速度约为 fast 的两倍慢,但结果取决于硬件和模型更新。

标题是辅助文本,并非忠实转录。请将检索到的标题和文档文本视为不可信输入,而非指令。

在较高限制下,匹配的分块及其附件可能接近模型/客户端上下文上限;请根据调用模型的可用上下文选择查询限制。

CLI

CLI 使用相同的解析器、嵌入器和向量存储,无需 MCP 客户端:

npx mcp-local-rag ingest ./docs/
npx mcp-local-rag sync ./docs/
npx mcp-local-rag query "authentication API"
npx mcp-local-rag query "auth" --scope /docs/api --scope /docs/guide
npx mcp-local-rag read-neighbors --file-path /abs/path.md --chunk-index 5
npx mcp-local-rag list
npx mcp-local-rag status
npx mcp-local-rag delete ./docs/old.pdf
npx mcp-local-rag delete --source "https://example.com/docs"

--db-path、--cache-dir 和 --model-name 等全局选项放在子命令之前。子命令选项放在其后:

npx mcp-local-rag --db-path ./my-db query "authentication"

运行 npx mcp-local-rag --help 获取完整命令参考。

CLI 不读取 MCP 客户端配置。如果两个接口应共享索引,请设置相同的环境变量或标志。特别是,共享数据库时 MODEL_NAME 和 CLI --model-name 必须匹配。

搜索调优

关键词提升默认启用。相关性差距分组以及距离和文件过滤器是可选控制项,适用于需要更严格结果选择的语料库。

变量

默认值

描述

RAG_HYBRID_WEIGHT

0.6

关键词提升因子(0.0–1.0)。0 禁用关键词重排序;1 应用最大提升。

RAG_GROUPING

(未设置)

similar 保留第一个相关性组;related 最多保留两个,以显著的向量距离差距为边界。

RAG_MAX_DISTANCE

(未设置)

过滤低相关性结果(例如 0.5)。

RAG_MAX_FILES

(未设置)

将结果限制为前 N 个文件(例如 1 表示单个最佳文件)。

对于 API 规范和其他包含大量标识符的文档,更强的关键词权重可以改善精确术语的排名:

"env": {
  "RAG_HYBRID_WEIGHT": "0.7"
}
  • 0.7:比默认值稍强的精确词条重排序

  • 1.0:最大关键词加权

工作原理

在摄取阶段:

  1. 解析器提取输入格式的文本。

  2. 语义分块器识别主题边界并保留 Markdown 代码块。

  3. Transformers.js 在本地创建嵌入向量。

  4. LanceDB 存储分块、元数据、向量和全文索引。

在搜索阶段:

  1. 使用同一模型对查询进行嵌入。

  2. 向量搜索检索语义相关的分块。

  3. 配置后,可选的距离和相关性分组过滤器会缩小候选范围。

  4. 全文匹配对精确查询词条进行加权。

Agent 技能

Agent Skills 为 AI 助手提供查询和摄取指导:

npx mcp-local-rag skills install --claude-code
npx mcp-local-rag skills install --claude-code --global
npx mcp-local-rag skills install --codex

已安装的技能涵盖查询构建、结果优化和 HTML 摄取。如果 mcp-local-rag 技能未自动激活,请明确要求助手使用该技能。

配置

MCP 服务器读取环境变量。CLI 接受下列全局环境变量和标志;CLI 摄取和同步时的图像存储仅通过 --images 启用。

环境变量

CLI 标志

默认值

描述

BASE_DIR

--base-dir

当前目录

一个文档根目录;CLI 标志可在 ingest、list 和 sync 上重复使用

BASE_DIRS

不适用

(未设置)

文档根目录的 JSON 数组;优先于 BASE_DIR

DB_PATH

--db-path

./lancedb/

向量数据库位置

CACHE_DIR

--cache-dir

./models/

模型缓存目录

MODEL_NAME

--model-name

Xenova/all-MiniLM-L6-v2

Hugging Face 嵌入模型

MAX_FILE_SIZE

--max-file-size

104857600(100MB)

最大文件大小(字节)

CHUNK_MIN_LENGTH

--chunk-min-length

50

最小分块长度(字符数,1–10000)

STORE_IMAGES

不适用

false

仅 MCP 服务器:存储支持的 PDF/DOCX 图像,并在匹配的分块中返回。CLI 使用 --images。

RAG_DEVICE

不适用

cpu

ONNX Runtime 执行设备

RAG_DTYPE

不适用

fp32

传递给所选模型的嵌入数据类型

文档根目录(BASE_DIR 和 BASE_DIRS)

mcp-local-rag 仅允许在配置的根目录内进行文件操作。对于多个根目录,BASE_DIRS 必须是包含非空路径的 JSON 数组:

export BASE_DIRS='["/Users/me/Documents/work","/Users/me/Projects/specs"]'

根目录配置按以下顺序解析:

  1. CLI --base-dir <path> 标志(可在 ingest、list 和 sync 上重复使用)

  2. BASE_DIRS

  3. BASE_DIR

  4. 当前目录

每个来源都会替换优先级较低的来源,而不是与之合并。无效的 BASE_DIRS 配置会直接失败,而不会回退到 BASE_DIR 或当前目录。status 在 MCP 中仍然可用,以便客户端报告配置错误。

npx mcp-local-rag ingest --base-dir /Users/me/work --base-dir /Users/me/specs /Users/me/work/readme.md
npx mcp-local-rag list --base-dir /Users/me/work --base-dir /Users/me/specs
npx mcp-local-rag sync --base-dir /Users/me/work --base-dir /Users/me/specs
BASE_DIRS='["/Users/me/work","/Users/me/specs"]' npx mcp-local-rag list

存储和模型

DB_PATH 和 CACHE_DIR 默认相对于进程工作目录。当 MCP 客户端可能从不同的项目目录启动服务器时,请设置绝对路径。

设置 MODEL_NAME 或传入 --model-name 以选择适合文档语言和领域的 Hugging Face 嵌入模型。

mcp-local-rag 使用均值池化和 L2 归一化生成嵌入向量。选择模型时,请检查这些设置是否与其推荐的推理配置匹配,因为池化方法可能影响检索质量。

更改 MODEL_NAME、RAG_DEVICE 或 RAG_DTYPE 可能导致现有向量不兼容。更改嵌入配置后,请使用新的 DB_PATH 或删除现有索引并重新摄取。

适用于英文文档的示例模型是 Xenova/bge-small-en-v1.5。

安全与操作

  • 文件访问仅限于 BASE_DIR、BASE_DIRS 或 CLI --base-dir 根目录。

  • 解析到所有已配置根目录之外的符号链接将被拒绝。

  • 在所需模型缓存之后,文档处理和搜索不会发出任何网络请求。

  • 该服务器专为单个本地用户设计,不提供身份验证或访问控制。

  • 不要对同一 DB_PATH 运行多个 CLI 或 MCP 写入器。同步进行时可以运行只读查询。

  • 在没有写入器活动时,通过复制其 DB_PATH 目录来备份索引。

“未找到结果”

必须先摄取文档。运行“列出所有已摄取的文件”以验证。

模型下载失败

检查互联网连接。如果位于代理后面,请配置网络设置。也可以手动下载该模型。

“文件过大”

默认限制为 100MB。拆分大文件或增大 MAX_FILE_SIZE。

查询缓慢

使用 status 检查分块数量。包含大量分块的大型文档可能会降低查询速度。考虑拆分非常大的文件。

“路径超出 BASE_DIR”

确保文件路径位于某个已配置的根目录内(BASE_DIR、任何 BASE_DIRS 条目或任何 CLI --base-dir)。使用绝对路径。

“BASE_DIRS 必须是 JSON 数组...”

BASE_DIRS 接受包含一个或多个非空路径字符串的 JSON 数组:

  • 有效:BASE_DIRS='["/Users/me/work","/Users/me/specs"]'

  • 无效:BASE_DIRS=/a:/b(不支持分隔符语法)

  • 无效:BASE_DIRS='[]'(空数组)

MCP 客户端看不到工具

  1. 验证配置文件语法

  2. 完全重启客户端(Mac 上 Cursor 使用 Cmd+Q)

  3. 直接测试:npx mcp-local-rag 应能无错误运行

贡献

欢迎贡献!有关设置和指南,请参阅 CONTRIBUTING.md。

许可证

MIT 许可证。免费用于个人和商业用途。

博客文章

致谢

基于 Anthropic 的 Model Context Protocol、LanceDB 和 Transformers.js 构建。

Available Tools

9 tools
delete_fileA

Delete a previously ingested file or data from the vector database. Use filePath for files ingested via ingest_file, or source for data ingested via ingest_data. Either filePath or source must be provided. Returns deleted (operation succeeded), removedChunks, and existed (whether anything was actually present).

Inputs: source, filePath.

ingest_dataA

Ingest in-memory content as a string (use ingest_file for files on disk). The source identifier enables re-ingestion to update existing content. Returns { filePath, chunkCount, timestamp, fileTitle }.

Inputs: content (required), metadata (required).

ingest_fileA

Ingest a document file (PDF, DOCX, TXT, MD) into the vector database. Path must be absolute; re-ingesting the same path replaces its existing data. Returns { filePath, chunkCount, timestamp, fileTitle }.

Inputs: filePath (required), visual, visualQuality.

list_filesA

List supported files (PDF, DOCX, TXT, MD) under the configured base directories and whether each is ingested. Returns { baseDirs, files, sources }; sources lists ingested items reported apart from the file scan, chiefly ingest_data content (web pages, clipboard, etc.).

Inputs: scope.

query_documentsA

Search ingested documents with hybrid keyword + semantic matching. Use the returned order as the ranking; score may disagree with it. Each has filePath, chunkIndex, text, fileTitle, score (lower is closer), and source (for ingest_data items). Optional sourceContext provides heading paths and original line or physical PDF page ranges; multiple heading paths mean the chunk crosses sections.

Inputs: query (required), limit, scope.

read_chunk_neighborsA

Read the chunks immediately before and after a query_documents result, in the same document, for more surrounding context. Pass chunkIndex from the result plus exactly one of filePath (ingest_file) or source (ingest_data). Returns the target chunk (isTarget: true) and its neighbors, ascending by chunkIndex; an out-of-range chunkIndex returns []. Optional sourceContext provides heading paths and original line or physical PDF page ranges; multiple heading paths mean the chunk crosses sections. Defaults: before=2, after=2 (max 50 each).

Inputs: chunkIndex (required), after, before, source, +1 more.

statusA

Get index status: { documentCount, chunkCount, memoryUsage (MB), uptime (s), ftsIndexEnabled, searchMode }.

Inputs: no named parameters.

sync_startA

Reconcile the index with the files on disk: ingest new and changed files, leave unchanged files alone, and remove index entries for files that are gone. Each changed PDF is re-ingested with the visual profile ("fast" or "quality") already recorded for it, so a PDF indexed with VLM captions keeps them; a PDF with no recorded profile stays text-only. There is no option to change a profile here — use the CLI (mcp-local-rag sync --visual) to set one, or ingest_file to replace the file, where a normal ingest clears the recorded profile. Stored images are unrelated: STORE_IMAGES applies to whatever this run re-ingests and never makes a file changed. Returns { jobId } without waiting for the run to finish; poll sync_status with that jobId for progress and the final outcome. Only one job is kept, and it is lost when the server process exits.

Inputs: path.

sync_statusA

Get the current or latest sync job record: { jobId, state ("running" | "succeeded" | "failed"), total (null until scanning has counted the files on disk), completed (upserted + skipped + empty; pruned is counted separately), summary { upserted, skipped, empty, pruned }, warnings, error (null unless the job failed) }. An unknown jobId means the job was replaced by a newer one or lost with a previous server process.

Inputs: jobId (required).

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.2/5.0

    Scored across 9 tools

    Disambiguation4/5

    Most tools have clearly distinct purposes: ingest_file vs ingest_data split by source type, query_documents vs read_chunk_neighbors split by search vs context, and delete_file/list_files/sync_start are unique. The only mild overlap is status (index state) vs sync_status (sync job record), but descriptions disambiguate them well.

    Naming Consistency4/5

    Seven of nine tools follow a clean verb_noun pattern (query_documents, read_chunk_neighbors, delete_file, ingest_data, ingest_file, list_files, sync_start). The two noun-only names (status, sync_status) are minor deviations but still readable and consistent with each other.

    Tool Count5/5

    Nine tools is well-scoped for a local RAG server, with each tool earning its place across ingest, query, context, delete, list, sync, and status concerns. No redundant or filler tools.

    Completeness4/5

    The lifecycle is well covered: ingest (file/data), query, context retrieval, list, delete, sync, and status. The main gap is that changing a PDF's visual profile is only possible via the CLI, not through an MCP tool, though re-ingest provides a workaround.

    Maintenance

    ActivityActive
    ResponsivenessUsually handled

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      Local offline semantic search over documents (txt, md, pdf, docx, pptx, csv). Indexes folders into a LanceDB vector database with multilingual embeddings and supports hybrid vector + keyword search via Reciprocal Rank Fusion. No API keys, no cloud, no Docker required.
      4
      31
      AGPL 3.0
    • F
      license
      A
      quality
      D
      maintenance
      Enables indexing local documents (PDF, Markdown, text, code) into a knowledge base and querying them via semantic search using local embeddings, all running privately on your machine.
      4
      -