@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.
Files changed (74) hide show
  1. package/LICENSE +18 -0
  2. package/README.md +1004 -2
  3. package/build/api/PaperlessAPI.d.ts +63 -0
  4. package/build/api/PaperlessAPI.js +405 -0
  5. package/build/api/documentEnhancer.d.ts +24 -0
  6. package/build/api/documentEnhancer.js +111 -0
  7. package/build/api/documentEnhancer.test.d.ts +1 -0
  8. package/build/api/documentEnhancer.test.js +80 -0
  9. package/build/api/types.d.ts +203 -0
  10. package/build/api/types.js +15 -0
  11. package/build/api/utils.d.ts +16 -0
  12. package/build/api/utils.js +29 -0
  13. package/build/index.d.ts +2 -0
  14. package/build/index.js +189 -0
  15. package/build/resources/documents.d.ts +7 -0
  16. package/build/resources/documents.js +119 -0
  17. package/build/resources/documents.test.d.ts +1 -0
  18. package/build/resources/documents.test.js +124 -0
  19. package/build/server.d.ts +24 -0
  20. package/build/server.js +70 -0
  21. package/build/server.test.d.ts +1 -0
  22. package/build/server.test.js +54 -0
  23. package/build/test/mocks/paperlessApi.d.ts +4 -0
  24. package/build/test/mocks/paperlessApi.js +33 -0
  25. package/build/tools/boundedContent.test.d.ts +1 -0
  26. package/build/tools/boundedContent.test.js +544 -0
  27. package/build/tools/correspondents.d.ts +3 -0
  28. package/build/tools/correspondents.js +149 -0
  29. package/build/tools/customFields.d.ts +3 -0
  30. package/build/tools/customFields.js +142 -0
  31. package/build/tools/documentTypes.d.ts +3 -0
  32. package/build/tools/documentTypes.js +143 -0
  33. package/build/tools/documents.d.ts +134 -0
  34. package/build/tools/documents.js +814 -0
  35. package/build/tools/documents.test.d.ts +1 -0
  36. package/build/tools/documents.test.js +658 -0
  37. package/build/tools/mail.d.ts +3 -0
  38. package/build/tools/mail.js +187 -0
  39. package/build/tools/mail.test.d.ts +1 -0
  40. package/build/tools/mail.test.js +212 -0
  41. package/build/tools/notes.d.ts +3 -0
  42. package/build/tools/notes.js +55 -0
  43. package/build/tools/notes.test.d.ts +1 -0
  44. package/build/tools/notes.test.js +177 -0
  45. package/build/tools/schemaCompat.test.d.ts +1 -0
  46. package/build/tools/schemaCompat.test.js +59 -0
  47. package/build/tools/tags.d.ts +3 -0
  48. package/build/tools/tags.js +143 -0
  49. package/build/tools/utils/descriptions.d.ts +1 -0
  50. package/build/tools/utils/descriptions.js +4 -0
  51. package/build/tools/utils/documentQuery.d.ts +71 -0
  52. package/build/tools/utils/documentQuery.js +270 -0
  53. package/build/tools/utils/empty.d.ts +2 -0
  54. package/build/tools/utils/empty.js +7 -0
  55. package/build/tools/utils/matchingAlgorithm.d.ts +2 -0
  56. package/build/tools/utils/matchingAlgorithm.js +15 -0
  57. package/build/tools/utils/middlewares.d.ts +3 -0
  58. package/build/tools/utils/middlewares.js +31 -0
  59. package/build/tools/utils/monetary.d.ts +5 -0
  60. package/build/tools/utils/monetary.js +34 -0
  61. package/build/tools/utils/monetary.test.d.ts +1 -0
  62. package/build/tools/utils/monetary.test.js +25 -0
  63. package/build/tools/utils/queryString.d.ts +1 -0
  64. package/build/tools/utils/queryString.js +12 -0
  65. package/build/tools/utils/resourceUri.d.ts +29 -0
  66. package/build/tools/utils/resourceUri.js +37 -0
  67. package/build/tools/utils/resourceUri.test.d.ts +1 -0
  68. package/build/tools/utils/resourceUri.test.js +50 -0
  69. package/build/tools/utils/selectFields.d.ts +13 -0
  70. package/build/tools/utils/selectFields.js +91 -0
  71. package/build/tools/utils/selectFields.test.d.ts +1 -0
  72. package/build/tools/utils/selectFields.test.js +164 -0
  73. package/package.json +59 -4
  74. package/paperless-mcp.dxt +0 -0
@@ -0,0 +1,59 @@
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 __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const strict_1 = __importDefault(require("node:assert/strict"));
16
+ const node_test_1 = require("node:test");
17
+ const index_js_1 = require("@modelcontextprotocol/sdk/client/index.js");
18
+ const inMemory_js_1 = require("@modelcontextprotocol/sdk/inMemory.js");
19
+ const server_1 = require("../server");
20
+ // Strict MCP clients and gateways reject an array-valued `type` and silently drop
21
+ // the whole tool (#138). A JSON Schema converter reaches that form by collapsing a
22
+ // union of unchecked primitives: `zod-to-json-schema` (the zod v3 path) always does
23
+ // it, and zod's own converter did it again from 4.5.0 on. The tools are only free
24
+ // of it because the server is on the zod v4 path with zod pinned to 4.4.x, so this
25
+ // walks every advertised schema rather than a field list: bumping that pin, moving
26
+ // off zod v4, or adding a construct that reintroduces the form fails here.
27
+ function arrayFormTypes(node, path = "") {
28
+ if (Array.isArray(node)) {
29
+ return node.flatMap((item, i) => arrayFormTypes(item, `${path}[${i}]`));
30
+ }
31
+ if (!node || typeof node !== "object") {
32
+ return [];
33
+ }
34
+ return Object.entries(node).flatMap(([key, value]) => key === "type" && Array.isArray(value)
35
+ ? [`${path}.type = ${JSON.stringify(value)}`]
36
+ : arrayFormTypes(value, `${path}.${key}`));
37
+ }
38
+ (0, node_test_1.test)("no tool advertises an array-form `type` (#138)", () => __awaiter(void 0, void 0, void 0, function* () {
39
+ const server = (0, server_1.createMcpServer)({
40
+ baseUrl: "http://paperless.test",
41
+ token: "test-token",
42
+ version: "0.0.0-test",
43
+ publicUrl: "http://paperless.test",
44
+ });
45
+ const [clientTransport, serverTransport] = inMemory_js_1.InMemoryTransport.createLinkedPair();
46
+ const client = new index_js_1.Client({ name: "schema-compat-test", version: "1.0.0" });
47
+ yield Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
48
+ try {
49
+ const { tools } = yield client.listTools();
50
+ const found = tools
51
+ .flatMap((tool) => arrayFormTypes(tool.inputSchema).map((hit) => `${tool.name} ${hit}`))
52
+ .sort();
53
+ strict_1.default.deepEqual(found, []);
54
+ }
55
+ finally {
56
+ yield client.close();
57
+ yield server.close();
58
+ }
59
+ }));
@@ -0,0 +1,3 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp";
2
+ import { PaperlessAPI } from "../api/PaperlessAPI";
3
+ export declare function registerTagTools(server: McpServer, api: PaperlessAPI): void;
@@ -0,0 +1,143 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.registerTagTools = registerTagTools;
13
+ const zod_1 = require("zod");
14
+ const utils_1 = require("../api/utils");
15
+ const matchingAlgorithm_1 = require("./utils/matchingAlgorithm");
16
+ const middlewares_1 = require("./utils/middlewares");
17
+ const queryString_1 = require("./utils/queryString");
18
+ function registerTagTools(server, api) {
19
+ server.tool("list_tags", "List all tags. IMPORTANT: When a user query may refer to a tag or document type, you should fetch all tags and all document types up front (with a large enough page_size), cache them for the session, and search locally for matches by name or slug before making further API calls. This reduces redundant requests and handles ambiguity between tags and document types efficiently.", {
20
+ page: zod_1.z.number().optional(),
21
+ page_size: zod_1.z.number().optional(),
22
+ name__icontains: zod_1.z.string().optional(),
23
+ name__iendswith: zod_1.z.string().optional(),
24
+ name__iexact: zod_1.z.string().optional(),
25
+ name__istartswith: zod_1.z.string().optional(),
26
+ ordering: zod_1.z.string().optional(),
27
+ }, (0, middlewares_1.withErrorHandling)((args) => __awaiter(this, void 0, void 0, function* () {
28
+ if (!api)
29
+ throw new Error("Please configure API connection first");
30
+ const queryString = (0, queryString_1.buildQueryString)(args);
31
+ const tagsResponse = yield api.request(`/tags/${queryString ? `?${queryString}` : ""}`);
32
+ const enhancedResults = (0, utils_1.enhanceMatchingAlgorithmArray)(tagsResponse.results || []);
33
+ return {
34
+ content: [
35
+ {
36
+ type: "text",
37
+ text: JSON.stringify(Object.assign(Object.assign({}, tagsResponse), { results: enhancedResults })),
38
+ },
39
+ ],
40
+ };
41
+ })));
42
+ server.tool("create_tag", "Create a new tag with optional color, matching pattern, and matching algorithm for automatic document tagging.", {
43
+ name: zod_1.z.string(),
44
+ color: zod_1.z
45
+ .string()
46
+ .regex(/^#[0-9A-Fa-f]{6}$/)
47
+ .optional(),
48
+ match: zod_1.z.string().optional(),
49
+ matching_algorithm: matchingAlgorithm_1.matchingAlgorithmSchema.optional(),
50
+ }, (0, middlewares_1.withErrorHandling)((args, extra) => __awaiter(this, void 0, void 0, function* () {
51
+ if (!api)
52
+ throw new Error("Please configure API connection first");
53
+ const tag = yield api.createTag(args);
54
+ const enhancedTag = (0, utils_1.enhanceMatchingAlgorithm)(tag);
55
+ return {
56
+ content: [
57
+ {
58
+ type: "text",
59
+ text: JSON.stringify(enhancedTag),
60
+ },
61
+ ],
62
+ };
63
+ })));
64
+ server.tool("update_tag", "Update an existing tag's name, color, matching pattern, or matching algorithm.", {
65
+ id: zod_1.z.number(),
66
+ name: zod_1.z.string(),
67
+ color: zod_1.z
68
+ .string()
69
+ .regex(/^#[0-9A-Fa-f]{6}$/)
70
+ .optional(),
71
+ match: zod_1.z.string().optional(),
72
+ matching_algorithm: matchingAlgorithm_1.matchingAlgorithmSchema.optional(),
73
+ }, (0, middlewares_1.withErrorHandling)((args, extra) => __awaiter(this, void 0, void 0, function* () {
74
+ if (!api)
75
+ throw new Error("Please configure API connection first");
76
+ const tag = yield api.updateTag(args.id, args);
77
+ const enhancedTag = (0, utils_1.enhanceMatchingAlgorithm)(tag);
78
+ return {
79
+ content: [
80
+ {
81
+ type: "text",
82
+ text: JSON.stringify(enhancedTag),
83
+ },
84
+ ],
85
+ };
86
+ })));
87
+ server.tool("delete_tag", "⚠️ DESTRUCTIVE: Permanently delete a tag from the entire system. This will remove the tag from ALL documents that use it. Use with extreme caution.", {
88
+ id: zod_1.z.number(),
89
+ confirm: zod_1.z
90
+ .boolean()
91
+ .describe("Must be true to confirm this destructive operation"),
92
+ }, (0, middlewares_1.withErrorHandling)((args, extra) => __awaiter(this, void 0, void 0, function* () {
93
+ if (!api)
94
+ throw new Error("Please configure API connection first");
95
+ if (!args.confirm) {
96
+ throw new Error("Confirmation required for destructive operation. Set confirm: true to proceed.");
97
+ }
98
+ yield api.deleteTag(args.id);
99
+ return {
100
+ content: [
101
+ {
102
+ type: "text",
103
+ text: JSON.stringify({ status: "deleted" }),
104
+ },
105
+ ],
106
+ };
107
+ })));
108
+ server.tool("bulk_edit_tags", "Bulk edit tags. ⚠️ WARNING: 'delete' operation permanently removes tags from the entire system. Use with caution.", {
109
+ tag_ids: zod_1.z.array(zod_1.z.number()),
110
+ operation: zod_1.z.enum(["set_permissions", "delete"]),
111
+ confirm: zod_1.z
112
+ .boolean()
113
+ .optional()
114
+ .describe("Must be true when operation is 'delete' to confirm destructive operation"),
115
+ owner: zod_1.z.number().optional(),
116
+ permissions: zod_1.z
117
+ .object({
118
+ view: zod_1.z.object({
119
+ users: zod_1.z.array(zod_1.z.number()).optional(),
120
+ groups: zod_1.z.array(zod_1.z.number()).optional(),
121
+ }),
122
+ change: zod_1.z.object({
123
+ users: zod_1.z.array(zod_1.z.number()).optional(),
124
+ groups: zod_1.z.array(zod_1.z.number()).optional(),
125
+ }),
126
+ })
127
+ .optional(),
128
+ merge: zod_1.z.boolean().optional(),
129
+ }, (0, middlewares_1.withErrorHandling)((args, extra) => __awaiter(this, void 0, void 0, function* () {
130
+ if (!api)
131
+ throw new Error("Please configure API connection first");
132
+ if (args.operation === "delete" && !args.confirm) {
133
+ throw new Error("Confirmation required for destructive operation. Set confirm: true to proceed.");
134
+ }
135
+ return api.bulkEditObjects(args.tag_ids, "tags", args.operation, args.operation === "set_permissions"
136
+ ? {
137
+ owner: args.owner,
138
+ permissions: args.permissions,
139
+ merge: args.merge,
140
+ }
141
+ : {});
142
+ })));
143
+ }
@@ -0,0 +1 @@
1
+ export declare const CUSTOM_FIELD_VALUE_DESCRIPTION = "The value for the custom field. For monetary fields, use currency code prefix format (e.g., USD10.00, GBP123.45, EUR9.99) \u2014 NOT trailing symbol format (e.g., 10.00$). For documentlink fields, use a single document ID (e.g., 123) or an array of document IDs (e.g., [123, 456]). For select fields, pass the option's label (the display text from get_custom_field / list_custom_fields); the server translates it to the encoding Paperless expects.";
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CUSTOM_FIELD_VALUE_DESCRIPTION = void 0;
4
+ exports.CUSTOM_FIELD_VALUE_DESCRIPTION = "The value for the custom field. For monetary fields, use currency code prefix format (e.g., USD10.00, GBP123.45, EUR9.99) — NOT trailing symbol format (e.g., 10.00$). For documentlink fields, use a single document ID (e.g., 123) or an array of document IDs (e.g., [123, 456]). For select fields, pass the option's label (the display text from get_custom_field / list_custom_fields); the server translates it to the encoding Paperless expects.";
@@ -0,0 +1,71 @@
1
+ import { z } from "zod";
2
+ declare const CUSTOM_FIELD_QUERY_GROUP_OPERATORS: readonly ["AND", "OR"];
3
+ export type CustomFieldQueryValue = string | number | boolean | null | Array<string | number | boolean | null>;
4
+ export type CustomFieldQuery = [fieldNameOrId: string | number, operator: string, value: CustomFieldQueryValue] | [
5
+ groupOperator: (typeof CUSTOM_FIELD_QUERY_GROUP_OPERATORS)[number],
6
+ clauses: CustomFieldQuery[]
7
+ ];
8
+ export declare const customFieldQuerySchema: z.ZodType<CustomFieldQuery>;
9
+ export declare const paperlessFilterValueSchema: z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>, z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>]>;
10
+ export declare const paperlessFiltersSchema: z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>, z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>]>>;
11
+ export declare const LIST_DOCUMENTS_ARGS_SHAPE: {
12
+ custom_field_query: z.ZodOptional<z.ZodString>;
13
+ page: z.ZodOptional<z.ZodNumber>;
14
+ page_size: z.ZodOptional<z.ZodNumber>;
15
+ search: z.ZodOptional<z.ZodString>;
16
+ correspondent: z.ZodOptional<z.ZodNumber>;
17
+ document_type: z.ZodOptional<z.ZodNumber>;
18
+ tag: z.ZodOptional<z.ZodNumber>;
19
+ storage_path: z.ZodOptional<z.ZodNumber>;
20
+ created__date__gte: z.ZodOptional<z.ZodString>;
21
+ created__date__lte: z.ZodOptional<z.ZodString>;
22
+ ordering: z.ZodOptional<z.ZodString>;
23
+ archive_serial_number: z.ZodOptional<z.ZodNumber>;
24
+ archive_serial_number__isnull: z.ZodOptional<z.ZodBoolean>;
25
+ custom_fields__icontains: z.ZodOptional<z.ZodString>;
26
+ };
27
+ export declare const QUERY_DOCUMENTS_ARGS_SHAPE: {
28
+ query: z.ZodOptional<z.ZodString>;
29
+ more_like_id: z.ZodOptional<z.ZodNumber>;
30
+ custom_field_query: z.ZodOptional<z.ZodType<CustomFieldQuery, unknown, z.core.$ZodTypeInternals<CustomFieldQuery, unknown>>>;
31
+ paperless_filters: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>, z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>]>>>;
32
+ page: z.ZodOptional<z.ZodNumber>;
33
+ page_size: z.ZodOptional<z.ZodNumber>;
34
+ search: z.ZodOptional<z.ZodString>;
35
+ correspondent: z.ZodOptional<z.ZodNumber>;
36
+ document_type: z.ZodOptional<z.ZodNumber>;
37
+ tag: z.ZodOptional<z.ZodNumber>;
38
+ storage_path: z.ZodOptional<z.ZodNumber>;
39
+ created__date__gte: z.ZodOptional<z.ZodString>;
40
+ created__date__lte: z.ZodOptional<z.ZodString>;
41
+ ordering: z.ZodOptional<z.ZodString>;
42
+ archive_serial_number: z.ZodOptional<z.ZodNumber>;
43
+ archive_serial_number__isnull: z.ZodOptional<z.ZodBoolean>;
44
+ custom_fields__icontains: z.ZodOptional<z.ZodString>;
45
+ };
46
+ export declare const SEARCH_DOCUMENTS_ARGS_SHAPE: {
47
+ query: z.ZodString;
48
+ };
49
+ export type PaperlessFilterValue = z.infer<typeof paperlessFilterValueSchema>;
50
+ export type BuildDocumentQueryArgs = {
51
+ page?: number;
52
+ page_size?: number;
53
+ ordering?: string;
54
+ query?: string;
55
+ search?: string;
56
+ more_like_id?: number;
57
+ correspondent?: number;
58
+ document_type?: number;
59
+ tag?: number;
60
+ storage_path?: number;
61
+ created__date__gte?: string;
62
+ created__date__lte?: string;
63
+ archive_serial_number?: number;
64
+ archive_serial_number__isnull?: boolean;
65
+ custom_field_query?: string | CustomFieldQuery;
66
+ custom_fields__icontains?: string;
67
+ paperless_filters?: Record<string, PaperlessFilterValue>;
68
+ };
69
+ export declare const DOCUMENT_QUERY_PAPERLESS_FILTER_KEYS: readonly ["added__date__gt", "added__date__gte", "added__date__lt", "added__date__lte", "added__day", "added__gt", "added__gte", "added__lt", "added__lte", "added__month", "added__year", "archive_serial_number", "archive_serial_number__gt", "archive_serial_number__gte", "archive_serial_number__isnull", "archive_serial_number__lt", "archive_serial_number__lte", "checksum__icontains", "checksum__iendswith", "checksum__iexact", "checksum__istartswith", "content__icontains", "content__iendswith", "content__iexact", "content__istartswith", "correspondent__id", "correspondent__id__in", "correspondent__id__none", "correspondent__isnull", "correspondent__name__icontains", "correspondent__name__iendswith", "correspondent__name__iexact", "correspondent__name__istartswith", "created__date__gt", "created__date__gte", "created__date__lt", "created__date__lte", "created__day", "created__gt", "created__gte", "created__lt", "created__lte", "created__month", "created__year", "custom_field_query", "custom_fields__icontains", "custom_fields__id__all", "custom_fields__id__in", "custom_fields__id__none", "document_type__id", "document_type__id__in", "document_type__id__none", "document_type__isnull", "document_type__name__icontains", "document_type__name__iendswith", "document_type__name__iexact", "document_type__name__istartswith", "fields", "full_perms", "has_custom_fields", "id", "id__in", "is_in_inbox", "is_tagged", "mime_type", "modified__date__gt", "modified__date__gte", "modified__date__lt", "modified__date__lte", "modified__day", "modified__gt", "modified__gte", "modified__lt", "modified__lte", "modified__month", "modified__year", "ordering", "original_filename__icontains", "original_filename__iendswith", "original_filename__iexact", "original_filename__istartswith", "owner__id", "owner__id__in", "owner__id__none", "owner__isnull", "page", "page_size", "query", "search", "shared_by__id", "storage_path__id", "storage_path__id__in", "storage_path__id__none", "storage_path__isnull", "storage_path__name__icontains", "storage_path__name__iendswith", "storage_path__name__iexact", "storage_path__name__istartswith", "tags__id", "tags__id__all", "tags__id__in", "tags__id__none", "tags__name__icontains", "tags__name__iendswith", "tags__name__iexact", "tags__name__istartswith", "title__icontains", "title__iendswith", "title__iexact", "title__istartswith", "title_content"];
70
+ export declare function buildDocumentQueryString(args: BuildDocumentQueryArgs): string;
71
+ export {};
@@ -0,0 +1,270 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DOCUMENT_QUERY_PAPERLESS_FILTER_KEYS = exports.SEARCH_DOCUMENTS_ARGS_SHAPE = exports.QUERY_DOCUMENTS_ARGS_SHAPE = exports.LIST_DOCUMENTS_ARGS_SHAPE = exports.paperlessFiltersSchema = exports.paperlessFilterValueSchema = exports.customFieldQuerySchema = void 0;
4
+ exports.buildDocumentQueryString = buildDocumentQueryString;
5
+ const zod_1 = require("zod");
6
+ const CUSTOM_FIELD_QUERY_GROUP_OPERATORS = ["AND", "OR"];
7
+ const customFieldQueryPrimitiveSchema = zod_1.z.union([
8
+ zod_1.z.string(),
9
+ zod_1.z.number(),
10
+ zod_1.z.boolean(),
11
+ zod_1.z.null(),
12
+ ]);
13
+ const customFieldQueryValueSchema = zod_1.z.union([
14
+ customFieldQueryPrimitiveSchema,
15
+ zod_1.z.array(customFieldQueryPrimitiveSchema),
16
+ ]);
17
+ function isCustomFieldQueryPrimitive(value) {
18
+ return (typeof value === "string" ||
19
+ typeof value === "number" ||
20
+ typeof value === "boolean" ||
21
+ value === null);
22
+ }
23
+ function isCustomFieldQueryValue(value) {
24
+ if (isCustomFieldQueryPrimitive(value)) {
25
+ return true;
26
+ }
27
+ return (Array.isArray(value) && value.every((item) => isCustomFieldQueryPrimitive(item)));
28
+ }
29
+ function isCustomFieldQueryGroupOperator(value) {
30
+ return (typeof value === "string" &&
31
+ CUSTOM_FIELD_QUERY_GROUP_OPERATORS.includes(value));
32
+ }
33
+ function isCustomFieldQuery(value) {
34
+ if (!Array.isArray(value)) {
35
+ return false;
36
+ }
37
+ if (value.length === 3 &&
38
+ (typeof value[0] === "string" || typeof value[0] === "number") &&
39
+ !isCustomFieldQueryGroupOperator(value[0]) &&
40
+ typeof value[1] === "string" &&
41
+ isCustomFieldQueryValue(value[2])) {
42
+ return true;
43
+ }
44
+ if (value.length === 2 &&
45
+ isCustomFieldQueryGroupOperator(value[0]) &&
46
+ Array.isArray(value[1]) &&
47
+ value[1].length >= 1) {
48
+ return value[1].every((item) => isCustomFieldQuery(item));
49
+ }
50
+ return false;
51
+ }
52
+ exports.customFieldQuerySchema = zod_1.z
53
+ .array(zod_1.z.unknown())
54
+ .superRefine((value, ctx) => {
55
+ if (!isCustomFieldQuery(value)) {
56
+ ctx.addIssue({
57
+ code: zod_1.z.ZodIssueCode.custom,
58
+ message: "Invalid custom_field_query. Use [field_name_or_id, operator, value] or ['AND'|'OR', [clause1, clause2]].",
59
+ });
60
+ }
61
+ });
62
+ const paperlessFilterScalarSchema = zod_1.z.union([
63
+ zod_1.z.string(),
64
+ zod_1.z.number(),
65
+ zod_1.z.boolean(),
66
+ ]);
67
+ exports.paperlessFilterValueSchema = zod_1.z.union([
68
+ paperlessFilterScalarSchema,
69
+ zod_1.z.array(paperlessFilterScalarSchema),
70
+ ]);
71
+ exports.paperlessFiltersSchema = zod_1.z.record(zod_1.z.string(), exports.paperlessFilterValueSchema);
72
+ const DOCUMENT_QUERY_BASE_ARGS_SHAPE = {
73
+ page: zod_1.z.number().optional(),
74
+ page_size: zod_1.z.number().optional(),
75
+ search: zod_1.z.string().optional(),
76
+ correspondent: zod_1.z.number().optional(),
77
+ document_type: zod_1.z.number().optional(),
78
+ tag: zod_1.z.number().optional(),
79
+ storage_path: zod_1.z.number().optional(),
80
+ created__date__gte: zod_1.z.string().optional(),
81
+ created__date__lte: zod_1.z.string().optional(),
82
+ ordering: zod_1.z.string().optional(),
83
+ archive_serial_number: zod_1.z.number().optional(),
84
+ archive_serial_number__isnull: zod_1.z.boolean().optional(),
85
+ custom_fields__icontains: zod_1.z.string().min(1).optional(),
86
+ };
87
+ exports.LIST_DOCUMENTS_ARGS_SHAPE = Object.assign(Object.assign({}, DOCUMENT_QUERY_BASE_ARGS_SHAPE), { custom_field_query: zod_1.z.string().min(1).optional() });
88
+ exports.QUERY_DOCUMENTS_ARGS_SHAPE = Object.assign(Object.assign({}, DOCUMENT_QUERY_BASE_ARGS_SHAPE), { query: zod_1.z.string().optional(), more_like_id: zod_1.z.number().optional(), custom_field_query: exports.customFieldQuerySchema
89
+ .optional()
90
+ .describe("Paperless custom field query. Use [field_name_or_id, operator, value] for a single clause or ['AND'|'OR', [clause1, clause2]] for grouped clauses."), paperless_filters: exports.paperlessFiltersSchema
91
+ .optional()
92
+ .describe("Additional documented /api/documents/ Paperless filters. Keys must match Paperless query parameter names exactly. Prefer first-class arguments when available.") });
93
+ exports.SEARCH_DOCUMENTS_ARGS_SHAPE = {
94
+ query: zod_1.z.string(),
95
+ };
96
+ const FIRST_CLASS_QUERY_PARAM_MAP = {
97
+ page: "page",
98
+ page_size: "page_size",
99
+ ordering: "ordering",
100
+ query: "query",
101
+ search: "search",
102
+ more_like_id: "more_like_id",
103
+ correspondent: "correspondent__id",
104
+ document_type: "document_type__id",
105
+ tag: "tags__id",
106
+ storage_path: "storage_path__id",
107
+ created__date__gte: "created__date__gte",
108
+ created__date__lte: "created__date__lte",
109
+ archive_serial_number: "archive_serial_number",
110
+ archive_serial_number__isnull: "archive_serial_number__isnull",
111
+ custom_fields__icontains: "custom_fields__icontains",
112
+ };
113
+ // Derived from the documented /api/documents/ query parameters in Paperless_ngx_REST_API.yaml.
114
+ exports.DOCUMENT_QUERY_PAPERLESS_FILTER_KEYS = [
115
+ "added__date__gt",
116
+ "added__date__gte",
117
+ "added__date__lt",
118
+ "added__date__lte",
119
+ "added__day",
120
+ "added__gt",
121
+ "added__gte",
122
+ "added__lt",
123
+ "added__lte",
124
+ "added__month",
125
+ "added__year",
126
+ "archive_serial_number",
127
+ "archive_serial_number__gt",
128
+ "archive_serial_number__gte",
129
+ "archive_serial_number__isnull",
130
+ "archive_serial_number__lt",
131
+ "archive_serial_number__lte",
132
+ "checksum__icontains",
133
+ "checksum__iendswith",
134
+ "checksum__iexact",
135
+ "checksum__istartswith",
136
+ "content__icontains",
137
+ "content__iendswith",
138
+ "content__iexact",
139
+ "content__istartswith",
140
+ "correspondent__id",
141
+ "correspondent__id__in",
142
+ "correspondent__id__none",
143
+ "correspondent__isnull",
144
+ "correspondent__name__icontains",
145
+ "correspondent__name__iendswith",
146
+ "correspondent__name__iexact",
147
+ "correspondent__name__istartswith",
148
+ "created__date__gt",
149
+ "created__date__gte",
150
+ "created__date__lt",
151
+ "created__date__lte",
152
+ "created__day",
153
+ "created__gt",
154
+ "created__gte",
155
+ "created__lt",
156
+ "created__lte",
157
+ "created__month",
158
+ "created__year",
159
+ "custom_field_query",
160
+ "custom_fields__icontains",
161
+ "custom_fields__id__all",
162
+ "custom_fields__id__in",
163
+ "custom_fields__id__none",
164
+ "document_type__id",
165
+ "document_type__id__in",
166
+ "document_type__id__none",
167
+ "document_type__isnull",
168
+ "document_type__name__icontains",
169
+ "document_type__name__iendswith",
170
+ "document_type__name__iexact",
171
+ "document_type__name__istartswith",
172
+ "fields",
173
+ "full_perms",
174
+ "has_custom_fields",
175
+ "id",
176
+ "id__in",
177
+ "is_in_inbox",
178
+ "is_tagged",
179
+ "mime_type",
180
+ "modified__date__gt",
181
+ "modified__date__gte",
182
+ "modified__date__lt",
183
+ "modified__date__lte",
184
+ "modified__day",
185
+ "modified__gt",
186
+ "modified__gte",
187
+ "modified__lt",
188
+ "modified__lte",
189
+ "modified__month",
190
+ "modified__year",
191
+ "ordering",
192
+ "original_filename__icontains",
193
+ "original_filename__iendswith",
194
+ "original_filename__iexact",
195
+ "original_filename__istartswith",
196
+ "owner__id",
197
+ "owner__id__in",
198
+ "owner__id__none",
199
+ "owner__isnull",
200
+ "page",
201
+ "page_size",
202
+ "query",
203
+ "search",
204
+ "shared_by__id",
205
+ "storage_path__id",
206
+ "storage_path__id__in",
207
+ "storage_path__id__none",
208
+ "storage_path__isnull",
209
+ "storage_path__name__icontains",
210
+ "storage_path__name__iendswith",
211
+ "storage_path__name__iexact",
212
+ "storage_path__name__istartswith",
213
+ "tags__id",
214
+ "tags__id__all",
215
+ "tags__id__in",
216
+ "tags__id__none",
217
+ "tags__name__icontains",
218
+ "tags__name__iendswith",
219
+ "tags__name__iexact",
220
+ "tags__name__istartswith",
221
+ "title__icontains",
222
+ "title__iendswith",
223
+ "title__iexact",
224
+ "title__istartswith",
225
+ "title_content",
226
+ ];
227
+ const DOCUMENT_QUERY_PAPERLESS_FILTER_KEY_SET = new Set(exports.DOCUMENT_QUERY_PAPERLESS_FILTER_KEYS);
228
+ function hasValue(value) {
229
+ return value !== undefined && value !== null;
230
+ }
231
+ function setQueryParam(query, key, value, jsonEncode = false) {
232
+ if (jsonEncode) {
233
+ query.set(key, JSON.stringify(value));
234
+ return;
235
+ }
236
+ if (Array.isArray(value)) {
237
+ query.set(key, value.map((item) => String(item)).join(","));
238
+ return;
239
+ }
240
+ query.set(key, String(value));
241
+ }
242
+ function buildDocumentQueryString(args) {
243
+ const query = new URLSearchParams();
244
+ const firstClassKeys = new Set();
245
+ for (const [argName, queryParamName] of Object.entries(FIRST_CLASS_QUERY_PARAM_MAP)) {
246
+ const value = args[argName];
247
+ if (!hasValue(value)) {
248
+ continue;
249
+ }
250
+ setQueryParam(query, queryParamName, value);
251
+ firstClassKeys.add(queryParamName);
252
+ }
253
+ if (hasValue(args.custom_field_query)) {
254
+ setQueryParam(query, "custom_field_query", args.custom_field_query, typeof args.custom_field_query !== "string");
255
+ firstClassKeys.add("custom_field_query");
256
+ }
257
+ if (!args.paperless_filters) {
258
+ return query.toString() ? `?${query.toString()}` : "";
259
+ }
260
+ for (const [key, value] of Object.entries(args.paperless_filters)) {
261
+ if (!DOCUMENT_QUERY_PAPERLESS_FILTER_KEY_SET.has(key)) {
262
+ throw new Error(`Unsupported paperless_filters key '${key}'. Use documented /api/documents/ query parameter names only.`);
263
+ }
264
+ if (firstClassKeys.has(key)) {
265
+ throw new Error(`Duplicate filter '${key}' provided both as a first-class argument and in paperless_filters.`);
266
+ }
267
+ setQueryParam(query, key, value);
268
+ }
269
+ return query.toString() ? `?${query.toString()}` : "";
270
+ }
@@ -0,0 +1,2 @@
1
+ export declare const arrayNotEmpty: <T>(array: T[] | undefined) => T[] | undefined;
2
+ export declare const objectNotEmpty: <T>(object: T) => T | undefined;
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.objectNotEmpty = exports.arrayNotEmpty = void 0;
4
+ const arrayNotEmpty = (array) => (array === null || array === void 0 ? void 0 : array.length) ? array : undefined;
5
+ exports.arrayNotEmpty = arrayNotEmpty;
6
+ const objectNotEmpty = (object) => object && Object.keys(object).length ? object : undefined;
7
+ exports.objectNotEmpty = objectNotEmpty;
@@ -0,0 +1,2 @@
1
+ import { z } from "zod";
2
+ export declare const matchingAlgorithmSchema: z.ZodPipe<z.ZodNumber, z.ZodTransform<0 | 1 | 2 | 3 | 4 | 5 | 6, number>>;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.matchingAlgorithmSchema = void 0;
4
+ const zod_1 = require("zod");
5
+ const types_1 = require("../../api/types");
6
+ // The 0-6 range the API declares is exactly the set `MatchingAlgorithm`
7
+ // enumerates, so narrowing to it after the check lets the PaperlessAPI request
8
+ // types take the parsed value without a cast at every call site.
9
+ exports.matchingAlgorithmSchema = zod_1.z
10
+ .number()
11
+ .int()
12
+ .min(0)
13
+ .max(6)
14
+ .transform((value) => value)
15
+ .describe(types_1.MATCHING_ALGORITHM_DESCRIPTION);
@@ -0,0 +1,3 @@
1
+ import { ToolCallback } from "@modelcontextprotocol/sdk/server/mcp";
2
+ import { ZodRawShape } from "zod";
3
+ export declare const withErrorHandling: <Args extends ZodRawShape>(cb: ToolCallback<Args>) => ToolCallback<Args>;
@@ -0,0 +1,31 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.withErrorHandling = void 0;
13
+ const withErrorHandling = (cb) => {
14
+ return ((args, extra) => __awaiter(void 0, void 0, void 0, function* () {
15
+ var _a, _b;
16
+ try {
17
+ return yield cb(args, extra);
18
+ }
19
+ catch (err) {
20
+ const errorMessage = err instanceof Error ? err.message : String(err);
21
+ const responseData = (_a = err === null || err === void 0 ? void 0 : err.response) === null || _a === void 0 ? void 0 : _a.data;
22
+ const status = (_b = err === null || err === void 0 ? void 0 : err.response) === null || _b === void 0 ? void 0 : _b.status;
23
+ throw new Error(JSON.stringify({
24
+ error: errorMessage,
25
+ responseData,
26
+ status,
27
+ }));
28
+ }
29
+ }));
30
+ };
31
+ exports.withErrorHandling = withErrorHandling;
@@ -0,0 +1,5 @@
1
+ export declare function getMonetaryValidationError(value: string): string | null;
2
+ export declare function validateCustomFields(custom_fields: {
3
+ field: number;
4
+ value: unknown;
5
+ }[] | undefined): void;