@xevos117/mcp-zotero 2.0.4 → 2.1.0

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 (45) hide show
  1. package/README.md +66 -12
  2. package/build/citation-injector/citation-formatter.js +3 -0
  3. package/build/citation-injector/citation-json.js +37 -0
  4. package/build/citation-injector/citekey-resolver.js +122 -0
  5. package/build/citation-injector/document-prefs.js +6 -3
  6. package/build/citation-injector/field-codes.js +2 -8
  7. package/build/citation-injector/formats/docx.js +83 -0
  8. package/build/citation-injector/formats/odt.js +149 -0
  9. package/build/citation-injector/formats/types.js +1 -0
  10. package/build/citation-injector/injector.js +100 -184
  11. package/build/citation-injector/model.js +9 -0
  12. package/build/citation-injector/odt-normalizer.js +169 -0
  13. package/build/citation-injector/pandoc-body.js +99 -0
  14. package/build/citation-injector/pipeline.js +189 -0
  15. package/build/citation-injector/zcite-normalizer.js +27 -11
  16. package/build/citation-injector/zcite.js +36 -0
  17. package/build/cited-document/create.js +40 -0
  18. package/build/cited-document/document.js +83 -0
  19. package/build/cited-document/markdown.js +104 -0
  20. package/build/cited-document/model.js +1 -0
  21. package/build/cited-document/number.js +17 -0
  22. package/build/cited-document/pandoc-cite.js +74 -0
  23. package/build/prompts/index.js +127 -0
  24. package/build/server.js +12 -5
  25. package/build/tools/add-items.js +9 -41
  26. package/build/tools/check-retractions.js +131 -0
  27. package/build/tools/create-cited-document.js +101 -0
  28. package/build/tools/create-note.js +77 -0
  29. package/build/tools/delete-collection.js +1 -1
  30. package/build/tools/delete-items.js +96 -25
  31. package/build/tools/find-duplicates.js +163 -0
  32. package/build/tools/get-collections.js +8 -18
  33. package/build/tools/get-items-details.js +11 -6
  34. package/build/tools/index.js +10 -0
  35. package/build/tools/inject-citations.js +29 -7
  36. package/build/tools/search-library.js +2 -2
  37. package/build/tools/update-item.js +123 -0
  38. package/build/utils/atomic-write.js +62 -0
  39. package/build/utils/crossref-retractions.js +76 -0
  40. package/build/utils/doi.js +55 -0
  41. package/build/utils/duplicates.js +64 -0
  42. package/build/utils/item-fields.js +58 -0
  43. package/build/utils/item-formatter.js +8 -0
  44. package/build/utils/unpaywall.js +1 -1
  45. package/package.json +11 -9
@@ -2,25 +2,36 @@ import { z } from "zod";
2
2
  import { zoteroKey } from "../utils/zotero-keys.js";
3
3
  import { isZoteroApiError } from "../types/zotero-types.js";
4
4
  import { formatJsonResult, formatErrorResponse } from "../utils/error-formatter.js";
5
+ import { formatWriteErrors } from "../utils/write-results.js";
5
6
  import { canDeleteItems } from "../utils/unsafe-operations.js";
6
7
  import { fetchItemsByKeys } from "../utils/pagination.js";
7
8
  import { resolveLibrary, libraryArgsSchema } from "../utils/library-context.js";
8
9
  import { ITEM_KEY_HINT, unsafeOperationsHint, zoteroStatusHint } from "../utils/error-hints.js";
9
10
  export const toolConfig = {
10
11
  name: "delete_items",
11
- description: "Delete one or more items from your Zotero library: they are permanently deleted (not moved to the Zotero trash), so confirm with the user first. Accepts up to 50 item keys per call. Disabled unless the server setting UNSAFE_OPERATIONS is 'items' or 'all'.",
12
+ description: "Delete one or more items from your Zotero library. By default they are moved to the Zotero trash (recoverable by the user from Zotero → Trash); pass permanent: true to delete them for good (not recoverable), which is the old behaviour — confirm with the user first for a permanent delete. Moving an item to the trash does not move its child notes or attachments to the trash (they stay in the library), matching the Zotero app; a permanent delete also removes an item's children. A key already in the trash is reported in already_in_trash (use permanent: true to erase it). Accepts up to 50 item keys per call. Disabled unless the server setting UNSAFE_OPERATIONS is 'items' or 'all' (the same setting gates both trash and permanent deletion).",
12
13
  inputSchema: {
13
14
  item_keys: z
14
15
  .array(zoteroKey())
15
16
  .min(1)
16
17
  .max(50)
17
18
  .describe('Array of Zotero item keys to delete (e.g. ["EUHUT5K3", "F9UQM7N2"]). Max 50 per call.'),
19
+ permanent: z
20
+ .boolean()
21
+ .optional()
22
+ .default(false)
23
+ .describe("false (default): move the items to the Zotero trash, where the user can restore them. true: delete them permanently (not recoverable)."),
18
24
  ...libraryArgsSchema,
19
25
  },
20
26
  };
21
27
  const DeleteItemsSchema = z.object(toolConfig.inputSchema);
22
28
  export async function handleDeleteItems(zoteroApi, userId, args, unsafeOps = "none") {
23
- const { item_keys, library_type, library_id } = DeleteItemsSchema.parse(args);
29
+ const parsed = DeleteItemsSchema.parse(args);
30
+ const { permanent, library_type, library_id } = parsed;
31
+ // Drop duplicate keys (keep first-seen order): a repeated key would otherwise be written twice in the
32
+ // trash POST or the DELETE, and the server reports the second write as a failure, so the same key could
33
+ // end up in both deleted_keys and failed.
34
+ const item_keys = [...new Set(parsed.item_keys)];
24
35
  const { type: libraryType, id: libraryId } = resolveLibrary({ library_type, library_id }, userId);
25
36
  if (!canDeleteItems(unsafeOps)) {
26
37
  return formatErrorResponse(`Deletion of items is not allowed: destructive operations are disabled in this server's configuration (UNSAFE_OPERATIONS is '${unsafeOps}'). Nothing was deleted.`, {
@@ -34,14 +45,21 @@ export async function handleDeleteItems(zoteroApi, userId, args, unsafeOps = "no
34
45
  const notFoundKeys = [];
35
46
  let pending = item_keys;
36
47
  for (let attempt = 1;; attempt++) {
37
- const { items, version: libraryVersion } = await fetchItemsByKeys((params) => zoteroApi.library(libraryType, libraryId).items().get(params), pending);
38
- const foundKeys = new Set(items.map((item) => item.key).filter(Boolean));
39
- notFoundKeys.push(...pending.filter((k) => !foundKeys.has(k)));
40
- if (foundKeys.size === 0) {
48
+ const { items, version: libraryVersion } = await fetchItemsByKeys(
49
+ // Always include trashed items: a permanent delete must reach items already in the trash, and a
50
+ // default (trash) delete must recognise an item that is already there — reported as
51
+ // already_in_trash rather than written again.
52
+ (params) => zoteroApi.library(libraryType, libraryId).items().get({ ...params, includeTrashed: 1 }), pending);
53
+ const byKey = new Map();
54
+ for (const item of items)
55
+ if (typeof item.key === "string")
56
+ byKey.set(item.key, item);
57
+ notFoundKeys.push(...pending.filter((k) => !byKey.has(k)));
58
+ if (byKey.size === 0) {
41
59
  return formatErrorResponse("No items found for the given keys", {
42
60
  item_keys,
43
61
  status: "not_found",
44
- hint: `Nothing was deleted: none of these keys exists in this library (already deleted, or in another library). ${ITEM_KEY_HINT}`,
62
+ hint: `Nothing was deleted: none of these keys exists in this library (in another library, or permanently deleted). ${ITEM_KEY_HINT}`,
45
63
  });
46
64
  }
47
65
  // Use library version from response header (Last-Modified-Version),
@@ -52,30 +70,83 @@ export async function handleDeleteItems(zoteroApi, userId, args, unsafeOps = "no
52
70
  hint: "Nothing was deleted. Retry the same call once.",
53
71
  });
54
72
  }
55
- // only keys the caller asked for, whatever the API returned
56
- const keysToDelete = pending.filter((k) => foundKeys.has(k));
57
- try {
58
- await zoteroApi
59
- .library(libraryType, libraryId)
60
- .items()
61
- .version(libraryVersion)
62
- .delete(keysToDelete);
73
+ // only keys the caller asked for that exist (whatever extra the API returned)
74
+ const foundKeys = pending.filter((k) => byKey.has(k));
75
+ const isTrashed = (k) => {
76
+ const d = byKey.get(k)?.deleted;
77
+ return d === 1 || d === true;
78
+ };
79
+ if (permanent) {
80
+ // DELETE reaches live and already-trashed items alike; Zotero erases child notes/attachments
81
+ // server-side (so a permanent delete of a parent removes its children too).
82
+ try {
83
+ await zoteroApi.library(libraryType, libraryId).items().version(libraryVersion).delete(foundKeys);
84
+ }
85
+ catch (err) {
86
+ if (attempt === 1 && isZoteroApiError(err) && err.response.status === 412) {
87
+ pending = foundKeys;
88
+ continue;
89
+ }
90
+ throw err;
91
+ }
92
+ const result = { deleted_keys: foundKeys, deleted_count: foundKeys.length, mode: "permanent" };
93
+ if (notFoundKeys.length > 0)
94
+ result.not_found = notFoundKeys;
95
+ return formatJsonResult(result);
63
96
  }
64
- catch (err) {
65
- // 412: the library changed between the GET and the DELETE (another client, a sync). Read the new
66
- // version and the keys that still exist, and retry once with those.
67
- if (attempt === 1 && isZoteroApiError(err) && err.response.status === 412) {
68
- pending = keysToDelete;
69
- continue;
97
+ // Default: move the live items to the Zotero trash by setting deleted:1 in a multi-object write (POST
98
+ // has PATCH semantics, so only `deleted` changes); the library version from the GET header
99
+ // (If-Unmodified-Since-Version) guards against a concurrent change, exactly like the DELETE path.
100
+ // Trashing a parent does NOT move its child notes/attachments to the trash — that matches the Zotero
101
+ // client (Zotero.Items.trash marks only the selected items), unlike permanent deletion. An item
102
+ // already in the trash is left as it is and reported in already_in_trash.
103
+ const alreadyInTrash = foundKeys.filter(isTrashed);
104
+ const toTrash = foundKeys.filter((k) => !isTrashed(k));
105
+ let trashErrors = null;
106
+ if (toTrash.length > 0) {
107
+ try {
108
+ const payload = toTrash.map((key) => ({ key, version: libraryVersion, deleted: 1 }));
109
+ const response = await zoteroApi
110
+ .library(libraryType, libraryId)
111
+ .items()
112
+ .version(libraryVersion)
113
+ .post(payload);
114
+ const errors = response.getErrors();
115
+ if (Object.keys(errors).length > 0)
116
+ trashErrors = errors;
117
+ }
118
+ catch (err) {
119
+ if (attempt === 1 && isZoteroApiError(err) && err.response.status === 412) {
120
+ pending = toTrash;
121
+ continue;
122
+ }
123
+ throw err;
70
124
  }
71
- throw err;
125
+ }
126
+ // Per-object outcome of the trash write: an index in getErrors() failed (a partial failure is
127
+ // possible — the server writes each object independently), the rest were moved to the trash.
128
+ const failedIndexes = trashErrors ? Object.keys(trashErrors).map(Number) : [];
129
+ const trashed = toTrash.filter((_, i) => !failedIndexes.includes(i));
130
+ if (toTrash.length > 0 && trashed.length === 0 && alreadyInTrash.length === 0) {
131
+ return formatErrorResponse(`Could not move items to the trash: ${formatWriteErrors(trashErrors ?? {})}. Nothing was deleted.`, {
132
+ item_keys,
133
+ hint: "Retry the same call once.",
134
+ });
72
135
  }
73
136
  const result = {
74
- deleted_keys: keysToDelete,
75
- deleted_count: keysToDelete.length,
137
+ deleted_keys: trashed,
138
+ deleted_count: trashed.length,
139
+ mode: "trash",
76
140
  };
77
- if (notFoundKeys.length > 0) {
141
+ if (notFoundKeys.length > 0)
78
142
  result.not_found = notFoundKeys;
143
+ const failedKeys = failedIndexes.map((i) => toTrash[i]);
144
+ if (failedKeys.length > 0)
145
+ result.failed = failedKeys;
146
+ if (alreadyInTrash.length > 0) {
147
+ result.already_in_trash = alreadyInTrash;
148
+ result.hint =
149
+ "These keys were already in the Zotero trash and were left as they are; call again with permanent: true to delete them for good.";
79
150
  }
80
151
  return formatJsonResult(result);
81
152
  }
@@ -0,0 +1,163 @@
1
+ import { z } from "zod";
2
+ import { zoteroKey } from "../utils/zotero-keys.js";
3
+ import { isZoteroApiError } from "../types/zotero-types.js";
4
+ import { formatJsonResult, formatErrorResponse } from "../utils/error-formatter.js";
5
+ import { resolveLibrary, libraryArgsSchema } from "../utils/library-context.js";
6
+ import { COLLECTION_KEY_HINT } from "../utils/error-hints.js";
7
+ import { asArray } from "../utils/pagination.js";
8
+ import { firstCreatorName } from "../utils/item-formatter.js";
9
+ import { itemDoi, normalizeDoi } from "../utils/doi.js";
10
+ import { normalizeTitle, itemYear, titleSubgroups, isTitleLongEnough } from "../utils/duplicates.js";
11
+ /** Items per page; 100 is the real Web API maximum for a multi-object request. */
12
+ const SCAN_PAGE = 100;
13
+ /** Cap on the number of regular items scanned, so one call never walks an unbounded library. Reported as `truncated`. */
14
+ const MAX_SCAN_ITEMS = 5000;
15
+ export const toolConfig = {
16
+ name: "find_duplicates",
17
+ description: `Find duplicate items in your Zotero library. Read-only: it never merges, edits or deletes anything — it only reports candidates for the user to resolve.
18
+
19
+ Two modes:
20
+ - With 'dois' (up to 50): checks which of those DOIs are ALREADY in the library. Returns, per DOI, the matching items (item_key, title, year, first author, type). Run this before add_items_by_doi and skip the DOIs that already have an entry, to avoid creating duplicates.
21
+ - Without 'dois': scans the library (or a single collection) for duplicate groups — items that share a normalized DOI, or a normalized title (ignoring case, accents and punctuation; same year required when both items have one; very short/generic titles skipped). Each group lists its items so the user decides which to keep.
22
+
23
+ Only regular items are scanned: notes, attachments and the trash are skipped, up to 5000 items (in both modes). The result reports 'scanned' (regular items examined) and 'truncated' (true if the cap was hit before the end; in 'dois' mode a DOI past the cap may then be missed). Pass 'collection_key' to limit the scan to one collection.`,
24
+ inputSchema: {
25
+ dois: z
26
+ .array(z.string().trim().min(1, "DOI must not be empty"))
27
+ .max(50, "Pass at most 50 DOIs per call")
28
+ .optional()
29
+ .describe('Optional: check these DOIs (bare or as https://doi.org/… URLs, up to 50) against the library and return, per DOI, the items already present. Use before add_items_by_doi. Omit to scan for duplicate groups instead.'),
30
+ collection_key: zoteroKey()
31
+ .optional()
32
+ .describe("Optional: limit the scan to the items directly in this collection (from get_collections). Omit to scan the whole library."),
33
+ ...libraryArgsSchema,
34
+ },
35
+ };
36
+ const FindDuplicatesSchema = z.object(toolConfig.inputSchema);
37
+ function toEntry(item) {
38
+ return {
39
+ key: item.key ?? null,
40
+ title: item.title || "Untitled",
41
+ year: itemYear(item),
42
+ first_author: firstCreatorName(item.creators),
43
+ item_type: item.itemType ?? null,
44
+ doi: itemDoi(item),
45
+ };
46
+ }
47
+ /** Add a value to the list stored under `key`, creating the list on first use. */
48
+ function pushGroup(map, key, value) {
49
+ const bucket = map.get(key);
50
+ if (bucket)
51
+ bucket.push(value);
52
+ else
53
+ map.set(key, [value]);
54
+ }
55
+ /**
56
+ * Walk the regular items of a library or collection, 100 per page, up to MAX_SCAN_ITEMS. `.top()` excludes
57
+ * child notes/attachments and the trash; standalone notes/attachments are dropped here too. The page length
58
+ * (not the filtered count) advances the offset, so server-side paging stays correct.
59
+ */
60
+ async function scanRegularItems(buildRequest) {
61
+ const items = [];
62
+ let start = 0;
63
+ let total = null;
64
+ let truncated = false;
65
+ for (;;) {
66
+ const response = await buildRequest({ limit: SCAN_PAGE, start });
67
+ if (total === null)
68
+ total = response.getTotalResults();
69
+ const page = asArray(response.getData());
70
+ if (page.length === 0)
71
+ break;
72
+ for (const item of page) {
73
+ if (item.itemType !== "attachment" && item.itemType !== "note")
74
+ items.push(item);
75
+ }
76
+ start += page.length;
77
+ if (start >= MAX_SCAN_ITEMS) {
78
+ truncated = total === null ? page.length === SCAN_PAGE : start < total;
79
+ break;
80
+ }
81
+ if (total !== null && start >= total)
82
+ break;
83
+ if (total === null && page.length < SCAN_PAGE)
84
+ break;
85
+ }
86
+ return { items, scanned: items.length, truncated };
87
+ }
88
+ export async function handleFindDuplicates(zoteroApi, userId, args) {
89
+ const { dois, collection_key, library_type, library_id } = FindDuplicatesSchema.parse(args);
90
+ const { type: libraryType, id: libraryId } = resolveLibrary({ library_type, library_id }, userId);
91
+ const buildRequest = (params) => {
92
+ const library = zoteroApi.library(libraryType, libraryId);
93
+ const scope = collection_key ? library.collections(collection_key).items() : library.items();
94
+ return scope.top().get(params);
95
+ };
96
+ let items;
97
+ let scanned;
98
+ let truncated;
99
+ try {
100
+ ({ items, scanned, truncated } = await scanRegularItems(buildRequest));
101
+ }
102
+ catch (err) {
103
+ if (collection_key && isZoteroApiError(err) && err.response?.status === 404) {
104
+ return formatErrorResponse("Collection not found: no collection with this key in this library, or the API key cannot access it.", { collection_key, suggestion: COLLECTION_KEY_HINT, status: "not_found" });
105
+ }
106
+ throw err;
107
+ }
108
+ const byKey = (a, b) => (a.key ?? "").localeCompare(b.key ?? "");
109
+ if (dois) {
110
+ const byDoi = new Map();
111
+ for (const item of items) {
112
+ const doi = itemDoi(item);
113
+ if (doi)
114
+ pushGroup(byDoi, doi, item);
115
+ }
116
+ // Deterministic output: results follow the input DOI order, each `existing` sorted by key.
117
+ const results = dois.map((raw) => {
118
+ const normalized = normalizeDoi(raw);
119
+ const existing = normalized ? byDoi.get(normalized) ?? [] : [];
120
+ return { doi: raw, normalized, existing: existing.map(toEntry).sort(byKey) };
121
+ });
122
+ return formatJsonResult({ mode: "dois", scanned, truncated, dois: results });
123
+ }
124
+ const groups = [];
125
+ // DOI duplicates first: a shared DOI is the strongest signal, so those items are excluded from the title pass.
126
+ const byDoi = new Map();
127
+ for (const item of items) {
128
+ const doi = itemDoi(item);
129
+ if (doi)
130
+ pushGroup(byDoi, doi, item);
131
+ }
132
+ const doiGroupedKeys = new Set();
133
+ for (const [doi, group] of byDoi) {
134
+ if (group.length < 2)
135
+ continue;
136
+ for (const item of group)
137
+ if (item.key)
138
+ doiGroupedKeys.add(item.key);
139
+ groups.push({ match: "doi", key: doi, items: group.map(toEntry) });
140
+ }
141
+ const byTitle = new Map();
142
+ for (const item of items) {
143
+ if (item.key && doiGroupedKeys.has(item.key))
144
+ continue;
145
+ const title = normalizeTitle(item.title);
146
+ if (!isTitleLongEnough(title))
147
+ continue;
148
+ pushGroup(byTitle, title, item);
149
+ }
150
+ for (const [title, bucket] of byTitle) {
151
+ if (bucket.length < 2)
152
+ continue;
153
+ for (const subgroup of titleSubgroups(bucket)) {
154
+ if (subgroup.length >= 2)
155
+ groups.push({ match: "title", key: title, items: subgroup.map(toEntry) });
156
+ }
157
+ }
158
+ // Deterministic order: DOI groups before title groups, then by key.
159
+ groups.sort((a, b) => (a.match === b.match ? a.key.localeCompare(b.key) : a.match === "doi" ? -1 : 1));
160
+ for (const group of groups)
161
+ group.items.sort(byKey);
162
+ return formatJsonResult({ mode: "scan", scanned, truncated, duplicate_groups: groups.length, groups });
163
+ }
@@ -1,10 +1,10 @@
1
1
  import { z } from "zod";
2
- import { formatJsonResult, formatEmptyResult } from "../utils/error-formatter.js";
2
+ import { formatJsonResult } from "../utils/error-formatter.js";
3
3
  import { fetchAllPages } from "../utils/pagination.js";
4
4
  import { resolveLibrary, libraryArgsSchema } from "../utils/library-context.js";
5
5
  export const toolConfig = {
6
6
  name: "get_collections",
7
- description: "List all collections (folders) in your Zotero library. Returns collection keys, names, and parent relationships. Use collection keys with get_collection_items or as parent_collection in create_collection. Trashed collections are excluded by default.",
7
+ description: "List all collections (folders) in your Zotero library. Returns an array of collection keys, names, and parent relationships (an empty array [] when the library has no collections — items can still be found with search_library, and create_collection makes one). Use collection keys with get_collection_items or as parent_collection in create_collection. Trashed collections are excluded by default.",
8
8
  inputSchema: {
9
9
  include_trashed: z
10
10
  .boolean()
@@ -19,21 +19,11 @@ export async function handleGetCollections(zoteroApi, userId, args) {
19
19
  const { include_trashed, library_type, library_id } = GetCollectionsSchema.parse(args);
20
20
  const { type: libraryType, id: libraryId } = resolveLibrary({ library_type, library_id }, userId);
21
21
  const { items: allCollections } = await fetchAllPages((params) => zoteroApi.library(libraryType, libraryId).collections().get(params));
22
- if (!Array.isArray(allCollections) || allCollections.length === 0) {
23
- return formatEmptyResult("No collections found", {
24
- suggestion: "This library has no collections. Items can still be found with search_library; to organize them, create one with create_collection.",
25
- helpUrl: "https://www.zotero.org/support/collections",
26
- });
27
- }
28
- // Zotero API returns deleted collections despite not requesting them —
29
- // filter client-side as a workaround
30
- const collections = include_trashed
31
- ? allCollections
32
- : allCollections.filter((c) => !c.deleted);
33
- if (collections.length === 0) {
34
- return formatEmptyResult("No collections found", {
35
- suggestion: "All collections of this library are in the Zotero trash: call again with include_trashed=true to see them, or create a new one with create_collection.",
36
- });
37
- }
22
+ // Always return an array (never a message object), so the type is the same for an empty and a non-empty
23
+ // library — and for a user and a group library. An empty library (no collections, or all trashed and
24
+ // filtered out below) returns []. The guidance for that case lives in the tool description.
25
+ const list = Array.isArray(allCollections) ? allCollections : [];
26
+ // Zotero API returns deleted collections despite not requesting them — filter client-side as a workaround.
27
+ const collections = include_trashed ? list : list.filter((c) => !c.deleted);
38
28
  return formatJsonResult(collections);
39
29
  }
@@ -1,16 +1,17 @@
1
1
  import { z } from "zod";
2
2
  import { zoteroKey } from "../utils/zotero-keys.js";
3
- import { formatJsonResult, formatErrorResponse, formatEmptyResult } from "../utils/error-formatter.js";
3
+ import { formatJsonResult, formatEmptyResult } from "../utils/error-formatter.js";
4
4
  import { formatCreators } from "../utils/item-formatter.js";
5
5
  import { fetchItemsByKeys } from "../utils/pagination.js";
6
6
  import { resolveLibrary, libraryArgsSchema } from "../utils/library-context.js";
7
7
  import { ITEM_KEY_HINT } from "../utils/error-hints.js";
8
8
  export const toolConfig = {
9
9
  name: "get_items_details",
10
- description: "Get metadata for multiple Zotero items in a single call. Accepts an array of item keys and returns a map of key → metadata. Use this instead of one call per item. Returns all type-specific fields (e.g. bookTitle for bookSection, proceedingsTitle for conferencePaper, university for thesis). Set include_abstract to include abstracts (excluded by default to keep responses lightweight). Keys not found in the library are listed in not_found (present only when some are missing).",
10
+ description: "Get metadata for multiple Zotero items in a single call. Accepts an array of item keys and returns a map of key → metadata. Use this instead of one call per item. Returns all type-specific fields (e.g. bookTitle for bookSection, proceedingsTitle for conferencePaper, university for thesis). Each entry also carries its current `version`: pass it to update_item to edit the item safely (update_item rejects a stale version). Set include_abstract to include abstracts (excluded by default to keep responses lightweight). Keys not found in the library are listed in not_found (present only when some are missing).",
11
11
  inputSchema: {
12
12
  item_keys: z
13
13
  .array(zoteroKey())
14
+ .min(1, "Provide at least one item key")
14
15
  .describe('Array of Zotero item keys (e.g. ["EUHUT5K3", "F9UQM7N2"]). Get these from search_library, add_items_by_doi, or get_collection_items.'),
15
16
  include_abstract: z
16
17
  .boolean()
@@ -28,16 +29,15 @@ const SKIP_FIELDS = new Set([
28
29
  "abstractNote",
29
30
  ]);
30
31
  export async function handleGetItemsDetails(zoteroApi, userId, args) {
32
+ // item_keys is validated with .min(1), so an empty array is a schema error (-32602) before we get here,
33
+ // consistent with delete_items/add_items.
31
34
  const { item_keys, include_abstract, library_type, library_id } = GetItemsDetailsSchema.parse(args);
32
35
  const { type: libraryType, id: libraryId } = resolveLibrary({ library_type, library_id }, userId);
33
- if (item_keys.length === 0) {
34
- return formatErrorResponse("At least one item key is required: pass item_keys from search_library, get_collection_items or add_items_by_doi.");
35
- }
36
36
  const { items } = await fetchItemsByKeys((params) => zoteroApi.library(libraryType, libraryId).items().get(params), item_keys);
37
37
  if (items.length === 0) {
38
38
  return formatEmptyResult("No items found for the given keys", {
39
39
  item_keys,
40
- suggestion: `None of these keys exists in this library (deleted, or from another library). ${ITEM_KEY_HINT}`,
40
+ suggestion: `None of these keys exists in this library as a live item (permanently deleted, in another library, or in the trash: restore it in Zotero, or remove it for good with delete_items permanent: true). ${ITEM_KEY_HINT}`,
41
41
  });
42
42
  }
43
43
  const result = {};
@@ -50,6 +50,11 @@ export async function handleGetItemsDetails(zoteroApi, userId, args) {
50
50
  title: item.title || "Untitled",
51
51
  authors: formatCreators(item.creators),
52
52
  };
53
+ // Current object version, needed by update_item (optimistic concurrency); still excluded from the
54
+ // generic field loop below via SKIP_FIELDS. The skill's inject.js metadataToCsl ignores it.
55
+ if (typeof item.version === "number") {
56
+ entry.version = item.version;
57
+ }
53
58
  // Structured names as stored in Zotero (firstName/lastName or single-field name): lets the
54
59
  // skill's inject.js build CSL names exactly like inject_citations, multi-word surnames included
55
60
  if (item.creators && item.creators.length > 0) {
@@ -5,14 +5,19 @@ import { handleSearchLibrary, toolConfig as searchConfig } from "./search-librar
5
5
  import { handleCreateCollection, toolConfig as createCollectionConfig } from "./create-collection.js";
6
6
  import { handleAddItemsByDoi, toolConfig as addItemsByDoiConfig } from "./add-items-by-doi.js";
7
7
  import { handleInjectCitations, toolConfig as injectCitationsConfig } from "./inject-citations.js";
8
+ import { handleCreateCitedDocument, toolConfig as createCitedDocumentConfig } from "./create-cited-document.js";
8
9
  import { handleGetItemFulltext, toolConfig as getItemFulltextConfig } from "./get-item-fulltext.js";
9
10
  import { handleGetUserId, toolConfig as getUserIdConfig } from "./get-user-id.js";
10
11
  import { handleAddLinkedUrlAttachment, toolConfig as addLinkedUrlAttachmentConfig } from "./add-linked-url-attachment.js";
11
12
  import { handleAddItems, toolConfig as addItemsConfig } from "./add-items.js";
13
+ import { handleUpdateItem, toolConfig as updateItemConfig } from "./update-item.js";
14
+ import { handleCreateNote, toolConfig as createNoteConfig } from "./create-note.js";
12
15
  import { handleImportPdfToZotero, toolConfig as importPdfToZoteroConfig } from "./import-pdf-to-zotero.js";
13
16
  import { handleFindAndAttachPdfs, toolConfig as findAndAttachPdfsConfig } from "./find-and-attach-pdfs.js";
17
+ import { handleFindDuplicates, toolConfig as findDuplicatesConfig } from "./find-duplicates.js";
14
18
  import { handleDeleteCollection, toolConfig as deleteCollectionConfig } from "./delete-collection.js";
15
19
  import { handleDeleteItems, toolConfig as deleteItemsConfig } from "./delete-items.js";
20
+ import { handleCheckRetractions, toolConfig as checkRetractionsConfig } from "./check-retractions.js";
16
21
  import { formatErrorResponse, logToolError } from "../utils/error-formatter.js";
17
22
  import { describeError } from "../utils/error-hints.js";
18
23
  const tools = [
@@ -23,14 +28,19 @@ const tools = [
23
28
  { config: createCollectionConfig, handler: handleCreateCollection },
24
29
  { config: addItemsByDoiConfig, handler: handleAddItemsByDoi },
25
30
  { config: injectCitationsConfig, handler: handleInjectCitations },
31
+ { config: createCitedDocumentConfig, handler: handleCreateCitedDocument },
26
32
  { config: getItemFulltextConfig, handler: handleGetItemFulltext },
27
33
  { config: getUserIdConfig, handler: handleGetUserId },
28
34
  { config: addLinkedUrlAttachmentConfig, handler: handleAddLinkedUrlAttachment },
29
35
  { config: addItemsConfig, handler: handleAddItems },
36
+ { config: updateItemConfig, handler: handleUpdateItem },
37
+ { config: createNoteConfig, handler: handleCreateNote },
30
38
  { config: importPdfToZoteroConfig, handler: handleImportPdfToZotero },
31
39
  { config: findAndAttachPdfsConfig, handler: handleFindAndAttachPdfs },
40
+ { config: findDuplicatesConfig, handler: handleFindDuplicates },
32
41
  { config: deleteCollectionConfig, handler: handleDeleteCollection },
33
42
  { config: deleteItemsConfig, handler: handleDeleteItems },
43
+ { config: checkRetractionsConfig, handler: handleCheckRetractions },
34
44
  ];
35
45
  const handlers = new Map(tools.map(({ config, handler }) => [config.name, handler]));
36
46
  /**
@@ -5,7 +5,11 @@ import { injectCitations } from "../citation-injector/injector.js";
5
5
  import { resolveLibrary, libraryArgsSchema } from "../utils/library-context.js";
6
6
  export const toolConfig = {
7
7
  name: "inject_citations",
8
- description: `Replace <zcite> placeholder tags in a .docx file with native Zotero field codes that Zotero for Word can recognize and manage. The tool fetches item metadata from Zotero automatically — you only need to provide the .docx file.
8
+ description: `Replace citation placeholders in a .docx (or .odt) file with native Zotero field codes that Zotero can recognize and manage. The tool fetches item metadata from Zotero automatically — you only need to provide the file.
9
+
10
+ PLACEHOLDER SYNTAX — two kinds, recognized automatically (no flag):
11
+ - <zcite keys="ITEMKEY"/> tags (see ZCITE TAG FORMAT below). If the document has any <zcite> tag, it is handled as a zcite document.
12
+ - Pandoc citation markers when there are no <zcite> tags: bracketed [@KEY], [@K1; @K2], [see @KEY, p. 12], -@KEY to suppress the author, or inline @KEY. KEY may be a Zotero 8-character key or a Better BibTeX citation key (e.g. [@rossi2020]); citation keys are case-sensitive and resolved against each item's citationKey field or a "Citation Key: <key>" line in Extra. Prefer the bracketed form [@KEY] — it is the reliable one: an inline @word that does not resolve (a handle, an email, code like @media or @angular/core, or a marker Word split across runs) is left as plain text with a warning, never an error, whereas an unknown or ambiguous key in a bracketed [@…] IS an error and nothing is written. A document that mixes <zcite> and [@…] is treated as zcite, and the Pandoc markers are reported so you can call the tool again on the output.
9
13
 
10
14
  WORKFLOW — how to create a Word document with live Zotero citations:
11
15
  1. Collect item keys: use add_items_by_doi or add_items (or search_library for existing items)
@@ -35,12 +39,16 @@ WHERE THE FILE LIVES: this tool reads and writes files on the machine where this
35
39
  inputSchema: {
36
40
  file_path: z
37
41
  .string()
38
- .describe('Absolute path to the .docx file containing <zcite keys="..."/> placeholder tags'),
42
+ .describe('Absolute path to the .docx (Word) or .odt (LibreOffice) file containing <zcite keys="..."/> placeholder tags'),
39
43
  style: z
40
44
  .enum(["apa", "ieee", "vancouver", "harvard", "chicago"])
41
45
  .optional()
42
46
  .default("apa")
43
47
  .describe("Citation style for the visible placeholder text. Zotero will reformat on refresh. Default: apa"),
48
+ format: z
49
+ .enum(["docx", "odt"])
50
+ .optional()
51
+ .describe("Document format: docx for Word, odt for LibreOffice. Defaults to the file extension; an error if it disagrees with the extension or the file content."),
44
52
  ...libraryArgsSchema,
45
53
  },
46
54
  };
@@ -50,22 +58,36 @@ const FILE_NOT_FOUND = "File not found on the machine where this MCP server runs
50
58
  "zotero-mcp-integrations skill, which injects the citations inside the sandbox. If the skill is not installed, " +
51
59
  "ask the user to add zotero-skill-mcp-integrations.zip from https://github.com/Xevos117/mcp-zotero/releases/latest.";
52
60
  export async function handleInjectCitations(zoteroApi, userId, args) {
53
- const { file_path, style, library_type, library_id } = InjectCitationsSchema.parse(args);
61
+ const { file_path, style, format, library_type, library_id } = InjectCitationsSchema.parse(args);
54
62
  const { type: libraryType, id: libraryId } = resolveLibrary({ library_type, library_id }, userId);
55
- if (!file_path.endsWith(".docx")) {
56
- return formatErrorResponse("File must be a .docx file", {
63
+ const extFormat = file_path.endsWith(".docx") ? "docx" : file_path.endsWith(".odt") ? "odt" : undefined;
64
+ if (!extFormat) {
65
+ return formatErrorResponse("File must be a .docx (Word) or .odt (LibreOffice) file", {
66
+ file_path,
67
+ hint: "The name must end in lowercase .docx or .odt: convert .doc or .rtf first, or create the document as .docx/.odt with <zcite> placeholders.",
68
+ });
69
+ }
70
+ if (format && format !== extFormat) {
71
+ return formatErrorResponse(`format '${format}' does not match the file extension of ${file_path}`, {
57
72
  file_path,
58
- hint: "Only Word .docx files are supported and the name must end in lowercase .docx: convert .doc, .odt or .rtf to .docx first, or create the document as .docx with <zcite> placeholders.",
73
+ hint: `The file ends in .${extFormat}: pass format "${extFormat}" or omit it, or rename the file to match the format.`,
59
74
  });
60
75
  }
76
+ const resolvedFormat = format ?? extFormat;
61
77
  let result;
62
78
  try {
63
- result = await injectCitations(file_path, zoteroApi, libraryType, libraryId, style);
79
+ result = await injectCitations(file_path, zoteroApi, libraryType, libraryId, style, resolvedFormat);
64
80
  }
65
81
  catch (err) {
66
82
  // A path from a sandbox or cloud workspace (Claude.ai, Claude Desktop code execution) does not exist here:
67
83
  // say so and point to the skill instead of a bare ENOENT.
68
84
  const code = err.code;
85
+ if (code === "EBUSY") {
86
+ return formatErrorResponse("Cannot write the _cited copy: the output file is locked (EBUSY).", {
87
+ file_path,
88
+ hint: "Close the _cited file if it is open in Word (or another program) and call again.",
89
+ });
90
+ }
69
91
  if (code === "EACCES" || code === "EPERM" || code === "EROFS") {
70
92
  return formatErrorResponse(`Cannot read the file or write the _cited copy next to it (${code}).`, {
71
93
  file_path,
@@ -7,7 +7,7 @@ export const toolConfig = {
7
7
  description: `Search your Zotero library or list items sorted by a field.
8
8
 
9
9
  When 'query' is provided, matches it against titles, creator names and years (not abstracts, tags or full text).
10
- When 'query' is omitted, lists items sorted by the chosen field (default: dateAdded, descending).
10
+ When 'query' is omitted — or is empty / only whitespace — it is treated as no query: the tool lists items sorted by the chosen field (default: dateAdded, descending), up to 'limit'.
11
11
 
12
12
  Examples:
13
13
  - Search: { "query": "deep learning" }
@@ -19,7 +19,7 @@ Use the returned item keys with get_items_details, get_item_fulltext, or inject_
19
19
  query: z
20
20
  .string()
21
21
  .optional()
22
- .describe("Search query. If omitted, returns items sorted by the chosen field."),
22
+ .describe("Search query. If omitted, empty or only whitespace, returns items sorted by the chosen field."),
23
23
  sort: z
24
24
  .enum(["dateAdded", "dateModified", "title", "creator", "date"])
25
25
  .optional()