Skip to main content
Glama
MCP Document Processor

MCP Document Processor

Official
by leanzero-srl

MCP Document Processor

An MCP (Model Context Protocol) server for reading, creating, and managing PDF, DOCX, and Excel documents. Built for AI agents that need to process documents with professional styling, automatic categorization, and intelligent document management.

Part of the LeanZero ecosystem.

Features

  • Read any document -- PDF, DOCX, and Excel with OCR support for image-based PDFs

  • Create polished documents -- DOCX, Markdown, and Excel with 8 style presets (including a "claude-like" modern professional look), proper rendering of bullet/numbered lists, blockquotes, hyperlinks, code blocks, and tables embedded in markdown content

  • Generic read & upload bridges -- both read-doc and the create tools accept an HTTPS URL + Bearer auth so any Forge app, Cloudflare Worker, AWS Lambda, Express server, or other backend can plug in. doc-processor speaks one wire contract; you build the receiver however you like. CogniRunner's Jira-attachment bridge is the reference implementation, but the pattern is generic. Existing local-file callers are unaffected.

  • Polished or verbose output -- clientHint parameter lets host applications request a concise human-facing message or the full agent metadata response.

  • Document DNA -- project-level identity system that automatically applies styling, headers, and footers

  • Auto-categorization -- classifies documents into 6 categories (contracts, technical, business, legal, meeting, research) and organizes them into subfolders

  • Blueprint system -- structural templates extracted from existing documents or auto-learned from recurring patterns

  • Drift detection -- monitor documents for structural changes over time with fingerprint-based comparison

  • Lineage tracking -- automatic provenance chains that record which source documents informed each created document

  • Duplicate prevention -- atomic file locking and registry-based title matching to prevent overwrites

  • Document registry -- searchable index of all created documents with category, tag, and title filtering

Related MCP server: PDF Reader MCP Server

Tools

The server exposes 13 tools via the MCP protocol. Each tool uses an action or mode parameter for sub-operations where applicable.

Tool

Actions / Modes

Description

read-doc

summary, indepth, focused

Read and analyze PDF, DOCX, or Excel files. Summary gives an overview; indepth extracts full text and metadata; focused answers specific queries. Source can be a local filePath OR a remote url + authHeader -- see Reading from remote URLs.

detect-format

--

Recommend document format and tone (markdown / docx / excel) based on user query, title, and optional content preview. Call before create-* when the format is not specified.

create-doc

--

Create a Word DOCX with paragraphs, tables, headers, footers, and styling. Supports dry run preview.

create-markdown

--

Create a Markdown document.

create-excel

--

Create an Excel XLSX workbook with multiple sheets and styling.

edit-doc

append, replace

Edit existing DOCX files. Append preserves formatting via XML patching; replace overwrites content.

edit-excel

append-rows, append-sheet, replace-sheet

Edit existing Excel workbooks.

list-documents

--

Search and filter the document registry by category, tags, or title.

list-templates

--

List available blueprint templates that create-doc can validate against.

dna

init, get, evolve, save-memory, delete-memory

Manage Document DNA -- the project's automatic styling and identity system.

blueprint

learn, list, delete

Manage structural blueprints. Auto-learned during dna evolve or manually extracted from existing documents.

drift-monitor

watch, check

Register documents for monitoring and detect structural changes over time.

get-lineage

--

Trace the provenance chain for any document -- which sources informed it and what was derived from it.

Note: All old tool names from previous versions (get-doc-summary, get-doc-indepth, get-doc-focused, init-dna, get-dna, evolve-dna, save-memory, delete-memory, learn-blueprint, list-blueprints, watch-document, check-drift, search-registry) are accepted as backward-compatible aliases.

Polished output for human-facing UIs (clientHint)

create-doc, create-markdown, and create-excel accept an optional clientHint parameter:

  • "interactive" → response message is a single line (Created: <path>); chatty fields like enforcement, styleConfig, lineage, memoriesApplied are omitted. Use this when an end-user reads the response directly (e.g. CogniRunner showing the result in a Jira comment).

  • "agent" → verbose response with all metadata for AI consumption. This is the default behaviour.

  • "auto" → run a heuristic on the input shape, fall back to MCP_CLIENT_TYPE env var, then to "agent".

Set MCP_CLIENT_TYPE=interactive in the MCP server's environment to make "auto" resolve to interactive across all calls.

Generic remote-read bridge — read files from any authenticated endpoint

read-doc works on local files OR on a remote HTTPS URL guarded by a Bearer header. The remote shape is the mirror image of the upload bridge below — same wire contract, same security guarantees, same generic philosophy. doc-processor doesn't care what's on the other side; any HTTPS endpoint that returns the JSON envelope works.

Reference implementation: CogniRunner — Forge web trigger that exposes Jira attachments to local LM Studio inference, behind a one-shot capability. Use it as a template for your own bridge.

Decision: when does it activate?

The remote-read path fires if and only if BOTH url and authHeader are passed (and filePath is not). Otherwise read-doc works on the local path as before. Existing local-file callers are 100% unaffected.

Calling shape

{
  "url": "https://your-receiver.example/attachments/123?t=<token>",
  "authHeader": "Bearer <bearer>",
  "mode": "summary"
}

Wire contract

The endpoint is expected to return HTTP 200 with Content-Type: application/json and a body of:

{
  "data":     "<base64-encoded file content>",
  "filename": "invoice.pdf",
  "mimeType": "application/pdf",
  "size":     256832
}

read-doc decodes the base64 payload, writes it to a unique per-call temp directory under os.tmpdir(), runs the existing PDF/DOCX/XLSX extraction pipeline, and cleans up the temp dir afterward (even if the pipeline throws).

Security guarantees

Same as the upload bridge — see the next section for the full list. In short:

  • HTTPS only, no redirects, no auto-retry on 4xx, auth header never logged, URL token redacted in logs, 30-second timeout, payload size capped by READ_DOC_MAX_BYTES (default 50 MB).

Build your own remote-read source

It's the inverse of the upload receiver, so the same Forge / Express skeletons in the next section apply. For Forge, instead of POSTing to /rest/api/3/issue/{key}/attachments, GET from /rest/api/3/attachment/content/{id} and base64-encode the response into the JSON envelope shape above. The CogniRunner repo has the full pattern.

mcp.json example

{
  "mcpServers": {
    "doc-processor": {
      "command": "node",
      "args": ["/absolute/path/to/mcp-doc-processor/src/index.js"],
      "env": {
        "READ_DOC_MAX_BYTES": "52428800",
        "WRITE_DOC_MAX_BYTES": "26214400",
        "MCP_CLIENT_TYPE": "agent"
      }
    }
  }
}

The application that hosts the model (CogniRunner, your own Forge app, Claude Desktop with extra context, an internal post-function, etc.) injects the per-call url/authHeader for read OR uploadUrl/uploadAuthHeader for write into the model's prompt. doc-processor never sees the application — it just speaks the wire contract.

Generic upload bridge — attach files to any authenticated endpoint

create-doc, create-markdown, and create-excel can OPTIONALLY upload the file they just wrote to any HTTPS endpoint that implements a small, well-defined contract. Use this to:

  • Attach a generated document to a Jira issue (Atlassian Forge)

  • Drop a generated workbook into a Slack channel via a Slack-bot lambda

  • Push a generated markdown file to a GitHub issue via a tiny proxy

  • Send a generated PDF to a Cloudflare R2 / S3 signed-URL receiver

  • Hook into your internal document-management system

doc-processor doesn't know or care what's on the other side. It just speaks one well-defined wire contract; you build the receiver however you like.

Reference implementation: CogniRunner — a Forge app that exposes a per-issue, single-use upload capability so an LM Studio model can attach generated docs back to Jira tickets. The CogniRunner web trigger is ~150 lines and worth reading if you're building your own receiver.

Decision: when does it activate?

The upload bridge fires if and only if BOTH uploadUrl and uploadAuthHeader are present in the call. Otherwise the tool behaves exactly as before — writes the file locally, returns the path, no upload-related fields in the response. Existing callers and "normal" agent flows are 100% unaffected.

Caller passes

Behavior

Neither uploadUrl nor uploadAuthHeader

Local write only. Response has no upload-related fields. (default)

Both

Local write then upload. Response gains uploaded, uploadAttachment, uploadStatus, uploadError.

Only one

Local write succeeds. Response has uploaded: false, uploadError: "uploadUrl and uploadAuthHeader must be provided together". fetch is never called.

The model decides per-call. If your application injects upload credentials into the model's context (system prompt or per-tool extra args), the model uses them. If you don't, the model ignores those fields — there's nothing for it to fill in.

Wire contract

Request (doc-processor → your receiver)

POST <uploadUrl>
Authorization: <uploadAuthHeader>
Content-Type: application/json
Accept: application/json

{
  "data":     "<base64-encoded file bytes>",
  "filename": "q1-2026-strategy.docx",
  "mimeType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  "size":     27834
}

Success response (your receiver → doc-processor)

HTTP 200, Content-Type: application/json:

{
  "success": true,
  "attachment": {
    "id":       "<your-target-id>",
    "filename": "q1-2026-strategy.docx",
    "size":     27834,
    "mimeType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "content":  "<URL or pointer the user can use to access the uploaded file>"
  }
}

The attachment.content field is what gets shown in the model's interactive-mode response message — it should be a usable URL (e.g. the Jira attachment content URL) so end-users get a working link.

doc-processor tolerates any 2xx JSON shape — if attachment is missing it uses the whole body, but the strict shape above is recommended.

Failure responses

doc-processor surfaces these verbatim as uploadError and does not auto-retry:

Status

Meaning

400

malformed envelope

401

bearer mismatch

404

token expired / consumed (single-use)

413

payload too large for receiver

415

disallowed mimeType / extension

502

receiver's upstream (e.g. Jira) failed

500

unexpected receiver error

Receivers MUST NOT respond with 3xx — fetch is configured with redirect: "error" and aborts on any redirect.

Security guarantees the SENDER (doc-processor) provides

  • HTTPS only. Non-https:// URLs are rejected before fetch is called.

  • No redirects. redirect: "error" — receiver must respond directly.

  • No auto-retry on any 4xx/5xx. Single-use semantics are honored end-to-end.

  • uploadAuthHeader is never logged at any level.

  • URL ?t= token is redacted in log output — only host+path are emitted.

  • No caching. Bytes, URL, auth header live only for the duration of one call.

  • Bounded payload size. Capped by WRITE_DOC_MAX_BYTES env var (default 25 MB).

  • 60-second timeout on the upload fetch.

  • Local file is kept on upload failure — your caller can retry or fall back to the local path.

  • Hosted server: a confirmed upload removes the server copy (the receiver holds the file). The response then has serverCopyRemoved: true and no downloadUrl, so a key that delivers every document never fills its workspace quota. A failed upload keeps the copy; stdio never removes anything.

What your RECEIVER should provide

  • HTTPS endpoint with a valid certificate.

  • One-shot capability semantics if you're using URL+bearer pairs (mint per request, store with TTL, delete-on-consume, constant-time bearer compare).

  • Don't 3xx — return 4xx/5xx with a JSON body.

  • Validate filename extension on the receiver side; don't trust the envelope's mimeType field as authoritative.

  • Audit-log the upload event (caller, target, filename, bytes).

Build your own receiver

Atlassian Forge web trigger (the CogniRunner pattern)

Receives the JSON envelope, validates a one-shot capability, forwards to Jira's attachment endpoint via api.asApp().requestJira(). Skeleton (~50 lines):

import api, { route } from "@forge/api";
import storage from "@forge/kvs";
import FormData from "form-data";
import { timingSafeEqual } from "node:crypto";

export async function serveAttachmentUpload(request) {
  const token = request.queryParameters?.t?.[0];
  if (!token) return { statusCode: 404, body: "" };

  const auth = request.headers?.authorization?.[0] || "";
  if (!auth.startsWith("Bearer ")) return { statusCode: 401, body: "" };
  const bearer = auth.slice(7);

  const cap = await storage.get(`uploadcap:${token}`);
  await storage.delete(`uploadcap:${token}`);   // single-use: consume BEFORE any work
  if (!cap || cap.expiresAt < Date.now()) return { statusCode: 404, body: "" };

  const a = Buffer.from(cap.bearer, "utf8");
  const b = Buffer.from(bearer, "utf8");
  if (a.length !== b.length || !timingSafeEqual(a, b)) return { statusCode: 401, body: "" };

  const envelope = JSON.parse(request.body);
  if (typeof envelope.data !== "string") return { statusCode: 400, body: '{"error":"missing data"}' };

  const buf = Buffer.from(envelope.data, "base64");
  if (buf.length > 25 * 1024 * 1024) return { statusCode: 413, body: "" };

  const allowed = new Set([".pdf", ".docx", ".xlsx", ".md", ".txt", ".csv"]);
  const ext = (envelope.filename.match(/\.[^.]+$/) || [""])[0].toLowerCase();
  if (!allowed.has(ext)) return { statusCode: 415, body: "" };

  const form = new FormData();
  form.append("file", buf, { filename: envelope.filename, contentType: envelope.mimeType, knownLength: buf.length });

  const jiraResp = await api.asApp().requestJira(
    route`/rest/api/3/issue/${cap.issueKey}/attachments`,
    { method: "POST", body: form, headers: { Accept: "application/json", "X-Atlassian-Token": "no-check" } },
  );
  if (!jiraResp.ok) return { statusCode: 502, body: '{"error":"jira upstream failed"}' };

  const created = (await jiraResp.json())[0];
  return {
    statusCode: 200,
    headers: { "Content-Type": ["application/json"] },
    body: JSON.stringify({
      success: true,
      attachment: {
        id: created.id,
        filename: created.filename,
        size: created.size,
        mimeType: created.mimeType,
        content: created.content,
      },
    }),
  };
}

Express server (for local testing or non-Forge use cases)

import express from "express";
import { randomUUID } from "node:crypto";

const app = express();
app.use(express.json({ limit: "30mb" }));

const TOKEN = "test-token-123";
const BEARER = "Bearer test-bearer-456";

app.post("/upload", (req, res) => {
  if (req.query.t !== TOKEN) return res.status(404).end();
  if (req.headers.authorization !== BEARER) return res.status(401).end();

  const { data, filename, mimeType, size } = req.body;
  if (!data) return res.status(400).json({ error: "missing data" });

  const buf = Buffer.from(data, "base64");
  if (buf.length > 25 * 1024 * 1024) return res.status(413).end();

  // Persist the file or forward it somewhere — your call.
  console.log(`Received ${filename} (${mimeType}, ${size} bytes)`);

  res.json({
    success: true,
    attachment: {
      id: randomUUID(),
      filename,
      size: buf.length,
      mimeType,
      content: `https://your-storage.example/files/${filename}`,
    },
  });
});

app.listen(8443);

(For production, terminate TLS in front via a real cert — doc-processor refuses non-HTTPS.)

Calling shape (what you put in the model's tool args)

{
  "title": "Q1 2026 Engineering Strategy",
  "paragraphs": ["..."],
  "uploadUrl": "https://your-receiver.example/upload?t=<one-shot-token>",
  "uploadAuthHeader": "Bearer <one-shot-bearer>",
  "uploadFilename": "q1-2026-strategy.docx",
  "clientHint": "interactive"
}

The uploadFilename is optional and overrides the default (the local file's basename). Useful when duplicate prevention auto-suffixes the local filename and you still want a clean name on the receiver side.

Response shape (when upload was attempted)

The handler appends four fields to its normal response only when an upload was attempted (when both upload params were supplied). For "normal" agent calls without upload params, none of these fields appear.

Field

Type

Description

uploaded

boolean

true if 2xx, false if any error path

uploadAttachment

object | null

Whatever the receiver returned in attachment

uploadStatus

number | null

HTTP status code from the receiver

uploadError

string | null

Error message if the upload failed

In clientHint: "interactive" mode the response message collapses to one line:

  • Success: Created and uploaded: <path> → <attachment-content-url>

  • Failure: Created locally at <path>; upload failed: <error>

Quick Start

Installation

npm install

MCP Configuration

Add to your MCP client configuration (e.g., mcp.json, cline_mcp_settings.json, or equivalent):

{
  "mcpServers": {
    "doc-processor": {
      "command": "node",
      "args": ["/absolute/path/to/mcp-doc-processor/src/index.js"],
      "env": {}
    }
  }
}

With Vision OCR (cloud)

{
  "mcpServers": {
    "doc-processor": {
      "command": "node",
      "args": ["/absolute/path/to/mcp-doc-processor/src/index.js"],
      "env": {
        "Z_AI_API_KEY": "your-api-key"
      }
    }
  }
}

Running

npm start

The server communicates over stdio using the MCP JSON-RPC protocol. It is designed to be launched by an MCP client, not run interactively.

Style Presets

Eight built-in presets control document typography, spacing, and table formatting. The default for general-purpose create-doc calls is claude-like.

Preset

Font

Body Size

Key Traits

claude-like

Calibri

11pt

Default. Modern blue accents, generous whitespace, proper bullet/numbered lists, blockquotes, hyperlinks, inline tables — looks like a polished Claude chat answer rendered as a document

minimal

Arial

11pt

Clean, Swiss-style, subtle borders, light zebra striping

professional

Garamond

11pt

Serif, justified, small caps title, double-spaced headings

technical

Arial / Segoe UI

11pt

Left-aligned, strong hierarchy, high-contrast tables

legal

Times New Roman

12pt

Double-spaced, underlined headings, no decorative elements

business

Calibri / Calibri Light

11pt

Blue accent palette, centered title with bottom border

casual

Verdana / Trebuchet MS

12pt

Warm orange accents, friendly newsletter style

colorful

Segoe UI

11pt

Purple-teal gradient accents, vibrant table headers

Categories auto-select an appropriate preset when none is specified:

Category

Auto-Selected Preset

contracts

legal

legal

legal

technical

technical

business

business

meeting

professional

research

professional

Enhanced Styling System

The enhanced styling system provides advanced typography and formatting capabilities through the src/tools/styling.js module:

Color Constants

The system includes 20+ named color constants for consistent styling:

Color Name

Hex Code

Usage

WHITE

FFFFFF

Backgrounds, primary text

BLACK

1A1A1A

Primary text, dark elements

BLUE

2563EB

Primary accent, links

GREEN

22C55E

Success states, positive indicators

RED

EF4444

Error states, warnings

YELLOW

EAB308

Highlights, attention

ORANGE

F97316

Warm accents

PURPLE

A855F7

Creative accents

TEAL

14B8A6

Secondary accents

INDIGO

6366F1

Professional accents

GRAY_50

F9FAFB

Light backgrounds

GRAY_100

F3F4F6

Subtle backgrounds

GRAY_200

E5E7EB

Borders, dividers

GRAY_300

D1D5DB

Light borders

GRAY_400

9CA3AF

Secondary text

GRAY_500

6B7280

Tertiary text

GRAY_600

4B5563

Secondary content

GRAY_700

374151

Primary content

GRAY_800

1F2937

Dark content

GRAY_900

111827

Darkest elements

Page Layout Helpers

Helper

Purpose

PAGE_WIDTH

Standard page width in inches (8.5")

CONTENT_WIDTH

Content area width (6.5")

MARGIN_TOP

Top margin (1")

MARGIN_BOTTOM

Bottom margin (1")

MARGIN_LEFT

Left margin (1")

MARGIN_RIGHT

Right margin (1")

Heading Helpers

Helper

Purpose

heading1(text)

Main document title (Heading 1 style)

heading2(text)

Section headings (Heading 2 style)

heading3(text)

Subsection headings (Heading 3 style)

Text Formatting Helpers

Helper

Purpose

para(text)

Standard paragraph

bold(text)

Bold text

normal(text)

Normal text with optional styling

spacer(height)

Vertical spacing

divider()

Horizontal rule

List Helpers

Helper

Purpose

bulletItem(text)

Bullet list item

subBulletItem(text)

Nested bullet list item

Table Helpers

Helper

Purpose

infoTable(data)

Information table with professional styling

gapTable(data)

Table with spacing between rows

statusBadge(text, status)

Status indicator badge

Page Setup Helpers

Helper

Purpose

createHeader(text, alignment)

Document header

createFooter(text, alignment)

Document footer

createPageProperties()

Page layout properties

Document DNA

Document DNA (.document-dna.json) is a project-level configuration file that automatically applies consistent styling across all documents created by this server.

How It Works

  1. Initialize -- Run dna with action init to create the DNA file with your company name, preferred style, header, and footer defaults.

  2. Automatic application -- Every create-doc call checks for DNA and applies its defaults for any fields not explicitly provided (header, footer, style preset).

  3. Usage tracking -- Each document creation records the category, style, and any overrides to build a usage profile.

  4. Evolve -- Run dna with action evolve to analyze usage patterns. The system suggests mutations when it detects strong trends (e.g., "80% of your documents use the business preset"). Use apply: true to auto-apply the top suggestion.

  5. Auto-learned blueprints -- During evolution, recurring document structures are detected and saved as blueprints automatically. Future documents with matching patterns get a blueprintMatch suggestion in the response.

Memory System

Use dna with action save-memory to store document preferences (e.g., "Always use 1-inch margins for contracts"). Memories persist in the DNA file and are available to AI agents for context.

Inheritance

DNA supports three-level inheritance: System defaults (hardcoded) < Project DNA (.document-dna.json) < User DNA (.document-user.json). Missing fields fall through to the next level.

Environment Variables

Variable

Default

Description

Z_AI_API_KEY

--

API key for vision OCR service (also checks ZAI_API_KEY, ANTHROPIC_AUTH_TOKEN)

Z_AI_BASE_URL

Auto-detect

Override base URL for vision API

Z_AI_VISION_MODEL

glm-4.6v

Vision model name

Z_AI_TIMEOUT

300000

Request timeout in milliseconds

SKIP_TABLE_EXTRACTION

true

Skip table extraction from images during PDF processing

READ_DOC_MAX_BYTES

52428800 (50 MB)

Maximum decoded payload size accepted by the read-doc URL-fetch path. Requests with larger bodies are rejected before the file is materialized.

WRITE_DOC_MAX_BYTES

26214400 (25 MB)

Maximum file size the create-* tools will POST to a remote uploadUrl. Half of the read cap because Forge web trigger payload limits are tighter.

Workspace confinement (hosted HTTP server)

Every API key used against the hosted HTTP server (node src/server.js) works inside its own workspace directory, <DATA_DIR>/workspaces/<key id>/:

  • Paths. filePath and outputPath on every tool must resolve, after symlink resolution, inside that workspace. Relative paths resolve against it. Absolute paths elsewhere, .. segments, ~, file:// and symlinks that point outside are refused with a ... not allowed: ... error. The filePath values returned by earlier calls always work. X-Output-Dir names a sub-folder of the workspace (.. and ~ are refused with HTTP 400).

  • State. The document registry (list-documents), the drift watchlist (drift-monitor without a path), lineage, Document DNA and learned blueprints are stored in the workspace, so a key only ever sees and changes its own entries.

  • URLs. read-doc url, uploadUrl and fact-check webSearchUrl must be https:// and must not resolve to a loopback, private, link-local or CGNAT address; redirects are refused. The address is checked again at connect time on the connection that is actually used (a pinned, guarded DNS lookup), so a hostile DNS server cannot answer "public" for the check and "127.0.0.1" for the fetch. create-pdf renders without page JavaScript; its https:// sub-resources are fetched by the server over the same pinned connection and handed to Chromium (Chromium never resolves them itself), and only data: and public https:// sub-resources load.

  • Revoked keys. Revoking a key (admin or /v1/provision DELETE) moves its workspace to <DATA_DIR>/revoked-workspaces/<key id>--<epoch ms>/ at once; it is deleted after REVOKED_WORKSPACE_RETENTION_DAYS (default 7, 0 = straight away), swept on every revoke and every 6 hours.

  • Disk cap. Each workspace is capped at WORKSPACE_QUOTA_MB (default 100). A key at or over its cap gets Workspace full: ... from every tool that can write; reading and listing tools keep working.

  • Audit. Each key's lastUsedAt is updated (at most once a minute) and every tool call logs one metadata line: tool_call {tenant, tool, workspace: inside|outside, result: ok|error|refused, ms}. Document contents, paths and URLs are never logged.

The admin token only manages keys (/v1/admin, localhost only); it does not grant wider file access. The stdio transport (npm start) has no key and no workspace: it runs as the local user, on the local user's files, exactly as before. Guarded by npm run test:confinement, test:rebinding and test:lifecycle.

Testing

npm test                    # Markdown format router (custom-assert)
npm run test:read-doc       # read-doc URL-fetch — 14 tests (node:test)
npm run test:schemas        # MCP schema invariants + detect-format E2E — 6 tests (node:test)
npm run test:render         # parseMarkdownToDocx + create-doc round-trip — 15 tests (node:test)
npm run test:upload         # uploadFileToTarget + create-doc upload integration — 18 tests (node:test)
npm run test:confinement    # hosted-key workspace confinement, isolation and SSRF guards — 26 tests (node:test)
npm run test:rebinding      # DNS rebinding: check and fetch use one resolution (stub resolver, loopback canary)
npm run test:lifecycle      # revoked-key workspace archive/retention + per-key disk cap
npm run test:pdf            # pdf-parse regression on a generated PDF (test/fixtures/make-pdf.js)
npm run test:all            # Run every suite in sequence
npm run lint:no-console-log # Fail if any src/ file uses console.log (corrupts MCP stdio)

Generated Files

The server generates several configuration and data files:

.document-dna.json

Document DNA configuration file that stores:

  • Project-level styling defaults (style preset, category, header/footer)

  • Usage statistics (categories, styles, document counts)

  • Memory system (saved document preferences)

  • Auto-learned document structures

This file is automatically managed by the dna tool and should not be manually edited.

.document-blueprints.json

Blueprint repository that stores:

  • Extracted document structures

  • Section patterns and requirements

  • Style preset associations

  • Creation timestamps

Blueprints are created via blueprint action:'learn' or auto-learned during dna evolve.

docs/registry.json

Document registry containing:

  • All created documents with metadata

  • Category, tags, and descriptions

  • Lineage tracking information

  • Timestamps for creation and updates

.document-user.json (optional)

User-level DNA that inherits from project DNA. Allows personal overrides without affecting team settings.

Architecture

mcp-doc-processor/
  src/
    index.js                 # MCP server entry, tool definitions, dispatch
    tools/                   # Tool handlers (one file per tool)
    services/                # Business logic (lineage, drift, blueprints, OCR)
    parsers/                 # File-type parsers (PDF, DOCX, Excel)
    utils/                   # Shared utilities (logger, registry, DNA, categorizer)
  docs/                      # Generated documents (organized by category)
  test/                      # Test suites
  logs/                      # Server logs
  .document-dna.json         # Document DNA configuration
  .document-blueprints.json  # Blueprint repository
  docs/registry.json         # Document registry
  .document-user.json        # Optional user-level DNA

Dependencies

Package

Purpose

@modelcontextprotocol/sdk

MCP server SDK

docx

DOCX generation

jszip

ZIP/DOCX XML manipulation

mammoth

DOCX text extraction

marked

Markdown tokenization for inline formatting

pdf-parse

PDF text extraction

xlsx

Excel reading

xlsx-js-style

Excel writing with styling

License

See LICENSE for details.

Available Tools

17 tools
blueprintA

Manage structural blueprints — section/heading templates extracted from real documents. Actions: 'learn' (extract from a DOCX or PDF you already have), 'list' (show stored blueprints), 'delete' (remove by name). Blueprints are also auto-learned during 'dna evolve' when recurring structures are detected. Use a blueprint by passing { blueprint: '' } to create-doc — the tool will validate that your paragraphs match the structure.

Inputs: action (required), name, filePath, description.

create-docA

Create a styled, EDITABLE Word DOCX. USE for stakeholder/business/legal/research deliverables the user will keep editing in Word, or when they say 'Word / .docx / editable / draft / template'. NOT for: a final/print/send-as-PDF deliverable (→ create-pdf), code/API/README docs (→ create-markdown), or tabular/numeric data (→ create-excel). The most full-featured tool: Document DNA defaults, 8 style presets, headers/footers with page numbers, margins, blueprint validation, and real tables. ALWAYS format the body with markdown — never a wall of plain text. Simplest: put the whole body in the content string. Supported markdown: '# H1' '## H2' '### H3' headings; 'bold'; 'italic'; 'code'; '- ' or '1. ' lists; '> ' blockquotes; '---' horizontal rule; fenced code blocks; '| a | b |' GitHub tables (with a '|---|---|' separator row); 'text' links. EXAMPLE content: "## Overview\nThis report covers Q2 results.\n\n### Highlights\n- Revenue up 18%\n- Two new markets\n\n| Metric | Value |\n|---|---|\n| MRR | $42k |\n| Churn | 1.2% |\n\n> Next review: July." Title MUST be specific. Duplicate → { duplicate: true, existingPath } (switch to edit-doc). Response includes formattingQuality and formatSuggestion — if formatSuggestion is set, the content fits another format better, so heed it. Use dryRun: true for preview.

Inputs: title (required), tags, style, dryRun, +20 more.

create-excelA

Create a styled Excel XLSX (or CSV). USE for ANY tabular/numeric data — budgets, trackers, datasets, KPIs, price lists, schedules; even a table inside a 'report' belongs here, not in a doc. EXCEL SUPERPOWERS: a cell whose string starts with '=' becomes a LIVE formula (e.g. "=SUM(B2:B9)", "=B2C2") that Excel computes on open; columns whose header looks like money ($/price/cost/revenue) or percent (%) auto-format; the header row gets autofilter dropdowns; columns auto-fit. The first row of each sheet is the header (auto-styled bold/filled), body rows get zebra striping — you only supply values. Set outputFormat: "csv" for a plain CSV (first sheet only; no styling/formulas). EXAMPLE: sheets: [{ name: "Q2 Revenue", data: [["Month","Units","Price","Revenue"],["Apr",120,9.99,"=B2C2"],["Total","=SUM(B2:B2)","","=SUM(D2:D2)"]] }]. Sheet names MUST be specific (rejects 'Sheet1', 'Data', etc.). Use dryRun: true for preview.

Inputs: sheets (required), tags, style, title, +13 more.

create-markdownA

Create a Markdown (.md) file for technical/code content that lives in a repo. USE for READMEs, API docs, specs, runbooks, changelogs, integration guides, code-heavy content — anything for GitHub/developers. NOT for stakeholder-facing or printable deliverables (→ create-doc / create-pdf) or tabular data (→ create-excel). MARKDOWN SUPERPOWERS: set toc: true to auto-generate an anchor-linked Table of Contents from the H2/H3 headings; pass frontmatter: {...} to emit YAML frontmatter (title, date, tags[]) for static-site generators (Hugo/Jekyll/Astro). Simplest usage: put the whole body in the content string. Supported markdown: '# H1' '## H2' '### H3' headings; 'bold'; 'italic'; 'code'; '- ' or '1. ' lists; '> ' blockquotes; '---' horizontal rule; fenced code blocks; '| a | b |' GitHub tables (with a '|---|---|' separator row); 'text' links. The title becomes the H1, so start content at '## '. Title MUST be specific. Response includes formattingQuality. Use dryRun: true for preview.

Inputs: title (required), toc, tags, dryRun, +13 more.

create-pdfA

Create a FINAL, fixed-layout PDF to read / print / send / sign. USE when the user says PDF / print / 'send to the client' / official / invoice / flyer / resume / cover letter / 'read-only' / 'final version'. NOT for content they'll keep editing (→ create-doc) or code/repo docs (→ create-markdown). Rendered from markdown with the same 8 presets as create-doc, via headless Chromium. PDF SUPERPOWER: set toc: true for a clickable Table of Contents (with heading anchors) at the top. Supports headers/footers with {current}/{total} page numbers and margins. ALWAYS format the body with markdown. Easiest: put the whole body in the content string. Supported markdown: '# H1' '## H2' '### H3' headings; 'bold'; 'italic'; 'code'; '- ' or '1. ' lists; '> ' blockquotes; '---' horizontal rule; fenced code blocks; '| a | b |' GitHub tables (with a '|---|---|' separator row); 'text' links. EXAMPLE content: "## Overview\nThis report covers Q2 results.\n\n### Highlights\n- Revenue up 18%\n- Two new markets\n\n| Metric | Value |\n|---|---|\n| MRR | $42k |\n| Churn | 1.2% |\n\n> Next review: July." Title MUST be specific. Response includes formattingQuality and formatSuggestion. Use dryRun: true for preview. (To READ a PDF, use read-doc.)

Inputs: title (required), toc, tags, style, +18 more.

create-pptxA

Create an EDITABLE PowerPoint presentation (.pptx) you can open in PowerPoint / Keynote / Google Slides. USE when the user asks for slides / a deck / a presentation / a pitch deck / 'powerpoint' / 'keynote'. NOT for a flowing document (→ create-doc / create-pdf), code/repo docs (→ create-markdown), or pure tabular data (→ create-excel). SLIDE STRUCTURE: the title becomes a centered title slide; EACH '## ' heading starts a NEW slide whose body is the markdown beneath it. Inside a slide, '### ' is a sub-heading, '- '/'1. ' are bullets, '| a | b |' GitHub tables render as native slide tables, a chart fenced block (first line 'type: bar|column|line|pie|doughnut|area', optional 'title:', then a markdown table whose first column is the category and each other column is a data series) becomes a NATIVE editable chart, and fenced code blocks render as monospace. Keep each slide focused — a few bullets, not a wall of text. Styled from the same 8 presets as create-doc (colors/fonts map onto the slides). Supported markdown: '# H1' '## H2' '### H3' headings; 'bold'; 'italic'; 'code'; '- ' or '1. ' lists; '> ' blockquotes; '---' horizontal rule; fenced code blocks; '| a | b |' GitHub tables (with a '|---|---|' separator row); 'text' links. EXAMPLE content: "## Problem\n- Manual steps are slow\n- Errors slip through\n\n## Our Solution\n- One-click automation\n- Built-in checks\n\n## Results\n| Metric | Before | After |\n|---|---|---|\n| Time | 2h | 5m |". Title MUST be specific. Use dryRun: true to preview the slide breakdown. (To make a fixed, non-editable deck use create-pdf instead.)

Inputs: title (required), tags, style, dryRun, +14 more.

detect-formatA

PLAN the best output format BEFORE creating. Call this FIRST whenever the user didn't explicitly name a format. It weighs explicit format words, what the user wants to DO with the file, topic, and content shape — then returns a ready-to-use creation plan. Nuance it captures: 'README / API / spec / for the repo' → markdown; 'budget / tracker / dataset / table' → excel (CSV if they say csv); 'editable / draft / template / in Word' → docx; 'print / send to the client / official / invoice / resume / final / sign' → PDF. DOCX = editable Word; PDF = final, fixed-layout, print/sign/send. Returns { format (markdown|docx|excel|pdf), suggestedTool, stylePreset, category, docType, confidence, reason, alternativeFormat, outputFormat? ('csv'), unsupported? ('pptx'), note? }. Pass these straight into the create-* tool. There is no native slides/PowerPoint tool yet — it recommends the closest fit (usually PDF) and flags unsupported:'pptx'.

Inputs: userQuery (required), title, content.

dnaA

Manage the project's Document DNA — header/footer/style defaults that auto-apply to every create-doc call. Actions: 'init' (one-time setup with companyName/header/footer/stylePreset), 'get' (current config + project profile), 'evolve' (analyze usage trends; with apply:true, MUTATES dna config and may auto-create blueprints — irreversible without manual cleanup), 'save-memory'/'delete-memory' (project-wide preferences keyed by string).

Inputs: action (required), key, apply, memory, +7 more.

drift-monitorA

Monitor documents for structural drift over time. Actions: 'watch' (compute and store a fingerprint = SHA-256 + heading tree + word counts; capped at 500 paragraphs), 'check' (compare current state against the stored baseline; reports word-count delta, added/removed headings, category shifts, and a similarity score). Omit filePath on 'check' to compare all watched documents.

Inputs: action (required), name, filePath.

edit-docA

Edit an existing DOCX. Actions: 'append' (XML-patches new content, PRESERVES original formatting/headers/footers/images), 'replace' (overwrites body but keeps section properties), 'style' (apply a stylePreset to existing paragraphs without changing text), 'preview' (show what would change). Always read-doc with mode 'indepth' first so you understand the existing structure.

Inputs: action (required), filePath (required), tags, style, +8 more.

edit-excelA

Edit an existing XLSX workbook. Actions: 'append-rows' (add rows to a sheet, preserves existing styles), 'append-sheet' (add a new sheet — fails if name exists), 'replace-sheet' (overwrite a sheet's data), 'preview' (show what would change). Use read-doc first if you don't know the sheet structure.

Inputs: action (required), filePath (required), rows, tags, +6 more.

edit-pptxA

Edit an existing PowerPoint (.pptx). Actions: 'preview' (show the current slide outline), 'append-slides' (add new slides from markdown — one '## ' heading per slide), 'replace-slide' (replace one content slide by 1-based index with new markdown). IMPORTANT: edit-pptx REBUILDS the deck from the existing slides' extracted TEXT + speaker notes, normalized to a style preset — charts, images, and exact original formatting on pre-existing slides are NOT preserved (best for the text/bullet decks create-pptx makes). To author a brand-new deck use create-pptx; to read a deck use read-doc.

Inputs: action (required), filePath (required), style, title, +8 more.

fact-checkA

Fact-check a document (or explicit claims) against the LIVE WEB. CROSS-MCP tool: doc-processor extracts the claims, then CALLS the web-search MCP (get-web-search-summaries) to gather sources per claim, and optionally writes a cited PDF report. Provide claims (an array of statements) OR a filePath/content to auto-extract factual claims from. Because this reaches the web-search MCP you MUST pass webSearchBearer (your web-search demo key) and serperKey (your Serper key); webSearchUrl defaults to the hosted web-search endpoint. Returns, per claim, the retrieved evidence + source URLs + a ROUGH keyword-overlap support score — NOT a verdict; read the evidence and decide support/refute yourself. Set generateReport: true for a downloadable cited PDF.

Inputs: claims, content, filePath, maxClaims, +9 more.

get-lineageA

Trace the provenance chain of a document. Returns a tree { sources: [{filePath, ...}], derivatives: [{filePath, ...}] } showing which read documents informed this document (sources, traced upstream) and which created documents derived from it (derivatives, traced downstream). Lineage is recorded automatically when read-doc and create-doc are called within the same session.

Inputs: filePath (required), depth.

list-documentsA

Search the document registry. Filters compose with AND-logic: category match AND tag match AND title-substring match. Returns an array of registry entries with { id, title, filePath, category, tags, description, createdAt, updatedAt }. Use this before create-doc to check if a similar document exists.

Inputs: tags, title, category.

list-templatesA

List available document templates AND blueprints. Templates are static, named structures (e.g. 'claude-like', 'technical-docs', 'business-report') you can reference via tags on create-doc. Blueprints are auto-learned structures stored in .document-blueprints.json. Use the returned name as blueprint: in create-doc, or as a tag for create-doc tag-based style detection.

Inputs: category.

read-docA

Read and analyze PDF, DOCX, Excel, or PowerPoint (.pptx) files. Modes: 'summary' (overview with preview), 'indepth' (full text, structure, metadata), 'focused' (query-based search). For a .pptx it returns a per-slide transcript (titles, bullets, speaker notes) and the slide count. Source: either local filePath OR a remote https url whose response is {data:base64, filename, mimeType, size} JSON guarded by authHeader (used for one-shot capabilities like CogniRunner attachment fetches). Always read before editing; use 'indepth' before edit-doc.

Inputs: url, mode, context, filePath, +3 more.

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 17 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose: creation tools are separated by format, editing tools by format, and management tools (dna, blueprint, drift-monitor, get-lineage, fact-check) are unique. No two tools overlap in functionality.

    Naming Consistency5/5

    All tool names follow a consistent lowercase-hyphenated verb-noun pattern (e.g., create-doc, edit-excel, list-templates). Even single-word tools like 'dna' and 'blueprint' fit the pattern as action-oriented names.

    Tool Count5/5

    17 tools cover reading, creating, editing, and managing documents across common formats (DOCX, XLSX, PPTX, PDF, Markdown) plus auxiliary features (detection, templates, lineage, fact-checking). No tool feels extraneous, and the scope is well-balanced.

    Completeness4/5

    Core CRUD operations are covered for most formats, but there is no tool for editing Markdown files (only create-markdown) and no deletion capability. Minor gaps, but the surface handles document lifecycle well overall.

    Related MCP Connectors

    Related MCP Servers