suppa-mcp-2 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/utils.js ADDED
@@ -0,0 +1,391 @@
1
+ /**
2
+ * Shared utilities: filters, date parsing, HTML helpers.
3
+ *
4
+ * Faithful 1:1 port of the Python `suppa_mcp/utils.py`.
5
+ */
6
+ import { randomUUID } from "node:crypto";
7
+ import { statSync, readFileSync } from "node:fs";
8
+ import { extname, basename } from "node:path";
9
+ export function makeFilter(field, value, comparator = "=") {
10
+ return { field, value, comparator };
11
+ }
12
+ /**
13
+ * Parse human-friendly deadline strings into ISO datetime.
14
+ *
15
+ * Accepts: 'today', 'tomorrow', '+Nd'/'+Nh'/'+Nm' (relative), '+Nw' (weeks),
16
+ * or an ISO-8601 datetime. Anything else throws with guidance — passing free
17
+ * text through to the platform would store a garbage deadline.
18
+ */
19
+ export function parseDeadline(s) {
20
+ const now = new Date(); // UTC-based via gettime()
21
+ const raw = s.trim();
22
+ const lower = raw.toLowerCase();
23
+ if (lower === "today") {
24
+ return endOfDayISO(now);
25
+ }
26
+ if (lower === "tomorrow") {
27
+ const d = new Date(now.getTime() + 24 * 60 * 60 * 1000);
28
+ return endOfDayISO(d);
29
+ }
30
+ const m = lower.match(/^\+(\d+)([wdhm])$/);
31
+ if (m) {
32
+ const n = parseInt(m[1], 10);
33
+ const unit = m[2];
34
+ const msPer = {
35
+ w: 7 * 24 * 60 * 60 * 1000,
36
+ d: 24 * 60 * 60 * 1000,
37
+ h: 60 * 60 * 1000,
38
+ m: 60 * 1000,
39
+ };
40
+ const d = new Date(now.getTime() + n * msPer[unit]);
41
+ d.setUTCMilliseconds(0); // microseconds zeroed (Python .replace(microsecond=0))
42
+ return utcOffsetISO(d);
43
+ }
44
+ // Otherwise it must be a valid ISO-8601 datetime (naive = UTC on the platform).
45
+ if (isValidISO(raw)) {
46
+ return raw;
47
+ }
48
+ throw new Error(`Unrecognized deadline '${raw}'. Use 'today', 'tomorrow', '+3d', '+2h', ` +
49
+ "'+30m', '+1w', or an ISO datetime like '2026-06-15T17:00:00+03:00' " +
50
+ "(naive datetimes are treated as UTC).");
51
+ }
52
+ /** Today (of the given UTC date) at 23:59:59, microseconds zeroed, ISO with +00:00 offset. */
53
+ function endOfDayISO(d) {
54
+ const y = d.getUTCFullYear();
55
+ const mo = pad2(d.getUTCMonth() + 1);
56
+ const day = pad2(d.getUTCDate());
57
+ return `${y}-${mo}-${day}T23:59:59+00:00`;
58
+ }
59
+ /** Format a Date as ISO-8601 with an explicit +00:00 offset (matching Python's aware datetime). */
60
+ function utcOffsetISO(d) {
61
+ const y = d.getUTCFullYear();
62
+ const mo = pad2(d.getUTCMonth() + 1);
63
+ const day = pad2(d.getUTCDate());
64
+ const h = pad2(d.getUTCHours());
65
+ const mi = pad2(d.getUTCMinutes());
66
+ const s = pad2(d.getUTCSeconds());
67
+ return `${y}-${mo}-${day}T${h}:${mi}:${s}+00:00`;
68
+ }
69
+ function pad2(n) {
70
+ return n < 10 ? "0" + n : String(n);
71
+ }
72
+ /**
73
+ * Validate that `raw` parses as ISO-8601, mirroring Python's
74
+ * `datetime.fromisoformat(raw.replace("Z", "+00:00"))`.
75
+ */
76
+ function isValidISO(raw) {
77
+ const candidate = raw.replace(/Z/g, "+00:00");
78
+ // Require a date portion: YYYY-MM-DD, optionally followed by time / offset.
79
+ // datetime.fromisoformat is strict about the shape.
80
+ const isoRe = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?([+-]\d{2}:\d{2})?)?$/;
81
+ if (!isoRe.test(candidate)) {
82
+ return false;
83
+ }
84
+ const t = Date.parse(candidate);
85
+ return !Number.isNaN(t);
86
+ }
87
+ /**
88
+ * Parse a JSON tool parameter, raising an instructive Error.
89
+ *
90
+ * MCP tools usually receive structured payloads as JSON *strings*, but some
91
+ * clients deliver an already-parsed object/array. Accept both.
92
+ */
93
+ export function parseJsonParam(raw, param, expect = "any") {
94
+ let value;
95
+ if (typeof raw !== "string") {
96
+ value = raw; // already parsed by the client (object/array/...)
97
+ }
98
+ else {
99
+ try {
100
+ value = JSON.parse(raw);
101
+ }
102
+ catch (e) {
103
+ const detail = e instanceof Error ? e.message : String(e);
104
+ throw new Error(`Parameter '${param}' is not valid JSON (${detail}). ` +
105
+ `Pass a JSON-encoded string, e.g. '{"field": "value"}' — ` +
106
+ "check for unescaped quotes or trailing commas.");
107
+ }
108
+ }
109
+ if (!matchesExpectation(value, expect)) {
110
+ const names = expect === "object"
111
+ ? "dict"
112
+ : expect === "array"
113
+ ? "list"
114
+ : "dict or list";
115
+ throw new Error(`Parameter '${param}' must be a JSON ${names}, got ${typeName(value)}.`);
116
+ }
117
+ return value;
118
+ }
119
+ function matchesExpectation(value, expect) {
120
+ const isArray = Array.isArray(value);
121
+ const isPlainObject = typeof value === "object" && value !== null && !isArray;
122
+ if (expect === "object") {
123
+ return isPlainObject;
124
+ }
125
+ if (expect === "array") {
126
+ return isArray;
127
+ }
128
+ // "any" -> object or array (Python default expect=(dict, list))
129
+ return isArray || isPlainObject;
130
+ }
131
+ /** Python-ish type name for error messages. */
132
+ function typeName(value) {
133
+ if (value === null) {
134
+ return "NoneType";
135
+ }
136
+ if (Array.isArray(value)) {
137
+ return "list";
138
+ }
139
+ switch (typeof value) {
140
+ case "object":
141
+ return "dict";
142
+ case "string":
143
+ return "str";
144
+ case "number":
145
+ return Number.isInteger(value) ? "int" : "float";
146
+ case "boolean":
147
+ return "bool";
148
+ default:
149
+ return typeof value;
150
+ }
151
+ }
152
+ // Runs of one or more consecutive \uXXXX / \UXXXXXXXX escape literals.
153
+ const UNICODE_ESCAPE_RUN = /(?:\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8})+/g;
154
+ /** Decode one run of \uXXXX/\UXXXXXXXX literals, recombining surrogate pairs. */
155
+ function decodeEscapeRun(run) {
156
+ const codes = [];
157
+ const codeRe = /\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{8})/g;
158
+ let match;
159
+ while ((match = codeRe.exec(run)) !== null) {
160
+ codes.push(parseInt(match[1] || match[2], 16));
161
+ }
162
+ const out = [];
163
+ let i = 0;
164
+ while (i < codes.length) {
165
+ const c = codes[i];
166
+ if (c >= 0xd800 && c <= 0xdbff) {
167
+ // high surrogate — expect a low surrogate next
168
+ if (i + 1 < codes.length && codes[i + 1] >= 0xdc00 && codes[i + 1] <= 0xdfff) {
169
+ out.push(String.fromCodePoint(0x10000 + ((c - 0xd800) << 10) + (codes[i + 1] - 0xdc00)));
170
+ i += 2;
171
+ continue;
172
+ }
173
+ return run; // lone high surrogate — leave the run untouched
174
+ }
175
+ if (c >= 0xdc00 && c <= 0xdfff) {
176
+ return run; // lone low surrogate — not decodable
177
+ }
178
+ if (c > 0x10ffff) {
179
+ return run; // outside the Unicode range
180
+ }
181
+ out.push(String.fromCodePoint(c));
182
+ i += 1;
183
+ }
184
+ return out.join("");
185
+ }
186
+ /**
187
+ * Heal literal `\uXXXX` escape runs back into real characters, recombining
188
+ * UTF-16 surrogate pairs. Every other byte is left intact.
189
+ */
190
+ export function unescapeUnicode(text) {
191
+ if (!text || (!text.includes("\\u") && !text.includes("\\U"))) {
192
+ return text;
193
+ }
194
+ return text.replace(UNICODE_ESCAPE_RUN, (run) => decodeEscapeRun(run));
195
+ }
196
+ /** Wrap plain text in <p> if not already HTML (healing \uXXXX escapes first). */
197
+ export function wrapHtml(text, heal = true) {
198
+ if (heal) {
199
+ text = unescapeUnicode(text);
200
+ }
201
+ if (text.trim().startsWith("<")) {
202
+ return text;
203
+ }
204
+ return `<p>${text}</p>`;
205
+ }
206
+ /** Remove HTML tags for plain-text output. */
207
+ export function stripHtml(html) {
208
+ return (html || "").replace(/<[^>]+>/g, "");
209
+ }
210
+ /**
211
+ * Convert data to a compact JSON string for MCP tool response.
212
+ *
213
+ * Compact on purpose; non-ASCII stays literal. Mirrors Python's
214
+ * `json.dumps(data, ensure_ascii=False, separators=(",", ":"), default=str)`
215
+ * — the `default=str` fallback stringifies values the serializer can't handle.
216
+ */
217
+ export function jsonResponse(data) {
218
+ return JSON.stringify(data, (_key, value) => {
219
+ if (typeof value === "bigint" || typeof value === "function") {
220
+ return String(value);
221
+ }
222
+ return value;
223
+ });
224
+ }
225
+ /**
226
+ * Serialize a value the way Python's `json.dumps(value, ensure_ascii=False)`
227
+ * does with its DEFAULT separators: `, ` between items and `: ` between a key
228
+ * and its value (a space after each). Non-ASCII stays literal.
229
+ *
230
+ * Only used for the multipart `meta` part in `buildFileUpload`, where the
231
+ * platform expects exactly Python's spacing. `jsonResponse` stays compact.
232
+ */
233
+ function pyJsonDumps(value) {
234
+ if (value === null || value === undefined) {
235
+ return "null";
236
+ }
237
+ if (typeof value === "string") {
238
+ return JSON.stringify(value);
239
+ }
240
+ if (typeof value === "number" || typeof value === "boolean") {
241
+ return JSON.stringify(value);
242
+ }
243
+ if (Array.isArray(value)) {
244
+ return "[" + value.map((v) => pyJsonDumps(v)).join(", ") + "]";
245
+ }
246
+ if (typeof value === "object") {
247
+ const entries = Object.entries(value).filter(([, v]) => v !== undefined);
248
+ return ("{" +
249
+ entries.map(([k, v]) => `${JSON.stringify(k)}: ${pyJsonDumps(v)}`).join(", ") +
250
+ "}");
251
+ }
252
+ return JSON.stringify(String(value));
253
+ }
254
+ /**
255
+ * Build a header-injection-safe `filename=` / `filename*=` clause.
256
+ *
257
+ * CR/LF are stripped; the double-quote/backslash that delimit the quoted value
258
+ * are escaped. Non-ASCII bytes are kept verbatim in `filename=`; a best-effort
259
+ * RFC 5987 `filename*` is appended when the name has any char code > 127.
260
+ */
261
+ function contentDispositionFilename(filename) {
262
+ const name = filename.replace(/\r/g, "").replace(/\n/g, "");
263
+ const quoted = name.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
264
+ let disposition = `filename="${quoted}"`;
265
+ let hasNonAscii = false;
266
+ for (const ch of name) {
267
+ if (ch.codePointAt(0) > 127) {
268
+ hasNonAscii = true;
269
+ break;
270
+ }
271
+ }
272
+ if (hasNonAscii) {
273
+ disposition += `; filename*=UTF-8''${encodeURIComponent(name)}`;
274
+ }
275
+ return disposition;
276
+ }
277
+ // Hard ceiling on an upload's size (memory-DoS guard). 100 MiB.
278
+ export const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;
279
+ // Minimal extension -> mime map, mirroring the common cases mimetypes.guess_type covers.
280
+ const MIME_TYPES = {
281
+ ".txt": "text/plain",
282
+ ".html": "text/html",
283
+ ".htm": "text/html",
284
+ ".css": "text/css",
285
+ ".csv": "text/csv",
286
+ ".xml": "text/xml",
287
+ ".js": "text/javascript",
288
+ ".json": "application/json",
289
+ ".pdf": "application/pdf",
290
+ ".zip": "application/zip",
291
+ ".gz": "application/gzip",
292
+ ".tar": "application/x-tar",
293
+ ".doc": "application/msword",
294
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
295
+ ".xls": "application/vnd.ms-excel",
296
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
297
+ ".ppt": "application/vnd.ms-powerpoint",
298
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
299
+ ".png": "image/png",
300
+ ".jpg": "image/jpeg",
301
+ ".jpeg": "image/jpeg",
302
+ ".gif": "image/gif",
303
+ ".bmp": "image/bmp",
304
+ ".webp": "image/webp",
305
+ ".svg": "image/svg+xml",
306
+ ".ico": "image/vnd.microsoft.icon",
307
+ ".tif": "image/tiff",
308
+ ".tiff": "image/tiff",
309
+ ".mp3": "audio/mpeg",
310
+ ".wav": "audio/x-wav",
311
+ ".mp4": "video/mp4",
312
+ ".mpeg": "video/mpeg",
313
+ ".avi": "video/x-msvideo",
314
+ ".mov": "video/quicktime",
315
+ };
316
+ function guessMime(filename) {
317
+ const ext = extname(filename).toLowerCase();
318
+ return MIME_TYPES[ext] || "application/octet-stream";
319
+ }
320
+ /**
321
+ * Build a `multipart/form-data` body for `/api/core/files/upload`.
322
+ *
323
+ * Returns `{body, contentType}`. Throws if `file_path` is not a regular file,
324
+ * or if it exceeds `MAX_UPLOAD_BYTES`.
325
+ */
326
+ export function buildFileUpload(meta, filePath) {
327
+ let st;
328
+ try {
329
+ st = statSync(filePath);
330
+ }
331
+ catch {
332
+ throw new Error(filePath);
333
+ }
334
+ if (!st.isFile()) {
335
+ throw new Error(filePath);
336
+ }
337
+ const size = st.size;
338
+ if (size > MAX_UPLOAD_BYTES) {
339
+ throw new Error(`File is ${size} bytes; the upload limit is ${MAX_UPLOAD_BYTES} bytes ` +
340
+ `(${Math.floor(MAX_UPLOAD_BYTES / (1024 * 1024))} MiB).`);
341
+ }
342
+ const filename = basename(filePath);
343
+ const fileData = readFileSync(filePath);
344
+ const ctype = guessMime(filename);
345
+ const boundary = "----SuppaBoundary" + randomUUID().replace(/-/g, "");
346
+ const disposition = contentDispositionFilename(filename);
347
+ const CRLF = Buffer.from("\r\n");
348
+ const parts = [
349
+ Buffer.from(`--${boundary}`),
350
+ // NOTE: the meta part is intentionally a plain form field with NO
351
+ // Content-Type header (see Python source — adding one triggers a platform 500).
352
+ Buffer.from('Content-Disposition: form-data; name="meta"'),
353
+ Buffer.from(""),
354
+ Buffer.from(pyJsonDumps(meta), "utf-8"),
355
+ Buffer.from(`--${boundary}`),
356
+ Buffer.from(`Content-Disposition: form-data; name="files"; ${disposition}`, "utf-8"),
357
+ Buffer.from(`Content-Type: ${ctype}`),
358
+ Buffer.from(""),
359
+ fileData,
360
+ Buffer.from(`--${boundary}--`),
361
+ Buffer.from(""),
362
+ ];
363
+ const joined = [];
364
+ parts.forEach((p, idx) => {
365
+ if (idx > 0) {
366
+ joined.push(CRLF);
367
+ }
368
+ joined.push(p);
369
+ });
370
+ const body = Buffer.concat(joined);
371
+ return { body, contentType: `multipart/form-data; boundary=${boundary}` };
372
+ }
373
+ /**
374
+ * Approval-gate response returned by a mutating tool called without confirm=true.
375
+ * The operation is NOT performed.
376
+ */
377
+ export function confirmRequired(action, target, proposedChanges) {
378
+ const body = {
379
+ status: "confirmation_required",
380
+ action,
381
+ target,
382
+ message: `⚠️ APPROVAL REQUIRED before this ${action} — it was NOT performed. ` +
383
+ "Do not proceed on your own: show the target to the user (read the record " +
384
+ "first if it may be important), get explicit approval, then re-call this tool " +
385
+ "with confirm=true.",
386
+ };
387
+ if (proposedChanges !== undefined) {
388
+ body.proposed_changes = proposedChanges;
389
+ }
390
+ return jsonResponse(body);
391
+ }
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "suppa-mcp-2",
3
+ "version": "1.0.0",
4
+ "description": "MCP server for the Suppa platform (modern.suppa.me) — Tasks, Docs/Pages, Entities & Schema, Forms, Automations, and file attachments, with multi-tenant Google auth. Node port of PyPI suppa-mcp.",
5
+ "type": "module",
6
+ "bin": { "suppa-mcp": "dist/bin.js" },
7
+ "files": ["dist"],
8
+ "engines": { "node": ">=18" },
9
+ "scripts": {
10
+ "build": "tsc",
11
+ "test": "vitest run",
12
+ "prepublishOnly": "npm run build && npm test"
13
+ },
14
+ "keywords": ["mcp", "model-context-protocol", "suppa", "claude", "ai-tools"],
15
+ "license": "MIT",
16
+ "dependencies": {
17
+ "@modelcontextprotocol/sdk": "^1.18.0",
18
+ "@napi-rs/keyring": "^1.1.0",
19
+ "zod": "^3.23.8"
20
+ },
21
+ "devDependencies": {
22
+ "@types/node": "^20.0.0",
23
+ "typescript": "^5.6.0",
24
+ "vitest": "^2.1.0"
25
+ }
26
+ }