@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,80 @@
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 documentEnhancer_1 = require("./documentEnhancer");
18
+ const paperlessApi_1 = require("../test/mocks/paperlessApi");
19
+ const LARGE_DOCUMENT_COUNT = 709;
20
+ const MAX_RESPONSE_SIZE_BYTES = 2000;
21
+ function getTextContent(result) {
22
+ var _a;
23
+ const item = (_a = result.content) === null || _a === void 0 ? void 0 : _a[0];
24
+ if (!item || item.type !== "text") {
25
+ throw new Error("Expected text content");
26
+ }
27
+ return item.text;
28
+ }
29
+ (0, node_test_1.test)("convertDocsWithNames omits `all` and keeps paginated JSON shape", () => __awaiter(void 0, void 0, void 0, function* () {
30
+ const docsResponse = {
31
+ count: 2,
32
+ next: null,
33
+ previous: null,
34
+ all: [1, 2],
35
+ results: [(0, paperlessApi_1.createDocument)(), (0, paperlessApi_1.createDocument)({ id: 2, title: "Document 2" })],
36
+ };
37
+ const result = yield (0, documentEnhancer_1.convertDocsWithNames)(docsResponse, (0, paperlessApi_1.createPaperlessApiMock)());
38
+ const parsed = JSON.parse(getTextContent(result));
39
+ strict_1.default.ok(!("all" in parsed));
40
+ strict_1.default.deepEqual(parsed.results.map((doc) => doc.id), [1, 2]);
41
+ strict_1.default.ok(!("content" in parsed.results[0]));
42
+ }));
43
+ (0, node_test_1.test)("convertDocsWithNames keeps responses small when source has large `all` arrays", () => __awaiter(void 0, void 0, void 0, function* () {
44
+ const docsResponse = {
45
+ count: LARGE_DOCUMENT_COUNT,
46
+ next: "http://localhost:8000/api/documents/?page=2",
47
+ previous: null,
48
+ all: Array.from({ length: LARGE_DOCUMENT_COUNT }, (_, index) => index + 1),
49
+ results: [
50
+ (0, paperlessApi_1.createDocument)({
51
+ id: 123,
52
+ title: "Large all payload case",
53
+ content: "x".repeat(2700),
54
+ }),
55
+ ],
56
+ };
57
+ const result = yield (0, documentEnhancer_1.convertDocsWithNames)(docsResponse, (0, paperlessApi_1.createPaperlessApiMock)());
58
+ const responseText = getTextContent(result);
59
+ strict_1.default.ok(responseText.length < MAX_RESPONSE_SIZE_BYTES);
60
+ const parsed = JSON.parse(responseText);
61
+ strict_1.default.ok(!("all" in parsed));
62
+ strict_1.default.ok(!("content" in parsed.results[0]));
63
+ }));
64
+ (0, node_test_1.test)("convertDocsWithNames returns paginated JSON for empty multi-document results", () => __awaiter(void 0, void 0, void 0, function* () {
65
+ const docsResponse = {
66
+ count: 0,
67
+ next: null,
68
+ previous: null,
69
+ all: [],
70
+ results: [],
71
+ };
72
+ const result = yield (0, documentEnhancer_1.convertDocsWithNames)(docsResponse, (0, paperlessApi_1.createPaperlessApiMock)());
73
+ const parsed = JSON.parse(getTextContent(result));
74
+ strict_1.default.deepEqual(parsed, {
75
+ count: 0,
76
+ next: null,
77
+ previous: null,
78
+ results: [],
79
+ });
80
+ }));
@@ -0,0 +1,203 @@
1
+ export declare const MATCHING_ALGORITHM_OPTIONS: {
2
+ readonly 0: "None";
3
+ readonly 1: "Any word";
4
+ readonly 2: "All words";
5
+ readonly 3: "Exact match";
6
+ readonly 4: "Regular expression";
7
+ readonly 5: "Fuzzy word";
8
+ readonly 6: "Automatic";
9
+ };
10
+ export type MatchingAlgorithm = keyof typeof MATCHING_ALGORITHM_OPTIONS;
11
+ export declare const MATCHING_ALGORITHM_DESCRIPTION: string;
12
+ export interface Tag {
13
+ id: number;
14
+ slug: string;
15
+ name: string;
16
+ color: string;
17
+ text_color: string;
18
+ match: string;
19
+ matching_algorithm: MatchingAlgorithm;
20
+ is_insensitive: boolean;
21
+ is_inbox_tag: boolean;
22
+ document_count: number;
23
+ owner: number | null;
24
+ user_can_change: boolean;
25
+ }
26
+ export interface CustomField {
27
+ id: number;
28
+ name: string;
29
+ data_type: string;
30
+ extra_data?: Record<string, unknown> | null;
31
+ document_count: number;
32
+ }
33
+ export type CustomFieldValue = string | number | boolean | number[] | null;
34
+ export interface CustomFieldInstance {
35
+ field: number;
36
+ value: CustomFieldValue;
37
+ }
38
+ export interface CustomFieldInstanceRequest {
39
+ field: number;
40
+ value: CustomFieldValue;
41
+ }
42
+ export interface PaginationResponse<T> {
43
+ count: number;
44
+ next: string | null;
45
+ previous: string | null;
46
+ all: number[];
47
+ results: T[];
48
+ }
49
+ export interface GetTagsResponse extends PaginationResponse<Tag> {
50
+ }
51
+ export interface GetCustomFieldsResponse extends PaginationResponse<CustomField> {
52
+ }
53
+ export interface BasicUser {
54
+ id: number;
55
+ username: string;
56
+ first_name?: string;
57
+ last_name?: string;
58
+ }
59
+ export interface Note {
60
+ id: number;
61
+ note: string;
62
+ created: string;
63
+ user: BasicUser;
64
+ }
65
+ export interface DocumentsResponse extends PaginationResponse<Document> {
66
+ }
67
+ export interface Document {
68
+ id: number;
69
+ correspondent: number | null;
70
+ document_type: number | null;
71
+ storage_path: number | null;
72
+ title: string;
73
+ content: string | null;
74
+ tags: number[];
75
+ created: string;
76
+ created_date: string;
77
+ modified: string;
78
+ added: string;
79
+ deleted_at: string | null;
80
+ archive_serial_number: number | null;
81
+ original_file_name: string;
82
+ archived_file_name: string;
83
+ owner: number | null;
84
+ user_can_change: boolean;
85
+ is_shared_by_requester: boolean;
86
+ notes: Note[];
87
+ custom_fields: CustomFieldInstance[];
88
+ page_count: number;
89
+ mime_type: string;
90
+ __search_hit__?: SearchHit;
91
+ }
92
+ export interface SearchHit {
93
+ score: number;
94
+ highlights: string;
95
+ note_highlights: string;
96
+ rank: number;
97
+ }
98
+ export interface Correspondent {
99
+ id: number;
100
+ slug: string;
101
+ name: string;
102
+ match: string;
103
+ matching_algorithm: MatchingAlgorithm;
104
+ is_insensitive: boolean;
105
+ document_count: number;
106
+ last_correspondence: string;
107
+ owner: number | null;
108
+ permissions: Record<string, unknown>;
109
+ user_can_change: boolean;
110
+ }
111
+ export interface GetCorrespondentsResponse extends PaginationResponse<Correspondent> {
112
+ }
113
+ export interface DocumentType {
114
+ id: number;
115
+ slug: string;
116
+ name: string;
117
+ match: string;
118
+ matching_algorithm: MatchingAlgorithm;
119
+ is_insensitive: boolean;
120
+ document_count: number;
121
+ last_correspondence: string;
122
+ owner: number | null;
123
+ permissions: Record<string, unknown>;
124
+ user_can_change: boolean;
125
+ }
126
+ export interface GetDocumentTypesResponse extends PaginationResponse<DocumentType> {
127
+ }
128
+ export interface MailAccount {
129
+ id: number;
130
+ name: string;
131
+ imap_server: string;
132
+ imap_port: number | null;
133
+ imap_security: number;
134
+ username: string;
135
+ password?: string;
136
+ character_set: string;
137
+ is_token: boolean;
138
+ owner: number | null;
139
+ user_can_change: boolean;
140
+ account_type: number;
141
+ expiration: string | null;
142
+ }
143
+ export interface GetMailAccountsResponse extends PaginationResponse<MailAccount> {
144
+ }
145
+ export interface MailRule {
146
+ id: number;
147
+ name: string;
148
+ account: number;
149
+ enabled: boolean;
150
+ folder: string;
151
+ filter_from: string | null;
152
+ filter_to: string | null;
153
+ filter_subject: string | null;
154
+ filter_body: string | null;
155
+ filter_attachment_filename_include: string | null;
156
+ filter_attachment_filename_exclude: string | null;
157
+ maximum_age: number;
158
+ action: number;
159
+ action_parameter: string | null;
160
+ assign_title_from: number;
161
+ assign_tags: Array<number | null>;
162
+ assign_correspondent_from: number;
163
+ assign_correspondent: number | null;
164
+ assign_document_type: number | null;
165
+ assign_owner_from_rule: boolean;
166
+ order: number;
167
+ attachment_type: number;
168
+ consumption_scope: number;
169
+ pdf_layout: number;
170
+ owner: number | null;
171
+ user_can_change: boolean;
172
+ }
173
+ export interface GetMailRulesResponse extends PaginationResponse<MailRule> {
174
+ }
175
+ export interface BulkEditDocumentsResult {
176
+ result: string;
177
+ }
178
+ export interface BulkEditParameters {
179
+ add_custom_fields?: Record<string, CustomFieldInstanceRequest["value"]>;
180
+ remove_custom_fields?: number[];
181
+ add_tags?: number[];
182
+ remove_tags?: number[];
183
+ degrees?: number;
184
+ pages?: string;
185
+ metadata_document_id?: number;
186
+ delete_originals?: boolean;
187
+ correspondent?: number;
188
+ document_type?: number;
189
+ storage_path?: number;
190
+ tag?: number;
191
+ set_permissions?: {
192
+ view?: {
193
+ users?: number[];
194
+ groups?: number[];
195
+ };
196
+ change?: {
197
+ users?: number[];
198
+ groups?: number[];
199
+ };
200
+ };
201
+ owner?: number | null;
202
+ merge?: boolean;
203
+ }
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MATCHING_ALGORITHM_DESCRIPTION = exports.MATCHING_ALGORITHM_OPTIONS = void 0;
4
+ exports.MATCHING_ALGORITHM_OPTIONS = {
5
+ 0: "None",
6
+ 1: "Any word",
7
+ 2: "All words",
8
+ 3: "Exact match",
9
+ 4: "Regular expression",
10
+ 5: "Fuzzy word",
11
+ 6: "Automatic",
12
+ };
13
+ exports.MATCHING_ALGORITHM_DESCRIPTION = `Matching algorithm: ${Object.entries(exports.MATCHING_ALGORITHM_OPTIONS)
14
+ .map(([id, name]) => `${id}=${name}`)
15
+ .join(", ")}`;
@@ -0,0 +1,16 @@
1
+ import { MatchingAlgorithm } from "./types";
2
+ export declare const headersToObject: (headers: any) => Record<string, string>;
3
+ export interface NamedItem {
4
+ id: number;
5
+ name: string;
6
+ }
7
+ export declare function enhanceMatchingAlgorithm<T extends {
8
+ matching_algorithm: MatchingAlgorithm;
9
+ }>(obj: T): T & {
10
+ matching_algorithm: NamedItem;
11
+ };
12
+ export declare function enhanceMatchingAlgorithmArray<T extends {
13
+ matching_algorithm: MatchingAlgorithm;
14
+ }>(objects: T[]): (T & {
15
+ matching_algorithm: NamedItem;
16
+ })[];
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.headersToObject = void 0;
4
+ exports.enhanceMatchingAlgorithm = enhanceMatchingAlgorithm;
5
+ exports.enhanceMatchingAlgorithmArray = enhanceMatchingAlgorithmArray;
6
+ const types_1 = require("./types");
7
+ const headersToObject = (headers) => {
8
+ if (!headers)
9
+ return {};
10
+ if (typeof headers.forEach === "function") {
11
+ const obj = {};
12
+ headers.forEach((value, key) => {
13
+ obj[key] = value;
14
+ });
15
+ return obj;
16
+ }
17
+ return headers;
18
+ };
19
+ exports.headersToObject = headersToObject;
20
+ function enhanceMatchingAlgorithm(obj) {
21
+ return Object.assign(Object.assign({}, obj), { matching_algorithm: {
22
+ id: obj.matching_algorithm,
23
+ name: types_1.MATCHING_ALGORITHM_OPTIONS[obj.matching_algorithm] ||
24
+ String(obj.matching_algorithm),
25
+ } });
26
+ }
27
+ function enhanceMatchingAlgorithmArray(objects) {
28
+ return objects.map((obj) => enhanceMatchingAlgorithm(obj));
29
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/build/index.js ADDED
@@ -0,0 +1,189 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
4
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5
+ return new (P || (P = Promise))(function (resolve, reject) {
6
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
7
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
8
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
9
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
10
+ });
11
+ };
12
+ var __importDefault = (this && this.__importDefault) || function (mod) {
13
+ return (mod && mod.__esModule) ? mod : { "default": mod };
14
+ };
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ const sse_js_1 = require("@modelcontextprotocol/sdk/server/sse.js");
17
+ const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
18
+ const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
19
+ const express_1 = __importDefault(require("express"));
20
+ const node_util_1 = require("node:util");
21
+ const server_1 = require("./server");
22
+ const { version } = require("../package.json");
23
+ const { values: { baseUrl, token, http: useHttp, port, publicUrl, "no-auth": noAuth }, } = (0, node_util_1.parseArgs)({
24
+ options: {
25
+ baseUrl: { type: "string" },
26
+ token: { type: "string" },
27
+ http: { type: "boolean", default: false },
28
+ port: { type: "string" },
29
+ publicUrl: { type: "string", default: "" },
30
+ "no-auth": { type: "boolean", default: false },
31
+ },
32
+ allowPositionals: true,
33
+ });
34
+ const resolvedBaseUrl = baseUrl || process.env.PAPERLESS_URL;
35
+ const resolvedToken = token || process.env.PAPERLESS_API_KEY;
36
+ const resolvedPublicUrl = publicUrl || process.env.PAPERLESS_PUBLIC_URL || resolvedBaseUrl;
37
+ const resolvedPort = port ? parseInt(port, 10) : 3000;
38
+ if (!resolvedBaseUrl) {
39
+ console.error("Usage: paperless-mcp --baseUrl <url> --token <token> [--http] [--port <port>] [--publicUrl <url>] [--no-auth]");
40
+ console.error("Or set PAPERLESS_URL and PAPERLESS_API_KEY environment variables.");
41
+ process.exit(1);
42
+ }
43
+ if (!useHttp && !resolvedToken) {
44
+ console.error("Usage: paperless-mcp --baseUrl <url> --token <token> [--http] [--port <port>] [--publicUrl <url>] [--no-auth]");
45
+ console.error("Or set PAPERLESS_URL and PAPERLESS_API_KEY environment variables.");
46
+ process.exit(1);
47
+ }
48
+ if (noAuth && !resolvedToken) {
49
+ console.error("--no-auth allows unauthenticated requests to use the server's Paperless token, " +
50
+ "but no server token is configured. Provide --token <token> or set PAPERLESS_API_KEY, " +
51
+ "or drop --no-auth and have clients authenticate with 'Authorization: Bearer <token>'.");
52
+ process.exit(1);
53
+ }
54
+ function buildServer(requestToken) {
55
+ return (0, server_1.createMcpServer)({
56
+ baseUrl: resolvedBaseUrl,
57
+ token: requestToken,
58
+ version,
59
+ publicUrl: resolvedPublicUrl,
60
+ });
61
+ }
62
+ function main() {
63
+ return __awaiter(this, void 0, void 0, function* () {
64
+ if (useHttp) {
65
+ if (noAuth) {
66
+ console.log("[paperless-mcp] --no-auth is enabled: requests without an 'Authorization: Bearer' header " +
67
+ "will use the server's Paperless token. Only use this on a trusted/local network.");
68
+ }
69
+ else if (resolvedToken) {
70
+ console.log("[paperless-mcp] A server token is configured, but unauthenticated requests are rejected. " +
71
+ "Clients must send 'Authorization: Bearer <paperless-token>'. " +
72
+ "To use the server token for unauthenticated requests instead, restart with the --no-auth flag " +
73
+ "(trusted/local networks only).");
74
+ }
75
+ const app = (0, express_1.default)();
76
+ app.use(express_1.default.json());
77
+ // Store transports for each session
78
+ const sseTransports = {};
79
+ app.post("/mcp", (req, res) => __awaiter(this, void 0, void 0, function* () {
80
+ const requestToken = (0, server_1.getBearerToken)(req, {
81
+ fallbackToken: resolvedToken,
82
+ allowAnonymous: noAuth,
83
+ });
84
+ if (!requestToken) {
85
+ (0, server_1.sendUnauthorized)(res);
86
+ return;
87
+ }
88
+ try {
89
+ const server = buildServer(requestToken);
90
+ const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({
91
+ sessionIdGenerator: undefined,
92
+ });
93
+ res.on("close", () => {
94
+ transport.close();
95
+ });
96
+ yield server.connect(transport);
97
+ yield transport.handleRequest(req, res, req.body);
98
+ }
99
+ catch (error) {
100
+ console.error("Error handling MCP request:", error);
101
+ if (!res.headersSent) {
102
+ res.status(500).json({
103
+ jsonrpc: "2.0",
104
+ error: {
105
+ code: -32603,
106
+ message: "Internal server error",
107
+ },
108
+ id: null,
109
+ });
110
+ }
111
+ }
112
+ }));
113
+ app.get("/mcp", (req, res) => __awaiter(this, void 0, void 0, function* () {
114
+ res.writeHead(405).end(JSON.stringify({
115
+ jsonrpc: "2.0",
116
+ error: {
117
+ code: -32000,
118
+ message: "Method not allowed.",
119
+ },
120
+ id: null,
121
+ }));
122
+ }));
123
+ app.delete("/mcp", (req, res) => __awaiter(this, void 0, void 0, function* () {
124
+ res.writeHead(405).end(JSON.stringify({
125
+ jsonrpc: "2.0",
126
+ error: {
127
+ code: -32000,
128
+ message: "Method not allowed.",
129
+ },
130
+ id: null,
131
+ }));
132
+ }));
133
+ app.get("/sse", (req, res) => __awaiter(this, void 0, void 0, function* () {
134
+ console.log("SSE request received");
135
+ const requestToken = (0, server_1.getBearerToken)(req, {
136
+ fallbackToken: resolvedToken,
137
+ allowAnonymous: noAuth,
138
+ });
139
+ if (!requestToken) {
140
+ (0, server_1.sendUnauthorized)(res);
141
+ return;
142
+ }
143
+ try {
144
+ const server = buildServer(requestToken);
145
+ const transport = new sse_js_1.SSEServerTransport("/messages", res);
146
+ sseTransports[transport.sessionId] = transport;
147
+ res.on("close", () => {
148
+ delete sseTransports[transport.sessionId];
149
+ transport.close();
150
+ });
151
+ yield server.connect(transport);
152
+ }
153
+ catch (error) {
154
+ console.error("Error handling SSE request:", error);
155
+ if (!res.headersSent) {
156
+ res.status(500).json({
157
+ jsonrpc: "2.0",
158
+ error: {
159
+ code: -32603,
160
+ message: "Internal server error",
161
+ },
162
+ id: null,
163
+ });
164
+ }
165
+ }
166
+ }));
167
+ app.post("/messages", (req, res) => __awaiter(this, void 0, void 0, function* () {
168
+ const sessionId = req.query.sessionId;
169
+ const transport = sseTransports[sessionId];
170
+ if (transport) {
171
+ yield transport.handlePostMessage(req, res, req.body);
172
+ }
173
+ else {
174
+ res.status(400).send("No transport found for sessionId");
175
+ }
176
+ }));
177
+ app.listen(resolvedPort, () => {
178
+ console.log(`MCP Stateless Streamable HTTP Server listening on port ${resolvedPort}`);
179
+ });
180
+ // await new Promise((resolve) => setTimeout(resolve, 1000000));
181
+ }
182
+ else {
183
+ const server = buildServer(resolvedToken);
184
+ const transport = new stdio_js_1.StdioServerTransport();
185
+ yield server.connect(transport);
186
+ }
187
+ });
188
+ }
189
+ main().catch((e) => console.error(e.message));
@@ -0,0 +1,7 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import type { ReadResourceResult } from "@modelcontextprotocol/sdk/types";
3
+ import { PaperlessAPI } from "../api/PaperlessAPI";
4
+ type TemplateVariables = Record<string, string | string[]>;
5
+ export declare function registerDocumentResources(server: McpServer, api: PaperlessAPI): void;
6
+ export declare function readDocumentResource(api: PaperlessAPI, uri: URL, variables: TemplateVariables): Promise<ReadResourceResult>;
7
+ export {};
@@ -0,0 +1,119 @@
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.registerDocumentResources = registerDocumentResources;
13
+ exports.readDocumentResource = readDocumentResource;
14
+ const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
15
+ function registerDocumentResources(server, api) {
16
+ server.resource("paperless-document-resource", new mcp_js_1.ResourceTemplate("paperless://documents/{id}/{resource}", {
17
+ list: undefined,
18
+ }), (uri, variables) => __awaiter(this, void 0, void 0, function* () { return readDocumentResource(api, uri, variables); }));
19
+ server.resource("paperless-document-original-download", new mcp_js_1.ResourceTemplate("paperless://documents/{id}/download{?original}", {
20
+ list: undefined,
21
+ }), (uri, variables) => __awaiter(this, void 0, void 0, function* () {
22
+ return readDocumentDownloadResource(api, uri, parseDocumentId(readVariable(variables, "id")), isTrueQueryValue(readVariable(variables, "original")));
23
+ }));
24
+ }
25
+ function readDocumentResource(api, uri, variables) {
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ assertPaperlessDocumentsUri(uri);
28
+ const id = parseDocumentId(readVariable(variables, "id"));
29
+ const resource = readVariable(variables, "resource").split("?")[0];
30
+ switch (resource) {
31
+ case "download":
32
+ return readDocumentDownloadResource(api, uri, id, isTrueQueryValue(uri.searchParams.get("original") || undefined));
33
+ case "thumbnail":
34
+ case "thumb":
35
+ return readDocumentThumbnailResource(api, uri, id);
36
+ default:
37
+ throw new Error(`Unsupported Paperless document resource: ${resource}`);
38
+ }
39
+ });
40
+ }
41
+ function readDocumentDownloadResource(api, uri, id, original) {
42
+ return __awaiter(this, void 0, void 0, function* () {
43
+ const response = yield api.downloadDocument(id, original);
44
+ return {
45
+ contents: [
46
+ responseToResourceContents(uri.href, response, "application/octet-stream"),
47
+ ],
48
+ };
49
+ });
50
+ }
51
+ function readDocumentThumbnailResource(api, uri, id) {
52
+ return __awaiter(this, void 0, void 0, function* () {
53
+ const response = yield api.getThumbnail(id);
54
+ return {
55
+ contents: [responseToResourceContents(uri.href, response, "image/webp")],
56
+ };
57
+ });
58
+ }
59
+ function responseToResourceContents(uri, response, fallbackMimeType) {
60
+ const mimeType = getHeader(response, "content-type") || fallbackMimeType;
61
+ const data = Buffer.from(response.data);
62
+ if (isTextMimeType(mimeType)) {
63
+ return {
64
+ uri,
65
+ mimeType,
66
+ text: data.toString("utf8"),
67
+ };
68
+ }
69
+ return {
70
+ uri,
71
+ mimeType,
72
+ blob: data.toString("base64"),
73
+ };
74
+ }
75
+ function assertPaperlessDocumentsUri(uri) {
76
+ if (uri.protocol !== "paperless:" || uri.hostname !== "documents") {
77
+ throw new Error(`Unsupported Paperless resource URI: ${uri.href}`);
78
+ }
79
+ }
80
+ function parseDocumentId(idValue) {
81
+ const id = Number(idValue);
82
+ if (!Number.isInteger(id) || id <= 0) {
83
+ throw new Error(`Invalid Paperless document id in resource URI: ${idValue}`);
84
+ }
85
+ return id;
86
+ }
87
+ function readVariable(variables, name) {
88
+ const value = variables[name];
89
+ const stringValue = Array.isArray(value) ? value[0] : value;
90
+ if (!stringValue) {
91
+ throw new Error(`Missing ${name} in Paperless resource URI`);
92
+ }
93
+ return stringValue;
94
+ }
95
+ function isTrueQueryValue(value) {
96
+ return value === "true" || value === "1";
97
+ }
98
+ function getHeader(response, headerName) {
99
+ const headers = response.headers;
100
+ if (typeof headers.get === "function") {
101
+ const value = headers.get(headerName);
102
+ if (typeof value === "string") {
103
+ return value;
104
+ }
105
+ }
106
+ const value = headers[headerName] || headers[headerName.toLowerCase()];
107
+ if (Array.isArray(value)) {
108
+ return String(value[0]);
109
+ }
110
+ return typeof value === "string" ? value : undefined;
111
+ }
112
+ function isTextMimeType(mimeType) {
113
+ const normalizedMimeType = mimeType.split(";")[0].trim().toLowerCase();
114
+ return (normalizedMimeType.startsWith("text/") ||
115
+ normalizedMimeType === "application/json" ||
116
+ normalizedMimeType === "application/xml" ||
117
+ normalizedMimeType.endsWith("+json") ||
118
+ normalizedMimeType.endsWith("+xml"));
119
+ }
@@ -0,0 +1 @@
1
+ export {};