Skip to main content
Glama
README.md
# docs-mcp: an MCP server for document and knowledge access

A small, production-minded **Model Context Protocol (MCP) server** that lets AI
assistants (Claude Desktop, Claude Code, Cursor, VS Code or your own agent) **search and
read a folder of documents**: Markdown, plain text and PDF.

Point it at a folder of handbooks, policies or runbooks. The assistant can then answer
questions from them and cite where each answer came from.

```text
You:     How long do we have to write a postmortem after a SEV1?
Claude:  → search_docs("SEV1 postmortem deadline")
         → get_document("runbooks/incident-response.md", section="Closing and postmortem")
         Every SEV1 and SEV2 needs a blameless postmortem within five business days
         [runbooks/incident-response.md § Closing and postmortem].
```

**Highlights**

- **3 tools** (`search_docs`, `get_document`, `list_documents`), plus a **resource** and a **prompt**, so all three MCP primitives are covered
- **Ranked search** with BM25 over heading-aware chunks, with snippets and section/page citations
- **Typed structured output**: every tool publishes an `outputSchema`, so both LLMs and plain code can use the results
- **Context-window aware**: you can fetch a single section or PDF page, and long documents come back in pages
- **Safe by default**: read-only, allow-list lookups, no path traversal, hidden files and outside symlinks skipped
- **Live re-indexing**: edit a file and the next query sees the change, with no restart
- **Small and readable**: about 800 lines of heavily commented Python, 2 runtime dependencies, 21 tests

---

## Architecture

```mermaid
flowchart LR
    subgraph Host["MCP Host (Claude Desktop / Claude Code / IDE / demo_client.py)"]
        LLM["LLM"]
        MC["MCP Client"]
        LLM <--> MC
    end

    subgraph Server["docs-mcp server (Python)"]
        direction TB
        S["server.py<br/>MCPServer: tools · resource · prompt"]
        KB["knowledge_base.py<br/>doc registry + auto-refresh"]
        IDX["search.py<br/>chunking + BM25 + snippets"]
        LD["loader.py<br/>Markdown · TXT · PDF → Document"]
        S --> KB
        KB --> IDX
        KB --> LD
    end

    FS[("DOCS_DIR<br/>*.md *.txt *.pdf")]

    MC <-- "JSON-RPC over stdio<br/>(or Streamable HTTP)" --> S
    LD -- "read-only" --> FS
```

| Layer | File | Responsibility |
|---|---|---|
| **Protocol** | `server.py` | Registers tools, resource and prompt with the MCP SDK; validates input; shapes output; runs the transport |
| **Domain** | `knowledge_base.py` | Holds the documents and the index; re-indexes when the folder changes; looks documents up by ID only |
| **Retrieval** | `search.py` | Splits sections into ~1.2k-char chunks, ranks them with BM25 and builds snippets |
| **Ingestion** | `loader.py` | Turns each file format into one `Document` shape (title, text, sections) |
| **Config** | `config.py` | Env vars and CLI flags: folder, size limits, page size |

Each layer only talks to the one below it. You can swap BM25 for vector search, or add
a `.docx` loader, without touching the MCP layer.

### Request flow: search, then fetch, then cite

```mermaid
sequenceDiagram
    participant U as User
    participant H as Host + LLM
    participant S as docs-mcp
    participant F as DOCS_DIR

    H->>S: initialize
    S-->>H: capabilities + instructions (recommended workflow)
    H->>S: tools/list
    S-->>H: search_docs, get_document, list_documents (+ JSON schemas)
    U->>H: "How do I rotate API keys?"
    H->>S: tools/call search_docs {query: "rotate API keys"}
    S->>F: stat files (re-index only if changed)
    S-->>H: top passages: doc_id, section, score, snippet
    H->>S: tools/call get_document {doc_id, section: "Page 2"}
    S-->>H: section text (paginated if long)
    H-->>U: Answer with citation [policies/security-policy.pdf § Page 2]
```

Search returns short **snippets**, not whole files. The model reads the snippets first,
then opens only the sections it needs. This keeps token use low even when the document
set is large.

---

## What the server exposes

### Tools (called by the model)

| Tool | Arguments | Returns |
|---|---|---|
| `search_docs` | `query` (str), `top_k` (1–20, default 5), `path_prefix` (optional, e.g. `"runbooks/"`) | Ranked passages: `doc_id`, `title`, `section`, `page`, `score`, `snippet`, plus a `hint` for the next step |
| `get_document` | `doc_id`, `section` (optional heading or `"Page 3"`), `offset`, `max_chars` (500–50,000) | `content`, `total_chars`, `truncated`, `next_offset` for paging |
| `list_documents` | `path_prefix` (optional) | Every document with its title, type, section headings and modified date |

All tools carry `readOnlyHint: true` and `openWorldHint: false`. Hosts can use these
hints to auto-approve the tools safely, so the user isn't asked to confirm every call.

### Resource (attached by the user or app)

`docs://{+doc_id}` returns the full text of a document, e.g. `docs://runbooks/database-failover.md`.
In hosts that support resources, users can attach a document to the chat directly.

### Prompt (picked by the user)

`answer_from_docs(question)` is a ready-made "answer only from the docs and cite
sources" workflow. Hosts usually show it as a slash command.

---

## Quick start

**Requirements:** Python 3.10+.

```bash
git clone <your-repo-url> mcp-docs-server && cd mcp-docs-server

python -m venv .venv
source .venv/bin/activate          # Windows: .venv\Scripts\activate
pip install -e ".[dev]"

pytest                             # 21 tests, under 1 second
python client/demo_client.py       # end-to-end demo over stdio
```

<details>
<summary>Demo client output (abridged)</summary>

```text
── Connected to docs-mcp v0.1.0 ─────────────────────────────────────────
  • list_documents(path_prefix)
      List the documents available in the knowledge base, with their section headings
  • search_docs(query, top_k, path_prefix)
      Full-text search across all documents
  • get_document(doc_id, section, offset, max_chars)
      Retrieve the text of a document, or of one section of it

── list_documents ───────────────────────────────────────────────────────
  faq.txt                                text      Northwind Labs Engineering FAQ
  handbook/code-review-guidelines.md     markdown  Code Review Guidelines
  handbook/onboarding.md                 markdown  Engineering Onboarding Guide
  policies/security-policy.pdf           pdf       Information Security Policy
  runbooks/database-failover.md          markdown  Postgres Database Failover
  runbooks/incident-response.md          markdown  Incident Response Runbook

── search_docs("SEV1 postmortem deadline") ──────────────────────────────
  [ 6.67] runbooks/incident-response.md § Closing and postmortem
          The IC closes the incident once the impact has ended and monitoring is stable
          for 30 minutes. Every SEV1 and SEV2 needs a blameless postmortem within **five
          business days**, covering timeline, impact, root cause, and action items ...

── get_document("../../etc/passwd")  - path traversal attempt ───────────
  isError=True: Error executing tool get_document: Unknown doc_id '../../etc/passwd'. ...
```
</details>

Search your own folder with the client:

```bash
python client/demo_client.py --docs-dir ~/my-notes "quarterly planning"
```

---

## Connecting to an MCP host

Every option below starts the same server. Always use **absolute paths**, because hosts
don't launch servers from your project folder. Use the `docs-mcp` script inside your
virtual environment (`.venv/bin/docs-mcp`, or `.venv\Scripts\docs-mcp.exe` on Windows).

### MCP Inspector (best for debugging)

The official browser-based tester lets you see the schemas, call tools by hand and watch raw JSON-RPC:

```bash
npx @modelcontextprotocol/inspector .venv/bin/docs-mcp --docs-dir ./docs
```

### Claude Desktop

Open **Settings → Developer → Edit Config**, add the block below (also in
[`examples/claude_desktop_config.json`](examples/claude_desktop_config.json)), then restart Claude Desktop:

```json
{
  "mcpServers": {
    "company-docs": {
      "command": "/ABSOLUTE/PATH/TO/mcp-docs-server/.venv/bin/docs-mcp",
      "args": ["--docs-dir", "/ABSOLUTE/PATH/TO/your/docs"]
    }
  }
}
```

### Claude Code

```bash
claude mcp add --transport stdio company-docs -- \
  /ABSOLUTE/PATH/TO/mcp-docs-server/.venv/bin/docs-mcp --docs-dir /ABSOLUTE/PATH/TO/your/docs
claude mcp list        # should show company-docs as connected
```

To share the setup with your team, commit a `.mcp.json` to the repo instead
(see [`examples/mcp.json`](examples/mcp.json)).

### Over the network (Streamable HTTP)

```bash
docs-mcp --transport streamable-http --port 8000 --docs-dir ./docs
# endpoint: http://127.0.0.1:8000/mcp
```

The server binds to `localhost` by default. Put an authenticating reverse proxy or
gateway in front of it before exposing it beyond your machine (see *Security*).

---

## Configuration

| Setting | CLI flag | Env var | Default |
|---|---|---|---|
| Documents folder | `--docs-dir` | `DOCS_DIR` | `./docs` |
| Max file size indexed | | `DOCS_MAX_FILE_BYTES` | `10485760` (10 MB) |
| Default `get_document` page size | | `DOCS_MAX_CHARS` | `8000` |
| Log level (stderr) | | `DOCS_LOG_LEVEL` | `INFO` |
| Transport | `--transport` | | `stdio` |
| HTTP host / port | `--host` / `--port` | | `127.0.0.1` / `8000` |

Supported files: `.md`, `.markdown`, `.txt`, `.pdf` (text-based; scanned PDFs need OCR first).

---

## Project structure

```text
mcp-docs-server/
├── src/docs_mcp/
│   ├── server.py           # MCP layer: tools, resource, prompt, transports, CLI
│   ├── knowledge_base.py   # document registry, auto-refresh, safe lookup
│   ├── search.py           # chunking, BM25 ranking, snippets
│   ├── loader.py           # Markdown / TXT / PDF → Document
│   ├── config.py           # settings from env + CLI
│   └── __main__.py         # enables `python -m docs_mcp`
├── client/demo_client.py   # stdio client that exercises every tool
├── tests/test_docs_mcp.py  # loader, search and protocol-level tests
├── docs/                   # sample knowledge base (fictional "Northwind Labs")
│   ├── handbook/  runbooks/  policies/security-policy.pdf  faq.txt
├── examples/               # host configs: Claude Desktop, .mcp.json
├── scripts/make_sample_pdf.py
└── pyproject.toml
```

---

## Design decisions

| Decision | Why |
|---|---|
| **stdio as the default transport** | Nothing listens on a port and there are no credentials to manage. Each user's host runs its own private copy. This is the standard choice for local MCP servers. |
| **BM25 instead of embeddings** | No model download, API key or vector database. Results are deterministic and easy to explain. It is also strong on enterprise text full of exact terms (error codes, product names, policy IDs). The index is one small class, so you can swap it for hybrid or vector search later. |
| **Chunk by section, cite by section** | Chunks never cross a heading or PDF page. Every hit therefore has a precise citation, and `get_document(section=…)` fetches exactly that part. |
| **Search returns snippets; fetching is a separate call** | The model reads cheap previews first and spends context only on what is relevant. |
| **Pagination (`offset` / `next_offset`)** | A 200-page PDF would otherwise flood the model's context window or exceed host limits. |
| **Structured output (Pydantic models)** | `structuredContent` gives code a stable contract, and the text rendering serves the LLM. |
| **Server `instructions` + `hint` fields** | They teach the model the intended workflow (search, fetch, cite) and what to do when a search finds nothing, which reduces made-up answers. |
| **Re-index on change (stat fingerprint)** | Edits show up on the next call. This avoids a file-watcher thread and is the right trade-off for hundreds of files. |
| **`ToolError` for expected failures** | The model gets a clear, recoverable message such as "unknown doc_id, use search_docs". Unexpected exceptions stay on the server, so stack traces and paths don't leak. |

## Security

Tool arguments are written by an LLM, and the documents themselves could contain prompt
injection. The server therefore treats every argument as untrusted:

- **Read-only.** No tool writes, deletes or calls the network.
- **Allow-list lookup.** `get_document` looks documents up by ID in the in-memory index. It never builds a file path from user input, so `../../etc/passwd` is simply "unknown".
- **Contained folder.** Hidden files and folders (`.env`, `.git`, …) are never indexed. Symlinks that point outside `DOCS_DIR` are skipped. Resource URIs reject `..` traversal.
- **Bounded work.** File size cap, `top_k ≤ 20`, page size ≤ 50k characters, and inputs checked against their schemas.
- **Logs on stderr only.** stdout carries the JSON-RPC protocol, so nothing else is ever written there.

For a shared HTTP deployment, add authentication (the SDK supports OAuth token
verification), TLS, and per-user document permissions before go-live.

## Extending it

- **Semantic or hybrid search**: add an embeddings index next to `BM25Index` and merge results with reciprocal rank fusion.
- **More formats**: write a `_load_docx` or `_load_html` function and register it in `loader._LOADERS`.
- **Other sources**: back the `KnowledgeBase` with SharePoint, Confluence or a headless CMS such as Sitecore instead of a folder. The tools don't change.
- **Permissions**: filter `search` and `get` by the caller's identity when running over HTTP with auth.

## A note on SDK versions

This project targets the **official MCP Python SDK v2** (`mcp>=2`). In v2 the
high-level server class is `MCPServer` (it was `FastMCP` in v1), and the SDK has a
high-level `Client` class, which the demo client and tests use. To run on v1, pin
`mcp<2` and follow the SDK's v2 migration guide in reverse. The changes are small: the
import paths, `ToolAnnotations` field names, and using `ClientSession` in the client.

## License

MIT

TDQS

A4.1/5.0

Scored across 3 tools

Disambiguation5/5

Each tool maps to a distinct retrieval mode: browse the catalog (list_documents), find passages by query (search_docs), and read content (get_document). Descriptions explicitly chain them (search then get_document, list_documents to discover doc_ids), leaving no realistic misselection risk.

Naming Consistency4/5

All three follow a clean verb_noun pattern (list_, search_, get_ + docs/documents). The only wobble is the noun inconsistency between 'docs' and 'documents' as the resource label, which is cosmetic but slightly unpredictable.

Tool Count5/5

Three tools is exactly right for a read-only knowledge-base server: each covers a distinct step of the browse-search-read workflow and none is redundant. Nothing feels missing at the tool-granularity level for this scope.

Completeness4/5

The retrieve lifecycle (enumerate, search, fetch with pagination) is fully covered, so agents won't hit dead ends on read workflows. Gaps are minor and likely out of scope: no write/index operations and no standalone section enumeration beyond headings returned by list_documents.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues