@sketric/favstash-mcp 0.3.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.
@@ -0,0 +1,575 @@
1
+ import { createReadStream } from "node:fs";
2
+ import { createHash } from "node:crypto";
3
+ import { lstat, open } from "node:fs/promises";
4
+ import path from "node:path";
5
+
6
+ export const MAX_IMAGE_BYTES = 8 * 1024 * 1024;
7
+ export const MAX_THUMBNAIL_BYTES = 2 * 1024 * 1024;
8
+ export const MAX_VIDEO_BYTES = 200 * 1024 * 1024;
9
+ export const MAX_DOCUMENT_BYTES = 100 * 1024 * 1024;
10
+
11
+ const DEFAULT_UPLOAD_TIMEOUT_MS = 5 * 60 * 1000;
12
+ const MULTIPART_CONCURRENCY = 3;
13
+ const PUT_ATTEMPTS = 3;
14
+ const DURATION_SCAN_CHUNK_BYTES = 1024 * 1024;
15
+ const DURATION_SCAN_OVERLAP_BYTES = 256;
16
+
17
+ const FILE_TYPES = new Map([
18
+ [".jpg", { contentType: "image/jpeg", type: "image" }],
19
+ [".jpeg", { contentType: "image/jpeg", type: "image" }],
20
+ [".png", { contentType: "image/png", type: "image" }],
21
+ [".webp", { contentType: "image/webp", type: "image" }],
22
+ [".mp4", { contentType: "video/mp4", type: "video" }],
23
+ [".mov", { contentType: "video/quicktime", type: "video" }],
24
+ [".pdf", { contentType: "application/pdf", type: "document" }],
25
+ ]);
26
+
27
+ function mediaLabel(role) {
28
+ return role === "thumbnail" ? "thumbnail" : "media file";
29
+ }
30
+
31
+ function parseIsoBmffDurationSeconds(probe) {
32
+ const marker = Buffer.from("mvhd", "ascii");
33
+ let markerOffset = probe.indexOf(marker);
34
+ while (markerOffset >= 0) {
35
+ if (markerOffset < 4) {
36
+ markerOffset = probe.indexOf(marker, markerOffset + marker.length);
37
+ continue;
38
+ }
39
+ const boxStart = markerOffset - 4;
40
+ const compactSize = probe.readUInt32BE(boxStart);
41
+ let headerSize = 8;
42
+ let boxSize;
43
+ if (compactSize === 1) {
44
+ if (boxStart + 16 > probe.length) {
45
+ markerOffset = probe.indexOf(marker, markerOffset + marker.length);
46
+ continue;
47
+ }
48
+ const extendedSize = probe.readBigUInt64BE(boxStart + 8);
49
+ if (extendedSize > BigInt(Number.MAX_SAFE_INTEGER)) {
50
+ markerOffset = probe.indexOf(marker, markerOffset + marker.length);
51
+ continue;
52
+ }
53
+ headerSize = 16;
54
+ boxSize = Number(extendedSize);
55
+ } else if (compactSize === 0) {
56
+ boxSize = probe.length - boxStart;
57
+ } else {
58
+ boxSize = compactSize;
59
+ }
60
+
61
+ const payloadStart = boxStart + headerSize;
62
+ const boxEnd = boxStart + boxSize;
63
+ if (
64
+ boxSize < headerSize + 20 ||
65
+ boxEnd > probe.length ||
66
+ payloadStart + 4 > boxEnd
67
+ ) {
68
+ markerOffset = probe.indexOf(marker, markerOffset + marker.length);
69
+ continue;
70
+ }
71
+
72
+ const version = probe[payloadStart];
73
+ const timescaleOffset =
74
+ version === 0
75
+ ? payloadStart + 12
76
+ : version === 1
77
+ ? payloadStart + 20
78
+ : -1;
79
+ const durationOffset =
80
+ version === 0
81
+ ? payloadStart + 16
82
+ : version === 1
83
+ ? payloadStart + 24
84
+ : -1;
85
+ const durationBytes = version === 1 ? 8 : 4;
86
+ if (
87
+ timescaleOffset < 0 ||
88
+ durationOffset < 0 ||
89
+ durationOffset + durationBytes > boxEnd
90
+ ) {
91
+ markerOffset = probe.indexOf(marker, markerOffset + marker.length);
92
+ continue;
93
+ }
94
+
95
+ const timescale = probe.readUInt32BE(timescaleOffset);
96
+ const duration =
97
+ version === 1
98
+ ? probe.readBigUInt64BE(durationOffset)
99
+ : BigInt(probe.readUInt32BE(durationOffset));
100
+ if (timescale > 0 && duration > 0n) {
101
+ const seconds = Number(duration) / timescale;
102
+ if (Number.isFinite(seconds) && seconds > 0) {
103
+ return Math.round(seconds * 1_000) / 1_000;
104
+ }
105
+ }
106
+ markerOffset = probe.indexOf(marker, markerOffset + marker.length);
107
+ }
108
+ return undefined;
109
+ }
110
+
111
+ function matchesMagicBytes(contentType, head) {
112
+ if (contentType === "image/jpeg") {
113
+ return head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff;
114
+ }
115
+ if (contentType === "image/png") {
116
+ return (
117
+ head[0] === 0x89 &&
118
+ head[1] === 0x50 &&
119
+ head[2] === 0x4e &&
120
+ head[3] === 0x47
121
+ );
122
+ }
123
+ if (contentType === "image/webp") {
124
+ return (
125
+ head.subarray(0, 4).toString("ascii") === "RIFF" &&
126
+ head.subarray(8, 12).toString("ascii") === "WEBP"
127
+ );
128
+ }
129
+ if (contentType === "application/pdf") {
130
+ return head.subarray(0, 5).toString("ascii") === "%PDF-";
131
+ }
132
+ return head.subarray(4, 8).toString("ascii") === "ftyp";
133
+ }
134
+
135
+ async function scanVideoDuration(filePath, sizeBytes) {
136
+ const handle = await open(filePath, "r");
137
+ let offset = 0;
138
+ let overlap = Buffer.alloc(0);
139
+ try {
140
+ while (offset < sizeBytes) {
141
+ const length = Math.min(DURATION_SCAN_CHUNK_BYTES, sizeBytes - offset);
142
+ const chunk = Buffer.allocUnsafe(length);
143
+ const { bytesRead } = await handle.read(chunk, 0, length, offset);
144
+ if (!bytesRead) break;
145
+ const bytes = chunk.subarray(0, bytesRead);
146
+ const probe = overlap.length ? Buffer.concat([overlap, bytes]) : bytes;
147
+ const duration = parseIsoBmffDurationSeconds(probe);
148
+ if (duration) return duration;
149
+ overlap = Buffer.from(
150
+ probe.subarray(Math.max(0, probe.length - DURATION_SCAN_OVERLAP_BYTES)),
151
+ );
152
+ offset += bytesRead;
153
+ }
154
+ } finally {
155
+ await handle.close();
156
+ }
157
+ return undefined;
158
+ }
159
+
160
+ async function hashLocalFile(filePath) {
161
+ const hash = createHash("sha256");
162
+ for await (const chunk of createReadStream(filePath)) {
163
+ hash.update(chunk);
164
+ }
165
+ return hash.digest("hex");
166
+ }
167
+
168
+ export async function validateLocalMediaFile(filePath, role = "media") {
169
+ const label = mediaLabel(role);
170
+ if (!path.isAbsolute(filePath)) {
171
+ throw new Error(`Local ${label} path must be absolute: ${filePath}`);
172
+ }
173
+
174
+ let fileStats;
175
+ try {
176
+ fileStats = await lstat(filePath);
177
+ } catch (error) {
178
+ if (error?.code === "ENOENT") {
179
+ throw new Error(`Local ${label} was not found: ${filePath}`);
180
+ }
181
+ throw error;
182
+ }
183
+ if (fileStats.isSymbolicLink() || !fileStats.isFile()) {
184
+ throw new Error(`Local ${label} must be a regular file: ${filePath}`);
185
+ }
186
+ if (fileStats.size < 1) {
187
+ throw new Error(`Local ${label} is empty: ${filePath}`);
188
+ }
189
+
190
+ const extension = path.extname(filePath).toLowerCase();
191
+ const type = FILE_TYPES.get(extension);
192
+ if (!type) {
193
+ throw new Error(
194
+ `Unsupported local ${label} extension "${extension || "(none)"}". Use JPEG, PNG, WebP, MP4, MOV, or PDF.`,
195
+ );
196
+ }
197
+ if (
198
+ role === "thumbnail" &&
199
+ type.contentType !== "image/jpeg" &&
200
+ type.contentType !== "image/png"
201
+ ) {
202
+ throw new Error("Local thumbnails must be JPEG or PNG files.");
203
+ }
204
+
205
+ const maxBytes =
206
+ role === "thumbnail"
207
+ ? MAX_THUMBNAIL_BYTES
208
+ : type.type === "image"
209
+ ? MAX_IMAGE_BYTES
210
+ : type.type === "document"
211
+ ? MAX_DOCUMENT_BYTES
212
+ : MAX_VIDEO_BYTES;
213
+ if (fileStats.size > maxBytes) {
214
+ throw new Error(
215
+ `Local ${label} exceeds the ${Math.round(maxBytes / (1024 * 1024))}MB limit.`,
216
+ );
217
+ }
218
+
219
+ const handle = await open(filePath, "r");
220
+ const head = Buffer.alloc(16);
221
+ let bytesRead;
222
+ try {
223
+ ({ bytesRead } = await handle.read(head, 0, head.length, 0));
224
+ } finally {
225
+ await handle.close();
226
+ }
227
+ if (!matchesMagicBytes(type.contentType, head.subarray(0, bytesRead))) {
228
+ throw new Error(
229
+ `Local ${label} content does not match its ${extension} extension.`,
230
+ );
231
+ }
232
+
233
+ const durationSeconds =
234
+ type.type === "video"
235
+ ? await scanVideoDuration(filePath, fileStats.size)
236
+ : undefined;
237
+ const contentSha256 = await hashLocalFile(filePath);
238
+ return {
239
+ path: filePath,
240
+ sizeBytes: fileStats.size,
241
+ contentType: type.contentType,
242
+ contentSha256,
243
+ type: type.type,
244
+ ...(type.type === "document"
245
+ ? { title: path.basename(filePath).slice(0, 200) }
246
+ : {}),
247
+ ...(durationSeconds ? { durationSeconds } : {}),
248
+ };
249
+ }
250
+
251
+ export function deriveApiBaseUrl(mcpUrl, explicitApiUrl) {
252
+ if (explicitApiUrl) return explicitApiUrl.replace(/\/+$/, "");
253
+ const url = new URL(mcpUrl);
254
+ if (!/\/mcp\/?$/.test(url.pathname)) {
255
+ throw new Error(
256
+ "FAVSTASH_API_URL is required when FAVSTASH_MCP_URL does not end in /mcp.",
257
+ );
258
+ }
259
+ url.pathname = url.pathname.replace(/\/mcp\/?$/, "").replace(/\/+$/, "");
260
+ url.search = "";
261
+ url.hash = "";
262
+ return url.toString().replace(/\/+$/, "");
263
+ }
264
+
265
+ function responseMessage(payload, fallback) {
266
+ if (typeof payload?.message === "string") return payload.message;
267
+ if (typeof payload?.error === "string") return payload.error;
268
+ if (typeof payload?.error?.message === "string") return payload.error.message;
269
+ return fallback;
270
+ }
271
+
272
+ async function readJsonResponse(response, label) {
273
+ const text = await response.text();
274
+ let payload;
275
+ try {
276
+ payload = text ? JSON.parse(text) : null;
277
+ } catch {
278
+ throw new Error(
279
+ `${label} returned an invalid response (HTTP ${response.status}).`,
280
+ );
281
+ }
282
+ if (!response.ok) {
283
+ throw new Error(
284
+ responseMessage(payload, `${label} failed (HTTP ${response.status}).`),
285
+ );
286
+ }
287
+ return payload;
288
+ }
289
+
290
+ function uploadSignal(timeoutMs) {
291
+ return timeoutMs > 0 ? AbortSignal.timeout(timeoutMs) : undefined;
292
+ }
293
+
294
+ function retryableUploadStatus(status) {
295
+ return status === 408 || status === 429 || status >= 500;
296
+ }
297
+
298
+ async function uploadRange({
299
+ fetchImpl,
300
+ url,
301
+ file,
302
+ start,
303
+ end,
304
+ contentType,
305
+ allowAlreadyExists = false,
306
+ timeoutMs,
307
+ }) {
308
+ const sizeBytes = end - start;
309
+ let lastError;
310
+ for (let attempt = 1; attempt <= PUT_ATTEMPTS; attempt += 1) {
311
+ try {
312
+ const response = await fetchImpl(url, {
313
+ method: "PUT",
314
+ headers: {
315
+ "Content-Length": String(sizeBytes),
316
+ ...(contentType ? { "Content-Type": contentType } : {}),
317
+ ...(allowAlreadyExists ? { "If-None-Match": "*" } : {}),
318
+ },
319
+ body: createReadStream(file.path, { start, end: end - 1 }),
320
+ duplex: "half",
321
+ signal: uploadSignal(timeoutMs),
322
+ });
323
+ if (response.ok) return response.headers.get("etag");
324
+ if (allowAlreadyExists && response.status === 412) {
325
+ await response.body?.cancel().catch(() => undefined);
326
+ return undefined;
327
+ }
328
+ await response.body?.cancel().catch(() => undefined);
329
+ lastError = new Error(
330
+ `FavStash storage rejected the upload (HTTP ${response.status}).`,
331
+ );
332
+ lastError.retryable = retryableUploadStatus(response.status);
333
+ if (!lastError.retryable) throw lastError;
334
+ } catch (error) {
335
+ lastError = error;
336
+ if (error?.retryable === false) throw error;
337
+ if (attempt === PUT_ATTEMPTS) break;
338
+ }
339
+ await new Promise((resolve) => setTimeout(resolve, attempt * 150));
340
+ }
341
+ throw new Error(
342
+ `Could not upload local ${mediaLabel(file.role)} after ${PUT_ATTEMPTS} attempts: ${lastError?.message ?? "unknown storage error"}`,
343
+ );
344
+ }
345
+
346
+ async function runWithConcurrency(count, concurrency, worker) {
347
+ let next = 0;
348
+ async function run() {
349
+ while (next < count) {
350
+ const index = next;
351
+ next += 1;
352
+ await worker(index);
353
+ }
354
+ }
355
+ await Promise.all(
356
+ Array.from({ length: Math.min(count, concurrency) }, () => run()),
357
+ );
358
+ }
359
+
360
+ export function createLocalMediaUploadClient({
361
+ apiKey,
362
+ apiBaseUrl,
363
+ fetchImpl = fetch,
364
+ timeoutMs = DEFAULT_UPLOAD_TIMEOUT_MS,
365
+ }) {
366
+ if (!apiKey)
367
+ throw new Error("FavStash API credential is required for uploads.");
368
+ const baseUrl = apiBaseUrl.replace(/\/+$/, "");
369
+
370
+ async function postJson(route, body, label) {
371
+ const response = await fetchImpl(`${baseUrl}${route}`, {
372
+ method: "POST",
373
+ headers: {
374
+ Authorization: `Bearer ${apiKey}`,
375
+ "Content-Type": "application/json",
376
+ Accept: "application/json",
377
+ },
378
+ body: JSON.stringify(body),
379
+ signal: uploadSignal(timeoutMs),
380
+ });
381
+ return readJsonResponse(response, label);
382
+ }
383
+
384
+ async function uploadPreparedFile(file) {
385
+ const plan = await postJson(
386
+ "/social/media/presign",
387
+ {
388
+ contentType: file.contentType,
389
+ sizeBytes: file.sizeBytes,
390
+ contentSha256: file.contentSha256,
391
+ },
392
+ "FavStash upload planning",
393
+ );
394
+ if (!plan || typeof plan.key !== "string") {
395
+ throw new Error("FavStash returned an invalid media-upload plan.");
396
+ }
397
+
398
+ let completionInput;
399
+ if (plan.mode === "single" && typeof plan.url === "string") {
400
+ await uploadRange({
401
+ fetchImpl,
402
+ url: plan.url,
403
+ file,
404
+ start: 0,
405
+ end: file.sizeBytes,
406
+ contentType: file.contentType,
407
+ allowAlreadyExists: plan.immutable === true,
408
+ timeoutMs,
409
+ });
410
+ completionInput = { key: plan.key };
411
+ } else if (
412
+ plan.mode === "multipart" &&
413
+ typeof plan.uploadId === "string" &&
414
+ Number.isInteger(plan.partSize) &&
415
+ plan.partSize > 0 &&
416
+ Array.isArray(plan.urls)
417
+ ) {
418
+ const partCount = Math.ceil(file.sizeBytes / plan.partSize);
419
+ if (
420
+ plan.urls.length !== partCount ||
421
+ plan.urls.some((url) => typeof url !== "string")
422
+ ) {
423
+ throw new Error("FavStash returned an invalid multipart upload plan.");
424
+ }
425
+ const parts = new Array(partCount);
426
+ await runWithConcurrency(
427
+ partCount,
428
+ MULTIPART_CONCURRENCY,
429
+ async (index) => {
430
+ const start = index * plan.partSize;
431
+ const end = Math.min(file.sizeBytes, start + plan.partSize);
432
+ const etag = await uploadRange({
433
+ fetchImpl,
434
+ url: plan.urls[index],
435
+ file,
436
+ start,
437
+ end,
438
+ timeoutMs,
439
+ });
440
+ if (!etag) {
441
+ throw new Error(
442
+ `FavStash storage did not return an ETag for upload part ${index + 1}.`,
443
+ );
444
+ }
445
+ parts[index] = { ETag: etag, PartNumber: index + 1 };
446
+ },
447
+ );
448
+ completionInput = {
449
+ key: plan.key,
450
+ uploadId: plan.uploadId,
451
+ parts,
452
+ };
453
+ } else {
454
+ throw new Error("FavStash returned an unsupported media-upload plan.");
455
+ }
456
+
457
+ const completed = await postJson(
458
+ "/social/media/complete",
459
+ completionInput,
460
+ "FavStash upload completion",
461
+ );
462
+ if (!completed || typeof completed.cdnUrl !== "string") {
463
+ throw new Error(
464
+ "FavStash returned an invalid completed-upload response.",
465
+ );
466
+ }
467
+ return {
468
+ url: completed.cdnUrl,
469
+ type: completed.type ?? file.type,
470
+ ...((completed.type ?? file.type) === "document"
471
+ ? { title: completed.title ?? file.title ?? path.basename(file.path) }
472
+ : {}),
473
+ ...(file.durationSeconds
474
+ ? { durationSeconds: file.durationSeconds }
475
+ : {}),
476
+ ...(Number.isInteger(completed.width) ? { width: completed.width } : {}),
477
+ ...(Number.isInteger(completed.height)
478
+ ? { height: completed.height }
479
+ : {}),
480
+ };
481
+ }
482
+
483
+ return {
484
+ prepareFile: validateLocalMediaFile,
485
+ uploadPreparedFile,
486
+ async uploadFile(filePath, role = "media") {
487
+ const prepared = await validateLocalMediaFile(filePath, role);
488
+ return uploadPreparedFile({ ...prepared, role });
489
+ },
490
+ };
491
+ }
492
+
493
+ export async function normalizeLocalPostMedia(media, uploadClient) {
494
+ if (!media?.length) return media;
495
+ const prepared = [];
496
+ for (let index = 0; index < media.length; index += 1) {
497
+ const item = media[index];
498
+ if (item.localPath) {
499
+ prepared.push({
500
+ index,
501
+ field: "media",
502
+ file: {
503
+ ...(await uploadClient.prepareFile(item.localPath, "media")),
504
+ role: "media",
505
+ },
506
+ });
507
+ }
508
+ if (item.thumbnailPath) {
509
+ prepared.push({
510
+ index,
511
+ field: "thumbnail",
512
+ file: {
513
+ ...(await uploadClient.prepareFile(item.thumbnailPath, "thumbnail")),
514
+ role: "thumbnail",
515
+ },
516
+ });
517
+ }
518
+ }
519
+
520
+ const normalized = media.map((item) => {
521
+ const copy = { ...item };
522
+ delete copy.localPath;
523
+ delete copy.thumbnailPath;
524
+ return copy;
525
+ });
526
+ for (const entry of prepared) {
527
+ const uploaded = await uploadClient.uploadPreparedFile(entry.file);
528
+ if (entry.field === "thumbnail") {
529
+ normalized[entry.index].thumbnailUrl = uploaded.url;
530
+ continue;
531
+ }
532
+ normalized[entry.index].url = uploaded.url;
533
+ normalized[entry.index].kind = uploaded.type;
534
+ if (!normalized[entry.index].title && uploaded.title) {
535
+ normalized[entry.index].title = uploaded.title;
536
+ }
537
+ if (!normalized[entry.index].durationSeconds && uploaded.durationSeconds) {
538
+ normalized[entry.index].durationSeconds = uploaded.durationSeconds;
539
+ }
540
+ if (!normalized[entry.index].width && uploaded.width) {
541
+ normalized[entry.index].width = uploaded.width;
542
+ }
543
+ if (!normalized[entry.index].height && uploaded.height) {
544
+ normalized[entry.index].height = uploaded.height;
545
+ }
546
+ }
547
+ return normalized;
548
+ }
549
+
550
+ export async function normalizeLocalPostArguments(args, uploadClient) {
551
+ const normalized = { ...args };
552
+ if (args.media) {
553
+ normalized.media = await normalizeLocalPostMedia(args.media, uploadClient);
554
+ }
555
+ if (Array.isArray(args.targets)) {
556
+ normalized.targets = [];
557
+ for (const target of args.targets) {
558
+ normalized.targets.push({
559
+ ...target,
560
+ ...(target.media
561
+ ? {
562
+ media: await normalizeLocalPostMedia(target.media, uploadClient),
563
+ }
564
+ : {}),
565
+ });
566
+ }
567
+ }
568
+ if (args.target?.media) {
569
+ normalized.target = {
570
+ ...args.target,
571
+ media: await normalizeLocalPostMedia(args.target.media, uploadClient),
572
+ };
573
+ }
574
+ return normalized;
575
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Return the raw object shape the MCP SDK expects for tool registration.
3
+ *
4
+ * Zod 3 wraps object schemas in ZodEffects after `refine`/`superRefine`.
5
+ * Those wrappers intentionally have no public `.shape`, while the SDK needs
6
+ * the underlying object shape to publish an accurate JSON Schema descriptor.
7
+ * Execution still parses with the original refined schema.
8
+ */
9
+ export function registrationShape(schema) {
10
+ let current = schema;
11
+ const visited = new Set();
12
+
13
+ while (current && typeof current === "object" && !visited.has(current)) {
14
+ visited.add(current);
15
+ if (
16
+ current.shape &&
17
+ typeof current.shape === "object" &&
18
+ !Array.isArray(current.shape)
19
+ ) {
20
+ return current.shape;
21
+ }
22
+ current = current._def?.schema ?? current._def?.innerType;
23
+ }
24
+
25
+ throw new TypeError(
26
+ "FavStash MCP tool input must resolve to a Zod object schema.",
27
+ );
28
+ }