OCR_SERVER_API_TOKENS
A strong random secret followed by :console. It gates every route except /, /health and the console's static assets; the label only names it in the log.
Start here / GPU setup + first extraction
Prepare the GPU stack, configure access, and turn one document into structured text. Start here before opening a terminal.
Open this project in Claude Code, Codex or your preferred AI agent, with access to local files and a terminal. Copy the prompt into its chat to get started.
Create the settings file, set three distinct secrets, verify and start the stack, connect the MCP server and install both skills — then verify and parse one small document.
Set up Smart Document Manager in this repository, connect my AI agent to its MCP server, install its skills and verify a first extraction. Carry out the setup.
1. Work from the repository root. Follow AGENTS.md. Read scripts/README.md, .env.example, ocr-mcp-server/README.md and ocr-skill/README.md. Check git status and preserve existing changes. Detect the OS, shell and agent client; ask which client to configure only if unclear. Check the documented prerequisites, including an NVIDIA GPU that Docker can use (NVIDIA Container Toolkit on Linux, Docker Desktop with the WSL 2 backend on Windows). Report the exact next action if a prerequisite blocks you.
2. Create .env from .env.example only if absent. Preserve existing settings and secrets. If MCP_INPUT_ROOTS is set to a host path, it cannot work inside the ocr-mcp container (see .env.example): ask me whether to clear it.
3. Configure three distinct secrets: OCR_SERVER_API_TOKENS is a strong random secret followed by :console, MCP_API_TOKENS a different secret followed by :local-agent, UPSTREAM_CLIENT_TOKEN a third secret with no label. Generate a value only where one is missing or still a placeholder. Keep existing secrets and their labels; if an existing value breaks a rule (for example the same secret in two variables), ask me before replacing it. Never expose secrets or print them in chat.
4. Run the preflight: Windows: pwsh .\stack.ps1 verify; Linux: bash stack.sh verify. Resolve any reported problem before continuing.
5. Start and wait for readiness: Windows: pwsh .\stack.ps1 up -Wait; Linux: bash stack.sh up --wait. Allow time for image builds, model downloads and calibration; the first run can take a while. A printed URL or exit code alone does not prove readiness.
6. Register the app's MCP server in my chosen agent client under the name smart-document-mcp, using Streamable HTTP at http://127.0.0.1:8021/mcp, with the header Authorization: Bearer <the MCP token from MCP_API_TOKENS, without its :label suffix>. Use the client's documented configuration format and its supported secret mechanism. Preserve other client entries and reuse an existing matching connection. Do not expose the service publicly to make it reachable. If the client's configuration file sits inside this repository, confirm git ignores it (git check-ignore -v <path>) and add it to .git/info/exclude if it does not.
7. Install both supplied skills, copying SKILL.md and references/ (not evals/) from ocr-skill/smart-document-manager and ocr-skill/smart-document-reader. Codex personal skills live under ~/.agents/skills, Claude Code under ~/.claude/skills; for another client, use its documented skill location and say so if it has none. If a destination already exists, diff it against the supplied copy and ask me before replacing any file that differs; never overwrite silently. If a copy installed under the former name personal-smart-ocr exists, ask me before removing it.
8. Reload the MCP connection and skills, or tell me exactly how to reopen the agent if the session cannot discover them. Verify the client's live tools include ocr_check_health and call it with params {"response_format":"json"}, and verify the client lists both skills. If the tools or skills remain unavailable, or you cannot confirm the skills are loaded, report the specific blocker and do not claim the integration succeeded.
9. Parse one small document through the MCP tools of my agent client — for example calibration/plain_text.png (13 KB, one page, expected text in calibration/ground_truth.json), sent as image_base64 to ocr_parse_document with the default options (that is my approval for this one call), or any one-page PDF or image I provide. MCP_INPUT_ROOTS is empty by default, so file_path inputs are off. Follow the live tool schemas and the smart-document-manager skill. The call must go through the client's own MCP tool invocation: a direct REST call or a hand-written MCP/HTTP script does not prove the agent's connection works. If the file is too large to pass as base64 through the client, say so and stop instead of working around the client. Compare the extracted text with the expected text and report any difference.
10. Report what changed, readiness evidence, the console and MCP URLs, the installed skill paths, and the extraction result. Clearly state anything you could not complete.
Use the supplied defaults for your first run. The only file you create is .env; the launcher chooses the rest.
Open a terminal in the folder containing stack.ps1, stack.sh and .env.example. Copy .env.example to .env — the commands alongside do this only if .env does not already exist. If you already have one, keep it.
Open .env in a plain-text editor. Keep the filename exactly .env, not .env.txt. This file holds your local configuration and secrets; never publish it.
Run from the repository root
if (-not (Test-Path -LiteralPath .env)) {
Copy-Item -LiteralPath .env.example -Destination .env
}
if [ ! -e .env ]; then cp .env.example .env; fi
Edit .env locally. Set OCR_SERVER_API_TOKENS to a strong random secret followed by :console, MCP_API_TOKENS to a different secret followed by :local-agent, and UPSTREAM_CLIENT_TOKEN to a third secret with no label.
The template leaves credentials empty: API authentication is then disabled and MCP HTTP startup is refused. For an intentional API-only setup, start with -NoMcp / --no-mcp instead.
A strong random secret followed by :console. It gates every route except /, /health and the console's static assets; the label only names it in the log.
A different secret followed by :local-agent. With this list empty, verify reports it and the MCP server refuses to start.
A third secret, no label. The MCP server presents it to the API, which accepts it automatically — keep it out of the API list.
verify checks tokens, storage settings and Compose security without touching Docker state. Resolve anything it reports before starting — it is faster to fix .env now than to diagnose a half-started stack.
It is a preflight, not a health check: it validates your file, not the services.
Run from the repository root
pwsh .\stack.ps1 verify
bash stack.sh verify
Run the command for your terminal. up re-runs verify, builds the images and starts the services in readiness order; the wait flag holds until MCP listener health too.
First-run budget: the first start builds images, downloads the model and runs calibration — allow tens of minutes. Later starts reuse the cached work.
Run from the repository root
pwsh .\stack.ps1 up -Wait
bash stack.sh up --wait
Expected sequence
Verify → build images → wait for vllm-paddleocr → optional storage init → API calibration → MCP listener health. If startup reports an error, use the startup checks below.
The server in ocr-mcp-server/ gives your agent the extraction tools. Connect the client you actually use, such as Codex or Claude Code.
Using only the browser console? Continue to the console — this step and the next are for agent access.
Transport: Streamable HTTP. Server URL, with the supplied settings:
http://127.0.0.1:8021/mcp
Authenticate with the header Authorization: Bearer <your MCP token> — a raw token from MCP_API_TOKENS, without its :local-agent suffix. Keep the real token in your client's secret mechanism, not in chat or shared configuration. A wrong token fails the session.
Documents reach the server as base64 by default: MCP_INPUT_ROOTS ships empty and the container mounts no host folder, so file_path inputs stay off until you set the roots and mount that folder read-only into ocr-mcp. The skill sends base64 on its own.
Register this name, transport, URL and bearer header in your client's MCP settings — see the official client documentation linked inside each answer. The server guide documents the transport; the client commands belong to the client.
Codex keeps personal MCP connections in its own configuration. Follow its documented MCP setup to add a Streamable HTTP server named for this app at the URL above, supplying the bearer token through the client's supported secret mechanism. Official Codex MCP setup ↗
Equivalent manual configuration in each shell's home folder — illustrative, prefer the documented client command:
Check the registered servers
Get-Content "$env:USERPROFILE\.codex\config.toml"
cat "$HOME/.codex/config.toml"
Add a user-scoped HTTP MCP server at the URL above through Claude Code's documented MCP setup, supplying the bearer token through its supported secret mechanism. Official Claude Code MCP setup ↗
After registering, the entry lives in the client's own configuration:
Check the registered servers
Get-Content "$env:USERPROFILE\.claude.json"
cat "$HOME/.claude.json"
Next: reopen your agent session or reload its MCP connections, then check its connected-server list. In the Codex CLI and Claude Code, /mcp shows the connection. Then install the skills below.
ocr-skill/ contains two skills: smart-document-manager governs every OCR MCP call, a health check as much as an extraction, and carries the best practices the tools alone do not; smart-document-reader reads an existing /parse result or its stored archive — order, tables, captions and provenance.
Copy each skill's SKILL.md and references/ — evals/ is test material the client does not need. The commands keep an existing destination: compare its contents with the supplied copy before replacing local changes. Skill installation reference ↗
Choose your client and run the matching commands from the repository root. A copied folder alone does not load a skill — the client loads it from its skills directory.
Destinations: ~/.agents/skills/smart-document-manager and ~/.agents/skills/smart-document-reader. Here ~ means your home folder.
Run from the repository root
foreach ($skill in 'smart-document-manager', 'smart-document-reader') {
$target = "$env:USERPROFILE\.agents\skills\$skill"
if (Test-Path -LiteralPath $target) {
Write-Output "$skill already exists. Compare it with the supplied copy."
} else {
New-Item -ItemType Directory -Force $target | Out-Null
Copy-Item -Path ".\ocr-skill\$skill\SKILL.md", ".\ocr-skill\$skill\references" -Destination $target -Recurse
}
}
for skill in smart-document-manager smart-document-reader; do
target="$HOME/.agents/skills/$skill"
if [ -e "$target" ] || [ -L "$target" ]; then
printf '%s\n' "$skill already exists. Compare it with the supplied copy."
else
mkdir -p "$target"
cp -R "ocr-skill/$skill/SKILL.md" "ocr-skill/$skill/references" "$target/"
fi
done
Reopen Codex if the skills have not appeared, then select them in the client. Official Codex skill setup ↗
Destinations: ~/.claude/skills/smart-document-manager and ~/.claude/skills/smart-document-reader.
Run from the repository root
foreach ($skill in 'smart-document-manager', 'smart-document-reader') {
$target = "$env:USERPROFILE\.claude\skills\$skill"
if (Test-Path -LiteralPath $target) {
Write-Output "$skill already exists. Compare it with the supplied copy."
} else {
New-Item -ItemType Directory -Force $target | Out-Null
Copy-Item -Path ".\ocr-skill\$skill\SKILL.md", ".\ocr-skill\$skill\references" -Destination $target -Recurse
}
}
for skill in smart-document-manager smart-document-reader; do
target="$HOME/.claude/skills/$skill"
if [ -e "$target" ] || [ -L "$target" ]; then
printf '%s\n' "$skill already exists. Compare it with the supplied copy."
else
mkdir -p "$target"
cp -R "ocr-skill/$skill/SKILL.md" "ocr-skill/$skill/references" "$target/"
fi
done
Reopen Claude Code if necessary, then invoke the skills by name. Official Claude Code skill setup ↗
After loading the skills, send this read-only request in the same client you connected:
Use the smart-document-manager skill. Call ocr_check_health with params {"response_format":"json"}. Report the services it checks and their status. Do not change any data.
You are ready when the agent has loaded the skill, can call the MCP tool and the response reports the services healthy. A saved configuration or copied folder alone does not confirm that. Then try the first extraction walkthrough.
The guide itself needs only a browser. Running the stack needs the documented prerequisites: Docker with Compose 2.24.4+, Python 3.11+, and an NVIDIA GPU Docker can see — NVIDIA Container Toolkit on Linux, Docker Desktop with the WSL 2 backend on Windows. Check the launcher reference ↗
The console is the app's browser interface, served by the API. It is separate from these offline guides.
If the stack runs on this computer, the default console address is http://127.0.0.1:8020; its browser tab is titled Smart Document Manager. For a managed installation, use the address its operator gave you.
Choose API key in the top bar, enter the secret from OCR_SERVER_API_TOKENS without its :label — no Bearer prefix — and select Register. An MCP token is a different credential.
The connection bar probes the API. /health should report status=healthy with vllm=reachable; a degraded result means the model is still loading or unreachable. After the cause is resolved, choose Re-test.
Follow each step in the real console; the panels below illustrate what to look for. No live requests are made by this guide.
6 steps · at your pace
http://127.0.0.1:8020 in your browser.OCR_SERVER_API_TOKENS secret without its :label and select Register.What to checkThe connection bar reports the API healthy and the API key stays registered. Health proves reachability, not that every model feature is warm.
Illustrated console / connection bar
The console is static files served by the API. The key is kept for this browser session and sent only as the request bearer.
calibration/form943.pdf, a 3-page government form, or pick any one-page PDF, image or Office document.What to checkThe filename appears next to Choose file. PDF, image and Office files are all accepted; Office files are rendered to PDF before parsing.
The example you will parse
A known fixture keeps the first result reviewable. Ground truth for it ships in calibration/form943.txt.
markdown, json_ocr and json_rag checked for the full result.max_pages, dpi and table_format at their defaults for this first document.What to checkThe results region fills with markdown and structured JSON. The page errors, truncated and storage tiles summarize the run; the full warnings stay in the JSON — read them before trusting totals.
Illustrated console / Parse → Upload & Options
The console preselects markdown · pipes; choose html · lossless to keep merged cells. The same request is available as POST /parse (API default html); the console shows the request JSON it sends.
block_id.block_id order — that is the document's reading order. A null order comes from the label (captions, tables, headers…), not from a missing position.block_id adjacency and labels — the JSON has no relations field; bbox and page keep where each block came from.What to checkThe markdown and the block list tell the same story. Compare a few recognized lines with the original page — the fixture's form943.txt is the expected text.
An example of reading order / values abbreviated
title → field labels → table rows → footnote
The smart-document-reader skill documents how to read order, relations and provenance without re-running OCR.
table, formula, chart, seal, spotting or plain ocr.calibration/simple_table.png or calibration/formula.png.What to checkThe answer is the element you asked for — cells and merges for a table, LaTeX for a formula. This route is cheaper than parsing a whole document for one element.
Illustrated console / OCR tab
Focused recognition. The same call is POST /ocr; it refuses PDF and Office bytes.
json_rag.json files saved in Storage archives, so it needs the optional storage profile and a parse with json_rag checked. Without storage, skip this step.json_rag.json, keep the min token / max token targets and choose Run preflight. The targets are best-effort, not a strict limit.What to checkEach group is classified within, below or above range, and the original json_rag.json stays unchanged. For strict token-bounded chunks, call POST /chunk with the full /parse JSON and an explicit options.max_tokens.
Illustrated console / RAG tab
Refinement calls POST /storage/rag/refine. Strict chunking is a separate route: POST /chunk or /parse/chunks with options.max_tokens.
This walkthrough is an illustration. It does not connect to your app or change any data. Use the matching controls in your console to follow along.
The repository ships calibration fixtures you can parse: calibration/form943.pdf (3-page form), calibration/simple_table.png, calibration/formula.png, calibration/plain_text.png and calibration/dense_page.png. Select one through Choose file in the console — or use any one-page PDF.
These fixtures exist for deterministic calibration; expected text lives in calibration/ground_truth.json. Do not edit them — manifest.json guards their hashes.
http://127.0.0.1:8020, choose API key, register the OCR_SERVER_API_TOKENS secret without its :label and confirm the connection bar reports healthy.calibration/form943.pdf.markdown, json_ocr and json_rag checked, leave max_pages, dpi and table_format at defaults, then choose Parse document.block_id order; connect captions and footnotes to their objects by adjacency and label, and cite each fact by page and block.task — table, formula, chart, seal or spotting — choose an image file such as calibration/simple_table.png and select Run OCR.json_rag.json, run the preflight and save a refined file; the original stays unchanged.A parse returns markdown for reading and JSON for programs. Warnings belong to the result, not to a separate error log.
Markdown is the document reassembled for people. The JSON carries the same content as labelled blocks with positions, reading order and provenance — the shape agents and pipelines consume.
How to read the JSON ↗Page warnings report what recognition could not confirm. Truncation marks where a budget — pages, size or output — cut the result. A truncated page is incomplete, not failed. When the time budget runs out, the finished pages still return and the rest are marked unprocessed.
block_id order is the reading order; a null order is set by the label, not a missing position. Each block keeps the page and region it came from, so a quoted line traces back to the source.
Daily operation is start, check, stop. Rebuilds and re-downloads are for when something real changed.
up rebuilds from cache and reuses the downloaded model — after a reboot it is quick; pass -NoBuild / --no-build to skip the build entirely. Volumes are removed only by down -Volumes / --volumes.
status shows container state and readiness; logs narrows to a service. A timeout preserves containers and volumes so the evidence survives.
With the storage profile enabled, results can archive to S3 object storage with retention rules — browse them in the console's Storage tab. Disabled, nothing is archived.
Start with the reported error and the last service whose readiness did not complete.
Run from the repository root
pwsh .\stack.ps1 status
pwsh .\stack.ps1 logs -Service ocr-api,vllm-paddleocr -Tail 100
bash stack.sh status
bash stack.sh logs --service ocr-api,vllm-paddleocr --tail 100
A timeout preserves containers and volumes for diagnosis. Check GPU/runtime availability, downloads and calibration logs before changing the wait budget.
Check MCP_API_TOKENS=token:label, unique labels/tokens and separation from the API secrets. With API authentication on, UPSTREAM_CLIENT_TOKEN must be set (plain token, no label) and must not appear in OCR_SERVER_API_TOKENS.
Run urls to see configured addresses and status for container state. All host publications are loopback. A configured URL is not a live health check.
The API container is listening, but vllm-paddleocr is still loading weights or unreachable. Inspect vllm-paddleocr logs and confirm GPU memory availability before submitting documents.
If instead /health says status=healthy with mode=archive_only and vllm=disabled, nothing is wrong: the stack was started with -ArchiveOnly / --archive-only on purpose. Stored archives are readable; OCR returns with a plain up (after editing or overriding OCR_ARCHIVE_ONLY if .env fixes it to true).
In archive-only mode a degraded status means the archive bucket probe has not succeeded yet, or has failed: check the storage services; vLLM is not involved.
Yes. pwsh .\stack.ps1 up -ArchiveOnly or bash stack.sh up --archive-only starts the API, MCP and, when COMPOSE_PROFILES=storage, the storage profile, without vllm-paddleocr and without reserving a GPU, so no VRAM is allocated. The console opens on its Storage tab with Parse and OCR hidden, and together with the /storage/* routes and the MCP storage tools it works on everything archived earlier; the OCR routes answer 503 ocr_disabled_archive_only. It needs storage and its browser enabled — see the CLI guide.
Yes. /parse and the console's document field accept Office formats — .docx, .pptx, .xlsx, the legacy .doc/.ppt/.xls and OpenDocument types. The API renders them to PDF with LibreOffice before layout recognition, so allow extra time for the conversion.
The focused /ocr route is different: it recognizes a single image element and refuses PDF and Office bytes.
vllm-paddleocr needs free GPU memory for the model and its runtime budget, and layout analysis in ocr-api (container smart-document-manager) shares the same card (OCR_LAYOUT_GPU_MEMORY_MB). Other GPU processes compete for the same memory — check what else is using the device before starting. On a machine with several GPUs, move the stack to a free card with -GpuDevice 1 / --gpu-device 1 or OCR_GPU_DEVICE. On an 8 GB card, restart both services together.
Keep the GPU override settings empty until you have a measured reason to change them; the launcher tiers and budgets from the hardware it finds. If memory is the proven limit, reduce concurrent load rather than forcing a configuration.
Reload the MCP connection or reopen the agent session — clients typically discover tools at connect time. Then check the connected-server list; in the Codex CLI and Claude Code, /mcp shows the connection.
If the server is listed but calls fail, re-check the bearer: it must be a raw token from MCP_API_TOKENS without its :label suffix, sent as Authorization: Bearer. A copied skill folder does not create the MCP connection — both steps are needed.
Chunk creation is opt-in and requires an explicit options.max_tokens budget — a request without one is refused. In strict mode, the default, a budget smaller than a single protected unit also cannot be satisfied.
Send the complete /parse JSON to POST /chunk as parsed_document rather than re-parsing; the json_rag export is not chunker input. If chunks split poorly, raise the budget instead of forcing smaller units; provenance on each chunk still traces back to its source blocks.
This page takes you from installation to your first extraction. These companion guides explain the CLI, the settings and the system behind the results.
Every command, flag, exit behavior and recovery boundary for PowerShell and Bash, with an interactive command builder.
Template defaults, the token relationship, ports and the optional storage profile — every name in .env.example in plain language.
Follow a document through the API, layout recognition and the vLLM model. Explore deployment shapes, MCP and the skills, and where data stays.
How layout detection labels a page, how reading order is assigned, and what each block type means.
Read the pipeline guide ↗How the deterministic chunker packs document units under an explicit token budget while preserving provenance.
Read the chunking guide ↗Extraction runs where your services are hosted. If you connect an agent that uses a cloud model, prompts and returned content can cross that boundary. Review the deployment and boundary guide with the operator.