@xevos117/mcp-zotero 2.0.3 → 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.
- package/README.md +66 -12
- package/build/citation-injector/citation-formatter.js +3 -0
- package/build/citation-injector/citation-json.js +37 -0
- package/build/citation-injector/citekey-resolver.js +122 -0
- package/build/citation-injector/document-prefs.js +6 -3
- package/build/citation-injector/field-codes.js +2 -8
- package/build/citation-injector/formats/docx.js +83 -0
- package/build/citation-injector/formats/odt.js +149 -0
- package/build/citation-injector/formats/types.js +1 -0
- package/build/citation-injector/injector.js +100 -184
- package/build/citation-injector/model.js +9 -0
- package/build/citation-injector/odt-normalizer.js +169 -0
- package/build/citation-injector/pandoc-body.js +99 -0
- package/build/citation-injector/pipeline.js +189 -0
- package/build/citation-injector/zcite-normalizer.js +27 -11
- package/build/citation-injector/zcite.js +36 -0
- package/build/cited-document/create.js +40 -0
- package/build/cited-document/document.js +83 -0
- package/build/cited-document/markdown.js +104 -0
- package/build/cited-document/model.js +1 -0
- package/build/cited-document/number.js +17 -0
- package/build/cited-document/pandoc-cite.js +74 -0
- package/build/prompts/index.js +127 -0
- package/build/server.js +12 -5
- package/build/tools/add-items.js +9 -41
- package/build/tools/check-retractions.js +131 -0
- package/build/tools/create-cited-document.js +101 -0
- package/build/tools/create-note.js +77 -0
- package/build/tools/delete-collection.js +35 -22
- package/build/tools/delete-items.js +129 -42
- package/build/tools/find-duplicates.js +163 -0
- package/build/tools/get-collections.js +8 -18
- package/build/tools/get-items-details.js +11 -6
- package/build/tools/index.js +10 -0
- package/build/tools/inject-citations.js +29 -7
- package/build/tools/search-library.js +2 -2
- package/build/tools/update-item.js +123 -0
- package/build/utils/atomic-write.js +62 -0
- package/build/utils/crossref-retractions.js +76 -0
- package/build/utils/csl-to-zotero.js +69 -14
- package/build/utils/doi.js +55 -0
- package/build/utils/duplicates.js +64 -0
- package/build/utils/item-fields.js +58 -0
- package/build/utils/item-formatter.js +8 -0
- package/build/utils/unpaywall.js +1 -1
- 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
|
+
}
|
|
@@ -123,8 +123,33 @@ const CSL_NAME_CREATOR_TYPES = [
|
|
|
123
123
|
["collection-editor", "seriesEditor"],
|
|
124
124
|
["translator", "translator"],
|
|
125
125
|
];
|
|
126
|
+
/** Zotero field holding the CSL publisher, for the types that call it otherwise (Zotero's base field mappings). */
|
|
127
|
+
const PUBLISHER_FIELD = {
|
|
128
|
+
thesis: "university",
|
|
129
|
+
report: "institution",
|
|
130
|
+
preprint: "repository",
|
|
131
|
+
};
|
|
132
|
+
/** Zotero field holding the CSL number (report number, standard or manuscript number). */
|
|
133
|
+
const NUMBER_FIELD = {
|
|
134
|
+
report: "reportNumber",
|
|
135
|
+
standard: "number",
|
|
136
|
+
manuscript: "number",
|
|
137
|
+
};
|
|
138
|
+
/** arXiv DOIs (DataCite): the item is a preprint in the arXiv repository. */
|
|
139
|
+
const ARXIV_DOI = /^10\.48550\/arxiv\.(.+)$/i;
|
|
140
|
+
/** JATS abstract (Crossref: <jats:p>, <jats:italic>, …) → plain text, one line per paragraph, as Zotero's import does. */
|
|
141
|
+
function plainAbstract(abstract) {
|
|
142
|
+
if (!/<jats:/.test(abstract))
|
|
143
|
+
return abstract;
|
|
144
|
+
return abstract
|
|
145
|
+
.split(/<\/jats:p>/)
|
|
146
|
+
.map((p) => p.replace(/<\/?jats:[^>]*>/g, " ").replace(/\s+/g, " ").trim())
|
|
147
|
+
.filter(Boolean)
|
|
148
|
+
.join("\n");
|
|
149
|
+
}
|
|
126
150
|
export function cslToZoteroItem(csl, options) {
|
|
127
|
-
const
|
|
151
|
+
const arxiv = ARXIV_DOI.exec(csl.DOI ?? "");
|
|
152
|
+
const itemType = (arxiv ? "preprint" : (CSL_TO_ZOTERO_TYPE[csl.type] ?? "journalArticle"));
|
|
128
153
|
// Authors always (as before); other roles only where the item type has them, or the API rejects the item.
|
|
129
154
|
// A CSL `literal` (institution, consortium) is Zotero's single-field name
|
|
130
155
|
const validCreatorTypes = ITEM_TYPE_CREATOR_TYPES[itemType];
|
|
@@ -138,25 +163,39 @@ export function cslToZoteroItem(csl, options) {
|
|
|
138
163
|
collections.push(options.collectionKey);
|
|
139
164
|
}
|
|
140
165
|
const tags = (options?.tags ?? []).map((t) => ({ tag: t }));
|
|
166
|
+
// Zotero joins the subtitle to the title; the article number is the item's number, or its pages when it has none
|
|
167
|
+
const subtitle = Array.isArray(csl.subtitle) ? csl.subtitle[0] : csl.subtitle;
|
|
168
|
+
const title = subtitle ? `${csl.title ?? ""}: ${subtitle}` : (csl.title ?? "");
|
|
169
|
+
const number = csl.number ?? csl["article-number"] ?? "";
|
|
170
|
+
const numberField = NUMBER_FIELD[itemType];
|
|
141
171
|
// Build candidate fields (CSL → Zotero field names)
|
|
142
172
|
const candidates = {
|
|
143
|
-
title
|
|
173
|
+
title,
|
|
144
174
|
date,
|
|
145
175
|
DOI: csl.DOI ?? "",
|
|
146
176
|
volume: csl.volume ?? "",
|
|
147
177
|
issue: csl.issue ?? "",
|
|
148
|
-
pages: csl.page ?? "",
|
|
178
|
+
pages: csl.page ?? (numberField ? "" : (csl["article-number"] ?? "")),
|
|
149
179
|
publisher: csl.publisher ?? "",
|
|
150
180
|
place: csl["publisher-place"] ?? "",
|
|
151
181
|
url: csl.URL ?? "",
|
|
152
|
-
abstractNote: csl.abstract
|
|
182
|
+
abstractNote: csl.abstract ? plainAbstract(csl.abstract) : "",
|
|
153
183
|
ISBN: Array.isArray(csl.ISBN) ? csl.ISBN[0] : csl.ISBN ?? "",
|
|
154
184
|
ISSN: Array.isArray(csl.ISSN) ? csl.ISSN[0] : csl.ISSN ?? "",
|
|
155
185
|
edition: csl.edition ?? "",
|
|
156
186
|
numPages: csl["number-of-pages"] ?? "",
|
|
157
187
|
series: csl["collection-title"] ?? "",
|
|
158
188
|
language: csl.language ?? "",
|
|
189
|
+
journalAbbreviation: csl["container-title-short"] ?? "",
|
|
190
|
+
conferenceName: csl["event-title"] ?? csl.event ?? "",
|
|
159
191
|
};
|
|
192
|
+
if (numberField)
|
|
193
|
+
candidates[numberField] = number;
|
|
194
|
+
const publisherField = PUBLISHER_FIELD[itemType];
|
|
195
|
+
if (publisherField)
|
|
196
|
+
candidates[publisherField] = arxiv ? "arXiv" : (csl.publisher ?? "");
|
|
197
|
+
if (arxiv)
|
|
198
|
+
candidates.archiveID = `arXiv:${arxiv[1]}`;
|
|
160
199
|
// Map container-title to the correct field for this item type
|
|
161
200
|
const containerTitleField = CONTAINER_TITLE_FIELD[itemType];
|
|
162
201
|
if (containerTitleField) {
|
|
@@ -193,6 +232,16 @@ function containerTitle(item) {
|
|
|
193
232
|
const value = (field && fields[field]) || item.publicationTitle;
|
|
194
233
|
return typeof value === "string" && value ? value : undefined;
|
|
195
234
|
}
|
|
235
|
+
/**
|
|
236
|
+
* CSL date of a Zotero date: "YYYY-MM-DD" (or a prefix of it) as date-parts; a date that does not start that way
|
|
237
|
+
* ("October 2023", "Spring 2023") as `raw`, which citeproc parses itself, instead of being dropped.
|
|
238
|
+
*/
|
|
239
|
+
export function cslDate(value) {
|
|
240
|
+
if (!value)
|
|
241
|
+
return undefined;
|
|
242
|
+
const parts = value.split("-").map(Number).filter((n) => !isNaN(n));
|
|
243
|
+
return parts.length > 0 ? { "date-parts": [parts] } : { raw: value };
|
|
244
|
+
}
|
|
196
245
|
export function zoteroItemToCsl(item) {
|
|
197
246
|
const names = {};
|
|
198
247
|
for (const [variable, creatorType] of CSL_NAME_CREATOR_TYPES) {
|
|
@@ -200,28 +249,34 @@ export function zoteroItemToCsl(item) {
|
|
|
200
249
|
if (list.length > 0)
|
|
201
250
|
names[variable] = list;
|
|
202
251
|
}
|
|
203
|
-
let issued;
|
|
204
|
-
if (item.date) {
|
|
205
|
-
const parts = item.date.split("-").map(Number).filter((n) => !isNaN(n));
|
|
206
|
-
if (parts.length > 0) {
|
|
207
|
-
issued = { "date-parts": [parts] };
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
252
|
// The Zotero API returns every field of the item type, empty ones as "": keep them out of the field code
|
|
211
|
-
const
|
|
253
|
+
const fields = item;
|
|
254
|
+
const text = (...values) => values.find((v) => typeof v === "string" && v !== "") ?? undefined;
|
|
255
|
+
// accessDate is "YYYY-MM-DD hh:mm:ss" or ISO: only the day
|
|
256
|
+
const accessDate = text(fields.accessDate)?.replace(/[T ].*$/, "");
|
|
212
257
|
return {
|
|
213
258
|
type: ZOTERO_TO_CSL_TYPE[item.itemType ?? ""] ?? "article-journal",
|
|
214
259
|
title: text(item.title),
|
|
215
260
|
...names,
|
|
216
|
-
issued,
|
|
261
|
+
issued: cslDate(item.date),
|
|
217
262
|
DOI: text(item.DOI),
|
|
218
263
|
"container-title": containerTitle(item),
|
|
219
264
|
volume: text(item.volume),
|
|
220
265
|
issue: text(item.issue),
|
|
221
266
|
page: text(item.pages),
|
|
222
|
-
|
|
267
|
+
// Zotero's base fields: university (thesis), institution (report), repository (preprint) are the publisher;
|
|
268
|
+
// reportNumber and archiveID the number; thesisType and reportType the genre
|
|
269
|
+
publisher: text(item.publisher, fields.university, fields.institution, fields.repository),
|
|
223
270
|
"publisher-place": text(item.place),
|
|
271
|
+
number: text(fields.reportNumber, fields.archiveID),
|
|
272
|
+
genre: text(fields.thesisType, fields.reportType),
|
|
224
273
|
URL: text(item.url),
|
|
274
|
+
accessed: cslDate(accessDate),
|
|
275
|
+
ISBN: text(fields.ISBN),
|
|
276
|
+
ISSN: text(fields.ISSN),
|
|
277
|
+
edition: text(fields.edition),
|
|
278
|
+
language: text(fields.language),
|
|
279
|
+
"number-of-pages": text(fields.numPages),
|
|
225
280
|
// abstract deliberately omitted: it bloats every field code (same choice as the skill's inject.js)
|
|
226
281
|
};
|
|
227
282
|
}
|
|
@@ -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
|
}
|
package/build/utils/unpaywall.js
CHANGED
|
@@ -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
|
+
"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.
|
|
52
|
-
"dotenv": "^18.0.
|
|
53
|
-
"fast-xml-parser": "^5.
|
|
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.
|
|
56
|
-
"zod": "^4.6.
|
|
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.
|
|
61
|
+
"@anthropic-ai/claude-agent-sdk": "^0.3.319",
|
|
61
62
|
"@anthropic-ai/mcpb": "2.1.2",
|
|
62
|
-
"@types/node": "^26.6.
|
|
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
|
|
69
|
+
"vitest": "^5.1.0"
|
|
68
70
|
}
|
|
69
71
|
}
|