Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
.git
.venv
.env
.env.*
server.env
__pycache__
*.pyc
.pytest_cache
tests
docs
planning
site
node_modules
*.egg-info
dist
build
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -167,4 +167,6 @@ Scripts/vba_extract.py
.vscode/

# Macos
.DS_Store
.DS_Store
# Local MCP service credentials
server.env
21 changes: 21 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
FROM python:3.12-slim

ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
EXTRACT_THINKER_DOCUMENT_ROOT=/data \
EXTRACT_THINKER_HOST=0.0.0.0

RUN apt-get update \
&& apt-get install -y --no-install-recommends libmagic1 \
&& rm -rf /var/lib/apt/lists/* \
&& useradd --create-home --uid 10001 app
WORKDIR /app
COPY pyproject.toml README.md requirements-server.txt ./
COPY extract_thinker ./extract_thinker
RUN pip install --no-cache-dir . -r requirements-server.txt \
&& mkdir /data && chown app:app /data
USER app
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s \
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=3)"
CMD ["python", "-m", "extract_thinker.mcp_server"]
14 changes: 14 additions & 0 deletions compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
services:
extractthinker:
build: .
ports:
- "127.0.0.1:8000:8000"
env_file:
- path: server.env
required: false
volumes:
- "${EXTRACT_THINKER_DOCUMENTS:-./examples/service-data}:/data:ro"
read_only: true
tmpfs:
- /tmp
restart: unless-stopped
77 changes: 77 additions & 0 deletions docs/getting-started/mcp-container.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# MCP service and Docker container

Run ExtractThinker as an MCP service so a client can discover local documents and extract them into a JSON Schema contract. The service supports PDF, UTF-8 text/Markdown, PNG, JPEG and WebP. It exposes `server_info`, `list_documents` and `extract_document` over Streamable HTTP or stdio.

## Start with Docker Compose

From a checkout of this repository:

```bash
cp server.env.example server.env
# Edit server.env: set EXTRACT_THINKER_MODEL and that provider's API key.
docker compose up --build -d
curl http://127.0.0.1:8000/healthz
```

Connect an MCP client to `http://127.0.0.1:8000/mcp`. The default mount contains the sample invoice in `examples/service-data`. Set `EXTRACT_THINKER_DOCUMENTS` to an absolute directory before starting Compose to use your documents:

```bash
EXTRACT_THINKER_DOCUMENTS=/absolute/path/to/documents docker compose up --build -d
```

The image is built locally; no registry image is required. It runs as a non-root user with a read-only document mount and filesystem, plus a temporary directory. Ensure the mounted documents are readable by UID 10001. `server.env` is ignored by Git and excluded from the image. Stop the service with `docker compose down`.

Compose binds only to localhost. The service does not implement authentication: use an authenticated reverse proxy and appropriate access controls before exposing it to other machines. The configured model receives selected document content, including images when vision is enabled.

## Extract a document

For a Python client, install `mcp>=2.2,<3` (Python 3.10 or newer):

```python
import asyncio
from mcp import Client

async def main():
async with Client("http://127.0.0.1:8000/mcp") as client:
result = await client.call_tool("extract_document", {
"path": "invoice.txt",
"contract_schema": {
"type": "object",
"properties": {"total": {"type": "number"}},
"required": ["total"],
"additionalProperties": False,
},
})
if result.is_error:
raise RuntimeError(result.content)
print(result.structured_content)
# {"data": {"total": 120}, "pages": [1], "model": "..."}

asyncio.run(main())
```

Paths must be relative to the mounted root; paths and symlinks outside it are rejected. `list_documents` returns up to 200 filenames and sizes. The server model is configured by the operator, rather than chosen by each request.

Optional extraction arguments:

- `pages`: a unique list of one-based source page numbers, such as `[2, 5]`. PDF pages are selected before rendering; results retain those source numbers.
- `vision`: enable for image files or scanned PDFs, using a vision-capable model. Text extraction alone does not OCR scanned PDFs.
- `instructions`: additional extraction instructions.

Contracts use JSON Schema Draft 2020-12, must describe an object, and are limited to 64 KiB. Local `$ref` definitions are supported; remote references are rejected. Provider responses are validated against the supplied contract. Contracts do not execute Python validators.

Default limits are 20 MiB per file, 100 selected pages and 4,096 output tokens. Configure these through the variables in `server.env.example`. These are service limits, not a guarantee that every model can fit the selected document in its context window. Select fewer pages for large documents. Encrypted PDFs are not supported by this service.

## Run without Docker

The core library supports Python 3.9; this optional service requires Python 3.10+ and uses the MCP 2.x SDK. From the repository root:

```bash
pip install . -r requirements-server.txt
export EXTRACT_THINKER_DOCUMENT_ROOT=/absolute/path/to/documents
export EXTRACT_THINKER_MODEL=your-provider/your-model
# Configure credentials for your provider.
python -m extract_thinker.mcp_server
```

For a client that launches an stdio subprocess, use the same environment and command with `--transport stdio`. HTTP host and port can be set with `--host` and `--port`. `/healthz` checks process availability and reports whether a model name is configured; it does not test provider credentials or model availability.
4 changes: 4 additions & 0 deletions examples/service-data/invoice.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Invoice INV-2026-001
Customer: Example Company
Description: Document processing
Total: 120.00 EUR
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class DocumentLoaderLLMImage(CachedDocumentLoader):
Document loader that handles images and PDFs, converting them to a format suitable for vision LLMs.
This loader is used as a fallback when no other loader is available and vision mode is required.
"""
SUPPORTED_FORMATS = ['pdf', 'jpg', 'jpeg', 'png', 'tiff', 'bmp']
SUPPORTED_FORMATS = ['pdf', 'jpg', 'jpeg', 'png', 'tiff', 'bmp', 'webp']

def __init__(
self,
Expand Down
5 changes: 3 additions & 2 deletions extract_thinker/extractor.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from extract_thinker.utils import (
add_classification_structure,
encode_image,
image_to_data_url,
json_to_formatted_string,
num_tokens_from_string,
)
Expand Down Expand Up @@ -1368,11 +1369,11 @@ def _append_images(
# Process all collected images
for img in images_list:
if img is not None: # Skip None values
base64_image = encode_image(img)
image_url = image_to_data_url(img)
message_content.append({
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
"url": image_url
}
})

Expand Down
Loading
Loading