@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
@@ -0,0 +1,123 @@
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 { CreatorSchema, fieldValidationIssues, creatorValidationIssues, toZoteroCreator, } from "../utils/item-fields.js";
7
+ import { TITLE_FIELD_NAME } from "../utils/zotero-item-types.js";
8
+ import { ITEM_KEY_HINT } from "../utils/error-hints.js";
9
+ /**
10
+ * Fields a user must not set through update_item: identity, server-managed metadata, and structural
11
+ * relations that have their own dedicated tools (collections, parent, relations). itemType cannot change.
12
+ */
13
+ const PROTECTED_FIELDS = new Set([
14
+ "key",
15
+ "version",
16
+ "itemType",
17
+ "parentItem",
18
+ "collections",
19
+ "relations",
20
+ "dateAdded",
21
+ "dateModified",
22
+ ]);
23
+ const VERSION_CONFLICT_HINT = "Re-read the item with get_items_details to get its current version, then call update_item again with that version.";
24
+ export const toolConfig = {
25
+ name: "update_item",
26
+ description: "Update the metadata of an existing Zotero item: change field values and/or replace its creators. Pass the item's current `version` (from get_items_details) — the update is rejected as a version_conflict if the item changed since you read it, so re-read and retry in that case. `fields` are Zotero field names valid for the item's type (e.g. title, date, publicationTitle, volume, pages, DOI, url, publisher). itemType cannot be changed, and key/version/collections/parentItem/relations/dateAdded/dateModified are managed by Zotero and rejected. Use add_items for new items, create_note for notes, and delete_items to remove items.",
27
+ inputSchema: {
28
+ item_key: zoteroKey().describe("Key of the item to update (from search_library, get_items_details or get_collection_items)."),
29
+ version: z
30
+ .number()
31
+ .int()
32
+ .describe("The item's current version, as returned by get_items_details. Guards against overwriting a concurrent change."),
33
+ fields: z
34
+ .record(z.string(), z.string())
35
+ .describe('Field values to set, as { fieldName: value }. Use Zotero field names valid for the item type (e.g. { "title": "New title", "date": "2024" }). Pass {} if you only want to change creators.'),
36
+ creators: z
37
+ .array(CreatorSchema)
38
+ .optional()
39
+ .describe("Replaces the item's entire creators list when provided. Each creator is {firstName, lastName, creatorType} or {name, creatorType} for institutional authors."),
40
+ ...libraryArgsSchema,
41
+ },
42
+ };
43
+ const UpdateItemSchema = z.object(toolConfig.inputSchema);
44
+ export async function handleUpdateItem(zoteroApi, userId, args) {
45
+ const { item_key, version, fields, creators, library_type, library_id } = UpdateItemSchema.parse(args);
46
+ const { type: libraryType, id: libraryId } = resolveLibrary({ library_type, library_id }, userId);
47
+ const protectedUsed = Object.keys(fields).filter((k) => PROTECTED_FIELDS.has(k));
48
+ if (protectedUsed.length > 0) {
49
+ return formatErrorResponse(`These fields cannot be set with update_item: ${protectedUsed.join(", ")}`, {
50
+ hint: "itemType is fixed; key/version/collections/parentItem/relations/dateAdded/dateModified are managed by Zotero. Remove them and keep only editable metadata fields.",
51
+ });
52
+ }
53
+ if (Object.keys(fields).length === 0 && creators === undefined) {
54
+ return formatErrorResponse("Nothing to update: provide at least one field or creators.");
55
+ }
56
+ // Fetch the item for its type and current version.
57
+ let item;
58
+ try {
59
+ const resp = await zoteroApi.library(libraryType, libraryId).items(item_key).get();
60
+ item = resp.getData();
61
+ }
62
+ catch (err) {
63
+ if (isZoteroApiError(err) && err.response.status === 404) {
64
+ return formatErrorResponse(`Item ${item_key} not found`, { hint: ITEM_KEY_HINT });
65
+ }
66
+ throw err;
67
+ }
68
+ const itemType = item.itemType;
69
+ // Version mismatch: do not patch, tell the model to re-read.
70
+ if (item.version !== version) {
71
+ return formatErrorResponse("Version conflict: the item changed since you read it", {
72
+ code: "version_conflict",
73
+ item_key,
74
+ expected_version: version,
75
+ ...(typeof item.version === "number" ? { current_version: item.version } : {}),
76
+ hint: VERSION_CONFLICT_HINT,
77
+ });
78
+ }
79
+ // `title` is universal in our tools; map it to the type-specific field name where one exists.
80
+ const titleFieldName = TITLE_FIELD_NAME[itemType];
81
+ const patchFields = {};
82
+ for (const [k, v] of Object.entries(fields)) {
83
+ patchFields[k === "title" && titleFieldName ? titleFieldName : k] = v;
84
+ }
85
+ const fieldIssues = fieldValidationIssues(itemType, Object.keys(patchFields));
86
+ const creatorIssues = creators ? creatorValidationIssues(itemType, creators) : [];
87
+ if (fieldIssues.length > 0 || creatorIssues.length > 0) {
88
+ return formatErrorResponse(`Invalid fields for itemType "${itemType}"`, {
89
+ problems: [...fieldIssues, ...creatorIssues].map((i) => i.message),
90
+ hint: "Use field names and creator types valid for this item's type (see the message for the valid options).",
91
+ });
92
+ }
93
+ const patchBody = { ...patchFields };
94
+ if (creators) {
95
+ patchBody.creators = creators.map(toZoteroCreator);
96
+ }
97
+ try {
98
+ const resp = await zoteroApi
99
+ .library(libraryType, libraryId)
100
+ .items(item_key)
101
+ .version(version)
102
+ .patch(patchBody);
103
+ return formatJsonResult({
104
+ item_key,
105
+ version: resp.getVersion(),
106
+ updated_fields: Object.keys(patchFields),
107
+ ...(creators ? { creators_replaced: true } : {}),
108
+ });
109
+ }
110
+ catch (err) {
111
+ if (isZoteroApiError(err) && err.response.status === 412) {
112
+ const current = err.response.headers?.get?.("last-modified-version");
113
+ return formatErrorResponse("Version conflict: the item changed since you read it", {
114
+ code: "version_conflict",
115
+ item_key,
116
+ expected_version: version,
117
+ ...(current ? { current_version: Number(current) } : {}),
118
+ hint: VERSION_CONFLICT_HINT,
119
+ });
120
+ }
121
+ throw err;
122
+ }
123
+ }
@@ -0,0 +1,62 @@
1
+ import { open, rename, unlink, link, copyFile } from "node:fs/promises";
2
+ import { constants } from "node:fs";
3
+ import { dirname, basename, join } from "node:path";
4
+ import { randomBytes } from "node:crypto";
5
+ /**
6
+ * Scrive `data` in `path` in modo atomico: un file temporaneo nella stessa cartella (flag `wx`, così non
7
+ * collide), con fsync, poi `rename` sul percorso finale. Con `overwrite:false` usa `link`+`unlink` (il link
8
+ * fallisce con EEXIST se il file esiste già, senza sovrascriverlo), con fallback a `copyFile` COPYFILE_EXCL
9
+ * dove i link non sono supportati o attraversano filesystem diversi. Il temporaneo viene sempre rimosso.
10
+ *
11
+ * Il rename avviene nella stessa cartella del file finale, quindi è atomico sullo stesso filesystem: un
12
+ * lettore vede o il vecchio file o quello nuovo completo, mai un file a metà (p.es. Word che tiene aperto
13
+ * l'output mentre viene riscritto).
14
+ */
15
+ export async function writeFileAtomic(path, data, opts = {}) {
16
+ const overwrite = opts.overwrite ?? true;
17
+ const dir = dirname(path);
18
+ const tmp = join(dir, `.${basename(path)}.${randomBytes(6).toString("hex")}.tmp`);
19
+ let tmpExists = false;
20
+ try {
21
+ const fh = await open(tmp, "wx");
22
+ tmpExists = true;
23
+ try {
24
+ await fh.writeFile(data);
25
+ await fh.sync();
26
+ }
27
+ finally {
28
+ await fh.close();
29
+ }
30
+ if (overwrite) {
31
+ await rename(tmp, path);
32
+ tmpExists = false; // il rename ha consumato il temporaneo
33
+ return;
34
+ }
35
+ // overwrite:false → non deve toccare un file esistente
36
+ try {
37
+ await link(tmp, path);
38
+ }
39
+ catch (err) {
40
+ const code = err.code;
41
+ if (code === "EEXIST")
42
+ throw err; // il file esiste: non sovrascrivere
43
+ // link non supportato (fs senza hard link) o cross-device: copia che fallisce se l'output esiste
44
+ if (code === "ENOSYS" || code === "EPERM" || code === "EXDEV" || code === "EOPNOTSUPP") {
45
+ await copyFile(tmp, path, constants.COPYFILE_EXCL);
46
+ }
47
+ else {
48
+ throw err;
49
+ }
50
+ }
51
+ }
52
+ finally {
53
+ if (tmpExists) {
54
+ try {
55
+ await unlink(tmp);
56
+ }
57
+ catch {
58
+ /* il temporaneo potrebbe non esistere più: ignora */
59
+ }
60
+ }
61
+ }
62
+ }
@@ -0,0 +1,76 @@
1
+ import { fetchWithRetry } from "./fetch-retry.js";
2
+ import { readJsonObject } from "./json-response.js";
3
+ const CROSSREF_WORKS = "https://api.crossref.org/works/";
4
+ // Crossref update `type` → status bucket, most severe first. A work can carry several notices (e.g. a correction
5
+ // and a later retraction); the status is the most severe present, while `notices` keeps them all.
6
+ const RETRACTED_TYPES = new Set(["retraction", "partial_retraction", "removal", "withdrawal"]);
7
+ const CONCERN_TYPES = new Set(["expression_of_concern"]);
8
+ /**
9
+ * Canonical form of a Crossref update `type`: lowercase, hyphens and spaces to underscores. Crossref returns both
10
+ * `expression_of_concern` and `expression-of-concern` (the hyphen form is rarer but real), so normalize before
11
+ * comparing with the Sets above, and store the normalized form in the notices.
12
+ */
13
+ export function normalizeType(type) {
14
+ return (typeof type === "string" ? type : "update").trim().toLowerCase().replace(/[-\s]+/g, "_");
15
+ }
16
+ /** The most severe status implied by a work's notices. */
17
+ export function classifyNotices(notices) {
18
+ if (notices.some((n) => RETRACTED_TYPES.has(n.type)))
19
+ return "retracted";
20
+ if (notices.some((n) => CONCERN_TYPES.has(n.type)))
21
+ return "expression_of_concern";
22
+ if (notices.length > 0)
23
+ return "corrected";
24
+ return "ok";
25
+ }
26
+ /** A Crossref date object ({date-time} / {date-parts}) → YYYY-MM-DD, or undefined. */
27
+ function noticeDate(updated) {
28
+ if (!updated || typeof updated !== "object")
29
+ return undefined;
30
+ const u = updated;
31
+ if (typeof u["date-time"] === "string")
32
+ return u["date-time"].slice(0, 10);
33
+ const parts = u["date-parts"];
34
+ if (Array.isArray(parts) && Array.isArray(parts[0]) && parts[0].length) {
35
+ return parts[0].map((n, i) => (i > 0 ? String(n).padStart(2, "0") : String(n))).join("-");
36
+ }
37
+ return undefined;
38
+ }
39
+ // DOI normalisation and extraction (normalizeDoi / itemDoi) moved to ../utils/doi.ts, shared with
40
+ // find_duplicates. check_retractions imports itemDoi from there.
41
+ /** Look up one DOI on Crossref. Never throws: a network/timeout/parse error becomes `lookup_failed`. */
42
+ export async function lookupRetraction(doi, mailto) {
43
+ const url = CROSSREF_WORKS + encodeURIComponent(doi) + (mailto ? `?mailto=${encodeURIComponent(mailto)}` : "");
44
+ const userAgent = `mcp-zotero/1.0 (retraction check${mailto ? `; mailto:${mailto}` : ""})`;
45
+ let response;
46
+ try {
47
+ response = await fetchWithRetry(url, { headers: { Accept: "application/json", "User-Agent": userAgent } },
48
+ // Retry the transient server statuses Crossref can return, a bounded number of times (per-attempt timeout
49
+ // and backoff come from fetchWithRetry); 404 and other 4xx are definitive and not retried.
50
+ { label: "Crossref retraction lookup", retryableStatuses: [429, 500, 502, 503, 504], maxRetries: 2 });
51
+ }
52
+ catch {
53
+ return { status: "lookup_failed", notices: [] };
54
+ }
55
+ if (response.status === 404)
56
+ return { status: "not_in_crossref", notices: [] };
57
+ if (!response.ok)
58
+ return { status: "lookup_failed", notices: [] };
59
+ let updatedBy;
60
+ try {
61
+ const body = await readJsonObject(response);
62
+ const raw = body.message?.["updated-by"];
63
+ updatedBy = Array.isArray(raw) ? raw : [];
64
+ }
65
+ catch {
66
+ return { status: "lookup_failed", notices: [] };
67
+ }
68
+ const notices = updatedBy.map((u) => ({
69
+ type: normalizeType(u["type"]),
70
+ doi: typeof u["DOI"] === "string" ? u["DOI"].toLowerCase() : undefined,
71
+ date: noticeDate(u["updated"]),
72
+ source: typeof u["source"] === "string" ? u["source"] : undefined,
73
+ label: typeof u["label"] === "string" ? u["label"] : undefined,
74
+ }));
75
+ return { status: classifyNotices(notices), notices };
76
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Shared DOI helpers used by find_duplicates and check_retractions: normalise a DOI for comparison
3
+ * and extract the comparable DOI of a Zotero item (DOI field, or a "DOI:" line in Extra). Nothing
4
+ * here reads the network.
5
+ */
6
+ /** A DOI must start with "10." followed by the registrant code and a slash. */
7
+ const DOI_CORE = /10\.\d{4,9}\/\S+/;
8
+ /** A URL or "doi:" prefix in front of a DOI (any case), stripped before comparison. */
9
+ const DOI_PREFIX = /^(?:https?:\/\/)?(?:dx\.)?doi\.org\/|^doi:\s*/i;
10
+ /** A "DOI: 10.x/y" line in the item's Extra field (Zotero stores a DOI there for types without a DOI field). */
11
+ const EXTRA_DOI_LINE = /^[ \t]*DOI:[ \t]*(\S+)/im;
12
+ /**
13
+ * Strip trailing sentence punctuation from a DOI match: ".", "," and ";" always, and a ")" only when
14
+ * it is unbalanced (more ")" than "(") — so a DOI quoted inline ("(see 10.1000/abc)") loses the closer
15
+ * while a DOI that really contains parentheses (10.1016/S0140-6736(97)11096-0, the SICI scheme) keeps them.
16
+ */
17
+ function stripTrailingDoiPunctuation(doi) {
18
+ let end = doi.length;
19
+ for (; end > 0; end--) {
20
+ const ch = doi[end - 1];
21
+ if (ch === "." || ch === "," || ch === ";")
22
+ continue;
23
+ if (ch === ")") {
24
+ const head = doi.slice(0, end);
25
+ const opens = (head.match(/\(/g) ?? []).length;
26
+ const closes = (head.match(/\)/g) ?? []).length;
27
+ if (closes > opens)
28
+ continue;
29
+ }
30
+ break;
31
+ }
32
+ return doi.slice(0, end);
33
+ }
34
+ /**
35
+ * Normalise a DOI for comparison: drop any https://doi.org/ (or dx.doi.org / doi:) prefix, lowercase,
36
+ * trim trailing sentence punctuation, and keep only a value that has the DOI shape. Returns null when
37
+ * the string carries no DOI, so callers never act on a non-DOI.
38
+ */
39
+ export function normalizeDoi(raw) {
40
+ if (!raw)
41
+ return null;
42
+ const stripped = raw.trim().replace(DOI_PREFIX, "");
43
+ const match = DOI_CORE.exec(stripped);
44
+ // Strip from the match, not the whole string: a DOI quoted inline ("see 10.1000/abc, p.5") would
45
+ // otherwise keep the comma and never match a bare "10.1000/abc".
46
+ return match ? stripTrailingDoiPunctuation(match[0].toLowerCase()) : null;
47
+ }
48
+ /** The comparable DOI of an item: its DOI field, else a "DOI:" line in Extra. Null when it has none. */
49
+ export function itemDoi(item) {
50
+ const fromField = normalizeDoi(item.DOI);
51
+ if (fromField)
52
+ return fromField;
53
+ const fromExtra = item.extra ? EXTRA_DOI_LINE.exec(item.extra) : null;
54
+ return fromExtra ? normalizeDoi(fromExtra[1]) : null;
55
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Helpers for find_duplicates: normalising titles for comparison and grouping regular items into
3
+ * duplicate candidates by title and year. DOI normalisation and extraction live in ./doi.ts (shared
4
+ * with check_retractions). Nothing here reads the network; the tool does the scanning.
5
+ */
6
+ /**
7
+ * Normalise a title for comparison: NFKD, strip diacritics, lowercase, every non-alphanumeric run
8
+ * (of any script) to a single space, trimmed. "Café: a Review!" and "cafe a review" collapse to the
9
+ * same string.
10
+ */
11
+ export function normalizeTitle(title) {
12
+ if (!title)
13
+ return "";
14
+ return title
15
+ .normalize("NFKD")
16
+ .replace(/[̀-ͯ]/g, "")
17
+ .toLowerCase()
18
+ .replace(/[^\p{L}\p{N}]+/gu, " ")
19
+ .trim();
20
+ }
21
+ /**
22
+ * A normalised title shorter than this is too generic to group on ("note", "editorial", "reply"),
23
+ * which would pair unrelated items; such titles are skipped in the title pass.
24
+ */
25
+ export const MIN_TITLE_LENGTH = 10;
26
+ /**
27
+ * CJK and Hangul titles pack a whole title into a few characters ("深度学习" is 4), so the Latin
28
+ * threshold would drop every real duplicate; a shorter minimum applies when such a script is present.
29
+ */
30
+ export const MIN_TITLE_LENGTH_CJK = 4;
31
+ const CJK_SCRIPT = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
32
+ /** Whether a normalised title is long enough to group on (a lower bar for CJK/Hangul titles). */
33
+ export function isTitleLongEnough(normalizedTitle) {
34
+ const min = CJK_SCRIPT.test(normalizedTitle) ? MIN_TITLE_LENGTH_CJK : MIN_TITLE_LENGTH;
35
+ return normalizedTitle.length >= min;
36
+ }
37
+ /** The 4-digit year of an item's date (Zotero dates are "2024-01-15", "2024", or free text), or null. */
38
+ export function itemYear(item) {
39
+ const match = item.date ? /\b(\d{4})\b/.exec(item.date) : null;
40
+ return match ? match[1] : null;
41
+ }
42
+ /**
43
+ * Split items that share a normalised title into duplicate sub-groups by year. Two items are
44
+ * duplicates unless both carry a year and the years differ, so:
45
+ * - at most one distinct year present (all same, all undated, or one year plus undated ones): one group;
46
+ * - several distinct years: one group per year, plus the undated items as their own group (ambiguous,
47
+ * so never merged into a year).
48
+ * Callers emit only the sub-groups with 2+ items.
49
+ */
50
+ export function titleSubgroups(items) {
51
+ const years = new Set(items.map(itemYear).filter((y) => y !== null));
52
+ if (years.size <= 1)
53
+ return [items];
54
+ const byYear = new Map();
55
+ for (const item of items) {
56
+ const key = itemYear(item) ?? "";
57
+ const bucket = byYear.get(key);
58
+ if (bucket)
59
+ bucket.push(item);
60
+ else
61
+ byYear.set(key, [item]);
62
+ }
63
+ return [...byYear.values()];
64
+ }
@@ -0,0 +1,58 @@
1
+ import { z } from "zod";
2
+ import { ITEM_TYPE_FIELDS, ITEM_TYPE_CREATOR_TYPES, } from "./zotero-item-types.js";
3
+ /**
4
+ * Creator input shared by add_items and update_item: either an institutional single-field `name`
5
+ * or both `firstName` and `lastName`. creatorType defaults to "author".
6
+ */
7
+ export const CreatorSchema = z
8
+ .object({
9
+ firstName: z.string().optional(),
10
+ lastName: z.string().optional(),
11
+ name: z.string().optional(),
12
+ creatorType: z.string().default("author"),
13
+ })
14
+ .refine((data) => data.name != null || (data.firstName != null && data.lastName != null), {
15
+ message: "Provide either 'name' (institutional) or both firstName+lastName",
16
+ });
17
+ /**
18
+ * Issues for every key not valid for `itemType`, ignoring the names in `skip` (fields handled
19
+ * elsewhere, e.g. the universal `title`/`creators` inputs of add_items). Messages match the
20
+ * historical add_items wording so error text stays stable.
21
+ */
22
+ export function fieldValidationIssues(itemType, keys, skip = new Set()) {
23
+ const validFields = ITEM_TYPE_FIELDS[itemType];
24
+ const issues = [];
25
+ for (const key of keys) {
26
+ if (skip.has(key))
27
+ continue;
28
+ if (!validFields.has(key)) {
29
+ issues.push({
30
+ path: [key],
31
+ message: `Field "${key}" is not valid for itemType "${itemType}". Valid fields: ${[...validFields].join(", ")}`,
32
+ });
33
+ }
34
+ }
35
+ return issues;
36
+ }
37
+ /** Issues for every creator whose creatorType is not valid for `itemType`. */
38
+ export function creatorValidationIssues(itemType, creators = []) {
39
+ const validCreatorTypes = ITEM_TYPE_CREATOR_TYPES[itemType];
40
+ const issues = [];
41
+ for (const [i, creator] of creators.entries()) {
42
+ const creatorType = creator.creatorType ?? "author";
43
+ if (!validCreatorTypes.has(creatorType)) {
44
+ issues.push({
45
+ path: ["creators", i, "creatorType"],
46
+ message: `Invalid creatorType "${creatorType}" for "${itemType}". Valid: ${[...validCreatorTypes].join(", ")}`,
47
+ });
48
+ }
49
+ }
50
+ return issues;
51
+ }
52
+ /** Map a validated creator to the Zotero API shape (institutional `name` or first/last name). */
53
+ export function toZoteroCreator(c) {
54
+ if (c.name) {
55
+ return { name: c.name, creatorType: c.creatorType };
56
+ }
57
+ return { firstName: c.firstName, lastName: c.lastName, creatorType: c.creatorType };
58
+ }
@@ -5,6 +5,14 @@ export function formatCreators(creators) {
5
5
  .filter(Boolean)
6
6
  .join(", ") || "No authors listed");
7
7
  }
8
+ /** The display name of the first creator (an institutional `name`, else "First Last"), or null if there is none. */
9
+ export function firstCreatorName(creators) {
10
+ const first = creators?.[0];
11
+ if (!first)
12
+ return null;
13
+ const name = first.name?.trim() || `${first.firstName || ""} ${first.lastName || ""}`.trim();
14
+ return name || null;
15
+ }
8
16
  export function formatTags(tags) {
9
17
  return tags?.map((t) => t.tag).filter(Boolean) || [];
10
18
  }
@@ -26,7 +26,7 @@ function unavailableResult(what) {
26
26
  warning: `Unpaywall lookup failed (${what}): this does not mean there is no open access PDF. Retry later with find_and_attach_pdfs.`,
27
27
  };
28
28
  }
29
- function isValidEmail(email) {
29
+ export function isValidEmail(email) {
30
30
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
31
31
  }
32
32
  /**
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@xevos117/mcp-zotero",
3
3
  "type": "module",
4
- "version": "2.0.4",
4
+ "version": "2.1.0",
5
5
  "mcpName": "io.github.Xevos117/mcp-zotero",
6
6
  "description": "Unofficial MCP server for Zotero integration with citation management",
7
7
  "repository": {
@@ -26,6 +26,7 @@
26
26
  "test": "vitest run",
27
27
  "test:watch": "vitest",
28
28
  "build": "tsc",
29
+ "build:skill": "node scripts/build-skill.mjs",
29
30
  "smoke": "node scripts/smoke-stdio.mjs",
30
31
  "bundle": "node scripts/build-mcpb.mjs",
31
32
  "start": "node build/server.js",
@@ -48,22 +49,23 @@
48
49
  "author": "Xevos17",
49
50
  "license": "MIT",
50
51
  "dependencies": {
51
- "@modelcontextprotocol/sdk": "^1.32.1",
52
- "dotenv": "^18.0.6",
53
- "fast-xml-parser": "^5.11.2",
52
+ "@modelcontextprotocol/sdk": "^1.32.2",
53
+ "dotenv": "^18.0.9",
54
+ "fast-xml-parser": "^5.12.0",
54
55
  "jszip": "^3.10.2",
55
- "unpdf": "^1.8.1",
56
- "zod": "^4.6.5",
56
+ "unpdf": "^1.9.1",
57
+ "zod": "^4.6.7",
57
58
  "zotero-api-client": "^0.51.0"
58
59
  },
59
60
  "devDependencies": {
60
- "@anthropic-ai/claude-agent-sdk": "^0.3.296",
61
+ "@anthropic-ai/claude-agent-sdk": "^0.3.319",
61
62
  "@anthropic-ai/mcpb": "2.1.2",
62
- "@types/node": "^26.6.4",
63
+ "@types/node": "^26.6.6",
63
64
  "ajv": "^8.20.0",
64
65
  "ajv-formats": "^3.0.1",
65
66
  "citeproc": "^2.4.63",
67
+ "esbuild": "0.28.2",
66
68
  "typescript": "^7.0.2",
67
- "vitest": "^5.0.3"
69
+ "vitest": "^5.1.0"
68
70
  }
69
71
  }