Skip to main content
Glama
mcppaw-qdrant

mcppaw-qdrant

by pawin1122
README.md
# mcppaw-qdrant

**[English](#english) · [中文](#中文)**

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE)
[![Python 3.12+](https://img.shields.io/badge/python-3.12%2B-blue.svg)](https://www.python.org/downloads/)
[![MCP](https://img.shields.io/badge/MCP-compatible-8A2BE2.svg)](https://modelcontextprotocol.io/)

## English

**A lightweight, per-device MCP server that turns a Qdrant collection into a personal knowledge base.**

Each device runs its own independently configured instance. Qdrant and the embedding/rerank model services are external HTTP dependencies — this project does not include them.

### Why mcppaw-qdrant

- **Lightweight by design** — the MCP process loads no models and ships no web UI, no bundled database and no model weights. It slices text, calls HTTP services and assembles results. A small local instance next to an existing Qdrant is enough. The MCP process stays small; knowledge-base memory usage depends mainly on the Qdrant deployment.
- **One instance per device** — there is no central MCP. Every device installs and configures its own instance; instances are decoupled. Pointing several instances at the same Qdrant collection is a deployment choice, not a requirement.
- **Model freedom** — embeddings use any OpenAI-compatible `POST {base_url}/v1/embeddings` service; reranking uses any Cohere/Jina-compatible `POST {base_url}/v1/rerank` service. Query/document prefixes, dimension, encoding format, truncation and fallback channels are configurable.
- **Nine tools** — full document lifecycle: upload, add text, search, read, download, delete, find, list, stats.
- **Configurable chunking** — `[chunk]` strategy/size/overlap/min/max/separators; defaults are size 800, overlap 120, min 100, max 2000.
- **LAN-oriented transport** — stdio by default, plus an optional loopback-only HTTP endpoint (`http://127.0.0.1:8787/mcp`) with Origin/Host validation. The MCP server itself has no access token; it is designed for a trusted LAN.

### Qdrant is not included

This project does **not** ship, deploy, embed or manage Qdrant. You need an existing Qdrant instance (on a NAS or locally) reachable over your LAN. The embedding and rerank model services are external too: no models or model servers are bundled. Qdrant is a separate project distributed under its own license.

### Architecture

```mermaid
flowchart LR
    C["MCP client<br/>(stdio or loopback HTTP)"]
    M["mcppaw-qdrant<br/>MCP server<br/>(one per device)"]
    Q[("Qdrant<br/>(external)")]
    E["Embedding service<br/>(OpenAI-compatible)"]
    R["Rerank service<br/>(Cohere/Jina-compatible, optional)"]

    C -->|"stdio (default)"| M
    C -->|"HTTP 127.0.0.1:8787/mcp"| M
    M -->|"Qdrant REST"| Q
    M -->|"POST /v1/embeddings"| E
    M -.->|"POST /v1/rerank"| R
```

### Quick start

#### Prerequisites

- Python 3.12 or 3.13, and [uv](https://docs.astral.sh/uv/)
- macOS is the first verified platform; the core code is cross-platform, but Windows and Linux are not verified yet
- A reachable Qdrant instance (already running — not included)
- A reachable embedding service (OpenAI-compatible HTTP API)

#### Install

From a released wheel:

```bash
uv tool install ./mcppaw_qdrant-0.1.8-py3-none-any.whl
mcppaw-qdrant --version   # mcppaw-qdrant 0.1.8
```

From source:

```bash
git clone https://github.com/<owner>/mcppaw-qdrant.git
cd mcppaw-qdrant
uv sync --python 3.13
uv run mcppaw-qdrant --version
```

#### Configure

```bash
mcppaw-qdrant config init --path <CONFIG_PATH>
# edit the required values (knowledge base name, Qdrant URL, channel base_url/model)
mcppaw-qdrant config check --config <CONFIG_PATH>
mcppaw-qdrant doctor --offline --config <CONFIG_PATH>
mcppaw-qdrant doctor --online  --config <CONFIG_PATH>   # optional; needs Qdrant + channels
```

#### Connect a client

Use an absolute path for `--config`; relative paths resolve against the client's working directory.

stdio (default) — generic MCP client JSON:

```json
{
  "mcpServers": {
    "mcppaw-qdrant": {
      "command": "mcppaw-qdrant",
      "args": ["serve", "--config", "<CONFIG_PATH>", "--transport", "stdio"]
    }
  }
}
```

Loopback HTTP (for clients that only accept a URL):

```bash
mcppaw-qdrant serve --config <CONFIG_PATH> --transport http
# MCP endpoint: http://127.0.0.1:8787/mcp
```

### Minimal configuration

```toml
[knowledge_base]
name = "my-knowledge-base"

[qdrant]
url = "http://127.0.0.1:6333"
api_key = "${ENV:QDRANT_API_KEY}"   # or "" when your Qdrant has no auth

[[channels]]
name = "embedding-primary"
base_url = "https://embedding.example.com"   # no /v1 suffix
api_key = "${ENV:EMBEDDING_API_KEY}"
protocol = "openai_embeddings"
capabilities = ["embedding"]
embedding_model = "<embedding-model>"
embedding_dim = 0                            # 0 = probe before first write

[embedding]
channel = "embedding-primary"
model = "<embedding-model>"
dim = 0
```

Key rules:

- `channels[].base_url` must **not** include `/v1`: the adapter appends `/v1/embeddings` (and `/v1/rerank` for rerank channels).
- Secrets in TOML may only be `${ENV:NAME}`, an empty string, or a template placeholder. Any other non-empty literal is rejected with `CONFIG_INVALID`.
- If you keep `${ENV:NAME}` placeholders, export the referenced variables in the environment before running `config check`; use an empty string (`""`) for services that need no authentication.
- Direct environment overrides use `MCPPAW_` plus `__` for nesting — e.g. `MCPPAW_QDRANT__API_KEY` overrides `qdrant.api_key`. Channel secrets support only `${ENV:...}` placeholders or a `MCPPAW_CHANNELS` JSON document.
- `[chunk]`, `[retrieval]` and most other sections are optional; built-in defaults apply.

### Tools

| Tool | Purpose |
| --- | --- |
| `upload_document` | Upload a `.md`/`.markdown`/`.txt` text file: chunk, embed and store |
| `add_text` | Store plain text under a generated virtual filename |
| `search` | Semantic (RAG) retrieval over chunks, with optional rerank |
| `read_document` | Read a document by `document_id` or exact filename, paginated |
| `download_document` | Download the full plain text of a document by `document_id` |
| `delete_document` | Permanently hard-delete a document and its chunks |
| `find_documents` | Find documents by filename/title substring (not RAG) |
| `list_documents` | List ready documents with keyset pagination |
| `get_stats` | Show document/chunk counts and model information |

All tools return a uniform envelope: `{"ok": true, "data": {...}}` on success, or `{"ok": false, "error": {code, message, retryable, details}}` on business errors. Empty results, duplicate uploads, ambiguous filenames and missing documents are normal states with `ok: true`, not errors.

### Configuration highlights

| Group | Highlights |
| --- | --- |
| `[knowledge_base]` | `name` is required; the default collection name is derived from it |
| `[qdrant]` | `url`, optional `api_key`; `vector_name = "dense"`, `distance = "Cosine"`, `schema_version = 1` |
| `[transport]` / `[http]` | `stdio` (default) or `http`; loopback host, port 8787, path `/mcp` |
| `[[channels]]` | `openai_embeddings` / `cohere_jina_rerank`; `base_url` without `/v1` |
| `[embedding]` | `channel`, `model`, `dim` (0 = probe), `query_prefix`, `document_prefix`, `encoding_format`, `truncation`, `fallback_channels` |
| `[rerank]` | Optional; `enabled`, `channel`, `model`, `failure_policy = "degrade"` |
| `[chunk]` | `strategy`, `size`, `overlap`, `min`, `max`, `separators` |
| `[retrieval]` | `candidate_limit = 30`, `top_k = 8`, `score_threshold`, limits |
| `[dedup]` | Content-hash deduplication (SHA-256) enabled by default |

Precedence is fixed: CLI > environment variables (`MCPPAW_` + `__` nesting) > TOML > built-in defaults. See `config/config.example.toml` in the source tree for every key and default.

### Security model

- Intended for **LAN use only**. Do not expose the MCP server or Qdrant to the public internet.
- stdio is the default transport; the optional HTTP transport binds to loopback only and validates Origin/Host. Do not bind `0.0.0.0` or put it behind a public reverse proxy.
- The MCP server itself has **no access token**. Qdrant and model-service credentials come from the instance configuration/environment and are never sent over MCP.
- Secrets are held as `SecretStr`, redacted from logs and error details; `config export --redacted` never writes plaintext keys.
- Configuration and log files are created with `0600` permissions and directories with `0700` where supported.
- `delete_document` is a hard delete and cannot be undone.

### Development

```bash
uv sync --python 3.13
uv run ruff check .
uv run mypy
uv run pytest -q            # 709 passed, 10 skipped (live tests skipped by default)
uv build
```

Live tests require a disposable Qdrant instance and real embedding (and optionally rerank) endpoints; they are skipped by default.

### License

[MIT](./LICENSE) © 2026 mcppaw-qdrant contributors

---

## 中文

**一个每设备独立运行的轻量 MCP 服务,把 Qdrant collection 变成个人知识库。**

每台设备各自安装、各自配置、各自运行一个实例。Qdrant 与 embedding/rerank 模型服务都是外部 HTTP 依赖,本项目不包含它们。

### 为什么是 mcppaw-qdrant

- **轻量**:MCP 进程不加载模型,不提供 Web UI,不捆绑数据库,也不打包模型权重;只做文本切片、HTTP 调用与结果拼装。在既有 Qdrant 旁边跑一个小实例即可。MCP 进程占用小,知识库内存主要取决于 Qdrant 部署。
- **每设备独立**:不存在中央 MCP。每台设备安装并配置自己的实例,实例之间解耦;多个实例指向同一 Qdrant collection 只是部署选择,不是强制要求。
- **模型自由**:embedding 使用任意 OpenAI 兼容的 `POST {base_url}/v1/embeddings` 服务;rerank 使用任意 Cohere/Jina 兼容的 `POST {base_url}/v1/rerank` 服务。query/document prefix、维度、编码格式、截断与备用渠道均可配置。
- **九工具**:覆盖文档全生命周期——上传、追加文本、检索、读取、下载、删除、查找、列表、统计。
- **切片可调**:`[chunk]` 的 strategy/size/overlap/min/max/separators 均可配置;默认 size=800、overlap=120、min=100、max=2000。
- **面向局域网的传输**:默认 stdio;可选仅回环 HTTP(`http://127.0.0.1:8787/mcp`),并校验 Origin/Host。MCP 自身没有访问令牌,面向可信局域网设计。

### 本项目不包含 Qdrant

本项目**不**分发、不部署、不内嵌、不管理 Qdrant。你需要一个既有的、可通过局域网访问的 Qdrant 实例(NAS 上或本机均可)。embedding 与 rerank 模型服务同样是外部依赖:本项目不包含任何模型或模型服务。Qdrant 是独立项目,按其自身许可证分发。

### 架构

```mermaid
flowchart LR
    C["MCP 客户端<br/>(stdio 或回环 HTTP)"]
    M["mcppaw-qdrant<br/>MCP 服务<br/>(每设备一个)"]
    Q[("Qdrant<br/>(外部)")]
    E["Embedding 服务<br/>(OpenAI 兼容)"]
    R["Rerank 服务<br/>(Cohere/Jina 兼容,可选)"]

    C -->|"stdio(默认)"| M
    C -->|"HTTP 127.0.0.1:8787/mcp"| M
    M -->|"Qdrant REST"| Q
    M -->|"POST /v1/embeddings"| E
    M -.->|"POST /v1/rerank"| R
```

### 快速开始

#### 前置条件

- Python 3.12 或 3.13,以及 [uv](https://docs.astral.sh/uv/)
- macOS 为首个已验证平台;核心代码跨平台,Windows/Linux 尚未验收
- 一个可访问的既有 Qdrant 实例(本项目不包含)
- 一个可访问的 embedding 服务(OpenAI 兼容 HTTP API)

#### 安装

从发布 wheel 安装:

```bash
uv tool install ./mcppaw_qdrant-0.1.8-py3-none-any.whl
mcppaw-qdrant --version   # mcppaw-qdrant 0.1.8
```

从源码安装:

```bash
git clone https://github.com/<owner>/mcppaw-qdrant.git
cd mcppaw-qdrant
uv sync --python 3.13
uv run mcppaw-qdrant --version
```

#### 配置

```bash
mcppaw-qdrant config init --path <CONFIG_PATH>
# 编辑必填项:知识库名、Qdrant 地址、渠道 base_url 与模型名
mcppaw-qdrant config check --config <CONFIG_PATH>
mcppaw-qdrant doctor --offline --config <CONFIG_PATH>
mcppaw-qdrant doctor --online  --config <CONFIG_PATH>   # 可选;需要 Qdrant 与模型渠道
```

#### 接入客户端

`--config` 建议使用绝对路径(相对路径按客户端工作目录解析)。

stdio(默认)——通用 MCP 客户端 JSON:

```json
{
  "mcpServers": {
    "mcppaw-qdrant": {
      "command": "mcppaw-qdrant",
      "args": ["serve", "--config", "<CONFIG_PATH>", "--transport", "stdio"]
    }
  }
}
```

仅回环 HTTP(供只能按 URL 注册的客户端):

```bash
mcppaw-qdrant serve --config <CONFIG_PATH> --transport http
# MCP 端点:http://127.0.0.1:8787/mcp
```

### 最小配置示例

```toml
[knowledge_base]
name = "my-knowledge-base"

[qdrant]
url = "http://127.0.0.1:6333"
api_key = "${ENV:QDRANT_API_KEY}"   # Qdrant 无鉴权时留空 ""

[[channels]]
name = "embedding-primary"
base_url = "https://embedding.example.com"   # 不要带 /v1 后缀
api_key = "${ENV:EMBEDDING_API_KEY}"
protocol = "openai_embeddings"
capabilities = ["embedding"]
embedding_model = "<embedding-model>"
embedding_dim = 0                            # 0 = 首次写入前探测

[embedding]
channel = "embedding-primary"
model = "<embedding-model>"
dim = 0
```

要点:

- `channels[].base_url` **不要**带 `/v1`:适配器会自行追加 `/v1/embeddings`(rerank 渠道追加 `/v1/rerank`)。
- TOML 中的密钥只能是 `${ENV:NAME}`、空串或模板占位符;其它非空字面量会被判为 `CONFIG_INVALID`。
- 保留 `${ENV:NAME}` 占位符时,运行 `config check` 前需在环境中 export 对应变量;无鉴权的服务使用空串(`""`)。
- 直接用环境变量覆盖配置时,使用 `MCPPAW_` + `__` 表示层级,例如 `MCPPAW_QDRANT__API_KEY` 覆盖 `qdrant.api_key`;渠道密钥只支持 `${ENV:...}` 占位符或 `MCPPAW_CHANNELS` JSON。
- `[chunk]`、`[retrieval]` 等节可整体省略,使用内置默认值。

### 九工具

| 工具 | 作用 |
| --- | --- |
| `upload_document` | 上传 `.md`/`.markdown`/`.txt` 文本文件:切片、向量化并写入 |
| `add_text` | 以自动生成的虚拟文件名写入纯文本 |
| `search` | 基于 chunk 的语义(RAG)检索,可选 rerank |
| `read_document` | 按 `document_id` 或精确文件名读取文档(分页) |
| `download_document` | 按 `document_id` 下载文档全文纯文本 |
| `delete_document` | 永久硬删除文档及其切片 |
| `find_documents` | 按文件名/标题子串查找文档(非 RAG) |
| `list_documents` | keyset 分页列出 ready 文档 |
| `get_stats` | 显示文档/切片计数与模型信息 |

所有工具返回统一 envelope:成功为 `{"ok": true, "data": {...}}`,业务错误为 `{"ok": false, "error": {code, message, retryable, details}}`。空结果、重复上传、同名多篇、文档不存在都是 `ok: true` 的正常状态,不是错误。

### 配置要点

| 分组 | 要点 |
| --- | --- |
| `[knowledge_base]` | `name` 必填;默认 collection 名由它派生 |
| `[qdrant]` | `url`、可选 `api_key`;`vector_name = "dense"`、`distance = "Cosine"`、`schema_version = 1` |
| `[transport]` / `[http]` | `stdio`(默认)或 `http`;回环地址、端口 8787、路径 `/mcp` |
| `[[channels]]` | `openai_embeddings` / `cohere_jina_rerank`;`base_url` 不带 `/v1` |
| `[embedding]` | `channel`、`model`、`dim`(0 = 探测)、`query_prefix`、`document_prefix`、`encoding_format`、`truncation`、`fallback_channels` |
| `[rerank]` | 可选;`enabled`、`channel`、`model`、`failure_policy = "degrade"` |
| `[chunk]` | `strategy`、`size`、`overlap`、`min`、`max`、`separators` |
| `[retrieval]` | `candidate_limit = 30`、`top_k = 8`、`score_threshold` 与各分页上限 |
| `[dedup]` | 默认按正文 SHA-256 去重 |

优先级固定为:CLI > 环境变量(`MCPPAW_` + `__` 层级)> TOML > 内置默认。全部键与默认值见源码树中的 `config/config.example.toml`。

### 安全边界

- 仅面向**局域网**使用。不要把 MCP 服务或 Qdrant 暴露到公网。
- 默认 stdio;可选 HTTP 只绑定回环地址并校验 Origin/Host。不要绑定 `0.0.0.0`,也不要用公网反向代理暴露。
- MCP 自身**没有访问令牌**;Qdrant 与模型服务的凭据来自实例配置/环境变量,不经过 MCP 协议传输。
- 密钥以 `SecretStr` 保存,日志与错误详情脱敏;`config export --redacted` 不写明文密钥。
- 在支持的平台上,配置文件与日志以 `0600` 权限创建,目录以 `0700` 权限创建。
- `delete_document` 是硬删除,不可恢复。

### 开发

```bash
uv sync --python 3.13
uv run ruff check .
uv run mypy
uv run pytest -q            # 709 passed,10 skipped(live 测试默认跳过)
uv build
```

live 测试需要可丢弃的 Qdrant 实例与真实的 embedding(可选 rerank)端点;默认跳过。

### 许可证

[MIT](./LICENSE) © 2026 mcppaw-qdrant contributors