Skip to main content
Glama
README.md
# docling-mcp

> 把 [docling](https://github.com/docling-project/docling) 封装成 MCP 服务器,让纯文本大模型(DeepSeek 等)通过工具调用获得"文档视觉"。

`docling` 是 IBM 开源的高质量文档解析库(PDF / DOCX / PPTX / HTML / 图片),支持 OCR、表格识别、公式抽取、版面分析。但它只提供 Python API。本包把它包成 MCP(Model Context Protocol)服务器,暴露 4 个工具,任何 MCP 客户端都能调用。

---

## 中文用户速读

### 解决什么问题?

DeepSeek-v4 / pro 这类纯文本模型**看不了 PDF、图片、扫描件**。挂上 docling-mcp 后,模型可以调用工具:
- 解析 PDF → Markdown 喂回自己
- 把图片里的文字 OCR 出来
- 抽出表格结构化数据
- 把文档切片做 RAG

### 工具一览

| 工具 | 用途 | 输出 |
|------|------|------|
| `convert_to_markdown` | PDF/DOCX/HTML/图片 → Markdown(含表格、图片占位) | `{markdown, num_pages, num_tables, num_pictures, ...}` |
| `convert_to_text` | 同上 → 纯文本(无格式标记,适合 token 受限的模型) | string |
| `extract_tables` | 只抽表格 | `[{page, index, num_rows, num_cols, markdown, rows}, ...]` |
| `chunk_for_rag` | 用 HybridChunker 切片做 RAG | `[{text, index, page, headings, chunk_type, token_count}, ...]` |
| `describe_image` | **真正理解**图片(物体/场景/图表/动作),不是只 OCR 文字 | `{description, model, prompt_tokens, completion_tokens}` |

所有工具的第一个参数 `source` 都支持:
- 本地路径:`"E:/docs/report.pdf"`
- HTTP(S) URL:`"https://arxiv.org/pdf/2408.09869"`
- Data URI:`"data:application/pdf;base64,JVBERi0xLjQ..."`(适合远端 HTTP 客户端上传二进制)

### 安装

```bash
cd E:/ideadatabase/py_data/agent_coding/docling-mcp
pip install -e .

# 首次运行会自动下载 docling 模型(约 500MB,可能慢)
```

### ⚠️ 中国大陆网络(必读)

docling 首次启动要从 HuggingFace Hub 拉约 500MB 模型,直连 `huggingface.co` 通常失败。本包已内置如下规避策略,只需在 `.env` 或环境变量中配置:

```bash
DOCLING_MCP_HF_ENDPOINT=https://hf-mirror.com   # 走 HF 镜像
DOCLING_MCP_HF_BYPASS_PROXY=true                # 强制绕过本地代理(Clash 等常导致 SSL 错误)
```

`__init__.py` 在导入 HF 库之前会读取这两个变量并:
1. 设置 `HF_ENDPOINT=https://hf-mirror.com`
2. 设置 `HF_HUB_DISABLE_XET=1`(关掉 Xet,否则权重文件仍走 `us.aws.cdn.hf.co` 直连失败)
3. 清空 `HTTP_PROXY / HTTPS_PROXY` 等代理变量,设置 `NO_PROXY=*`(本地 VPN 代理常对 hf-mirror 做 MITM 触发 SSL EOF)

如果镜像仍报超时,手动预热模型(推荐用 Python API 而非 `huggingface-cli`,Windows GBK 控制台对 CLI 不友好):

```bash
# 在能上 HF 的机器或 VPN 上跑
python -c "from huggingface_hub import snapshot_download; \
           snapshot_download('docling-project/docling-layout-heron'); \
           snapshot_download('BAAI/bge-small-en-v1.5')"
# 然后把 ~/.cache/huggingface 拷到目标机器
```

或下载到自定义位置:

```bash
HF_HOME=E:/hf_cache python -c "from huggingface_hub import snapshot_download; \
                                snapshot_download('docling-project/docling-layout-heron')"
```

转换失败时,工具会返回带可操作提示的错误信息(检查 `error` 字段)。

### OCR 引擎

docling 支持多 OCR 引擎,本包按以下优先级自动选择:
1. **RapidOCR**(默认,推荐)—— onnxruntime 后端,无 torch 依赖,体积小,已通过 docling 自带安装。
2. **EasyOCR** —— torch 后端,语言覆盖广,需 `pip install easyocr`。
3. docling 默认 —— 上述都失败时使用。

切换为 EasyOCR:`pip install easyocr`,然后代码会自动用上(见 `converter.py:_build_pipeline_options`)。

### 配置

复制 `.env.example` 为 `.env`,按需修改:

```bash
DOCLING_MCP_OCR_LANGS=en,zh          # 默认 OCR 语言
DOCLING_MCP_VLM_URL=...               # 可选:OpenAI 兼容 VLM 端点
DOCLING_MCP_VLM_API_KEY=...
DOCLING_MCP_VLM_MODEL=gpt-4o-mini
DOCLING_MCP_VLM_ENABLED=false         # 默认禁用,工具入参 enable_vlm 可临时开
```

### 图片理解(describe_image 工具)

OCR 只提取图片里的文字,**不理解图片内容**。`describe_image` 通过一个视觉语言模型(VLM)真正"看"图:识别物体、场景、人物、图表含义。

免费方案:**智谱 GLM-4V-Flash**(OpenAI 兼容,国内直连):

```bash
# 到 https://open.bigmodel.cn 注册获取 API key
DOCLING_MCP_VLM_URL=https://open.bigmodel.cn/api/paas/v4/chat/completions
DOCLING_MCP_VLM_API_KEY=你的智谱key
DOCLING_MCP_VLM_MODEL=glm-4v-flash
```

配置好后,直接让模型描述图片:

```bash
# 本地图片
curl ... "describe_image" ... "arguments":{"source":"E:/photos/receipt.png","prompt":"这张图里有什么?"}
# 网络图片
curl ... "describe_image" ... "arguments":{"source":"https://example.com/photo.jpg"}
```

支持任意 OpenAI 兼容视觉端点,不限于智谱。未配置时工具返回清晰的错误提示。

### 启动(stdio 本地模式)

```bash
python -m docling_mcp                 # 默认 stdio
# 或
docling-mcp
```

### 配置 Claude Desktop

编辑 `claude_desktop_config.json`(macOS: `~/Library/Application Support/Claude/`,Windows: `%APPDATA%\Claude\`):

```json
{
  "mcpServers": {
    "docling": {
      "command": "docling-mcp",
      "env": {
        "DOCLING_MCP_OCR_LANGS": "en,zh"
      }
    }
  }
}
```

### 配置 Cursor / Cline / Continue

类似配置,使用 `docling-mcp` 命令作为 MCP server。

### 启动(HTTP 远程模式,供 DeepSeek API 调用)

```bash
DOCLING_MCP_TRANSPORT=http DOCLING_MCP_PORT=8765 python -m docling_mcp
# 或
docling-mcp-http
```

测试:

```bash
curl -X POST http://127.0.0.1:8765/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc":"2.0","id":1,"method":"tools/call",
    "params":{"name":"convert_to_text",
              "arguments":{"source":"https://arxiv.org/pdf/2408.09869"}}
  }'
```

### 给 DeepSeek 用

DeepSeek 当前不直接支持 MCP,但你可以:
1. 把本服务跑在 HTTP 模式
2. 在你的应用代码里,用 DeepSeek 的 function-calling 接口,把 4 个工具描述注册为 functions
3. 当 DeepSeek 决定调用工具时,你用 HTTP 转发到本 MCP,把结果作为 user message 注入对话

参考 `examples/deepseek_bridge.py`(若存在)。

---

## English Quick Reference

### What

Wraps [docling](https://github.com/docling-project/docling) as an MCP server. Text-only LLMs (DeepSeek v4/pro, etc.) gain document vision by calling these tools.

### Tools

- `convert_to_markdown(source, [ocr_languages], [enable_vlm], [page_range], [image_caption_mode])` → `{markdown, ...}`
- `convert_to_text(source, [ocr_languages], [page_range])` → `string`
- `extract_tables(source, [ocr_languages])` → `[{page, index, num_rows, num_cols, markdown, rows}, ...]`
- `chunk_for_rag(source, [chunk_size=1024], [overlap=100], [tokenizer], [ocr_languages])` → `[{text, index, page, headings, ...}, ...]`
- `describe_image(source, [prompt])` → `{description, model, prompt_tokens, completion_tokens}` — semantic image understanding via a VLM (not just OCR text). Requires `DOCLING_MCP_VLM_URL`/`API_KEY`/`MODEL`. Free option: Zhipu `glm-4v-flash` at `https://open.bigmodel.cn/api/paas/v4/chat/completions`.

`source` accepts local path, HTTP(S) URL, or `data:` URI.

### Install

```bash
pip install -e .
```

First run downloads docling models (~500MB).

### Run

```bash
python -m docling_mcp            # stdio (default, for Claude Desktop / Cursor)
python -m docling_mcp http       # streamable-http (for remote LLMs)
```

### Env vars

| Var | Default | Purpose |
|------|---------|---------|
| `DOCLING_MCP_TRANSPORT` | `stdio` | transport mode |
| `DOCLING_MCP_HOST` | `127.0.0.1` | http host |
| `DOCLING_MCP_PORT` | `8765` | http port |
| `DOCLING_MCP_OCR_LANGS` | `en` | comma-separated OCR langs |
| `DOCLING_MCP_VLM_URL` | (empty) | OpenAI-compatible chat completions URL |
| `DOCLING_MCP_VLM_API_KEY` | (empty) | VLM bearer key |
| `DOCLING_MCP_VLM_MODEL` | `gpt-4o-mini` | VLM model name |
| `DOCLING_MCP_VLM_ENABLED` | `false` | global VLM default |
| `DOCLING_MCP_MAX_FILE_MB` | `200` | per-file size cap |
| `DOCLING_MCP_HF_ENDPOINT` | (empty) | HuggingFace mirror, e.g. `https://hf-mirror.com` for China |
| `DOCLING_MCP_HF_BYPASS_PROXY` | `true` | drop local proxy env vars before HF imports |

### Tests

```bash
pip install -e .[dev]
pytest tests/ -v
```

Unit tests (sources normalization) run without docling. Smoke tests skip if docling is not installed.

---

## Architecture

```
src/docling_mcp/
├── __main__.py    CLI entrypoint, stdio/http switch
├── server.py      FastMCP + 4 @mcp.tool() functions
├── converter.py   DocumentConverter singleton, asyncio.Lock, optional VLM pipeline
├── sources.py     path/URL/data-URI normalization → local file
├── config.py      pydantic-settings env config
└── schemas.py     Pydantic models for tool I/O
```

Key design choices:
- **Lazy init** — DocumentConverter (loads torch + models) only built on first call.
- **Lock-serialized** — concurrent tool calls share one converter under a global lock.
- **VLM graceful degradation** — tries multiple docling API shapes; falls back to OCR-only on failure and emits a `warnings` field.
- **Three input modes** — local path, HTTP(S) URL, base64 data URI; unified to a `(Path, cleanup)` handle.

## License

MIT

TDQS

A4.2/5.0

Scored across 4 tools

Disambiguation5/5

Each tool has a clearly distinct purpose: plain text conversion, markdown conversion, table extraction, and RAG chunking. No two tools overlap in function, and the descriptions clarify the differences even between the two conversion tools.

Naming Consistency5/5

All tool names follow a consistent verb_noun pattern in snake_case (convert_to_text, convert_to_markdown, extract_tables, chunk_for_rag). The naming is uniform and predictable.

Tool Count5/5

With 4 tools, the server is well-scoped for document processing. Each tool covers a distinct need without redundancy, and the number is within the ideal range.

Completeness4/5

The server covers the primary conversion and extraction needs (text, markdown, tables) plus chunking for RAG. Minor gaps exist, such as direct document structure extraction or image extraction, but agents can work around these using the provided tools.

Maintenance

ActivitySlowing
ResponsivenessNo issues