Skip to main content
Glama
doc-extract-mcp

doc-extract-mcp

doc-extract-mcp

An MCP (Model Context Protocol) server that gives an LLM deterministic document tooling for structured-data extraction workflows. The LLM does the reading and extraction reasoning; this server provides the parts that should never be left to a language model: reliable file access, parsing, chunking, JSON Schema validation, and guarded file output.

Built by Koray Nar as a portfolio project for the AI document-automation workflows he is building — the target use case is turning messy PDFs (purchase orders, invoices, reports) into schema-validated JSON. Published as part of a public portfolio. Pairs with Claude Code and Claude Desktop, and with any other MCP client.

Why

An extraction agent fails in predictable places: it hallucinates file contents, loses track of long documents, silently produces JSON that almost matches the target schema, and writes output wherever it likes. This server removes those failure modes:

  • File access is confined to one allowed root (DOC_EXTRACT_ROOT).

  • PDF text arrives with explicit --- page N --- markers, so citations of "page 3" mean page 3.

  • Long documents are chunked deterministically with overlap and page hints.

  • Extracted JSON is checked against a JSON Schema (Draft 2020-12) and every error is reported with a JSON Pointer path — not just the first — so the model can fix all mistakes in one pass.

  • Output is written by the server (JSON or CSV), inside the same root, with a verifiable row/byte count.

Related MCP server: file-analyzer

Tools

Tool

Arguments

What it does

list_documents

directory, glob_pattern='*'

List files under a directory inside the allowed root, with size and modified time. Supports recursive globs like **/*.pdf. Patterns must be relative and free of ..; matches resolving outside the root are dropped.

read_document

path, pages=''

Return a document's text. .pdf via pypdf with --- page N --- markers and optional 1-indexed page selection ('3', '1-5', '1-3,7'); .txt/.md/.json read directly; .csv rendered as an aligned text table. Clear error for unsupported types.

document_info

path

Metadata without full content: type, size, modified time; page count and PDF metadata for PDFs; line count for text files.

chunk_document

path, max_chars=4000, overlap=200

Split a document into ordered overlapping chunks, each with an index, start offset, and (for PDFs) a page hint.

validate_json

data, json_schema

Validate a JSON string against a JSON Schema (Draft 2020-12). Returns every validation error with a JSON Pointer path via Draft202012Validator.iter_errors.

save_structured

path, data, format='json'|'csv'

Write extracted data inside the allowed root. CSV expects a JSON array of flat objects. Returns written path, row count, and byte count.

All path arguments are resolved and refused if they escape the allowed root (path traversal guard). The glob_pattern argument is confined the same way: absolute patterns and patterns containing .. are rejected, and any match that resolves outside the root (for example through a symlink) is silently dropped from the listing. Guard failures are raised as MCP tool errors, so the calling model sees the actual reason, not a masked generic error.

Quickstart

Requires Python 3.11+ and uv.

git clone https://github.com/koraynar/doc-extract-mcp.git
cd doc-extract-mcp
uv venv
uv pip install -e .

Run standalone (stdio transport):

DOC_EXTRACT_ROOT=/path/to/your/documents uv run doc-extract-mcp

Claude Code

claude mcp add doc-extract --env DOC_EXTRACT_ROOT=/path/to/your/documents \
  -- uv run --directory /absolute/path/to/doc-extract-mcp doc-extract-mcp

Claude Desktop

Add to claude_desktop_config.json:

{
  "mcpServers": {
    "doc-extract": {
      "command": "uv",
      "args": [
        "run",
        "--directory",
        "/absolute/path/to/doc-extract-mcp",
        "doc-extract-mcp"
      ],
      "env": {
        "DOC_EXTRACT_ROOT": "/path/to/your/documents"
      }
    }
  }
}

DOC_EXTRACT_ROOT defaults to the server's working directory if unset. Set it to the folder your documents live in; nothing outside it can be read or written.

Typical workflow

  1. list_documents(".", "*.pdf") — find the invoices.

  2. document_info("invoice.pdf") — check the page count.

  3. read_document("invoice.pdf", "1-3") or chunk_document(...) — get text.

  4. The LLM extracts fields into JSON.

  5. validate_json(data, json_schema) — fix every reported error, revalidate.

  6. save_structured("out/invoice.json", data, "json") — write the result.

Limitations (honest ones)

  • Text-based PDFs only. Extraction uses pypdf; scanned/image-only PDFs yield empty text. There is no OCR.

  • Extraction quality varies with how the PDF was produced. Complex layouts (multi-column, heavy tables) may come out with imperfect reading order — that is a pypdf characteristic this server inherits.

  • No .docx / .xlsx support. Supported types are .pdf, .txt, .md, .csv, .json.

  • The server does no extraction reasoning. It will not find your invoice total; it makes sure the model that does is working from real text and that the result matches your schema.

  • This is a working tool, built for the AI-automation work I'm building up and published as part of my portfolio — it is new and has no production mileage yet. It has tests and a path-confinement guard, but it has not been hardened beyond that — review before pointing it at sensitive directories.

Development

uv venv
uv pip install -e '.[dev]'
uv run pytest

The test suite builds a small two-page PDF fixture in-memory (a minimal hand-constructed PDF, no extra dependencies) and covers all six tools, the path-traversal guard, glob-pattern confinement (including symlink escapes), page-range errors, multi-error schema validation, a CSV round-trip, and tool registration plus error propagation through the MCP server object.

License

MIT © 2026 Koray Nar

Available Tools

6 tools
chunk_documentA

Split a document's text into ordered, overlapping chunks.

Useful for long documents that do not fit one context read. For PDFs the text keeps its '--- page N ---' markers and each chunk carries a 'page_hint' (the page active at the start of the chunk); for other types 'page_hint' is null.

Args: path: File path inside the allowed root. max_chars: Maximum characters per chunk (default 4000). overlap: Characters repeated between consecutive chunks (default 200, must be smaller than max_chars).

Returns a list of {index, start_char, page_hint, text} in document order.

Inputs: path (required), overlap, max_chars. Returns: result

document_infoA

Return metadata for a document without reading its full content.

Includes file type, size, and modification time; page count and PDF metadata for PDFs; line count for text-based files.

Args: path: File path inside the allowed root.

Inputs: path (required). Returns: object

list_documentsA

List files in a directory inside the allowed root.

Args: directory: Directory path, relative to the allowed root (use '.' for the root itself) or absolute but inside it. glob_pattern: Filename filter, e.g. '.pdf' or '**/.csv' for recursive matching. Defaults to '*'. Must be relative and must not contain '..'; matching never leaves the allowed root.

Returns a list of {path, name, size_bytes, modified} entries; 'path' is relative to the allowed root and is what other tools accept.

Inputs: directory (required), glob_pattern. Returns: result

read_documentA

Read a document and return its text content.

Supports .pdf (extracted per page with '--- page N ---' markers), .txt / .md / .json (read directly), and .csv (rendered as an aligned text table). Other types return a clear error.

Args: path: File path inside the allowed root. pages: Optional 1-indexed page selection for PDFs, e.g. '3', '1-5', or '1-3,7'. Empty string means all pages.

Inputs: path (required), pages. Returns: result

save_structuredA

Write extracted data to a file inside the allowed root.

Args: path: Output file path inside the allowed root; parent directories are created as needed. data: The data to write, as a JSON string. For 'csv' it must be a JSON array of flat objects (no nested arrays/objects). format: 'json' (pretty-printed) or 'csv'.

Returns {path, format, rows, bytes}; 'rows' is the row count for csv or the element count when the JSON payload is an array, otherwise null.

Inputs: data (required), path (required), format. Returns: object

validate_jsonA

Validate a JSON string against a JSON Schema (Draft 2020-12).

Reports EVERY validation error with a JSON Pointer path, not just the first, so extraction mistakes can be fixed in one pass.

Args: data: The JSON document to validate, as a string. json_schema: The JSON Schema to validate against, as a string.

Returns {valid, error_count, errors:[{pointer, message, validator}]}; 'pointer' is a JSON Pointer into the data ('' means the document root).

Inputs: data (required), json_schema (required). Returns: object

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A4.4/5.0

    Scored across 6 tools

    Disambiguation5/5

    Each tool serves a distinct purpose: listing, reading, metadata, chunking, validation, and saving. No overlap; even read_document and chunk_document are clearly differentiated (full content vs. splitting for context). The separation is clean and unambiguous.

    Naming Consistency4/5

    Most tools follow a consistent verb_noun pattern (list_documents, read_document, chunk_document, validate_json, save_structured). The exception is document_info, which uses a noun_noun form instead of get_document_info, creating a minor deviation from the otherwise predictable scheme.

    Tool Count5/5

    Six tools is an appropriate, well-scoped count for a document extraction server. Each tool covers a necessary step in the extraction workflow without redundancy or bloat.

    Completeness5/5

    The tool set provides a complete lifecycle for document extraction: discovering files (list), retrieving content (read), obtaining metadata (info), handling long documents (chunk), validating structured output (validate), and persisting results (save). No obvious gaps; the scope is tightly defined and fully covered.

    Maintenance

    ActivityInactive
    ResponsivenessLimited data

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables reading entire PDF documents into validated structured JSON, including tables, key-values, and markdown, with read-only extraction tools and layout reconstruction.
      -
    • F
      license
      A
      quality
      D
      maintenance
      Enables read-only analysis of local unstructured documents by scanning a folder, extracting text and structural metadata, and passing content with truncation and error-awareness to an LLM for summarization.
      9
      1
      -
    • F
      license
      Not graded
      quality
      B
      maintenance
      Enables agents to deterministically extract structured entities from input payloads and validate or coerce them against JSON schemas, returning a standardized response dossier with execution telemetry. It runs as a zero-dependency MCP server that plugs into Claude Desktop, Cursor, and other MCP clients.
      8
      -