HUB
Sign inSign up

dmeric/docs-to-ai

By dmeric

•Updated 7 days ago

A Model Context Protocol (MCP) server that enables LLMs to query local documents. PDF, Word, Excel

Image
Machine learning & AI
1

1.5K

dmeric/docs-to-ai repository overview

⁠Docs-to-AI: local RAG to search local PDFs, Word files, and any folder

Github repo: https://github.com/dorianmeric/docs-to-ai⁠

Docs-to-AI is a local RAG (retrieval-augmented generation) server for your own documents. It indexes one folder tree of PDFs, Word files, spreadsheets, Markdown, PowerPoint, HTML, TXT, and CSV, and hands the index to any LLM that speaks MCP. The LLM searches the index and answers with quotes from your files.

The container serves MCP over HTTP on port 38777: start it once and every MCP client on your network can use it. No cloud service and no API key: the embedding and re-ranking models run locally, so no text leaves the machine. Pages without a text layer are read with OCR, and a folder watcher keeps the index fresh.

⁠Quick start

You need Docker Desktop or Docker Engine. Budget about 5 GB of disk: the image already carries the embedding and re-ranking models. See Disk space⁠.

⁠1. Put your documents in ./my-docs

Create a folder called my-docs next to the compose file and copy your documents into it. Subfolders become topics, so my-docs/contracts/lease.pdf is indexed under the topic contracts. The container mounts this folder read-only.

⁠2. Save the compose file

Save this as docker-compose.yaml next to my-docs:

services:
  docs-to-ai:
    image: dmeric/docs-to-ai
    container_name: docs-to-ai

    volumes:
      - ./cache/chromadb:/app/cache/chromadb   # vector store
      - ./cache/doc_cache:/app/cache/doc_cache # extracted text
      - ./my-docs:/app/my-docs:ro              # your documents, read-only
      - ./logs:/app/logs                       # server.log and detail.jsonl

    # only needed for stdio over `docker exec` (see Connect an MCP client)
    stdin_open: true
    tty: false

    environment:
      - MCP_TRANSPORT=http                     # serves http://localhost:38777/mcp
      - MCP_HOST=0.0.0.0
      - MCP_PORT=38777
      - LOG_DIR=/app/logs                      # server.log and detail.jsonl

    ports:
      - "${MCP_PORT:-38777}:${MCP_PORT:-38777}"

    restart: unless-stopped

    ## Uncomment to enable GPU acceleration on an Nvidia GPU.
    # deploy:
    #   resources:
    #     reservations:
    #       devices:
    #         - driver: nvidia
    #           count: all          # or device_ids: ['0'] to pin one GPU
    #           capabilities: [gpu]

The image is published on Docker Hub as dmeric/docs-to-ai⁠. The repository ships its own docker-compose.yml⁠, which is the same service plus a build: block, all build args, and a comment on every setting. Use that file when you want to build the image yourself as mcp/docs-to-ai, for example to change build args or run unreleased code after docker compose build.

⁠3. Start the container
docker compose up -d

Note on GPU usage:he GPU host needs an NVIDIA driver, R580 or newer (the normal GeForce driver on Windows): the image ships a CUDA 13 PyTorch build. On Linux it also needs the NVIDIA Container Toolkit (nvidia-container-toolkit). Docker Desktop needs the WSL2 based engine, which is the default. No CUDA toolkit install is needed, because the image already ships the CUDA-enabled PyTorch wheel. GPU inside Docker⁠ shows the reservation file in full, the log check, and the .env alternative.

Either way, the container keeps running and serves MCP at http://localhost:38777/mcp. The log line names every address a client can use:

2026-11-27 13:56:18 SUCCESS ✅ [MCP Server] Listening on 0.0.0.0:38777/mcp
                                           From this Docker host or a browser on it: http://localhost:38777/mcp
                                           From another machine: http://<host-ip>:38777/mcp
⁠4. Connect your MCP client

Point the client at the HTTP endpoint:

{
  "mcpServers": {
    "docs-to-ai": {
      "url": "http://localhost:38777/mcp",
      "transport": "http"
    }
  }
}

Some clients want "type": "http" instead of "transport": "http". Use whichever key your client documents. From another machine, replace localhost with the host's IP address. Connect an MCP client⁠ covers the alternatives, including clients that only speak stdio.

⁠5. Confirm the first scan

A fresh container has an empty index, so the server scans /app/my-docs at startup even though FULL_SCAN_ON_BOOT defaults to False. A 500-chunk corpus takes several minutes to embed on CPU. Watch the progress, and check that the mount actually contains your files:

docker exec docs-to-ai ls /app/my-docs    # must list your files
docker logs -f docs-to-ai                 # shows the scan progress

Once the scan reports chunks, ask the LLM: "What documents do you have access to?", which proves the index is reachable.

To re-index later, ask the LLM to call scan_all_my_documents, or run it yourself:

docker exec docs-to-ai uv run --no-sync python -m app.scan_all_my_documents --doc-dir /app/my-docs

The folder watcher runs by default, so a file you drop into ./my-docs is indexed after DEBOUNCE_SECONDS without any further action.

⁠Docker reference

⁠Volumes and ports

Four bind mounts hold everything that must survive a container rebuild:

Host pathContainer pathWhy it matters
./cache/chromadb/app/cache/chromadbThe vector store. Without this mount the index is rebuilt on every container start. The path must match what the app reads: /app/chromadb does not work.
./cache/doc_cache/app/cache/doc_cacheExtracted text per document, so a second scan skips the parsing and the OCR.
./my-docs/app/my-docsYour documents. Mount it :ro so the server cannot modify them.
./logs/app/logsserver.log and detail.jsonl. Without this mount the logs stay inside the container and disappear when it is recreated.

Port 38777 publishes the HTTP endpoint for MCP clients. Keep the host port and MCP_PORT equal; if you publish a different host port, set MCP_PUBLIC_URL so the startup banner shows the address clients should use.

To index a folder that is not ./my-docs, add a second mount and point DOCS_DIR at it inside the container, for example - ./contracts:/app/contracts:ro together with DOCS_DIR=/app/contracts.

⁠Change settings without rebuilding

The compose file passes every setting to the container as ${SETTING:-default}, so a value in .env changes both the build args and the runtime environment:

echo "FULL_SCAN_ON_BOOT=True" > .env
echo "CHUNKING_STRATEGY=by_paragraph" >> .env   # cheaper than the semantic default
echo "CHUNK_SIZE=512" >> .env
docker compose up -d

The container does not read .env itself: Compose substitutes the values into the service definition. Every setting from Configuration⁠ can be changed this way, and a restart applies it.

⁠Build args and model baking

Build args bake values into the image, because the build pre-downloads models: the embedding model, the re-ranker, and the tiktoken data must match the settings the container will run with. A runtime environment variable always overrides a baked value.

docker compose build --build-arg CHUNKING_STRATEGY=by_paragraph --build-arg CHUNK_SIZE=512
docker compose up -d

The model, chunking, search, OCR, and startup settings are build args. The transport (MCP_*), logging (LOG_*), DOCS_DIR, and EMBEDDING_QUERY_PROMPT are runtime-only. Rebuild after changing EMBEDDING_MODEL or USE_RERANKER, because those models are downloaded during the build; chunking and search settings need a re-scan instead.

Scanned PDFs need the optional OCR engine, which the default image does not include:

docker compose build --build-arg INSTALL_MARKER=True

That adds Marker, its PyTorch build, and the OCR models to the image: about 110 MB of models for the default fast mode. Without it the container logs one warning and scanned pages stay empty. MARKER_MODE=balanced and vllm also need vllm and an NVIDIA GPU inside the container.

Changing EMBEDDING_MODEL, EMBEDDING_DIMENSION, or CHROMA_SPACE forces a new collection, because ChromaDB cannot change the vector size or the distance space in place. The server detects a stale collection at startup and recreates it, so re-scan after the recreate:

docker exec docs-to-ai uv run --no-sync python -m app.scan_all_my_documents --doc-dir /app/my-docs --reset

The vector store is a cache, so a recreate never touches the source files.

⁠GPU inside Docker

A container sees only the GPUs that Docker passes to it. Without a device reservation the log says No GPU is visible inside this container, even when the host has a GPU. Step 3⁠ covers the reservation and the start command. To keep plain docker compose up -d working on a GPU host, list both files in .env: COMPOSE_FILE=docker-compose.yaml;docker-compose.gpu.yaml (; on Windows, : on Linux/macOS).

Check that the container sees the GPU:

docker compose logs | grep "Compute device"

Expected log line: Compute device: cuda:0 (NVIDIA GeForce RTX 5090, 32 GB VRAM). A plain docker run needs --gpus all; add it yourself, otherwise the container starts on CPU.

⁠Connect an MCP client

MCP_TRANSPORT selects how clients talk to the server, and one transport runs per process:

TransportEndpointUse it for
httpMCP_HOST:MCP_PORT/mcpDocker and any long-running server. This is what the compose file sets.
stdiono port, stdin and stdoutA client that starts the process itself, or docker exec -i into a running container.
sseMCP_HOST:MCP_PORT/sseOlder HTTP clients that need Server-Sent Events.

The HTTP client config is in step 4⁠. Keep in mind:

  • From another machine, replace localhost with the host's IP address and open the port in the host firewall.
  • Do not put docker run -i --rm dmeric/docs-to-ai in a client config. docker run starts a fresh container for every connection, with no volumes and no index, so the client sees an empty document folder and re-scans from scratch each time.
⁠stdio inside the running container

A client that only speaks stdio can run the server inside the running container. This reuses the same container, mounts, and index:

{
  "mcpServers": {
    "docs-to-ai": {
      "command": "docker",
      "args": ["exec", "-e", "MCP_TRANSPORT=stdio", "-i", "docs-to-ai", "uv", "run", "--no-sync", "python", "mcp_server.py"]
    }
  }
}

The command goes through uv run, because the image keeps its packages in a virtualenv, and it sets MCP_TRANSPORT=stdio, because the container already owns the HTTP port. The container has to be running before the client connects.

⁠SSE clients and the published URL

Older clients use http://localhost:38777/sse with "transport": "sse"; start the server with MCP_TRANSPORT=sse for them.

Set MCP_PUBLIC_URL when the host port differs from MCP_PORT, or when a proxy sits in front of the server:

MCP_PUBLIC_URL=http://myserver.lan:8080/mcp

⁠How search works

Documents (PDF, Word, Excel, Markdown, PowerPoint, HTML, TXT, CSV)
  → text extraction (scanned PDF pages go through OCR)
    → chunking (semantic by default, 1024 tokens)
      → embeddings (Qwen3-Embedding-0.6B, 1024-dim)
        → ChromaDB (cosine HNSW, topic tags on every chunk)
          ↓
    hybrid retrieval: BM25 + dense → RRF → cross-encoder re-rank
          ↓
    MCP tools → Claude or any MCP client

Dense vectors catch meaning and BM25 catches exact strings; RRF merges both ranked lists, and a cross-encoder re-scores the merged candidates. Documents are parsed once at index time, so a search only touches the index.

⁠Folder topics: how to search a folder

The server maps folders to topics, and a topic narrows a search. One folder tree becomes one browsable index.

  • Each folder name becomes a topic.
  • Nested folders become nested topics, joined with >.
  • Files with the same name in different folders stay separate, so two introduction.pdf files do not overwrite each other.
my-docs/
├── Machine_Learning/
│   └── introduction.pdf
├── Python_Programming/
│   └── introduction.pdf        # separate document, separate topic
└── Data_Science/
    └── statistics.pdf

⁠MCP tools

Search and discovery:

  • search_documents runs hybrid search over all documents. Filters: topic, phrase_search, date_from, date_to, regex_pattern.
  • list_all_documents lists every indexed document, grouped by first topic. Filter with topic.
  • list_topic lists the documents of one topic (folder), including its subfolders, with the full path of each file. It accepts legal, legal > contracts, or legal/contracts.
  • list_topics lists topics, and get_collection_stats reports chunk counts, document counts, file types, and index details.

Read documents in full:

  • read_file_metadata returns one document's metadata: path, topics, size, dates, chunk count, page numbers with chunks, OCR pages, and whether the file changed on disk.
  • read_file returns one document's whole text, page by page, with the same metadata block. Use page for a single page and max_chars to cap the response.
  • read_multiple_files takes a list of names and returns the same metadata and text for each one as a JSON list. A name that does not resolve comes back as an entry with an error field, so one miss does not hide the rest.
  • read_file_raw returns the original file as a base64 string, with MIME type, byte count, and SHA-256, so the client can save or forward the real PDF, DOCX, or image. max_bytes defaults to 1 MB; raise it to fetch something bigger.

All four reading tools take the same document names: a filename, a full path, or part of either. If a name matches more than one document, the tool answers with the candidates instead of guessing.

Document management: scan_all_my_documents re-indexes the document folder, start_watching_folder and stop_watching_folder control the folder watcher, and get_time_of_last_folder_scan reports the last scan time and the next full scan.

⁠Configuration

Override any setting in the .env file next to the compose file, or as an environment variable on the container; a restart applies it. The full list with valid options is in .env.example⁠, and docker exec docs-to-ai uv run --no-sync python mcp_server.py --show-config prints the effective values.

⁠Chunking
SettingEnv varDefaultDescription
StrategyCHUNKING_STRATEGYsemanticsemantic, fixed_size, by_paragraph, semantic_heading, or by_token
Chunk sizeCHUNK_SIZE1024Tokens per chunk (CHUNK_BY_TOKEN=True) or characters (CHUNK_BY_TOKEN=False)
Chunk overlapCHUNK_OVERLAP200Overlap between chunks, same unit as CHUNK_SIZE
Token chunkingCHUNK_BY_TOKENTrueMeasure chunk sizes in tokens instead of characters

by_paragraph costs the least, and published tests find it matches semantic up to about 5k tokens. semantic is the slowest, because every sentence is embedded. semantic_heading keeps document structure, and fixed_size slices at CHUNK_SIZE and ignores structure.

⁠OCR for scanned PDFs

A scanned PDF stores a picture of each page, not text. When a page's text layer holds fewer than OCR_MIN_TEXT_CHARS characters, that page is read by Marker⁠, which runs layout analysis before OCR, so multi-column scans, tables, and forms come back in reading order. Each chunk records that it came from OCR, so results and read_file mark those pages (OCR).

SettingEnv varDefaultDescription
OCR onOCR_ENABLEDTrueRead pages that have no usable text layer
Scan thresholdOCR_MIN_TEXT_CHARS20A page below this many characters is treated as a scan
Pages per documentOCR_MAX_PAGES9999Ceiling on scanned pages read per document; 0 turns OCR off
Marker modeMARKER_MODEfastfast, balanced, vllm, no_ocr, or auto (see below)
Marker deviceMARKER_DEVICEemptycuda, cuda:1, mps, cpu; empty follows USE_GPU_ACCELERATION_IF_AVAILABLE
Model cacheMARKER_MODEL_CACHEemptyHF_HOME for Marker's models; empty uses the Hugging Face cache

fast is the default: in-process ONNX on CPU or GPU, no extra server, about 7 pages/s on mixed scans and ~110 MB of models. balanced (GPU, needs vllm or llama.cpp) reads tables, maths, and difficult scans at about 17 pages/s. vllm (GPU, needs vllm) handles degraded scans, handwriting, and dense formulas.

Changing MARKER_MODE, OCR_MIN_TEXT_CHARS, or OCR_MAX_PAGES makes the cached text of PDFs stale, so the next scan re-reads those PDFs and previously empty scans fill in.

SettingEnv varDefaultDescription
Default resultsDEFAULT_SEARCH_RESULTS10Results returned when the client asks for no count
Max resultsMAX_SEARCH_RESULTS20Hard cap on results per search
Re-rankerUSE_RERANKERTrueRe-score fused candidates with a cross-encoder
Re-rank candidatesRERANKER_TOP_N50Candidates passed to the re-ranker
Hybrid searchUSE_BM25TrueMerge a BM25 ranking with the dense ranking
BM25 weightBM25_WEIGHT0.3RRF weight of the BM25 list, 0.5 gives equal weight

On CPU, re-ranking 50 candidates costs about 1.8 s per search: lower RERANKER_TOP_N when a search feels slow.

⁠Embedding model and GPU
SettingEnv varDefaultDescription
ModelEMBEDDING_MODELQwen/Qwen3-Embedding-0.6BSentence-transformer model, 1024-dim, 32K context
DimensionEMBEDDING_DIMENSION1024Vector dimension, must match the model
Batch sizeEMBEDDING_BATCH_SIZE32Texts encoded per batch; 64-128 on a GPU, 8-32 on CPU
GPU if availableUSE_GPU_ACCELERATION_IF_AVAILABLETrueUse CUDA or Apple MPS when detected, otherwise CPU
GPU indexGPU_DEVICE_INDEX0Which CUDA GPU to use, 0 is the first GPU

A GPU makes indexing about 37× faster and re-ranking about 50× faster, and the server falls back to CPU automatically.

⁠Topics, storage, startup, and transport
SettingEnv varDefaultDescription
Documents dirDOCS_DIR/app/my-docsFolder scanned for documents
Full scan on bootFULL_SCAN_ON_BOOTFalseRe-index every document at server start
Watcher on bootFOLDER_WATCHER_ACTIVE_ON_BOOTTrueStart the folder watcher at server start
TransportMCP_TRANSPORTstdiostdio, http (/mcp), or sse (/sse). The compose file sets http
HostMCP_HOST0.0.0.0HTTP bind address. 127.0.0.1 binds inside the container only
PortMCP_PORT38777HTTP port
Public URLMCP_PUBLIC_URLemptyAddress printed at startup and used for client instructions

An empty index is scanned at startup even when FULL_SCAN_ON_BOOT=False, so a fresh container indexes its documents without extra configuration.

⁠Disk space

The models are the bulk of a setup: budget about 2.8 GB for a CPU install with OCR and 7 to 16 GB for a GPU install, depending on how much accuracy you ask Marker for. That is a one-time cost per machine, and the index and the extraction cache grow with your corpus on top of it.

SetupPackagesModelsTotal
CPU, text-layer PDFs only (OCR_ENABLED=False, no marker extra)1.2 GB1.3 GB~2.5 GB
CPU with Marker fast (the default setup)1.4 GB1.4 GB~2.8 GB
GPU with Marker fast5.5-6.5 GB1.4 GB~7-8 GB
GPU with Marker balanced or vllm11-13 GB2.9 GB~14-16 GB
FolderWhat growsMeasured
cache/chromadbOne vector (1024 floats = 4 KB) plus the chunk text and metadata, plus the HNSW graph18 MB for 514 chunks, about 35 KB per chunk
cache/doc_cacheThe extracted text of each document, so a re-scan skips the parseTypically 10-30% of the source documents' size

Rough guide for the vector store: 1 GB per 30,000 chunks, so 10,000 average documents need around 35 GB. Removing documents does not shrink it: run a scan with --reset, or delete cache/chromadb, to reclaim the space. The image itself is about 2.5 GB with the models baked in.

⁠Logs

Two files sit in /app/logs, bind-mounted to ./logs on the host. Every line on stderr also shows up in docker logs, prefixed with a level: INFO for progress, SUCCESS ✅ for something that worked, WARN ⚠️ for a fallback, and ERROR ❌ for a failure, whose message carries Problem, Cause, and Fix lines. stdout stays clean, because it carries the MCP protocol.

FileContent
logs/server.logEvery action of the server: startup, model loading, watcher events, scans, tool calls, searches, errors
logs/detail.jsonlOne JSON object per line for the events needed to debug retrieval: server_start, tool_call, search, scan_document, scan_summary, incremental_change, watch_batch, ocr_document

Both files rotate by size, and the oldest file beyond LOG_BACKUP_COUNT is deleted.

SettingEnv varDefaultDescription
LevelLOG_LEVELINFODEBUG, INFO, WARNING, or ERROR
Slow querySLOW_QUERY_MS20000A search slower than this logs a WARN with the step breakdown

One search record in detail.jsonl holds the query, the timing for every stage, and every returned chunk with its scores and text.

⁠Troubleshooting: error messages

Message you seeCauseFix
No supported documents were found in '/app/my-docs'.The container sees an empty documents folder. The bind mount points at a different host folder, docker compose ran from another directory, or DOCS_DIR is wrong.Run docker compose config and check the host side of ./my-docs:/app/my-docs:ro. Run docker exec docs-to-ai ls /app/my-docs and compare.
The index is empty again after every container restartThe cache volumes point at the wrong container paths, so the index is written inside the container and thrown away.Mount /app/cache/chromadb and /app/cache/doc_cache, as in the compose file above. Paths like /app/chromadb do not match what the app reads.
The index is empty, so '<query>' could not match anything.Nothing is indexed yet, or the last scan failed.Run the scan_all_my_documents tool, or the scan command from step 5⁠.
No text could be extracted from '<file>'. / OCR is enabled but unavailable: Marker is not installedThe file is empty, or the image was built without the OCR engine, so scanned pages stay empty.Build with INSTALL_MARKER=True, then restart. For a PDF, also check OCR_ENABLED=True, OCR_MAX_PAGES above zero, and that --show-config reports OCR_STATUS=ready.
The machine ran out of memory. / CUDA out of memoryThe embedding batch is too large for the RAM or VRAM.Lower EMBEDDING_BATCH_SIZE to 8 or 16, pick another GPU with GPU_DEVICE_INDEX, or set USE_GPU_ACCELERATION_IF_AVAILABLE=False.
The vector database at '<path>' could not be opened. / The vector database is locked or unreadable.Two containers use cache/chromadb at once, the folder is read-only, or the files are damaged.Run one container. Stop the other with docker compose down. Check write access. Delete the cache folder and re-scan.
Connection refused / the log shows Listening on 127.0.0.1:...The server runs with MCP_TRANSPORT=stdio, so nothing listens on the port, or MCP_HOST binds inside the container only.Start it with MCP_TRANSPORT=http (the compose file does this) and set MCP_HOST=0.0.0.0. Look for Listening on 0.0.0.0:38777/mcp.
No GPU is visible inside this container / could not select device driverDocker started the container without the GPU device reservation, or the host has no NVIDIA driver, no NVIDIA Container Toolkit, or Docker Desktop uses the Hyper-V backend.Add the reservation from GPU inside Docker⁠, install the driver and the toolkit, and enable the WSL2 based engine.

The scan command exits with code 0 when every document was indexed, 2 when the report holds a problem, and 1 on a fatal error.

⁠License

MIT

Tag summary
Recent tags
Content type
Image
Digest
sha256:bfbea5bba…
Size
4.1 GB
Last updated
7 days ago
docker pull dmeric/docs-to-ai:latest