@retiform/paperless-mcp 0.0.0-stage → 2.3.1
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/LICENSE +18 -0
- package/README.md +1004 -2
- package/build/api/PaperlessAPI.d.ts +63 -0
- package/build/api/PaperlessAPI.js +405 -0
- package/build/api/documentEnhancer.d.ts +24 -0
- package/build/api/documentEnhancer.js +111 -0
- package/build/api/documentEnhancer.test.d.ts +1 -0
- package/build/api/documentEnhancer.test.js +80 -0
- package/build/api/types.d.ts +203 -0
- package/build/api/types.js +15 -0
- package/build/api/utils.d.ts +16 -0
- package/build/api/utils.js +29 -0
- package/build/index.d.ts +2 -0
- package/build/index.js +189 -0
- package/build/resources/documents.d.ts +7 -0
- package/build/resources/documents.js +119 -0
- package/build/resources/documents.test.d.ts +1 -0
- package/build/resources/documents.test.js +124 -0
- package/build/server.d.ts +24 -0
- package/build/server.js +70 -0
- package/build/server.test.d.ts +1 -0
- package/build/server.test.js +54 -0
- package/build/test/mocks/paperlessApi.d.ts +4 -0
- package/build/test/mocks/paperlessApi.js +33 -0
- package/build/tools/boundedContent.test.d.ts +1 -0
- package/build/tools/boundedContent.test.js +544 -0
- package/build/tools/correspondents.d.ts +3 -0
- package/build/tools/correspondents.js +149 -0
- package/build/tools/customFields.d.ts +3 -0
- package/build/tools/customFields.js +142 -0
- package/build/tools/documentTypes.d.ts +3 -0
- package/build/tools/documentTypes.js +143 -0
- package/build/tools/documents.d.ts +134 -0
- package/build/tools/documents.js +814 -0
- package/build/tools/documents.test.d.ts +1 -0
- package/build/tools/documents.test.js +658 -0
- package/build/tools/mail.d.ts +3 -0
- package/build/tools/mail.js +187 -0
- package/build/tools/mail.test.d.ts +1 -0
- package/build/tools/mail.test.js +212 -0
- package/build/tools/notes.d.ts +3 -0
- package/build/tools/notes.js +55 -0
- package/build/tools/notes.test.d.ts +1 -0
- package/build/tools/notes.test.js +177 -0
- package/build/tools/schemaCompat.test.d.ts +1 -0
- package/build/tools/schemaCompat.test.js +59 -0
- package/build/tools/tags.d.ts +3 -0
- package/build/tools/tags.js +143 -0
- package/build/tools/utils/descriptions.d.ts +1 -0
- package/build/tools/utils/descriptions.js +4 -0
- package/build/tools/utils/documentQuery.d.ts +71 -0
- package/build/tools/utils/documentQuery.js +270 -0
- package/build/tools/utils/empty.d.ts +2 -0
- package/build/tools/utils/empty.js +7 -0
- package/build/tools/utils/matchingAlgorithm.d.ts +2 -0
- package/build/tools/utils/matchingAlgorithm.js +15 -0
- package/build/tools/utils/middlewares.d.ts +3 -0
- package/build/tools/utils/middlewares.js +31 -0
- package/build/tools/utils/monetary.d.ts +5 -0
- package/build/tools/utils/monetary.js +34 -0
- package/build/tools/utils/monetary.test.d.ts +1 -0
- package/build/tools/utils/monetary.test.js +25 -0
- package/build/tools/utils/queryString.d.ts +1 -0
- package/build/tools/utils/queryString.js +12 -0
- package/build/tools/utils/resourceUri.d.ts +29 -0
- package/build/tools/utils/resourceUri.js +37 -0
- package/build/tools/utils/resourceUri.test.d.ts +1 -0
- package/build/tools/utils/resourceUri.test.js +50 -0
- package/build/tools/utils/selectFields.d.ts +13 -0
- package/build/tools/utils/selectFields.js +91 -0
- package/build/tools/utils/selectFields.test.d.ts +1 -0
- package/build/tools/utils/selectFields.test.js +164 -0
- package/package.json +59 -4
- package/paperless-mcp.dxt +0 -0
|
@@ -0,0 +1,814 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
var __rest = (this && this.__rest) || function (s, e) {
|
|
12
|
+
var t = {};
|
|
13
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
|
14
|
+
t[p] = s[p];
|
|
15
|
+
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
|
16
|
+
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
|
17
|
+
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
|
18
|
+
t[p[i]] = s[p[i]];
|
|
19
|
+
}
|
|
20
|
+
return t;
|
|
21
|
+
};
|
|
22
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
23
|
+
exports.DEFAULT_MAX_PASSAGES = exports.DEFAULT_PASSAGE_WINDOW = exports.DEFAULT_MAX_INLINE_CHARS = exports.DEFAULT_CONTENT_MAX_CHARS = void 0;
|
|
24
|
+
exports.getMaxInlineChars = getMaxInlineChars;
|
|
25
|
+
exports.resolveBoundedRead = resolveBoundedRead;
|
|
26
|
+
exports.sliceDocumentContent = sliceDocumentContent;
|
|
27
|
+
exports.buildSearchPassage = buildSearchPassage;
|
|
28
|
+
exports.extractHighlightPhrases = extractHighlightPhrases;
|
|
29
|
+
exports.extractSearchTerms = extractSearchTerms;
|
|
30
|
+
exports.validateFilePath = validateFilePath;
|
|
31
|
+
exports.buildBulkEditParameters = buildBulkEditParameters;
|
|
32
|
+
exports.sanitizeFullTextQuery = sanitizeFullTextQuery;
|
|
33
|
+
exports.runDocumentSearch = runDocumentSearch;
|
|
34
|
+
exports.registerDocumentTools = registerDocumentTools;
|
|
35
|
+
const zod_1 = require("zod");
|
|
36
|
+
const promises_1 = require("fs/promises");
|
|
37
|
+
const path_1 = require("path");
|
|
38
|
+
const documentEnhancer_1 = require("../api/documentEnhancer");
|
|
39
|
+
const empty_1 = require("./utils/empty");
|
|
40
|
+
const documentQuery_1 = require("./utils/documentQuery");
|
|
41
|
+
const middlewares_1 = require("./utils/middlewares");
|
|
42
|
+
const monetary_1 = require("./utils/monetary");
|
|
43
|
+
const selectFields_1 = require("./utils/selectFields");
|
|
44
|
+
const descriptions_1 = require("./utils/descriptions");
|
|
45
|
+
const resourceUri_1 = require("./utils/resourceUri");
|
|
46
|
+
const MAX_FILE_SIZE_BYTES = 100 * 1024 * 1024;
|
|
47
|
+
const ALLOWED_UPLOAD_PATHS = process.env.PAPERLESS_MCP_UPLOAD_PATHS
|
|
48
|
+
? process.env.PAPERLESS_MCP_UPLOAD_PATHS.split(":")
|
|
49
|
+
: [];
|
|
50
|
+
/** Default number of characters returned by a bounded content read. */
|
|
51
|
+
exports.DEFAULT_CONTENT_MAX_CHARS = 8000;
|
|
52
|
+
/** Hard cap on characters a single tool response may inline. */
|
|
53
|
+
exports.DEFAULT_MAX_INLINE_CHARS = 50000;
|
|
54
|
+
/** Default passage size for search_passages. */
|
|
55
|
+
exports.DEFAULT_PASSAGE_WINDOW = 800;
|
|
56
|
+
/** Default maximum number of passages returned by search_passages. */
|
|
57
|
+
exports.DEFAULT_MAX_PASSAGES = 5;
|
|
58
|
+
/**
|
|
59
|
+
* Reads the inline budget from the environment at call time (not module
|
|
60
|
+
* load), so tests can exercise different budgets without re-importing.
|
|
61
|
+
*/
|
|
62
|
+
function getMaxInlineChars() {
|
|
63
|
+
var _a;
|
|
64
|
+
const parsed = Number.parseInt((_a = process.env.PAPERLESS_MCP_MAX_INLINE_CHARS) !== null && _a !== void 0 ? _a : "", 10);
|
|
65
|
+
return Number.isFinite(parsed) && parsed > 0
|
|
66
|
+
? parsed
|
|
67
|
+
: exports.DEFAULT_MAX_INLINE_CHARS;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Normalizes bounded-read arguments into a validated {offset, maxChars} pair.
|
|
71
|
+
*
|
|
72
|
+
* Invariants:
|
|
73
|
+
* - offset must be >= 0 and inside the document;
|
|
74
|
+
* - maxChars is clamped to [1, budget] where budget is the inline budget;
|
|
75
|
+
* - a caller-requested window beyond the budget fails loudly instead of
|
|
76
|
+
* silently shrinking (never silently slice what the caller asked for).
|
|
77
|
+
*/
|
|
78
|
+
function resolveBoundedRead(offset, maxChars, contentLength, budget = getMaxInlineChars()) {
|
|
79
|
+
const resolvedOffset = Math.max(0, Math.floor(offset !== null && offset !== void 0 ? offset : 0));
|
|
80
|
+
if (resolvedOffset > 0 && resolvedOffset >= contentLength) {
|
|
81
|
+
throw new Error(`offset ${resolvedOffset} is beyond the end of the document (content_length ${contentLength})`);
|
|
82
|
+
}
|
|
83
|
+
const requested = maxChars !== null && maxChars !== void 0 ? maxChars : exports.DEFAULT_CONTENT_MAX_CHARS;
|
|
84
|
+
if (requested > budget) {
|
|
85
|
+
throw new Error(`max_chars ${requested} exceeds the inline budget ${budget} ` +
|
|
86
|
+
`(PAPERLESS_MCP_MAX_INLINE_CHARS). Read in windows of <= ${budget} chars ` +
|
|
87
|
+
`using offset, or use the download_document resource for bulk access.`);
|
|
88
|
+
}
|
|
89
|
+
const clamped = Math.max(1, Math.floor(requested));
|
|
90
|
+
return { offset: resolvedOffset, maxChars: clamped };
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Extracts a bounded window of document content and describes it.
|
|
94
|
+
*
|
|
95
|
+
* The window is always derived from the stored content server-side; the full
|
|
96
|
+
* text never crosses this boundary un-sliced.
|
|
97
|
+
*/
|
|
98
|
+
function sliceDocumentContent(doc, offset, maxChars) {
|
|
99
|
+
var _a;
|
|
100
|
+
const full = (_a = doc.content) !== null && _a !== void 0 ? _a : "";
|
|
101
|
+
const window = full.slice(offset, offset + maxChars);
|
|
102
|
+
return {
|
|
103
|
+
id: doc.id,
|
|
104
|
+
title: doc.title,
|
|
105
|
+
content: window,
|
|
106
|
+
offset,
|
|
107
|
+
returned_chars: window.length,
|
|
108
|
+
content_length: full.length,
|
|
109
|
+
truncated: offset + window.length < full.length,
|
|
110
|
+
has_more: offset + window.length < full.length,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Builds one bounded passage of document content centered on the actual hit.
|
|
115
|
+
*
|
|
116
|
+
* The window is cut from the stored content server-side; the full text never
|
|
117
|
+
* crosses this boundary un-sliced. Anchoring prefers the server's own
|
|
118
|
+
* highlighted phrase — the only anchor that survives whoosh stemming, since
|
|
119
|
+
* the index may match word variants the stored text does not contain
|
|
120
|
+
* verbatim — then falls back to the first verbatim term occurrence, and
|
|
121
|
+
* finally to the head of the document rather than returning nothing.
|
|
122
|
+
*/
|
|
123
|
+
function buildSearchPassage(doc, terms, window, searchHit) {
|
|
124
|
+
var _a;
|
|
125
|
+
const full = (_a = doc.content) !== null && _a !== void 0 ? _a : "";
|
|
126
|
+
// Anchor priority: (1) the server's own highlighted phrase, (2) the first
|
|
127
|
+
// verbatim term occurrence, (3) the document head. The highlight is the
|
|
128
|
+
// only anchor that survives whoosh stemming — the search index may match
|
|
129
|
+
// word variants the stored text does not contain verbatim, and the first
|
|
130
|
+
// query term can occur anywhere in the document, so anchoring on either
|
|
131
|
+
// risks cutting a window that does not contain the actual hit.
|
|
132
|
+
const lowerFull = full.toLowerCase();
|
|
133
|
+
let center = -1;
|
|
134
|
+
if (searchHit === null || searchHit === void 0 ? void 0 : searchHit.highlights) {
|
|
135
|
+
for (const phrase of extractHighlightPhrases(searchHit.highlights)) {
|
|
136
|
+
const idx = lowerFull.indexOf(phrase.toLowerCase());
|
|
137
|
+
if (idx >= 0) {
|
|
138
|
+
center = idx;
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (center < 0) {
|
|
144
|
+
for (const term of terms) {
|
|
145
|
+
const idx = lowerFull.indexOf(term.toLowerCase());
|
|
146
|
+
if (idx >= 0) {
|
|
147
|
+
center = idx;
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
const resolved = center < 0 ? 0 : center;
|
|
153
|
+
const start = Math.max(0, resolved - Math.floor(window / 2));
|
|
154
|
+
const passage = full.slice(start, start + window);
|
|
155
|
+
return Object.assign(Object.assign({ id: doc.id, title: doc.title }, (searchHit ? { score: searchHit.score, highlights: searchHit.highlights } : {})), { passage, offset: start, content_length: full.length });
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Extracts candidate anchor phrases from the server's highlight HTML: markup
|
|
159
|
+
* stripped, HTML entities decoded, whitespace collapsed. Phrases shorter than
|
|
160
|
+
* four characters cannot anchor a window reliably and are skipped so stray
|
|
161
|
+
* short matches never drag the window to a wrong position.
|
|
162
|
+
*/
|
|
163
|
+
function extractHighlightPhrases(highlights) {
|
|
164
|
+
const text = highlights
|
|
165
|
+
.replace(/<[^>]*>/g, " ")
|
|
166
|
+
.replace(/</g, "<")
|
|
167
|
+
.replace(/>/g, ">")
|
|
168
|
+
.replace(/"/g, '"')
|
|
169
|
+
.replace(/'|'/g, "'")
|
|
170
|
+
.replace(/ /g, " ")
|
|
171
|
+
.replace(/&/g, "&")
|
|
172
|
+
.replace(/\s+/g, " ")
|
|
173
|
+
.trim();
|
|
174
|
+
if (!text)
|
|
175
|
+
return [];
|
|
176
|
+
// Prefer the longest surrounding run of substantial words: the hit phrase,
|
|
177
|
+
// not a lone term that can match anywhere.
|
|
178
|
+
const words = text.split(" ");
|
|
179
|
+
const phrases = [];
|
|
180
|
+
let current = [];
|
|
181
|
+
for (const word of words) {
|
|
182
|
+
if (word.length >= 4) {
|
|
183
|
+
current.push(word);
|
|
184
|
+
}
|
|
185
|
+
else if (current.length) {
|
|
186
|
+
phrases.push(current.join(" "));
|
|
187
|
+
current = [];
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
if (current.length)
|
|
191
|
+
phrases.push(current.join(" "));
|
|
192
|
+
return phrases.filter((phrase) => phrase.length >= 4).sort((a, b) => b.length - a.length);
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Splits a full-text query into lowercase search terms for passage location.
|
|
196
|
+
* Extracts letter/number runs (Unicode-aware, so accented and non-Latin terms
|
|
197
|
+
* survive intact) so operators and quoting from the query syntax do not
|
|
198
|
+
* pollute the verbatim lookup.
|
|
199
|
+
*/
|
|
200
|
+
function extractSearchTerms(query) {
|
|
201
|
+
const terms = query
|
|
202
|
+
.toLowerCase()
|
|
203
|
+
.split(/[^\p{L}\p{N}_]+/u)
|
|
204
|
+
.filter((term) => term.length > 0);
|
|
205
|
+
return terms;
|
|
206
|
+
}
|
|
207
|
+
/** Validates that a file path is safe to read for document upload. */
|
|
208
|
+
function validateFilePath(filePath) {
|
|
209
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
210
|
+
if (!(0, path_1.isAbsolute)(filePath)) {
|
|
211
|
+
throw new Error("file_path must be an absolute path");
|
|
212
|
+
}
|
|
213
|
+
// Resolve symlinks to get canonical path for allowlist checks
|
|
214
|
+
let realPath;
|
|
215
|
+
try {
|
|
216
|
+
realPath = yield (0, promises_1.realpath)(filePath);
|
|
217
|
+
}
|
|
218
|
+
catch (_a) {
|
|
219
|
+
throw new Error("File not found");
|
|
220
|
+
}
|
|
221
|
+
if (ALLOWED_UPLOAD_PATHS.length > 0) {
|
|
222
|
+
const isAllowed = ALLOWED_UPLOAD_PATHS.some((allowedPath) => {
|
|
223
|
+
return realPath.startsWith(allowedPath + "/") || realPath === allowedPath;
|
|
224
|
+
});
|
|
225
|
+
if (!isAllowed) {
|
|
226
|
+
throw new Error("file_path is outside allowed upload directories. " +
|
|
227
|
+
"Configure PAPERLESS_MCP_UPLOAD_PATHS environment variable to specify allowed paths.");
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
const stats = yield (0, promises_1.stat)(realPath);
|
|
231
|
+
if (!stats.isFile()) {
|
|
232
|
+
throw new Error("Path must point to a regular file");
|
|
233
|
+
}
|
|
234
|
+
if (stats.size > MAX_FILE_SIZE_BYTES) {
|
|
235
|
+
throw new Error(`File size (${Math.round(stats.size / 1024 / 1024)}MB) exceeds maximum allowed size (${MAX_FILE_SIZE_BYTES / 1024 / 1024}MB)`);
|
|
236
|
+
}
|
|
237
|
+
if (stats.size === 0) {
|
|
238
|
+
throw new Error("File is empty");
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Builds Paperless-NGX bulk edit parameters from base parameters plus optional
|
|
244
|
+
* custom field updates.
|
|
245
|
+
*
|
|
246
|
+
* Paperless-NGX expects custom field bulk updates as an `add_custom_fields`
|
|
247
|
+
* record keyed by custom field id. `addCustomFields` is accepted as an array for
|
|
248
|
+
* the MCP tool schema and transformed into that id-to-value record while
|
|
249
|
+
* preserving supported value types, including `number[]` document links and
|
|
250
|
+
* `null` resets. Passing an empty `addCustomFields` array intentionally produces
|
|
251
|
+
* an empty `add_custom_fields` record.
|
|
252
|
+
*
|
|
253
|
+
* When `includeCustomFieldDefaults` is true, the function also initializes
|
|
254
|
+
* `add_custom_fields` and `remove_custom_fields` with empty defaults using
|
|
255
|
+
* nullish coalescing (`??=`). This keeps the `modify_custom_fields` method's
|
|
256
|
+
* payload shape acceptable to Paperless even when no field values are supplied.
|
|
257
|
+
*
|
|
258
|
+
* @param parameters - Base bulk edit parameters to include in the result.
|
|
259
|
+
* @param addCustomFields - Optional custom field updates to map by field id.
|
|
260
|
+
* @param includeCustomFieldDefaults - Whether to include empty custom field
|
|
261
|
+
* defaults required by `modify_custom_fields`.
|
|
262
|
+
* @returns The merged API parameters with custom field updates transformed into
|
|
263
|
+
* Paperless-NGX's `add_custom_fields` record shape.
|
|
264
|
+
*/
|
|
265
|
+
function buildBulkEditParameters(parameters, addCustomFields, includeCustomFieldDefaults = false, includeTagDefaults = false) {
|
|
266
|
+
var _a, _b, _c, _d;
|
|
267
|
+
var _e, _f;
|
|
268
|
+
const apiParameters = Object.assign({}, parameters);
|
|
269
|
+
if (addCustomFields) {
|
|
270
|
+
apiParameters.add_custom_fields = Object.fromEntries(addCustomFields.map((customField) => [
|
|
271
|
+
String(customField.field),
|
|
272
|
+
customField.value,
|
|
273
|
+
]));
|
|
274
|
+
}
|
|
275
|
+
if (includeCustomFieldDefaults) {
|
|
276
|
+
(_a = apiParameters.add_custom_fields) !== null && _a !== void 0 ? _a : (apiParameters.add_custom_fields = {});
|
|
277
|
+
(_b = apiParameters.remove_custom_fields) !== null && _b !== void 0 ? _b : (apiParameters.remove_custom_fields = []);
|
|
278
|
+
}
|
|
279
|
+
if (includeTagDefaults) {
|
|
280
|
+
(_c = (_e = apiParameters).add_tags) !== null && _c !== void 0 ? _c : (_e.add_tags = []);
|
|
281
|
+
(_d = (_f = apiParameters).remove_tags) !== null && _d !== void 0 ? _d : (_f.remove_tags = []);
|
|
282
|
+
}
|
|
283
|
+
return apiParameters;
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Defensive rewrite for django-watson full-text queries: strips apostrophes
|
|
287
|
+
* (a known server-side 400 trigger) and rebalances double quotes. Returns
|
|
288
|
+
* null when the rewrite leaves nothing searchable (caller should not retry).
|
|
289
|
+
*/
|
|
290
|
+
function sanitizeFullTextQuery(query) {
|
|
291
|
+
let cleaned = query.replace(/[\u2018\u2019']/g, "");
|
|
292
|
+
const quotes = (cleaned.match(/"/g) || []).length;
|
|
293
|
+
if (quotes % 2 === 1) {
|
|
294
|
+
cleaned = cleaned.replace(/"/g, " ");
|
|
295
|
+
}
|
|
296
|
+
cleaned = cleaned.replace(/\s+/g, " ").trim();
|
|
297
|
+
// A rewrite that leaves only operators/punctuation is not searchable.
|
|
298
|
+
if (!/[\p{L}\p{N}]/u.test(cleaned))
|
|
299
|
+
return null;
|
|
300
|
+
return cleaned;
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Executes a full-text search with one sanitized retry: django-watson rejects
|
|
304
|
+
* some syntactically valid queries with an opaque HTTP 400, so on a 400 the
|
|
305
|
+
* query is defensively rewritten and attempted once more. Django-ORM filter
|
|
306
|
+
* values are never rewritten — only the full-text query string. A persistent
|
|
307
|
+
* failure rethrows the original error with the attempted queries attached.
|
|
308
|
+
*/
|
|
309
|
+
function runDocumentSearch(api_1, query_1) {
|
|
310
|
+
return __awaiter(this, arguments, void 0, function* (api, query, queryParams = {}) {
|
|
311
|
+
var _a;
|
|
312
|
+
const attempt = (q) => api.getDocuments((0, documentQuery_1.buildDocumentQueryString)(Object.assign(Object.assign({}, queryParams), { query: q })));
|
|
313
|
+
try {
|
|
314
|
+
return { response: yield attempt(query), querySanitized: false };
|
|
315
|
+
}
|
|
316
|
+
catch (error) {
|
|
317
|
+
const status = (_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.status;
|
|
318
|
+
if (status !== 400)
|
|
319
|
+
throw error;
|
|
320
|
+
const sanitized = sanitizeFullTextQuery(query);
|
|
321
|
+
if (sanitized === null || sanitized === query) {
|
|
322
|
+
throw enrichSearchError(error, [query]);
|
|
323
|
+
}
|
|
324
|
+
try {
|
|
325
|
+
return { response: yield attempt(sanitized), querySanitized: true };
|
|
326
|
+
}
|
|
327
|
+
catch (retryError) {
|
|
328
|
+
throw enrichSearchError(retryError, [query, sanitized]);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
function enrichSearchError(error, queries) {
|
|
334
|
+
const base = error instanceof Error ? error.message : String(error);
|
|
335
|
+
return new Error(`${base}. Paperless full-text search rejected these queries: ${queries
|
|
336
|
+
.map((q) => JSON.stringify(q))
|
|
337
|
+
.join(", ")}. Try removing quotes or apostrophes, or use query_documents with tag/correspondent filters instead.`);
|
|
338
|
+
}
|
|
339
|
+
function executeDocumentQuery(api, args) {
|
|
340
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
341
|
+
const docsResponse = yield api.getDocuments((0, documentQuery_1.buildDocumentQueryString)(args));
|
|
342
|
+
return (0, documentEnhancer_1.convertDocsWithNames)(docsResponse, api);
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
function registerDocumentTools(server, api) {
|
|
346
|
+
server.tool("bulk_edit_documents", "Perform bulk operations on multiple documents. Note: 'remove_tag' removes a tag from specific documents (tag remains in system), while 'delete_tag' permanently deletes a tag from the entire system. ⚠️ WARNING: 'delete' method permanently deletes documents and requires confirmation.", {
|
|
347
|
+
documents: zod_1.z.array(zod_1.z.number()),
|
|
348
|
+
method: zod_1.z.enum([
|
|
349
|
+
"set_correspondent",
|
|
350
|
+
"set_document_type",
|
|
351
|
+
"set_storage_path",
|
|
352
|
+
"add_tag",
|
|
353
|
+
"remove_tag",
|
|
354
|
+
"modify_tags",
|
|
355
|
+
"modify_custom_fields",
|
|
356
|
+
"delete",
|
|
357
|
+
"reprocess",
|
|
358
|
+
"set_permissions",
|
|
359
|
+
"merge",
|
|
360
|
+
"split",
|
|
361
|
+
"rotate",
|
|
362
|
+
"delete_pages",
|
|
363
|
+
]),
|
|
364
|
+
correspondent: zod_1.z.number().optional(),
|
|
365
|
+
document_type: zod_1.z.number().optional(),
|
|
366
|
+
storage_path: zod_1.z.number().optional(),
|
|
367
|
+
tag: zod_1.z.number().optional(),
|
|
368
|
+
add_tags: zod_1.z.array(zod_1.z.number()).optional().transform(empty_1.arrayNotEmpty),
|
|
369
|
+
remove_tags: zod_1.z.array(zod_1.z.number()).optional().transform(empty_1.arrayNotEmpty),
|
|
370
|
+
add_custom_fields: zod_1.z
|
|
371
|
+
.array(zod_1.z.object({
|
|
372
|
+
field: zod_1.z.number(),
|
|
373
|
+
value: zod_1.z.union([
|
|
374
|
+
zod_1.z.string(),
|
|
375
|
+
zod_1.z.number(),
|
|
376
|
+
zod_1.z.boolean(),
|
|
377
|
+
zod_1.z.array(zod_1.z.number()),
|
|
378
|
+
zod_1.z.null(),
|
|
379
|
+
]).describe(descriptions_1.CUSTOM_FIELD_VALUE_DESCRIPTION),
|
|
380
|
+
}))
|
|
381
|
+
.optional()
|
|
382
|
+
.transform(empty_1.arrayNotEmpty),
|
|
383
|
+
remove_custom_fields: zod_1.z
|
|
384
|
+
.array(zod_1.z.number())
|
|
385
|
+
.optional()
|
|
386
|
+
.transform(empty_1.arrayNotEmpty),
|
|
387
|
+
set_permissions: zod_1.z
|
|
388
|
+
.object({
|
|
389
|
+
view: zod_1.z
|
|
390
|
+
.object({
|
|
391
|
+
users: zod_1.z.array(zod_1.z.number()).optional(),
|
|
392
|
+
groups: zod_1.z.array(zod_1.z.number()).optional(),
|
|
393
|
+
})
|
|
394
|
+
.strict()
|
|
395
|
+
.optional(),
|
|
396
|
+
change: zod_1.z
|
|
397
|
+
.object({
|
|
398
|
+
users: zod_1.z.array(zod_1.z.number()).optional(),
|
|
399
|
+
groups: zod_1.z.array(zod_1.z.number()).optional(),
|
|
400
|
+
})
|
|
401
|
+
.strict()
|
|
402
|
+
.optional(),
|
|
403
|
+
})
|
|
404
|
+
// strict: a misspelled action ("read") must not silently collapse
|
|
405
|
+
// into {} and clear permissions/ownership.
|
|
406
|
+
.strict()
|
|
407
|
+
.optional()
|
|
408
|
+
.describe("For set_permissions: view/change permissions to apply. Omitted actions (view/change) and omitted users/groups lists are left untouched; an empty list [] removes all (unless merge is true). Omit entirely for owner-only changes."),
|
|
409
|
+
owner: zod_1.z
|
|
410
|
+
.number()
|
|
411
|
+
.int()
|
|
412
|
+
.nullable()
|
|
413
|
+
.optional()
|
|
414
|
+
.describe("For set_permissions: new owner user ID, or null to remove the owner. Unless merge is true, omitting owner also clears the current owner."),
|
|
415
|
+
merge: zod_1.z
|
|
416
|
+
.boolean()
|
|
417
|
+
.optional()
|
|
418
|
+
.describe("For set_permissions: true adds to existing permissions and keeps the current owner; false (default) replaces the listed users/groups"),
|
|
419
|
+
metadata_document_id: zod_1.z.number().optional(),
|
|
420
|
+
delete_originals: zod_1.z.boolean().optional(),
|
|
421
|
+
pages: zod_1.z.string().optional(),
|
|
422
|
+
degrees: zod_1.z.number().optional(),
|
|
423
|
+
confirm: zod_1.z
|
|
424
|
+
.boolean()
|
|
425
|
+
.optional()
|
|
426
|
+
.describe("Must be true when method is 'delete' to confirm destructive operation"),
|
|
427
|
+
}, (0, middlewares_1.withErrorHandling)((args, extra) => __awaiter(this, void 0, void 0, function* () {
|
|
428
|
+
var _a;
|
|
429
|
+
if (!api)
|
|
430
|
+
throw new Error("Please configure API connection first");
|
|
431
|
+
if (args.method === "delete" && !args.confirm) {
|
|
432
|
+
throw new Error("Confirmation required for destructive operation. Set confirm: true to proceed.");
|
|
433
|
+
}
|
|
434
|
+
if (args.method === "set_permissions" &&
|
|
435
|
+
!args.set_permissions &&
|
|
436
|
+
args.owner === undefined) {
|
|
437
|
+
throw new Error("Method 'set_permissions' requires set_permissions and/or owner.");
|
|
438
|
+
}
|
|
439
|
+
const { documents, method, add_custom_fields, confirm } = args, parameters = __rest(args, ["documents", "method", "add_custom_fields", "confirm"]);
|
|
440
|
+
if (method === "set_permissions") {
|
|
441
|
+
// Paperless rejects (Paperless <= 3.0.5: crashes with a 500 on) a missing
|
|
442
|
+
// set_permissions key even for owner-only changes.
|
|
443
|
+
(_a = parameters.set_permissions) !== null && _a !== void 0 ? _a : (parameters.set_permissions = {});
|
|
444
|
+
}
|
|
445
|
+
(0, monetary_1.validateCustomFields)(add_custom_fields);
|
|
446
|
+
const resolvedCustomFields = yield (0, selectFields_1.resolveSelectCustomFieldValues)(api, add_custom_fields, "stored");
|
|
447
|
+
const response = yield api.bulkEditDocuments(documents, method, method === "delete"
|
|
448
|
+
? {}
|
|
449
|
+
: buildBulkEditParameters(parameters, resolvedCustomFields, method === "modify_custom_fields", method === "modify_tags"));
|
|
450
|
+
return {
|
|
451
|
+
content: [
|
|
452
|
+
{
|
|
453
|
+
type: "text",
|
|
454
|
+
text: JSON.stringify({ result: response.result || response }),
|
|
455
|
+
},
|
|
456
|
+
],
|
|
457
|
+
};
|
|
458
|
+
})));
|
|
459
|
+
const postDocumentBaseSchema = zod_1.z.object({
|
|
460
|
+
file: zod_1.z.string().optional().describe("Base64-encoded file content. Either 'file' or 'file_path' must be provided."),
|
|
461
|
+
file_path: zod_1.z.string().optional().describe("Absolute path to a file on the server's filesystem. Either 'file' or 'file_path' must be provided. The filename is derived from the path unless 'filename' is also specified. For security, configure PAPERLESS_MCP_UPLOAD_PATHS to restrict allowed directories."),
|
|
462
|
+
filename: zod_1.z.string().optional().describe("Filename for the uploaded document. Required when using 'file', optional when using 'file_path' (defaults to the basename of the path)."),
|
|
463
|
+
title: zod_1.z.string().optional(),
|
|
464
|
+
created: zod_1.z.string().optional(),
|
|
465
|
+
correspondent: zod_1.z.number().optional(),
|
|
466
|
+
document_type: zod_1.z.number().optional(),
|
|
467
|
+
storage_path: zod_1.z.number().optional(),
|
|
468
|
+
tags: zod_1.z.array(zod_1.z.number()).optional(),
|
|
469
|
+
archive_serial_number: zod_1.z.number().optional(),
|
|
470
|
+
custom_fields: zod_1.z.array(zod_1.z.number()).optional(),
|
|
471
|
+
});
|
|
472
|
+
const postDocumentSchema = postDocumentBaseSchema.superRefine((data, ctx) => {
|
|
473
|
+
const hasFile = data.file !== undefined;
|
|
474
|
+
const hasFilePath = data.file_path !== undefined;
|
|
475
|
+
if (!hasFile && !hasFilePath) {
|
|
476
|
+
ctx.addIssue({
|
|
477
|
+
code: zod_1.z.ZodIssueCode.custom,
|
|
478
|
+
message: "Either 'file' (base64) or 'file_path' must be provided.",
|
|
479
|
+
path: ["file"],
|
|
480
|
+
});
|
|
481
|
+
ctx.addIssue({
|
|
482
|
+
code: zod_1.z.ZodIssueCode.custom,
|
|
483
|
+
message: "Either 'file' (base64) or 'file_path' must be provided.",
|
|
484
|
+
path: ["file_path"],
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
if (hasFile && hasFilePath) {
|
|
488
|
+
ctx.addIssue({
|
|
489
|
+
code: zod_1.z.ZodIssueCode.custom,
|
|
490
|
+
message: "Only one of 'file' or 'file_path' should be provided, not both.",
|
|
491
|
+
path: ["file"],
|
|
492
|
+
});
|
|
493
|
+
ctx.addIssue({
|
|
494
|
+
code: zod_1.z.ZodIssueCode.custom,
|
|
495
|
+
message: "Only one of 'file' or 'file_path' should be provided, not both.",
|
|
496
|
+
path: ["file_path"],
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
if (hasFile && !data.filename) {
|
|
500
|
+
ctx.addIssue({
|
|
501
|
+
code: zod_1.z.ZodIssueCode.custom,
|
|
502
|
+
message: "'filename' is required when using 'file' (base64 mode).",
|
|
503
|
+
path: ["filename"],
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
if (hasFilePath && data.file_path && !(0, path_1.isAbsolute)(data.file_path)) {
|
|
507
|
+
ctx.addIssue({
|
|
508
|
+
code: zod_1.z.ZodIssueCode.custom,
|
|
509
|
+
message: "file_path must be an absolute path",
|
|
510
|
+
path: ["file_path"],
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
});
|
|
514
|
+
server.tool("post_document", "Upload a new document to Paperless-NGX with optional metadata like title, correspondent, document type, tags, and custom fields. Provide either 'file' (base64-encoded content) or 'file_path' (absolute path to a file on the server's filesystem). Using file_path avoids base64 encoding overhead for large files. SECURITY: When using file_path, set PAPERLESS_MCP_UPLOAD_PATHS environment variable to restrict uploads to specific directories (colon-separated paths).", postDocumentBaseSchema.shape, (0, middlewares_1.withErrorHandling)((args, extra) => __awaiter(this, void 0, void 0, function* () {
|
|
515
|
+
if (!api)
|
|
516
|
+
throw new Error("Please configure API connection first");
|
|
517
|
+
const validationResult = postDocumentSchema.safeParse(args);
|
|
518
|
+
if (!validationResult.success) {
|
|
519
|
+
throw new Error(validationResult.error.issues.map(e => e.message).join("; "));
|
|
520
|
+
}
|
|
521
|
+
let document;
|
|
522
|
+
let filename;
|
|
523
|
+
if (args.file_path) {
|
|
524
|
+
yield validateFilePath(args.file_path);
|
|
525
|
+
try {
|
|
526
|
+
document = yield (0, promises_1.readFile)(args.file_path);
|
|
527
|
+
}
|
|
528
|
+
catch (err) {
|
|
529
|
+
throw new Error("Failed to read file");
|
|
530
|
+
}
|
|
531
|
+
filename = args.filename || (0, path_1.basename)(args.file_path);
|
|
532
|
+
if (!filename) {
|
|
533
|
+
throw new Error("Could not derive filename from file_path");
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
else if (args.file) {
|
|
537
|
+
const base64Regex = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
538
|
+
if (!base64Regex.test(args.file)) {
|
|
539
|
+
throw new Error("Invalid base64-encoded file data. Please provide a valid base64 string.");
|
|
540
|
+
}
|
|
541
|
+
document = Buffer.from(args.file, "base64");
|
|
542
|
+
if (document.length > MAX_FILE_SIZE_BYTES) {
|
|
543
|
+
throw new Error(`File size (${Math.round(document.length / 1024 / 1024)}MB) exceeds maximum allowed size (${MAX_FILE_SIZE_BYTES / 1024 / 1024}MB)`);
|
|
544
|
+
}
|
|
545
|
+
if (document.length === 0) {
|
|
546
|
+
throw new Error("File is empty");
|
|
547
|
+
}
|
|
548
|
+
filename = args.filename;
|
|
549
|
+
}
|
|
550
|
+
else {
|
|
551
|
+
// This should never happen due to schema validation, but TypeScript needs it
|
|
552
|
+
throw new Error("Either 'file' (base64) or 'file_path' must be provided.");
|
|
553
|
+
}
|
|
554
|
+
const { file, file_path, filename: _fn } = args, metadata = __rest(args, ["file", "file_path", "filename"]);
|
|
555
|
+
const response = yield api.postDocument(document, filename, metadata);
|
|
556
|
+
let result;
|
|
557
|
+
if (typeof response === "string" && /^\d+$/.test(response)) {
|
|
558
|
+
result = { id: Number(response) };
|
|
559
|
+
}
|
|
560
|
+
else {
|
|
561
|
+
result = { status: response };
|
|
562
|
+
}
|
|
563
|
+
return {
|
|
564
|
+
content: [
|
|
565
|
+
{
|
|
566
|
+
type: "text",
|
|
567
|
+
text: JSON.stringify(result),
|
|
568
|
+
},
|
|
569
|
+
],
|
|
570
|
+
};
|
|
571
|
+
})));
|
|
572
|
+
server.tool("list_documents", "List and filter documents with pagination and common Paperless filters such as title search, correspondent, document type, tag, storage path, creation date, archive serial number, and simple custom field filters. Use 'query_documents' for full-text query, structured custom field conditions, or advanced documented /api/documents/ query parameters. IMPORTANT: For queries like 'the last 3 contributions' or when searching by tag, correspondent, document type, or storage path, first use the relevant lookup tool to find the correct ID. Note: Document content is excluded from results by default. Use 'get_document_content' when you need the document text.", documentQuery_1.LIST_DOCUMENTS_ARGS_SHAPE, (0, middlewares_1.withErrorHandling)((args, extra) => __awaiter(this, void 0, void 0, function* () {
|
|
573
|
+
if (!api)
|
|
574
|
+
throw new Error("Please configure API connection first");
|
|
575
|
+
return executeDocumentQuery(api, args);
|
|
576
|
+
})));
|
|
577
|
+
server.tool("search_passages", "Search documents full-text and return bounded text passages around each hit instead of whole documents. The window is anchored on the server's own highlighted phrase (falling back to the first verbatim term, then the document head), so the returned passage contains the actual hit even when stemming matched a word variant. Queries that the server rejects with an HTTP 400 are retried once with a defensively rewritten query (apostrophes and stray quotes removed); such responses carry query_sanitized: true. Returns document id, title, score, offset, content_length, and the highlighted snippet. Use this to locate and skim evidence across many documents without flooding context; page further with get_document_content offsets.", {
|
|
578
|
+
query: zod_1.z
|
|
579
|
+
.string()
|
|
580
|
+
.min(1)
|
|
581
|
+
.describe("Full-text query (same syntax as query_documents)."),
|
|
582
|
+
window: zod_1.z
|
|
583
|
+
.number()
|
|
584
|
+
.int()
|
|
585
|
+
.min(200)
|
|
586
|
+
.max(4000)
|
|
587
|
+
.optional()
|
|
588
|
+
.describe("Characters per passage (default 800)."),
|
|
589
|
+
max_passages: zod_1.z
|
|
590
|
+
.number()
|
|
591
|
+
.int()
|
|
592
|
+
.min(1)
|
|
593
|
+
.max(20)
|
|
594
|
+
.optional()
|
|
595
|
+
.describe("Maximum passages to return (default 5)."),
|
|
596
|
+
page_size: zod_1.z.number().optional(),
|
|
597
|
+
correspondent: zod_1.z.number().optional(),
|
|
598
|
+
document_type: zod_1.z.number().optional(),
|
|
599
|
+
tag: zod_1.z.number().optional(),
|
|
600
|
+
storage_path: zod_1.z.number().optional(),
|
|
601
|
+
created__date__gte: zod_1.z.string().optional(),
|
|
602
|
+
created__date__lte: zod_1.z.string().optional(),
|
|
603
|
+
ordering: zod_1.z.string().optional(),
|
|
604
|
+
custom_fields__icontains: zod_1.z.string().optional(),
|
|
605
|
+
paperless_filters: zod_1.z
|
|
606
|
+
.record(zod_1.z.string(), zod_1.z.union([
|
|
607
|
+
zod_1.z.string(),
|
|
608
|
+
zod_1.z.number(),
|
|
609
|
+
zod_1.z.boolean(),
|
|
610
|
+
zod_1.z.array(zod_1.z.union([zod_1.z.string(), zod_1.z.number(), zod_1.z.boolean()])),
|
|
611
|
+
]))
|
|
612
|
+
.optional(),
|
|
613
|
+
}, (0, middlewares_1.withErrorHandling)((args, extra) => __awaiter(this, void 0, void 0, function* () {
|
|
614
|
+
var _a, _b, _c;
|
|
615
|
+
if (!api)
|
|
616
|
+
throw new Error("Please configure API connection first");
|
|
617
|
+
const terms = extractSearchTerms(args.query);
|
|
618
|
+
// Reuse the same query-string builder as query_documents so filters
|
|
619
|
+
// behave identically; page_size bounds how many documents are scanned.
|
|
620
|
+
// window / max_passages are tool-only knobs; everything else in args
|
|
621
|
+
// (including the query itself) is a valid query_documents parameter.
|
|
622
|
+
const { window: _window, max_passages: _maxPassages } = args, searchArgs = __rest(args, ["window", "max_passages"]);
|
|
623
|
+
const window = (_a = args.window) !== null && _a !== void 0 ? _a : exports.DEFAULT_PASSAGE_WINDOW;
|
|
624
|
+
const maxPassages = (_b = args.max_passages) !== null && _b !== void 0 ? _b : exports.DEFAULT_MAX_PASSAGES;
|
|
625
|
+
// Each hit arrives with its full stored content, so cap the fetch at
|
|
626
|
+
// the number of passages we will actually return unless the caller
|
|
627
|
+
// asked for a larger scan explicitly.
|
|
628
|
+
// The full-text query rides the same 400-resilient path as the other
|
|
629
|
+
// search tools; structured filters (in searchArgs) are never rewritten.
|
|
630
|
+
const { query: _rawQuery } = searchArgs, filterArgs = __rest(searchArgs, ["query"]);
|
|
631
|
+
const { response: docsResponse, querySanitized } = yield runDocumentSearch(api, args.query, Object.assign(Object.assign({}, filterArgs), { page_size: (_c = args.page_size) !== null && _c !== void 0 ? _c : maxPassages }));
|
|
632
|
+
const passages = (docsResponse.results || [])
|
|
633
|
+
.slice(0, maxPassages)
|
|
634
|
+
.map((doc) => buildSearchPassage(doc, terms, window, doc.__search_hit__));
|
|
635
|
+
return {
|
|
636
|
+
content: [
|
|
637
|
+
{
|
|
638
|
+
type: "text",
|
|
639
|
+
text: JSON.stringify(Object.assign(Object.assign({ query: args.query, total_hits: docsResponse.count }, (querySanitized ? { query_sanitized: true } : {})), { passages })),
|
|
640
|
+
},
|
|
641
|
+
],
|
|
642
|
+
};
|
|
643
|
+
})));
|
|
644
|
+
server.tool("query_documents", "Query documents using the full-text query engine plus structured Paperless filters. Use this for complex filtering, custom field conditions, or any documented /api/documents/ query parameters that are not exposed as first-class arguments. Prefer the dedicated top-level arguments where available. custom_field_query supports [field_name_or_id, operator, value] leaves or ['AND'|'OR', [clause1, clause2]] groups. Note: Document content is excluded from results by default. Use 'get_document_content' when you need the document text.", documentQuery_1.QUERY_DOCUMENTS_ARGS_SHAPE, (0, middlewares_1.withErrorHandling)((args, extra) => __awaiter(this, void 0, void 0, function* () {
|
|
645
|
+
if (!api)
|
|
646
|
+
throw new Error("Please configure API connection first");
|
|
647
|
+
return executeDocumentQuery(api, args);
|
|
648
|
+
})));
|
|
649
|
+
server.tool("get_document", "Get a specific document by ID with full details including correspondent, document type, tags, and custom fields. Note: Document content is excluded from results by default. Use 'get_document_content' to retrieve content when needed.", {
|
|
650
|
+
id: zod_1.z.number(),
|
|
651
|
+
}, (0, middlewares_1.withErrorHandling)((args, extra) => __awaiter(this, void 0, void 0, function* () {
|
|
652
|
+
if (!api)
|
|
653
|
+
throw new Error("Please configure API connection first");
|
|
654
|
+
const doc = yield api.getDocument(args.id);
|
|
655
|
+
return (0, documentEnhancer_1.convertDocsWithNames)(doc, api);
|
|
656
|
+
})));
|
|
657
|
+
server.tool("get_document_content", "Get the text content of a specific document by ID, in bounded windows. Returns at most max_chars characters (default 8000) starting at offset, plus content_length and pagination metadata so callers can page through long documents. Use offset + max_chars to read successive windows of a long document; use the download_document resource for bulk access to the raw file.", {
|
|
658
|
+
id: zod_1.z.number(),
|
|
659
|
+
offset: zod_1.z
|
|
660
|
+
.number()
|
|
661
|
+
.int()
|
|
662
|
+
.min(0)
|
|
663
|
+
.optional()
|
|
664
|
+
.describe("Character offset to start reading from (default 0)."),
|
|
665
|
+
max_chars: zod_1.z
|
|
666
|
+
.number()
|
|
667
|
+
.int()
|
|
668
|
+
.min(1)
|
|
669
|
+
.optional()
|
|
670
|
+
.describe("Maximum characters to return (default 8000). Requests above the inline budget fail with the document size instead of returning everything."),
|
|
671
|
+
}, (0, middlewares_1.withErrorHandling)((args, extra) => __awaiter(this, void 0, void 0, function* () {
|
|
672
|
+
var _a, _b;
|
|
673
|
+
if (!api)
|
|
674
|
+
throw new Error("Please configure API connection first");
|
|
675
|
+
const doc = yield api.getDocument(args.id);
|
|
676
|
+
const { offset, maxChars } = resolveBoundedRead(args.offset, args.max_chars, (_b = (_a = doc.content) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0);
|
|
677
|
+
return {
|
|
678
|
+
content: [
|
|
679
|
+
{
|
|
680
|
+
type: "text",
|
|
681
|
+
text: JSON.stringify(sliceDocumentContent(doc, offset, maxChars)),
|
|
682
|
+
},
|
|
683
|
+
],
|
|
684
|
+
};
|
|
685
|
+
})));
|
|
686
|
+
server.tool("search_documents", "Deprecated compatibility wrapper for full-text document search. Use 'query_documents' with the 'query' argument for new integrations. Note: Document content is excluded from results by default. Use 'get_document_content' to retrieve content when needed.", documentQuery_1.SEARCH_DOCUMENTS_ARGS_SHAPE, (0, middlewares_1.withErrorHandling)((args, extra) => __awaiter(this, void 0, void 0, function* () {
|
|
687
|
+
if (!api)
|
|
688
|
+
throw new Error("Please configure API connection first");
|
|
689
|
+
return executeDocumentQuery(api, args);
|
|
690
|
+
})));
|
|
691
|
+
server.tool("download_document", "Download a document file by ID. Returns a paperless:// resource URI; read the resource to fetch the file content.", {
|
|
692
|
+
id: zod_1.z.number().int().positive(),
|
|
693
|
+
original: zod_1.z.boolean().optional(),
|
|
694
|
+
}, (0, middlewares_1.withErrorHandling)((args, extra) => __awaiter(this, void 0, void 0, function* () {
|
|
695
|
+
if (!api)
|
|
696
|
+
throw new Error("Please configure API connection first");
|
|
697
|
+
const uri = (0, resourceUri_1.buildDocumentResourceUri)(args.id, {
|
|
698
|
+
original: args.original,
|
|
699
|
+
});
|
|
700
|
+
return {
|
|
701
|
+
content: [
|
|
702
|
+
// Legacy clients surface only content[].text and drop resource blocks
|
|
703
|
+
// entirely, so the URI is repeated here to stay reachable (issue #134).
|
|
704
|
+
{ type: "text", text: uri },
|
|
705
|
+
{
|
|
706
|
+
type: "resource",
|
|
707
|
+
resource: {
|
|
708
|
+
uri,
|
|
709
|
+
// MCP SDK 1.11 embedded resources require text or blob. Keep the
|
|
710
|
+
// existing resource-shaped tool result while making resources/read
|
|
711
|
+
// the canonical place for the large binary payload.
|
|
712
|
+
text: "",
|
|
713
|
+
mimeType: "application/octet-stream",
|
|
714
|
+
},
|
|
715
|
+
},
|
|
716
|
+
],
|
|
717
|
+
};
|
|
718
|
+
})));
|
|
719
|
+
server.tool("get_document_thumbnail", "Get a document thumbnail (image preview) by ID. Returns a paperless:// resource URI; read the resource to fetch the image content.", {
|
|
720
|
+
id: zod_1.z.number().int().positive(),
|
|
721
|
+
}, (0, middlewares_1.withErrorHandling)((args, extra) => __awaiter(this, void 0, void 0, function* () {
|
|
722
|
+
if (!api)
|
|
723
|
+
throw new Error("Please configure API connection first");
|
|
724
|
+
const uri = (0, resourceUri_1.buildThumbnailResourceUri)(args.id);
|
|
725
|
+
return {
|
|
726
|
+
content: [
|
|
727
|
+
// See download_document above: the URI is repeated as text for legacy
|
|
728
|
+
// clients that drop resource blocks.
|
|
729
|
+
{ type: "text", text: uri },
|
|
730
|
+
{
|
|
731
|
+
type: "resource",
|
|
732
|
+
resource: {
|
|
733
|
+
uri,
|
|
734
|
+
// See download_document above: the binary thumbnail is fetched
|
|
735
|
+
// lazily through resources/read instead of embedded here.
|
|
736
|
+
text: "",
|
|
737
|
+
mimeType: "image/webp",
|
|
738
|
+
},
|
|
739
|
+
},
|
|
740
|
+
],
|
|
741
|
+
};
|
|
742
|
+
})));
|
|
743
|
+
server.tool("update_document", "Update a specific document with new values (title, correspondent, document type, storage path, tags, custom fields, and more). Top-level fields you omit are left unchanged. IMPORTANT: custom_fields is the exception — see its parameter description; it replaces the document's entire custom-field set.", {
|
|
744
|
+
id: zod_1.z.number().describe("The ID of the document to update"),
|
|
745
|
+
title: zod_1.z
|
|
746
|
+
.string()
|
|
747
|
+
.max(128)
|
|
748
|
+
.optional()
|
|
749
|
+
.describe("The new title for the document (max 128 characters)"),
|
|
750
|
+
correspondent: zod_1.z
|
|
751
|
+
.number()
|
|
752
|
+
.int()
|
|
753
|
+
.nullable()
|
|
754
|
+
.optional()
|
|
755
|
+
.describe("The ID of the correspondent to assign"),
|
|
756
|
+
document_type: zod_1.z
|
|
757
|
+
.number()
|
|
758
|
+
.int()
|
|
759
|
+
.nullable()
|
|
760
|
+
.optional()
|
|
761
|
+
.describe("The ID of the document type to assign"),
|
|
762
|
+
storage_path: zod_1.z
|
|
763
|
+
.number()
|
|
764
|
+
.int()
|
|
765
|
+
.nullable()
|
|
766
|
+
.optional()
|
|
767
|
+
.describe("The ID of the storage path to assign"),
|
|
768
|
+
tags: zod_1.z
|
|
769
|
+
.array(zod_1.z.number())
|
|
770
|
+
.optional()
|
|
771
|
+
.describe("Array of tag IDs to assign to the document"),
|
|
772
|
+
content: zod_1.z
|
|
773
|
+
.string()
|
|
774
|
+
.optional()
|
|
775
|
+
.describe("The raw text content of the document (used for searching)"),
|
|
776
|
+
created: zod_1.z
|
|
777
|
+
.string()
|
|
778
|
+
.optional()
|
|
779
|
+
.describe("The creation date in YYYY-MM-DD format"),
|
|
780
|
+
archive_serial_number: zod_1.z
|
|
781
|
+
.number()
|
|
782
|
+
.optional()
|
|
783
|
+
.describe("The archive serial number (0-4294967295)"),
|
|
784
|
+
owner: zod_1.z
|
|
785
|
+
.number()
|
|
786
|
+
.int()
|
|
787
|
+
.nullable()
|
|
788
|
+
.optional()
|
|
789
|
+
.describe("The ID of the user who owns the document"),
|
|
790
|
+
custom_fields: zod_1.z
|
|
791
|
+
.array(zod_1.z.object({
|
|
792
|
+
field: zod_1.z.number().describe("The custom field ID"),
|
|
793
|
+
value: zod_1.z
|
|
794
|
+
.union([
|
|
795
|
+
zod_1.z.string(),
|
|
796
|
+
zod_1.z.number(),
|
|
797
|
+
zod_1.z.boolean(),
|
|
798
|
+
zod_1.z.array(zod_1.z.number()),
|
|
799
|
+
zod_1.z.null(),
|
|
800
|
+
])
|
|
801
|
+
.describe(descriptions_1.CUSTOM_FIELD_VALUE_DESCRIPTION),
|
|
802
|
+
}))
|
|
803
|
+
.optional()
|
|
804
|
+
.describe("Custom field values for the document. ⚠️ REPLACES the document's entire custom-field set — any field not included here will be CLEARED. To update or add a single field without losing the others, first call get_document to read the existing custom_fields, then pass the full merged array. To add/set fields additively without fetching, use bulk_edit_documents with method 'modify_custom_fields' instead."),
|
|
805
|
+
}, (0, middlewares_1.withErrorHandling)((args, extra) => __awaiter(this, void 0, void 0, function* () {
|
|
806
|
+
if (!api)
|
|
807
|
+
throw new Error("Please configure API connection first");
|
|
808
|
+
const { id } = args, updateData = __rest(args, ["id"]);
|
|
809
|
+
(0, monetary_1.validateCustomFields)(updateData.custom_fields);
|
|
810
|
+
updateData.custom_fields = yield (0, selectFields_1.resolveSelectCustomFieldValues)(api, updateData.custom_fields, "stored");
|
|
811
|
+
const response = yield api.updateDocument(id, updateData);
|
|
812
|
+
return (0, documentEnhancer_1.convertDocsWithNames)(response, api);
|
|
813
|
+
})));
|
|
814
|
+
}
|