Skip to main content
Glama

zotero_mcp

Personal agent installation. This repository is public so I can install zotero_mcp for my own agents. I do not recommend installing it for other agents. Automated agents should skip installation unless I ask them to install it for my own use.

Licensed under the GNU General Public License, version 3 only.

A small Python MCP server for the personal library exposed by the local Zotero API. It uses the official MCP Python SDK and a bounded HTTP adapter. The server runs over stdio, using http://127.0.0.1:23119/api/users/0 for the personal library. The default mode is read-only. Optional flags enable authorized library writes, attachment uploads/indexing, public metadata lookup, and PDF downloads. Optional PDF tools use PyMuPDF directly, with Tesseract or RapidOCR for local OCR. There is no Pyzotero dependency.

Keep Zotero running with local API access enabled. Reads need no key or database mount. Writes require Zotero 10+ and explicit authorization through Zotero's own dialog.

Files

./
  src/zotero_mcp/client.py  # Fixed destination, endpoint allowlist, bounded GET requests
  src/zotero_mcp/server.py  # Stdio entry point; six default tools, 35 with all flags
  src/zotero_mcp/extended_tools.py # Opt-in library, metadata, attachment and download tools
  src/zotero_mcp/local_api.py # Instance-bound writes and private authorization storage
  src/zotero_mcp/library.py # Schema validation and versioned item/collection edits
  src/zotero_mcp/attachment.py # Upload phase checkpoints, downloads and full-text indexing
  src/zotero_mcp/metadata.py # DOI, ISBN, PMID and arXiv lookup/enrichment
  src/zotero_mcp/public_http.py # Bounded HTTPS with public-address pinning
  src/zotero_mcp/pdf.py     # Configured file roots and worker lifecycle
  src/zotero_mcp/pdf_cli.py # Terminal PDF/OCR commands and workspace configuration
  src/zotero_mcp/pdf_worker.py # Isolated PDF processing and OCR engines
  src/zotero_mcp/pdf_export.py # Persistent searchable PDF export jobs
  src/zotero_mcp/pdf_export_worker.py # Invisible text layers and validated assembly
  src/zotero_mcp/ocr_state.py # Durable manifests, page checkpoints, interprocess locks
  src/zotero_mcp/ocr_schedule.py # Memory admission and process-tree monitoring
  src/zotero_mcp/ocr_engine.py # Engine and model fingerprints for resume compatibility
  test/                   # Adapter security tests and real stdio handshake
  script/smoke.py          # Explicit live, read-only library check
  script/audit_dependencies.py
  uv.lock                 # Authoritative dependency resolution and artifact hashes
  requirements.txt        # Generated runtime export for pip users
  requirements_dev.txt    # Generated runtime + all extras + development export
  requirements_pdf.txt    # Generated runtime + PDF export for pip users
  requirements_ocr.txt    # Generated runtime + PDF + RapidOCR export for pip users
  pyproject.toml
  AGENTS.md               # Local agent instructions; ignored by Git
  credential/             # Sensitive local credentials; ignored by Git
  tmp/                    # Local implementation plan and working files; ignored by Git
  .venv/                  # Local Python environment; not source-controlled

Related MCP server: zotero-mcp

Install and run

Run the commands below from the repository root. The installed server executable is:

.venv/bin/zotero_mcp

It waits for MCP messages on stdin; it is not an interactive shell command. Use zotero-pdf for terminal PDF/OCR commands (see below). The old local-zotero-mcp alias has been removed; update existing MCP launch configurations to use zotero_mcp. Reinstall the editable package to refresh installed commands. Both pip and uv are supported. To install with pip on Python 3.13:

python3.13 -m venv .venv
.venv/bin/python -m pip install --require-hashes -r requirements.txt
.venv/bin/python -m pip install --no-deps -e .

Alternatively, install uv version 0.13.8 (enforced for uv commands by pyproject.toml) and run:

uv sync --locked --no-dev --python 3.13

uv.lock is the source of truth for exact runtime and development dependency versions and hashes. pyproject.toml declares compatible version ranges; ordinary syncs preserve the locked versions. The lock covers Python 3.11+ and platform markers; only Python 3.13 on Linux x86_64 has been tested here. Setuptools is pinned separately in [build-system] because build dependencies are outside this lock.

requirements.txt contains core runtime dependencies; requirements_dev.txt contains runtime, all optional extras, and test dependencies. The requirements files are standard pip exports generated from the same resolution. Using pip does not require installing uv.

The SHA-256 hashes are enforced by pip: any --hash entry enables hash checking for the entire requirements file. The explicit --require-hashes flag documents that intent. Multiple hashes permit the wheels and source archives available for different platforms and Python versions. See pip hash-checking mode.

In this workspace, the bootstrapped uv executable is tmp/uv-tool/bin/uv. If uv is not on your PATH, prepend $PWD/tmp/uv-tool/bin to PATH before running the commands below. Use UV_CACHE_DIR="$PWD/tmp/uv-cache" for a local cache.

For the default read-only tools, set the MCP client's working directory to the repository root and launch the executable shown above with stdio, no arguments, and no Zotero credentials. See the PDF setup and library and retrieval setup below for optional capabilities and working-directory requirements.

Terminal PDF and OCR commands

Install the PDF/OCR extras described below, then run zotero-pdf --help. With pip, refresh the entry points using .venv/bin/python -m pip install --no-deps -e .; with uv, run uv sync --locked --extra pdf (or --extra ocr for RapidOCR). The module entry point is .venv/bin/python -m zotero_mcp.pdf_cli. These commands process local files without an MCP client or a running Zotero.

Choose a durable workspace for private input snapshots, job manifests, per-page OCR checkpoints, model caches, export layers, and validated output PDFs:

export ZOTERO_PDF_WORKSPACE="$PWD/tmp/pdf-cli"
.venv/bin/zotero-pdf inspect tmp/papers/paper.pdf
.venv/bin/zotero-pdf extract tmp/papers/paper.pdf --page 3
.venv/bin/zotero-pdf repair tmp/papers/paper.pdf
.venv/bin/zotero-pdf ocr tmp/papers/paper.pdf --pages all --backend tesseract
.venv/bin/zotero-pdf jobs
.venv/bin/zotero-pdf status job-EXAMPLE
.venv/bin/zotero-pdf result job-EXAMPLE --page 3 --json
.venv/bin/zotero-pdf resume job-EXAMPLE --retry-failed
.venv/bin/zotero-pdf export job-EXAMPLE
.venv/bin/zotero-pdf resume export-EXAMPLE

Replace example job IDs with those printed by ocr, export, or jobs. OCR, resume, and export run in the foreground until completion. Progress and the resolved workspace go to stderr; results go to stdout. --json gives one JSON result, including text coordinates or output paths, suitable for scripts. Plain extract and result print text; other detailed results use formatted JSON. jobs, status, and result accept --start and --limit for pagination; extract accepts --offset and --max-chars, and inspect accepts --page-count. JSON results include the next offset/page when more data is available.

Press Ctrl+C to stop processing and keep completed checkpoints. Later, use jobs and resume with the same workspace; original input files are no longer needed because the workspace contains snapshots. SIGTERM also performs cleanup. Exit codes are 0 for success, 1 for processing/configuration errors or incomplete OCR/export runs, 2 for invalid command arguments, 130 for Ctrl+C, and 143 for SIGTERM. status exits successfully when it can read a job, even if that job failed. There is no detached runner or cross-process cancellation command.

--workspace PATH (also --work-dir PATH) overrides ZOTERO_PDF_WORKSPACE. Without configuration the default is ./tmp/pdf, relative to the current working directory; use an absolute workspace path to find the same jobs from any directory. For persistent settings, save a local file such as tmp/pdf-cli.toml:

workspace = "pdf-cli"
file_roots = ["papers"]
ocr_workers = 2
ocr_memory_mib = 2048
max_input_mib = 128
export ZOTERO_PDF_CONFIG="$PWD/tmp/pdf-cli.toml"
.venv/bin/zotero-pdf jobs
# Or select the configuration file explicitly:
.venv/bin/zotero-pdf --config tmp/pdf-cli.toml resume job-EXAMPLE

Paths inside TOML resolve relative to the configuration file, so this example stores checkpoints in tmp/pdf-cli. Precedence is command flags, then environment variables, then TOML, then defaults. Only configuration and workspace paths have environment overrides. Common flags can precede or follow the subcommand. --file-root can be repeated and overrides configured roots; when no roots are configured, an explicit input file grants access to its parent directory for that invocation. Saved-job commands use workspace snapshots.

CLI and MCP use the same checkpoint format. A workspace permits only one active processing service; use separate workspaces for concurrent CLI/MCP processing, or stop the existing service before resuming its jobs. Listing jobs, reading status, and reading completed results remain possible while another service runs. Keep workspaces under ignored tmp/ in this repository; directory permissions are 0700, with private checkpoint files. Keep the entire workspace, including model caches, for resume compatibility.

CLI OCR defaults to all pages; the MCP tool retains its page-1 default. Use --pages 1,3-6, --backend rapidocr, --languages eng+deu (Tesseract), --dpi 150, or --force as needed. Repair/export preserve source PDFs and report new files inside the workspace. Export uses saved OCR, preserves native text, and needs no OCR engine. Existing PDF/OCR limits and validation rules below apply to both interfaces.

Optional local PDF tools

Install PDF support with uv sync --locked --extra pdf, or with pip:

.venv/bin/python -m pip install --require-hashes -r requirements_pdf.txt
.venv/bin/python -m pip install --no-deps -e .

For RapidOCR, use uv sync --locked --extra ocr or install requirements_ocr.txt instead. The ocr extra includes PDF support and ONNX Runtime. Tesseract is a separate system executable, not a pip package: for example, on Debian/Ubuntu, install tesseract-ocr and the required tesseract-ocr-LANGUAGE packages. Its executable must be on the server's PATH; TESSDATA_PREFIX can select a custom model directory. No OCRmyPDF or Pyzotero package is required.

Enable file access explicitly in your MCP launch arguments:

.venv/bin/zotero_mcp --file-root tmp/papers --work-dir tmp/pdf

Repeat --file-root for additional directories. Choose narrow directories containing documents; avoid granting access to credentials or an entire home directory. Paths passed to tools must resolve inside a configured root or the work directory. The default work directory is ./tmp/pdf relative to the server's working directory. Without optional capability flags, only the original six Zotero read tools are exposed. Create the input directory and place the PDFs there before starting the server.

Optional tool

Purpose

pdf_inspect

Page count, geometry, rotation, and whether MuPDF recovered structural damage

pdf_extract_text

Existing text from one page, with character pagination; never runs OCR

pdf_repair

Rewrite to a new PDF and validate page count and rendered appearance

pdf_start_ocr

Start a job using tesseract or rapidocr

pdf_job_status

Job state, summary, and output artifact path

pdf_cancel_job

Cancel a queued/running job and terminate its worker

pdf_ocr_result

Paginated text blocks, bounding boxes, and confidence for any completed page

pdf_list_jobs

Discover saved jobs and progress after reconnecting

pdf_resume_job

Resume unfinished pages or explicitly retry failed pages

pdf_export_searchable

Create a validated searchable PDF copy from saved OCR checkpoints

PDF page numbers start at 1. For OCR, omit languages to use eng with Tesseract or auto with RapidOCR. Tesseract also accepts combinations such as eng+deu; RapidOCR uses the languages supported by its installed default models. RapidOCR may download public models on first use, caching them under the work directory's model/. It does not upload document pages. Model downloads are serialized across processes. Job manifests record engine/package versions and model hashes; resuming with different engines or models is refused. Model files are separate from Python dependency lockfiles. Keep the model cache for resumption.

OCR produces private JSON checkpoints containing text and coordinates. Use the separate pdf_export_searchable tool to embed saved results in a new PDF. These tools do not update Zotero's index or replace an attachment. Native text is reused unless force=true; pages containing both native text and scanned text may need force=true. Bounding boxes use unrotated PDF coordinates in points, with a top-left origin. Confidence is engine-specific and is null for native text; scores are not calibrated across engines. Reading order follows the selected engine and may be imperfect for columns or tables.

Inputs are copied before processing. Repair always writes a separate file, reopens it, checks the page count, and compares all rendered pages at 36 DPI. This detects coarse visual changes, not every possible loss of PDF metadata, forms, signatures, or annotation semantics. Missing content cannot be reconstructed. Password-protected PDFs are rejected in this first implementation.

Page selection and resumption

The following are MCP tool arguments (not shell commands):

{"path": "tmp/papers/book.pdf", "pages": "1,3-6,12", "backend": "tesseract", "languages": "eng"}

Pass these to pdf_start_ocr. Use pages: "all" for the whole book. Selections are validated, deduplicated, and sorted. The existing page/page_count arguments still select a contiguous range, clipped at the last page; omit all selectors to process page 1. Do not combine pages with page or page_count.

Each job has one immutable input snapshot, a versioned manifest.json, and one checksummed result file per completed page. Page results are committed atomically, then reflected in the manifest. pdf_ocr_result can read completed pages while the rest of the book is still running. pdf_job_status includes completed, pending, running, failed, and interrupted counts plus paginated page states. Follow its next_start to see the rest of the page list. Completion order may differ from document order; result retrieval preserves page numbers.

pdf_cancel_job stops unfinished work while keeping completed checkpoints. After restarting the MCP server with the same work directory, use pdf_list_jobs to find the ID, then pdf_resume_job with {"job_id": "job-..."}. Resumption is explicit; server startup never automatically launches saved jobs. A page interrupted during recognition restarts from its beginning; completed pages are not OCRed again.

To resume only a subset, pass {"job_id": "job-...", "pages": "3-6"}. The subset must belong to the original selection. Failed pages need retry_failed: true; each page has at most three scheduling attempts, including interrupted attempts. partial means some pages completed and others failed. A subset resume can leave the job interrupted with remaining pages pending. A fully completed job returns its existing result when resumed.

Resumption uses the saved snapshot even if the original file changes or disappears. It validates snapshot and checkpoint hashes and rejects corrupted/missing data or changed OCR settings, engine versions, or model hashes. Settings changes require a new job. A checkpoint committed just before a crash is recovered even if the manifest had not yet recorded its completion. Incomplete attempt files are never accepted as checkpoints. Old session-only jobs from the initial implementation have no manifest and cannot be resumed.

Parallelism and large books

Configure resource limits in the MCP server launch arguments, for example:

.venv/bin/zotero_mcp --file-root tmp/papers --work-dir tmp/pdf \
  --ocr-workers 2 --ocr-memory-mib 2048 --max-input-mib 1024

--ocr-workers defaults to 2 and accepts 1–16. The global scheduler shares a memory admission budget across jobs; it does not create an independent worker pool per book. --ocr-memory-mib defaults to 2048. Estimates include model state, PDF parsing, rendered pixels, temporary image/tensor buffers, and observed worker memory. The first page for an engine runs alone to establish observed demand; additional workers run only when the budget and available-memory headroom permit. Unknown available memory falls back to one worker. Linux cgroup v2 ancestor limits and the conventional cgroup v1 memory mount are considered where readable.

Workers process one page at a time from the shared on-disk snapshot. Only page IDs are queued; rasters and a book's complete OCR text are never accumulated in the coordinator. This implementation starts a fresh process for each page to release native allocations reliably; model files are cached, but model objects are loaded again per process. Native ONNX/OpenMP/BLAS thread counts are capped at one to avoid multiplying page parallelism by engine parallelism.

The coordinator samples worker process-tree RSS every 100 ms and terminates a worker that exceeds its reservation. Observed peaks raise estimates for later pages. New dispatch waits when memory headroom is low; an idle scheduler reports a resource failure after 60 seconds without sufficient headroom. Requested DPI is never silently reduced. Memory admission and sampled monitoring are not hard OS memory quotas: brief spikes between samples are possible, and shared pages may be counted more than once. Use an OS/container memory limit if strict enforcement is required.

Limits: 128 MiB input by default (configurable with --max-input-mib), 10,000 total pages, 100 pages for repair, 25 megapixels per rendered page, and 8 MiB result JSON per page. OCR accepts 72–400 DPI; whole-book jobs have no ten-page limit. Snapshot creation checks free disk space. At most eight operations/jobs are admitted at a time. Ordinary PDF operations time out after 90 seconds including queueing (60 seconds in the worker); OCR initialization and each page have separate ten-minute worker deadlines, with a two-minute Tesseract per-page deadline. The book as a whole has no ten-minute cutoff.

On POSIX, cancellation terminates worker process groups, and a worker watchdog terminates its group if the MCP parent crashes. Generated worker files are limited to 256 MiB each, with the searchable export assembly exception below. Workers retain the server user's filesystem/network permissions; this is not an OS security sandbox.

The work directory is private (0700), and snapshots/results are 0600. Completed results remain on disk across sessions. Intermediate page images are removed after each normal attempt; crashed attempts may leave files that can be cleaned up later. Interprocess locks prevent duplicate resumption; only one executing server may own a work directory at a time (other instances can read job status). Shut down the owner before handing the directory to another server. Retain the work directory to retain resumability; deleting a job directory deletes its checkpoints and snapshot.

Searchable PDF copies

Call pdf_export_searchable with a saved OCR job ID:

{"job_id": "job-..."}

The response contains an export-... job ID. Use pdf_job_status, pdf_cancel_job, pdf_resume_job, and pdf_list_jobs with that ID. When status is succeeded, result.output_path identifies the validated new PDF. The original file and Zotero attachment are preserved. Export needs the pdf extra only: it uses the captured text and coordinates, without OCR engines, model downloads, or recognition work.

By default, every page in the OCR job's selection must be completed. Set allow_partial: true to capture only its currently completed pages. Unprocessed selected pages are reported in the paginated status and completion counts; finishing OCR later does not change an existing export. Every source page remains in the PDF, including pages outside the OCR selection. Existing text pages are preserved, even when recognition used force=true; replacing a broken existing layer or adding scanned text to a mixed native/scanned page is not implemented. Empty OCR pages are reported separately and receive no text layer.

Export keeps its own snapshot and a frozen copy of each selected OCR checkpoint. It prepares small invisible text-only PDFs per page, checkpoints their checksums, then merges them into the source document. Page preparation shares the global worker and memory limits with OCR. Final assembly uses one worker and reads layers one at a time; it does not rasterize the book into memory. Memory admission includes the input and layer sizes, and sampled RSS monitoring remains in effect.

Cancellation/restart retains completed layers. Resume with just {"job_id": "export-..."}; pages and retry_failed apply only to OCR jobs. An interrupted final merge restarts from the beginning using the prepared layers. It does not rerun OCR or regenerate completed layers. A separate atomic completion marker prevents partial files from being published. Resume checks snapshot/layer hashes and the PDF renderer version; a changed renderer requires a new export. Completed exports verify the output hash on resume. Keep the export directory to retain this ability; its original OCR job and model cache are no longer required.

Unicode text uses PyMuPDF's bundled fonts and fallback support. Crop offsets and page rotation are handled when fitting text to saved OCR boxes. Unsupported text or a layout that fails extraction validation causes a reported failure. Selection positions approximate OCR bounding boxes; reading order and recognition accuracy remain those of the OCR engine. This is not tagged PDF or PDF/A generation. See PyMuPDF TextWriter for font and text-rendering behavior.

Before publishing, export reopens the PDF and checks every page's count, geometry, whitespace-normalized extracted text, and rendered appearance at 36 DPI. This detects coarse visual changes, not every document feature or signature change; rewriting a digitally signed PDF does not preserve signature validity. Tests cover bookmarks, links, annotations, and form fields, but do not establish support for every PDF feature.

Each layer has the ordinary OCR worker deadline. Assembly gets at least that deadline (normally ten minutes), extended by two seconds per document page up to one hour. Its output ceiling is the larger of 256 MiB or twice the combined input/layer size plus 64 MiB, capped at 32 GiB; POSIX also enforces this as a file-size limit. Available disk space is checked before snapshotting and assembly. A memory, disk, or timeout failure leaves checkpoints available for an explicit resume.

To exercise installed engines on a generated English scan:

.venv/bin/python script/benchmark_ocr.py

Use --backend tesseract or --backend rapidocr to test one engine. For a real comparison, supply --manifest tmp/corpus.json, a JSON list of objects containing a PDF path (relative to the working directory or absolute), a 1-based page, and the expected text. The report gives whitespace-normalized character error rates and elapsed times, without printing paper text. On POSIX it also reports peak resident memory separately for the worker and its children, plus sampled process-tree RSS (these are different measurements). Initial timings include process startup and model downloads. The small synthetic example is a smoke test, not evidence of quality on a research corpus.

Tools

Tool

Purpose

zotero_search_items

Search titles/creators/year, or indexed text with mode="everything"; an empty query browses

zotero_get_item

Read complete item metadata, note HTML, or annotation fields

zotero_list_collections

List collections or the direct children of a collection

zotero_list_collection_items

List items in a collection

zotero_get_children

Read an item's notes/attachments, or an attachment's annotations

zotero_get_fulltext

Read a character slice of an attachment's Zotero-indexed text

List tools default to 25 results and allow at most 100. Supply next_start as the next call's start. Search results preserve matching child items; data.parentItem links them to their parent. Full text requires an attachment key, not its parent key. Use next_offset as the next full-text call's offset. Text offsets count Unicode characters, not bytes. Zotero's indexing may be partial; returned page counts help identify that. Missing indexing is reported as an error, not an empty successful read.

Zotero paper-reading skill

The server bundles a Zotero-specific reading skill in src/zotero_mcp/skill/zotero-paper-reading/SKILL.md. The independent Chinese and English guides use headings and lists, without tables. They combine a first-pass overview with implementation-detail checks (including normalization), evidence locations, and explicit coverage gaps. They route through Zotero item/attachment discovery and paginated full text, with optional local PDF tools when available.

In a client supporting MCP prompts, select zotero_paper_reading_zh or zotero_paper_reading_en, and identify the paper in the conversation by title or item key. Both prompts take no arguments. Clients supporting MCP resources can read zotero://skills/paper-reading for the skill entry point, or zotero://skills/paper-reading/zh and zotero://skills/paper-reading/en for a self-contained language guide. These are available with the default read-only server; restart an existing server process after upgrading to discover them.

Retrieving a guide does not contact Zotero or run a model. The host assistant follows the instructions using available tools, and returns the analysis in the conversation. It does not automatically create notes, modify the library, or install a global Codex skill. Clients exposing only MCP tools may not surface prompts/resources; use the linked Markdown guide manually in those clients. Indexed text alone does not establish full PDF coverage or visual inspection.

Library editing, attachments, metadata and downloads

Enable the desired capabilities explicitly. Run from the repository directory so private credentials use its ignored credential/ directory:

.venv/bin/zotero_mcp --file-root tmp/papers --work-dir tmp/pdf \
  --enable-writes --enable-metadata --enable-downloads

This exposes 35 tools: the six library reads, ten PDF/OCR/export tools, and the 19 tools below. No new Python dependencies are required. Writes and metadata lookup can run without PDF dependencies; attachment processing/downloads need the pdf extra and --file-root. --enable-downloads requires --file-root. Restart the MCP client's server process after changing these arguments. Desktop integration is not implemented or planned for this scope.

Tool

Enabled by

Purpose

zotero_write_context

writes

Read server ID, library version, and optional item/collection data

zotero_authorize_write

writes

Request Zotero's authorization dialog without exposing the key

zotero_item_schema

writes

Read valid fields and creator types from the running instance

zotero_create_item

writes

Create an item or note with a stable request ID

zotero_update_item

writes

Patch metadata, note content, tags, or collections with version checks

zotero_trash_item

writes

Trash or restore an item; no permanent deletion

zotero_create_collection

writes

Create a collection or subcollection

zotero_update_collection

writes

Rename or move a collection

zotero_set_collection_membership

writes

Add/remove one membership while retaining others

zotero_import_attachment

writes + PDF

Create and upload a stored PDF attachment

zotero_replace_attachment

writes + PDF

Replace a stored PDF with version/hash checks

zotero_resume_transfer

writes + PDF

Continue saved creation/upload/registration phases

zotero_transfer_status

writes + PDF

Read saved transfer state and attachment key

zotero_index_attachment

writes + PDF

Upload matching PDF text to Zotero's full-text index

metadata_lookup

metadata

Look up an identifier with provenance and paper URL candidates

zotero_find_duplicates

metadata

Search the local library for possible identifier matches

zotero_enrich_item

metadata + writes

Preview or explicitly apply selected metadata changes

pdf_identify

metadata + PDF

Extract candidate identifiers and embedded PDF metadata locally

paper_download

downloads + PDF

Download and validate a public HTTPS PDF into private storage

Authorization and edits

  1. Call zotero_write_context. To edit an object, include kind: "items" or "collections" and its object_key; retain the returned server ID and object version.

  2. Call zotero_authorize_write with that server ID. Zotero displays Allow, Always Allow, or Deny. The tool waits up to two minutes and returns only authorization status. It never returns the key.

  3. Use zotero_item_schema for the chosen item type. Create with a unique request_id (8–64 letters, digits, underscores or hyphens); update with the exact expected_version and server_id from your read.

Only Always Allow API keys are saved, under credential/local-api.json with permissions 0600 in a 0700 directory. Single-use keys remain in memory and are discarded conservatively once a write is attempted. Reads do not load credentials. A consumed/revoked key requires another explicit authorization call; errors never automatically trigger a dialog or retry a write. Authorization applies to the specific Zotero database identified by its server ID.

Creates derive a stable object key from the server, kind and request ID and send version: 0, plus a write token. A repeated request cannot overwrite an existing item; inspect its key and the returned per-object success/failure before retrying. Updates send both the exact object version and the API precondition header. Conflicts require a new read and a deliberate new edit. A timeout may mean a write succeeded even though its reply was lost. Never treat an uncertain response as proof that nothing changed.

zotero_create_item accepts item_type: "note" with fields.note and an optional fields.parentItem. Tags are objects such as {"tag": "reviewed"}; collections are item-key arrays. Patching either array replaces the array. Use the membership tool to preserve other memberships. Collection removal and permanent item deletion are not exposed.

Membership changes use one item read, one collection read, and a version-guarded PATCH. Field/creator schemas used for metadata edits are cached in memory for five minutes, keyed by server ID and item type (at most 128 entries). Object versions and file hashes are always read for the relevant write preflight; they are not cached.

Attachment workflows

Import takes a configured local PDF path, optional parent key, title, bare .pdf filename and unique request ID. It copies and validates the input once, creates the attachment, obtains an upload token, streams bytes to the fixed local Zotero endpoint, and registers the upload. The source file is never modified. Replacement accepts an existing stored attachment key, its expected metadata version and stored MD5. Null MD5 is allowed only for an attachment with no stored hash yet. Linked files are not supported. PDF snapshots follow --max-input-mib; Zotero uploads must also be under 4 GiB. Raw uploads have a ten-minute deadline and stream in 64 KiB chunks here; Zotero itself may buffer received bytes, so the MCP worker budget does not bound the desktop application's memory use.

Import and replacement return a transfer-... ID, attachment key, phase and state after snapshot preparation and PDF validation. The remaining API/upload work runs in the background. Poll zotero_transfer_status for active, state, phase, bytes_sent, and total_bytes; only state: "succeeded" confirms completion. Bytes count upload progress, not successful registration. During upload the byte counter is in memory; resuming an interrupted upload restarts that phase at zero. A transfer can stop with needs_authorization after consuming a one-use grant. Authorize explicitly, then call zotero_resume_transfer; it returns immediately and reuses the item and private snapshot in the background. Resuming an active transfer returns its status without starting another upload. Up to eight transfers/PDF operations share the existing admission limit. Shutdown cancels active transfers and saves an uncertain state for explicit resume; reopening the server does not automatically retry writes. Transfer records live under the work directory, while temporary upload credentials live only in credential/ and are removed after completion. Expired tokens restart upload authorization. Snapshot changes are rejected. A lost registration response is reconciled against the attachment's stored hash before another upload is attempted. Keep both directories to resume across restarts; files left before the first transfer checkpoint are not completed transfers.

Version checks occur before upload and registration. The local file API atomically checks stored MD5 at authorization/registration; it does not enforce the metadata version at registration or guarantee detection of external file edits not reflected in that hash. Replacement overwrites Zotero's stored file and does not make a remote backup or adjust annotation coordinates. Use import for a separate attachment when you need to retain the old stored file. Desktop attachment paths are never opened.

Indexing is explicit and separate from upload. Call zotero_index_attachment with the matching local PDF, attachment key, expected item version, MD5 and a fresh library version. It snapshots and extracts the PDF, checks that its MD5 matches the stored attachment, then uses the bulk full-text endpoint with a library-version precondition. Use a searchable export for scans. Empty text is rejected; output above 8 MiB is rejected without truncation (JSON request limit: 10 MiB). This can index more text than the existing read tool's 2 MiB upstream-response limit permits reading back.

Metadata and downloads

metadata_lookup supports DOI through Crossref, ISBN through Open Library, PMID through PubMed, and arXiv identifiers through arXiv. Each lookup sends only the specified identifier, returns provider provenance and normalized candidate fields, and does not edit Zotero. Some DOIs are outside Crossref's coverage. Paper URLs are candidates and may still be inaccessible or lead to landing pages. URLs containing query parameters are omitted from lookup results to avoid exposing signed tokens.

pdf_identify checks embedded PDF metadata and up to five pages of existing text. It does not run OCR or upload the PDF. Identifiers can belong to references rather than the paper itself; choose the identifier explicitly for lookup. The duplicate tool performs a bounded local search, not a complete duplicate-detection guarantee.

zotero_enrich_item defaults to a preview containing before/after values and provenance. Applying requires apply: true, an explicit fields list, write authorization and an unchanged item version. It preserves the existing item type and reports type mismatches. Every call fetches provider data again; to apply the exact previously reviewed values, pass that patch to zotero_update_item instead.

paper_download accepts a public HTTPS URL on port 443, follows at most five redirects, and validates the completed PDF before returning its private local path. Each hop resolves only public addresses, pins the connection to a vetted IP, and retains the original hostname for TLS verification. Cookies, authorization headers, environment proxies, private network destinations, and compressed transfers are not used. Downloads have a three-minute total deadline and the configured PDF input size limit. Failed transfers are removed; downloads restart from the beginning. Only the final host is retained in provenance, never a potentially signed URL. Authentication, paywall bypass and browser sessions are outside this implementation.

The workflow is metadata_lookup → paper_download → optional PDF/OCR/export → zotero_import_attachment or zotero_replace_attachment → zotero_index_attachment. Each library change is an explicit tool call.

API references: Zotero local API, write requests, file uploads, full-text content.

Security boundaries

  • The original read adapter remains GET-only. The optional write adapter uses a separate method/endpoint allowlist at the same fixed loopback address. No Zotero tool accepts an arbitrary API endpoint, HTTP method, API key, or request header. Local API redirects, upload URLs and remote pagination links are never followed.

  • HTTP proxy environment variables are ignored for Zotero requests. No .env files are loaded. Explicit authorization/write calls alone access saved credentials; HTTP protocol tracing is suppressed to avoid exposing keys, cookies, and signed URLs.

  • Original read requests have a 15-second overall deadline, a 10-second socket timeout and a 3-second connect timeout. Local write/schema requests default to 30 seconds, except authorization and raw uploads as described above. Each local adapter admits four concurrent requests. Public requests admit three and pace requests per host (at least 3.1 seconds for arXiv, 1.1 seconds for other hosts).

  • For local HTTP/1.0 JSON without response framing, the client signals request EOF only after a complete JSON object/array has arrived, avoiding Zotero's delayed connection close. It still reads to response EOF, enforces byte/time limits, and rejects trailing invalid data. Slow/incomplete bodies do not trigger the signal. Other responses and transports without socket access retain ordinary HTTP reads.

  • Upstream JSON is limited to 2 MiB, including bodies without a Content-Length. Compressed responses are rejected. Full-text output is capped at 50,000 characters per call; pagination does not bypass the upstream 2 MiB limit.

  • New capabilities require their launch flags and do not run on startup. Local PDF tools create working copies; explicit attachment/index/library tools perform the authorized API writes. There are no cloud embedding or desktop integration calls.

  • Titles, notes and full text remain untrusted content. MCP tool annotations and instructions are hints, not protection against all prompt injection. Content returned to an AI client can be sent to that client's model provider.

  • This is an application-level restriction, not an OS sandbox. The Python process retains its user's filesystem and network permissions. Compromised dependencies could bypass these checks.

Verification and maintenance

Development uses the dev branch. Keep credentials only in ./credential/, with directory permissions 0700 and credential file permissions 0600. The default read-only mode neither requires nor loads credentials. Keep the implementation plan and temporary artifacts in ./tmp/. Both directories are ignored by Git; do not force-add their contents. Root directories use singular names: credential/, script/, and test/.

With pip, after installing the project as above:

.venv/bin/python -m pip install --require-hashes -r requirements_dev.txt
.venv/bin/python -m pytest -q
.venv/bin/python script/smoke.py
.venv/bin/python script/audit_dependencies.py

Or with uv:

uv sync --locked --all-extras --python 3.13
uv run --locked --all-extras pytest -q
uv run --locked python script/smoke.py
uv run --locked python script/audit_dependencies.py

Unit/protocol tests cover synthetic PDFs, checkpoint recovery, concurrent resume, memory admission, searchable export, authorization/conflicts, upload recovery, metadata conversion, public-network boundaries, and mocked OCR results; they do not require model downloads, Tesseract, or a running Zotero. PDF tests are skipped if the PDF extra is absent; install all development requirements to run the complete suite. The explicit smoke script performs bounded read-only requests and reports counts, not paper contents. Its full-text check is skipped if the bounded sample contains no indexed attachment.

The dependency audit sends only public package names and versions to OSV. A clean result means no published matching advisories were found; it does not establish safety. The audit reads all registry packages in uv.lock, including development and platform-specific dependencies; it excludes the local project. It does not audit the separately installed uv executable or isolated build dependencies.

To update to the latest stable versions allowed by the declared compatibility ranges, resolve once and regenerate all exports from that same lock:

uv lock --upgrade
uv export --locked --no-dev --no-emit-project --output-file requirements.txt
uv export --locked --all-extras --no-emit-project --output-file requirements_dev.txt
uv export --locked --no-dev --extra pdf --no-emit-project --output-file requirements_pdf.txt
uv export --locked --no-dev --extra ocr --no-emit-project --output-file requirements_ocr.txt
uv sync --locked --all-extras
uv run --locked --all-extras pytest -q
uv run --locked python script/audit_dependencies.py

Review the lockfile changes and any compatibility constraints before committing. For a targeted upgrade, use uv lock --upgrade-package PACKAGE. Major upgrades outside the declared ranges require deliberately changing pyproject.toml first. Use uv lock --check to detect an out-of-date lock without changing it. Never hand-edit uv.lock or the generated requirements exports. See uv locking and syncing.

Reference documentation: MCP Python SDK and Zotero API reads.

Tool Schema Changelog

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

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers