code-mode-for-zotero 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. code_mode_for_zotero-0.1.0/.gitignore +9 -0
  2. code_mode_for_zotero-0.1.0/CHANGELOG.md +18 -0
  3. code_mode_for_zotero-0.1.0/LICENSE +22 -0
  4. code_mode_for_zotero-0.1.0/NOTICE +14 -0
  5. code_mode_for_zotero-0.1.0/PKG-INFO +139 -0
  6. code_mode_for_zotero-0.1.0/PRIVACY.md +17 -0
  7. code_mode_for_zotero-0.1.0/README.md +105 -0
  8. code_mode_for_zotero-0.1.0/SECURITY.md +26 -0
  9. code_mode_for_zotero-0.1.0/pyproject.toml +73 -0
  10. code_mode_for_zotero-0.1.0/src/code_mode_zotero/__init__.py +4 -0
  11. code_mode_for_zotero-0.1.0/src/code_mode_zotero/__main__.py +5 -0
  12. code_mode_for_zotero-0.1.0/src/code_mode_zotero/_sandbox_child.py +182 -0
  13. code_mode_for_zotero-0.1.0/src/code_mode_zotero/bbt_keys.py +116 -0
  14. code_mode_for_zotero-0.1.0/src/code_mode_zotero/codemode_api.py +547 -0
  15. code_mode_for_zotero-0.1.0/src/code_mode_zotero/codemode_server.py +232 -0
  16. code_mode_for_zotero-0.1.0/src/code_mode_zotero/collections_scope.py +93 -0
  17. code_mode_for_zotero-0.1.0/src/code_mode_zotero/data/zotero_basefields.json +1398 -0
  18. code_mode_for_zotero-0.1.0/src/code_mode_zotero/extract.py +829 -0
  19. code_mode_for_zotero-0.1.0/src/code_mode_zotero/fulltext_cache.py +266 -0
  20. code_mode_for_zotero-0.1.0/src/code_mode_zotero/library.py +366 -0
  21. code_mode_for_zotero-0.1.0/src/code_mode_zotero/local_db.py +3805 -0
  22. code_mode_for_zotero-0.1.0/src/code_mode_zotero/rag.py +531 -0
  23. code_mode_for_zotero-0.1.0/src/code_mode_zotero/sandbox.py +392 -0
  24. code_mode_for_zotero-0.1.0/src/code_mode_zotero/schema.py +177 -0
  25. code_mode_for_zotero-0.1.0/src/code_mode_zotero/search_semantics.py +260 -0
  26. code_mode_for_zotero-0.1.0/src/code_mode_zotero/strict_sqlite.py +207 -0
  27. code_mode_for_zotero-0.1.0/src/code_mode_zotero/utils.py +856 -0
  28. code_mode_for_zotero-0.1.0/tests/_full_db.py +121 -0
  29. code_mode_for_zotero-0.1.0/tests/_search_corpus.py +393 -0
  30. code_mode_for_zotero-0.1.0/tests/conftest.py +45 -0
  31. code_mode_for_zotero-0.1.0/tests/test_bbt_keys.py +87 -0
  32. code_mode_for_zotero-0.1.0/tests/test_codemode_server.py +178 -0
  33. code_mode_for_zotero-0.1.0/tests/test_collection_scope_expansion.py +174 -0
  34. code_mode_for_zotero-0.1.0/tests/test_composed_display_titles.py +194 -0
  35. code_mode_for_zotero-0.1.0/tests/test_creator_formatting.py +73 -0
  36. code_mode_for_zotero-0.1.0/tests/test_date_range_conditions.py +67 -0
  37. code_mode_for_zotero-0.1.0/tests/test_embedding_function_registration.py +198 -0
  38. code_mode_for_zotero-0.1.0/tests/test_extract.py +660 -0
  39. code_mode_for_zotero-0.1.0/tests/test_extract_ocr.py +390 -0
  40. code_mode_for_zotero-0.1.0/tests/test_extract_repair.py +107 -0
  41. code_mode_for_zotero-0.1.0/tests/test_extract_yaml.py +38 -0
  42. code_mode_for_zotero-0.1.0/tests/test_full_item_date_fields.py +24 -0
  43. code_mode_for_zotero-0.1.0/tests/test_fulltext_cache.py +229 -0
  44. code_mode_for_zotero-0.1.0/tests/test_fulltext_non_pdf_html.py +155 -0
  45. code_mode_for_zotero-0.1.0/tests/test_gemini_batch.py +218 -0
  46. code_mode_for_zotero-0.1.0/tests/test_index_record_builder.py +151 -0
  47. code_mode_for_zotero-0.1.0/tests/test_install_hint.py +102 -0
  48. code_mode_for_zotero-0.1.0/tests/test_local_db.py +568 -0
  49. code_mode_for_zotero-0.1.0/tests/test_local_db_discovery.py +177 -0
  50. code_mode_for_zotero-0.1.0/tests/test_local_db_wal_snapshot.py +420 -0
  51. code_mode_for_zotero-0.1.0/tests/test_multicore_extraction.py +305 -0
  52. code_mode_for_zotero-0.1.0/tests/test_note_search_limit.py +76 -0
  53. code_mode_for_zotero-0.1.0/tests/test_rag.py +350 -0
  54. code_mode_for_zotero-0.1.0/tests/test_sandbox.py +172 -0
  55. code_mode_for_zotero-0.1.0/tests/test_schema.py +121 -0
  56. code_mode_for_zotero-0.1.0/tests/test_search_database_status.py +112 -0
  57. code_mode_for_zotero-0.1.0/tests/test_search_variant_order.py +48 -0
  58. code_mode_for_zotero-0.1.0/tests/test_sqlite_backend_collection_items.py +52 -0
  59. code_mode_for_zotero-0.1.0/tests/test_write_json_atomic.py +51 -0
  60. code_mode_for_zotero-0.1.0/tests/test_zotero_ft_cache.py +223 -0
@@ -0,0 +1,9 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ dist/
7
+ build/
8
+ *.egg-info/
9
+ .DS_Store
@@ -0,0 +1,18 @@
1
+ # Changelog
2
+
3
+ All notable changes are listed here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and versions follow [Semantic Versioning](https://semver.org/).
4
+
5
+ ## [Unreleased]
6
+
7
+ ## [0.1.0] - 2026-11-28
8
+
9
+ First release as a standalone project, extracted from a fork of Zotero MCP 0.17.4.
10
+
11
+ ### Added
12
+ - MCP server with two tools, `search_api` and `execute`, in code mode.
13
+ - Read API for scripts: `search`, `get_item` (Zotero keys, citation keys, Better BibTeX keys, all libraries), `fulltext` and `find` with page numbers, `passages`, `rag_index`, `rag_status`.
14
+ - Sandbox for scripts: separate process, allowlisted calls, `sandbox-exec` on macOS (including Homebrew and Xcode Pythons), network namespace on Linux, resource limits, `--check-sandbox`.
15
+ - Passage index in SQLite: page-bound passages, reference lists and tables filtered, FTS5 over French and English stems, optional embeddings from any OpenAI-compatible endpoint, reciprocal rank fusion, keyword fallback when the endpoint is down. `--index`, `--index --force`, `--check-embeddings`.
16
+
17
+ ### Removed (compared with Zotero MCP)
18
+ - The 38 per-operation tools, write operations, the Zotero web API path, WebDAV, the Zotero browser plugin, ChromaDB semantic search and the online schema refresh. The server reads only local files and makes no network call except to the embeddings endpoint you configure.
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Loïc Talignani and Thierry Valéro
4
+ Copyright (c) 2025 Zotero MCP Contributors
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1,14 @@
1
+ Code Mode for Zotero
2
+ Copyright (c) 2026 Loïc Talignani and Thierry Valéro
3
+
4
+ This project started from Zotero MCP (https://github.com/54yyyu/zotero-mcp),
5
+ MIT License, Copyright (c) 2025 Zotero MCP Contributors, at commit 0e6ff62
6
+ (release 0.17.4). The modules local_db, library, extract, utils, schema,
7
+ strict_sqlite, fulltext_cache, search_semantics and collections_scope, the
8
+ vendored data/zotero_basefields.json, and part of the test suite come from
9
+ that project, adapted. The Zotero browser-plugin part of Zotero MCP, which is
10
+ under the AGPL, is not included.
11
+
12
+ Zotero is a project of the Corporation for Digital Scholarship.
13
+ This project is not affiliated with or endorsed by Zotero or the Corporation
14
+ for Digital Scholarship.
@@ -0,0 +1,139 @@
1
+ Metadata-Version: 2.5
2
+ Name: code-mode-for-zotero
3
+ Version: 0.1.0
4
+ Summary: A local MCP server that lets an AI assistant read your Zotero library by writing short Python scripts, run in a sandbox, with page-level passage search.
5
+ Project-URL: Homepage, https://github.com/ltalignani/code-mode-for-zotero
6
+ Project-URL: Issues, https://github.com/ltalignani/code-mode-for-zotero/issues
7
+ Project-URL: Changelog, https://github.com/ltalignani/code-mode-for-zotero/blob/main/CHANGELOG.md
8
+ Author: Loïc Talignani, Thierry Valéro
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ License-File: NOTICE
12
+ Keywords: bibliography,claude,code mode,mcp,model context protocol,rag,zotero
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Operating System :: MacOS
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Topic :: Scientific/Engineering
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: fastmcp<5,>=3
21
+ Requires-Dist: httpx>=0.27
22
+ Requires-Dist: markdownify>=1.2
23
+ Requires-Dist: pdf-inspector==0.2.6
24
+ Requires-Dist: snowballstemmer>=2.2
25
+ Requires-Dist: unidecode>=1.3
26
+ Provides-Extra: dev
27
+ Requires-Dist: numpy>=1.26; extra == 'dev'
28
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
29
+ Requires-Dist: pytest>=8; extra == 'dev'
30
+ Requires-Dist: ruff>=0.6; extra == 'dev'
31
+ Provides-Extra: embeddings
32
+ Requires-Dist: numpy>=1.26; extra == 'embeddings'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # Code Mode for Zotero
36
+
37
+ Read your Zotero library from Claude, ChatGPT or any MCP client, by letting the model write short Python scripts instead of calling dozens of tools. The scripts run in a sandbox on your computer, read the local `zotero.sqlite`, and only what they print goes back to the model. Passages can be searched by meaning, in French or English, and every hit comes with its page, so answers can be cited as `citekey, p. 12`.
38
+
39
+ > Not affiliated with Zotero or the Corporation for Digital Scholarship. Zotero is their project; this is an independent tool that reads the files Zotero keeps on your disk.
40
+
41
+ Status: alpha (0.1). macOS and Linux. Windows is not supported yet, because scripts cannot be isolated there.
42
+
43
+ ## Why code mode
44
+
45
+ A classic Zotero MCP server exposes one tool per operation, which puts thousands of tokens of tool definitions in every conversation and sends every intermediate result through the model. This server has two tools:
46
+
47
+ | Tool | What it does |
48
+ |---|---|
49
+ | `search_api(query="")` | Lists the `zotero.*` functions a script can call, with their documentation. |
50
+ | `execute(code, timeout_seconds=30)` | Runs a script and returns what it printed. |
51
+
52
+ The two definitions take about 230 tokens. A search over 200 items, a filter and a sort happen inside the script, and only the five lines the script prints reach the model.
53
+
54
+ ## What a script can call
55
+
56
+ All read-only. Records are small flat dicts (key, title, creators, year, DOI, tags, `citationKey`, library).
57
+
58
+ | Function | Returns |
59
+ |---|---|
60
+ | `zotero.search(query, ...)` | Items matching a query, at most 200 |
61
+ | `zotero.get_item(ref, detail)` | One item, by Zotero key, citation key or Better BibTeX key |
62
+ | `zotero.fulltext(ref, first, last)` | The text of an item's PDF, one entry per page |
63
+ | `zotero.find(ref, query)` | Paragraphs of one document that contain every word, with page numbers |
64
+ | `zotero.passages(query, limit, keys)` | The most relevant passages across the library, with page numbers |
65
+ | `zotero.rag_index(...)`, `zotero.rag_status()` | Build and inspect the passage index |
66
+
67
+ Every library in the database is searched (personal and groups) unless `ZOTERO_MCP_LIBRARY` says otherwise (`0` for the personal library, or a group id).
68
+
69
+ ## Install
70
+
71
+ Requires Python 3.10 or later and Zotero installed on the same computer (it does not need to be running).
72
+
73
+ ```bash
74
+ uv tool install 'code-mode-for-zotero[embeddings]' # or: pipx install ..., pip install ...
75
+ code-mode-zotero --check-sandbox # what scripts can and cannot do here
76
+ ```
77
+
78
+ Claude Desktop, in `claude_desktop_config.json`:
79
+
80
+ ```json
81
+ {
82
+ "mcpServers": {
83
+ "zotero": {
84
+ "command": "code-mode-zotero",
85
+ "env": {
86
+ "ZOTERO_RAG_EMBED_URL": "http://localhost:1234/v1",
87
+ "ZOTERO_RAG_EMBED_MODEL": "text-embedding-bge-m3"
88
+ }
89
+ }
90
+ }
91
+ }
92
+ ```
93
+
94
+ The `env` block is optional; without it, passage search works on keywords only. Claude Desktop does not read your shell profile, so variables go in this block.
95
+
96
+ ## Passage search
97
+
98
+ ```bash
99
+ code-mode-zotero --check-embeddings # one call to your embeddings server, with a sanity check
100
+ code-mode-zotero --index # build or refresh the index; resumable
101
+ code-mode-zotero --index --force # rebuild everything, e.g. after changing the model
102
+ ```
103
+
104
+ Passages are cut from each PDF without crossing a page, cleaned of reference lists, tables and line numbers, and stored in one SQLite file. Keyword search uses French and English word stems, so "pyréthrinoïde" finds "pyréthrinoïdes". When an embeddings endpoint is configured (LM Studio, Ollama, vLLM or any OpenAI-compatible `/v1/embeddings`), passages are also ranked by meaning and the two rankings are merged. If the endpoint is unreachable, search falls back to keywords and says so in each result.
105
+
106
+ ## What it runs, reads, writes and sends
107
+
108
+ This section is complete; if the code does something not listed here, it is a bug.
109
+
110
+ - **Runs**: the MCP server, and for each `execute` call a child Python process with the script. On macOS the child runs under `sandbox-exec` with no network, no file writes, no new processes and no access to your home folder; on Linux it runs in an empty network namespace (files and processes are not blocked there, so scripts only run with `ZOTERO_MCP_SANDBOX=relaxed`). CPU time, output size and run time are limited everywhere, memory on Linux.
111
+ - **Reads**: `zotero.sqlite`, read-only (it may be copied to a temporary folder so it can be read while Zotero is writing), `better-bibtex.sqlite` if present, and attachment files in Zotero's storage folder.
112
+ - **Writes**: the passage index (`~/.local/share/code-mode-for-zotero/rag.sqlite`, or `ZOTERO_RAG_DB`) and a cache of extracted text (`~/.cache/code-mode-for-zotero/fulltext/`). It never writes to your Zotero library.
113
+ - **Sends**: passage text and search queries to the embeddings endpoint you configure, and nowhere else. With no endpoint configured, the server makes no network call. There is no telemetry.
114
+
115
+ See [PRIVACY.md](PRIVACY.md) and [SECURITY.md](SECURITY.md).
116
+
117
+ ## Settings
118
+
119
+ | Variable | Default | Meaning |
120
+ |---|---|---|
121
+ | `ZOTERO_DB_PATH` | found automatically | Path to `zotero.sqlite` |
122
+ | `ZOTERO_BBT_DB` | next to `zotero.sqlite` | Path to `better-bibtex.sqlite` |
123
+ | `ZOTERO_MCP_LIBRARY` | `all` | `all`, `0` (personal) or a group id |
124
+ | `ZOTERO_MCP_SANDBOX` | `strict` | `relaxed` runs scripts without full isolation |
125
+ | `ZOTERO_RAG_DB` | `~/.local/share/code-mode-for-zotero/rag.sqlite` | Passage index |
126
+ | `ZOTERO_RAG_EMBED_URL` | none | OpenAI-compatible endpoint, e.g. `http://localhost:1234/v1` |
127
+ | `ZOTERO_RAG_EMBED_MODEL` | `nomic-embed-text` | Embedding model name |
128
+ | `ZOTERO_RAG_EMBED_KEY` | none | Bearer token, if the endpoint needs one |
129
+
130
+ ## Limits
131
+
132
+ - Read-only: no adding, tagging or annotating items.
133
+ - A timeout stops a script but not a database call already running.
134
+ - Scanned PDFs without a text layer are reported (`needsOcr`) and not indexed.
135
+ - An index built with one embedding model cannot be queried with another.
136
+
137
+ ## Authors and origin
138
+
139
+ Loïc Talignani and Thierry Valéro. The data-access layer comes from [Zotero MCP](https://github.com/54yyyu/zotero-mcp) (MIT); see [NOTICE](NOTICE). MIT License.
@@ -0,0 +1,17 @@
1
+ # Privacy
2
+
3
+ Code Mode for Zotero runs on your computer and keeps your library there.
4
+
5
+ **What it reads.** Your local Zotero database (`zotero.sqlite`), the Better BibTeX database if you have one, and the attachment files in Zotero's storage folder. Only when an MCP client asks it to, through a script the model wrote.
6
+
7
+ **What it stores.** A passage index and a cache of text extracted from your PDFs, both in your home folder (paths in the README). Delete them at any time; they are rebuilt on demand. Nothing is written to your Zotero library.
8
+
9
+ **What leaves your computer.**
10
+
11
+ - To the AI assistant you use (Claude, ChatGPT or another MCP client): whatever the scripts print, which is what the model asked for. That assistant's own privacy policy applies to it.
12
+ - To the embeddings endpoint you configure with `ZOTERO_RAG_EMBED_URL`, if any: the text of passages when the index is built, and your search queries. Point it at a server on your own machine or network (LM Studio, Ollama) to keep this local.
13
+ - Nothing else. No telemetry, no analytics, no update checks, no call to Zotero's servers.
14
+
15
+ **Personal data.** Your library may contain personal data (authors' names, your notes). The server processes it only on your computer and only to answer your requests. It is not intended for use by children.
16
+
17
+ Contact: open an issue at https://github.com/ltalignani/code-mode-for-zotero/issues
@@ -0,0 +1,105 @@
1
+ # Code Mode for Zotero
2
+
3
+ Read your Zotero library from Claude, ChatGPT or any MCP client, by letting the model write short Python scripts instead of calling dozens of tools. The scripts run in a sandbox on your computer, read the local `zotero.sqlite`, and only what they print goes back to the model. Passages can be searched by meaning, in French or English, and every hit comes with its page, so answers can be cited as `citekey, p. 12`.
4
+
5
+ > Not affiliated with Zotero or the Corporation for Digital Scholarship. Zotero is their project; this is an independent tool that reads the files Zotero keeps on your disk.
6
+
7
+ Status: alpha (0.1). macOS and Linux. Windows is not supported yet, because scripts cannot be isolated there.
8
+
9
+ ## Why code mode
10
+
11
+ A classic Zotero MCP server exposes one tool per operation, which puts thousands of tokens of tool definitions in every conversation and sends every intermediate result through the model. This server has two tools:
12
+
13
+ | Tool | What it does |
14
+ |---|---|
15
+ | `search_api(query="")` | Lists the `zotero.*` functions a script can call, with their documentation. |
16
+ | `execute(code, timeout_seconds=30)` | Runs a script and returns what it printed. |
17
+
18
+ The two definitions take about 230 tokens. A search over 200 items, a filter and a sort happen inside the script, and only the five lines the script prints reach the model.
19
+
20
+ ## What a script can call
21
+
22
+ All read-only. Records are small flat dicts (key, title, creators, year, DOI, tags, `citationKey`, library).
23
+
24
+ | Function | Returns |
25
+ |---|---|
26
+ | `zotero.search(query, ...)` | Items matching a query, at most 200 |
27
+ | `zotero.get_item(ref, detail)` | One item, by Zotero key, citation key or Better BibTeX key |
28
+ | `zotero.fulltext(ref, first, last)` | The text of an item's PDF, one entry per page |
29
+ | `zotero.find(ref, query)` | Paragraphs of one document that contain every word, with page numbers |
30
+ | `zotero.passages(query, limit, keys)` | The most relevant passages across the library, with page numbers |
31
+ | `zotero.rag_index(...)`, `zotero.rag_status()` | Build and inspect the passage index |
32
+
33
+ Every library in the database is searched (personal and groups) unless `ZOTERO_MCP_LIBRARY` says otherwise (`0` for the personal library, or a group id).
34
+
35
+ ## Install
36
+
37
+ Requires Python 3.10 or later and Zotero installed on the same computer (it does not need to be running).
38
+
39
+ ```bash
40
+ uv tool install 'code-mode-for-zotero[embeddings]' # or: pipx install ..., pip install ...
41
+ code-mode-zotero --check-sandbox # what scripts can and cannot do here
42
+ ```
43
+
44
+ Claude Desktop, in `claude_desktop_config.json`:
45
+
46
+ ```json
47
+ {
48
+ "mcpServers": {
49
+ "zotero": {
50
+ "command": "code-mode-zotero",
51
+ "env": {
52
+ "ZOTERO_RAG_EMBED_URL": "http://localhost:1234/v1",
53
+ "ZOTERO_RAG_EMBED_MODEL": "text-embedding-bge-m3"
54
+ }
55
+ }
56
+ }
57
+ }
58
+ ```
59
+
60
+ The `env` block is optional; without it, passage search works on keywords only. Claude Desktop does not read your shell profile, so variables go in this block.
61
+
62
+ ## Passage search
63
+
64
+ ```bash
65
+ code-mode-zotero --check-embeddings # one call to your embeddings server, with a sanity check
66
+ code-mode-zotero --index # build or refresh the index; resumable
67
+ code-mode-zotero --index --force # rebuild everything, e.g. after changing the model
68
+ ```
69
+
70
+ Passages are cut from each PDF without crossing a page, cleaned of reference lists, tables and line numbers, and stored in one SQLite file. Keyword search uses French and English word stems, so "pyréthrinoïde" finds "pyréthrinoïdes". When an embeddings endpoint is configured (LM Studio, Ollama, vLLM or any OpenAI-compatible `/v1/embeddings`), passages are also ranked by meaning and the two rankings are merged. If the endpoint is unreachable, search falls back to keywords and says so in each result.
71
+
72
+ ## What it runs, reads, writes and sends
73
+
74
+ This section is complete; if the code does something not listed here, it is a bug.
75
+
76
+ - **Runs**: the MCP server, and for each `execute` call a child Python process with the script. On macOS the child runs under `sandbox-exec` with no network, no file writes, no new processes and no access to your home folder; on Linux it runs in an empty network namespace (files and processes are not blocked there, so scripts only run with `ZOTERO_MCP_SANDBOX=relaxed`). CPU time, output size and run time are limited everywhere, memory on Linux.
77
+ - **Reads**: `zotero.sqlite`, read-only (it may be copied to a temporary folder so it can be read while Zotero is writing), `better-bibtex.sqlite` if present, and attachment files in Zotero's storage folder.
78
+ - **Writes**: the passage index (`~/.local/share/code-mode-for-zotero/rag.sqlite`, or `ZOTERO_RAG_DB`) and a cache of extracted text (`~/.cache/code-mode-for-zotero/fulltext/`). It never writes to your Zotero library.
79
+ - **Sends**: passage text and search queries to the embeddings endpoint you configure, and nowhere else. With no endpoint configured, the server makes no network call. There is no telemetry.
80
+
81
+ See [PRIVACY.md](PRIVACY.md) and [SECURITY.md](SECURITY.md).
82
+
83
+ ## Settings
84
+
85
+ | Variable | Default | Meaning |
86
+ |---|---|---|
87
+ | `ZOTERO_DB_PATH` | found automatically | Path to `zotero.sqlite` |
88
+ | `ZOTERO_BBT_DB` | next to `zotero.sqlite` | Path to `better-bibtex.sqlite` |
89
+ | `ZOTERO_MCP_LIBRARY` | `all` | `all`, `0` (personal) or a group id |
90
+ | `ZOTERO_MCP_SANDBOX` | `strict` | `relaxed` runs scripts without full isolation |
91
+ | `ZOTERO_RAG_DB` | `~/.local/share/code-mode-for-zotero/rag.sqlite` | Passage index |
92
+ | `ZOTERO_RAG_EMBED_URL` | none | OpenAI-compatible endpoint, e.g. `http://localhost:1234/v1` |
93
+ | `ZOTERO_RAG_EMBED_MODEL` | `nomic-embed-text` | Embedding model name |
94
+ | `ZOTERO_RAG_EMBED_KEY` | none | Bearer token, if the endpoint needs one |
95
+
96
+ ## Limits
97
+
98
+ - Read-only: no adding, tagging or annotating items.
99
+ - A timeout stops a script but not a database call already running.
100
+ - Scanned PDFs without a text layer are reported (`needsOcr`) and not indexed.
101
+ - An index built with one embedding model cannot be queried with another.
102
+
103
+ ## Authors and origin
104
+
105
+ Loïc Talignani and Thierry Valéro. The data-access layer comes from [Zotero MCP](https://github.com/54yyyu/zotero-mcp) (MIT); see [NOTICE](NOTICE). MIT License.
@@ -0,0 +1,26 @@
1
+ # Security
2
+
3
+ ## Reporting a vulnerability
4
+
5
+ Please report security problems privately, through GitHub's "Report a vulnerability" button on this repository (Security tab), rather than in a public issue. We aim to acknowledge reports within 7 days and to publish a fix or a mitigation within 30 days for confirmed issues.
6
+
7
+ ## What the sandbox protects against
8
+
9
+ Scripts are written by a language model, and the text of your PDFs can contain instructions aimed at that model. The server therefore treats every script as untrusted:
10
+
11
+ - The script runs in a separate process with no database connection. Every `zotero.*` call goes back to the server over a pipe, and only the public read-only functions are answered, with JSON arguments.
12
+ - On macOS, the process runs under `sandbox-exec`: no network, no file writes, no new processes, no reading of your home folder or `/Volumes`. This is the only configuration reported as fully isolated.
13
+ - On Linux, the process runs in an empty network namespace. Files and processes are not restricted, so the server refuses to run scripts there unless `ZOTERO_MCP_SANDBOX=relaxed` is set.
14
+ - On every platform: CPU time, file size (zero), core dumps, run time (1 to 120 s) and output size are limited; memory is limited on Linux.
15
+
16
+ Run `code-mode-zotero --check-sandbox` to see what your machine provides. It tries to reach the network, write a file, create a folder, list your home folder, start a process and call a function that does not exist, and reports each result.
17
+
18
+ ## What it does not protect against
19
+
20
+ - A model that answers you with false information, including information planted in a PDF. Check citations against the page they cite.
21
+ - Anything your MCP client itself is allowed to do.
22
+ - A compromised Python installation or a malicious dependency. Install from PyPI, where releases are built by GitHub Actions with Trusted Publishing.
23
+
24
+ ## Supported versions
25
+
26
+ Only the latest release receives fixes during the 0.x series.
@@ -0,0 +1,73 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "code-mode-for-zotero"
7
+ version = "0.1.0"
8
+ description = "A local MCP server that lets an AI assistant read your Zotero library by writing short Python scripts, run in a sandbox, with page-level passage search."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE", "NOTICE"]
13
+ authors = [
14
+ { name = "Loïc Talignani" },
15
+ { name = "Thierry Valéro" },
16
+ ]
17
+ keywords = ["zotero", "mcp", "model context protocol", "code mode", "rag", "bibliography", "claude"]
18
+ classifiers = [
19
+ "Development Status :: 3 - Alpha",
20
+ "Intended Audience :: Science/Research",
21
+ "Operating System :: MacOS",
22
+ "Operating System :: POSIX :: Linux",
23
+ "Programming Language :: Python :: 3",
24
+ "Topic :: Scientific/Engineering",
25
+ ]
26
+ dependencies = [
27
+ # MCP server. Majors 3 and 4 are supported; 5 is untested.
28
+ "fastmcp>=3,<5",
29
+ # PDF text extraction (Rust, prebuilt wheels). Pinned while pre-1.0:
30
+ # the extracted text is what users read and what the index stores.
31
+ "pdf-inspector==0.2.6",
32
+ # HTML attachments to Markdown.
33
+ "markdownify>=1.2",
34
+ # Accent folding for search.
35
+ "unidecode>=1.3",
36
+ # French and English word stems for keyword search. Pure Python.
37
+ "snowballstemmer>=2.2",
38
+ # Calls to the embeddings endpoint the user configures. Nothing else.
39
+ "httpx>=0.27",
40
+ ]
41
+
42
+ [project.optional-dependencies]
43
+ # Vector search. Without numpy the index runs on keywords only.
44
+ embeddings = ["numpy>=1.26"]
45
+ dev = ["pytest>=8", "pytest-asyncio>=0.23", "ruff>=0.6", "numpy>=1.26"]
46
+
47
+ [project.scripts]
48
+ code-mode-zotero = "code_mode_zotero.codemode_server:main"
49
+
50
+ [project.urls]
51
+ Homepage = "https://github.com/ltalignani/code-mode-for-zotero"
52
+ Issues = "https://github.com/ltalignani/code-mode-for-zotero/issues"
53
+ Changelog = "https://github.com/ltalignani/code-mode-for-zotero/blob/main/CHANGELOG.md"
54
+
55
+ [tool.hatch.build.targets.wheel]
56
+ packages = ["src/code_mode_zotero"]
57
+
58
+ [tool.hatch.build.targets.sdist]
59
+ include = ["src", "tests", "README.md", "LICENSE", "NOTICE", "CHANGELOG.md", "SECURITY.md", "PRIVACY.md"]
60
+
61
+ [tool.ruff]
62
+ line-length = 110
63
+ target-version = "py310"
64
+
65
+ [tool.ruff.lint]
66
+ select = ["E", "F", "I", "B", "UP"]
67
+ # Long SQL and test literals read better unwrapped; zip() over equal-length
68
+ # sequences is the norm here.
69
+ ignore = ["E501", "B905"]
70
+
71
+ [tool.pytest.ini_options]
72
+ testpaths = ["tests"]
73
+ asyncio_mode = "auto"
@@ -0,0 +1,4 @@
1
+ """Code Mode for Zotero: a local MCP server that lets a model read a Zotero
2
+ library by writing short Python scripts, run in a sandbox."""
3
+
4
+ __version__ = "0.1.0"
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from code_mode_zotero.codemode_server import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,182 @@
1
+ """Child process that runs model-written code. Standard library only.
2
+
3
+ This file is run as a script (``python -I -B _sandbox_child.py IN OUT``) and
4
+ must not import anything from ``code_mode_zotero``: the child has no access to the
5
+ Zotero database, the library, or the network. Everything it can learn about
6
+ the library comes through the ``zotero`` object, whose methods forward each
7
+ call to the parent over a pipe and return the parent's JSON answer. The
8
+ parent decides which methods exist and checks every call.
9
+
10
+ Protocol, one JSON object per line:
11
+
12
+ parent -> child ``{"init": {"code", "methods", "timeout", "max_output"}}``
13
+ child -> parent ``{"id", "method", "args", "kwargs"}`` a call
14
+ parent -> child ``{"id", "result"}`` or ``{"id", "error"}`` its answer
15
+ child -> parent ``{"done": true, "stdout", "error", "truncated"}``
16
+
17
+ Nothing here is a security boundary on its own. The boundary is the operating
18
+ system sandbox the parent wraps this process in; the limits below only keep a
19
+ runaway script from hurting the machine when that sandbox is partial.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import ast
25
+ import contextlib
26
+ import json
27
+ import linecache
28
+ import os
29
+ import sys
30
+ import traceback
31
+
32
+ _FILENAME = "<script>"
33
+
34
+
35
+ class ZoteroCallError(Exception):
36
+ """The parent refused or failed a call made through ``zotero``."""
37
+
38
+
39
+ class _Bounded:
40
+ """A text sink that keeps the first ``limit`` characters and counts the rest."""
41
+
42
+ def __init__(self, limit: int) -> None:
43
+ self.limit = limit
44
+ self.parts: list[str] = []
45
+ self.size = 0
46
+ self.truncated = False
47
+
48
+ def write(self, text: str) -> int:
49
+ room = self.limit - self.size
50
+ if room > 0:
51
+ self.parts.append(text[:room])
52
+ self.size += min(len(text), room)
53
+ if len(text) > room:
54
+ self.truncated = True
55
+ return len(text)
56
+
57
+ def flush(self) -> None:
58
+ pass
59
+
60
+ def getvalue(self) -> str:
61
+ return "".join(self.parts)
62
+
63
+
64
+ def _apply_limits(cpu_seconds: int) -> None:
65
+ try:
66
+ import resource
67
+ except ImportError: # not POSIX
68
+ return
69
+ for name, value in (
70
+ ("RLIMIT_CPU", cpu_seconds),
71
+ ("RLIMIT_FSIZE", 0), # no file can grow: writes fail with EFBIG
72
+ ("RLIMIT_CORE", 0),
73
+ ("RLIMIT_AS", 2 * 1024**3), # enforced on Linux, ignored on macOS
74
+ ):
75
+ try:
76
+ limit = getattr(resource, name)
77
+ resource.setrlimit(limit, (value, value))
78
+ except (ValueError, OSError):
79
+ pass
80
+
81
+
82
+ class _Channel:
83
+ def __init__(self, read_fd: int, write_fd: int) -> None:
84
+ self._in = os.fdopen(read_fd, "r", encoding="utf-8", newline="\n")
85
+ self._out = os.fdopen(write_fd, "w", encoding="utf-8", newline="\n")
86
+ self._next = 0
87
+
88
+ def send(self, message: dict) -> None:
89
+ self._out.write(json.dumps(message, ensure_ascii=False) + "\n")
90
+ self._out.flush()
91
+
92
+ def receive(self) -> dict:
93
+ line = self._in.readline()
94
+ if not line:
95
+ raise SystemExit(0) # the parent went away
96
+ return json.loads(line)
97
+
98
+ def call(self, method: str, args: tuple, kwargs: dict):
99
+ self._next += 1
100
+ call_id = self._next
101
+ self.send({"id": call_id, "method": method, "args": list(args), "kwargs": kwargs})
102
+ while True:
103
+ reply = self.receive()
104
+ if reply.get("id") == call_id:
105
+ break
106
+ if "error" in reply:
107
+ raise ZoteroCallError(reply["error"])
108
+ return reply["result"]
109
+
110
+
111
+ class _Zotero:
112
+ """Forwards method calls to the parent. Only listed methods exist."""
113
+
114
+ def __init__(self, channel: _Channel, methods: list[str]) -> None:
115
+ self._channel = channel
116
+ self._methods = frozenset(methods)
117
+
118
+ def __getattr__(self, name: str):
119
+ if name.startswith("_") or name not in self._methods:
120
+ raise AttributeError(f"zotero has no method {name!r}; available: {sorted(self._methods)}")
121
+
122
+ def call(*args, **kwargs):
123
+ return self._channel.call(name, args, kwargs)
124
+
125
+ call.__name__ = name
126
+ return call
127
+
128
+ def __dir__(self):
129
+ return sorted(self._methods)
130
+
131
+ def __repr__(self) -> str:
132
+ return f"<zotero: {', '.join(sorted(self._methods))}>"
133
+
134
+
135
+ def _run(code: str, namespace: dict) -> None:
136
+ """Run ``code`` like a notebook cell: a final bare expression is printed."""
137
+ lines = code.splitlines(keepends=True)
138
+ linecache.cache[_FILENAME] = (len(code), None, lines, _FILENAME) # so errors can show the line
139
+ tree = ast.parse(code, _FILENAME, "exec")
140
+ last = None
141
+ if tree.body and isinstance(tree.body[-1], ast.Expr):
142
+ last = ast.Expression(tree.body.pop().value)
143
+ exec(compile(tree, _FILENAME, "exec"), namespace)
144
+ if last is not None:
145
+ value = eval(compile(last, _FILENAME, "eval"), namespace)
146
+ if value is not None:
147
+ print(repr(value))
148
+
149
+
150
+ def _format_error(exc: BaseException) -> str:
151
+ """The error as the script's author needs it: their own frames only."""
152
+ if isinstance(exc, SyntaxError):
153
+ where = f"line {exc.lineno}" if exc.lineno else "script"
154
+ return f"SyntaxError ({where}): {exc.msg}"
155
+ own = [f for f in traceback.extract_tb(exc.__traceback__) if f.filename == _FILENAME]
156
+ lines = ["Traceback (most recent call last):\n"] if own else []
157
+ lines += traceback.StackSummary.from_list(own).format()
158
+ lines += traceback.format_exception_only(type(exc), exc)
159
+ return "".join(lines).rstrip()
160
+
161
+
162
+ def main(argv: list[str]) -> int:
163
+ channel = _Channel(int(argv[1]), int(argv[2]))
164
+ init = channel.receive()["init"]
165
+ _apply_limits(int(init.get("timeout", 30)) + 5)
166
+
167
+ sink = _Bounded(int(init.get("max_output", 20_000)))
168
+ namespace = {"__name__": "__main__", "zotero": _Zotero(channel, init["methods"])}
169
+ error = None
170
+ with contextlib.redirect_stdout(sink), contextlib.redirect_stderr(sink):
171
+ try:
172
+ _run(init["code"], namespace)
173
+ except SystemExit as exc:
174
+ error = None if exc.code in (None, 0) else f"SystemExit: {exc.code}"
175
+ except BaseException as exc: # noqa: BLE001 - the script's failure is the result
176
+ error = _format_error(exc)
177
+ channel.send({"done": True, "stdout": sink.getvalue(), "error": error, "truncated": sink.truncated})
178
+ return 0
179
+
180
+
181
+ if __name__ == "__main__":
182
+ sys.exit(main(sys.argv))