ofw-mcp 2.26.1 → 2.27.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/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +45 -2
- package/dist/bundle.js +929 -359
- package/dist/config.js +12 -0
- package/dist/tools/attachments.js +31 -2
- package/dist/tools/messages.js +236 -79
- package/dist/tools/uploads.js +311 -0
- package/dist/version.js +1 -1
- package/mint.yaml +5 -0
- package/package.json +2 -2
- package/server.json +2 -2
- package/skills/ofw/SKILL.md +4 -4
package/dist/bundle.js
CHANGED
|
@@ -2279,7 +2279,7 @@ var require_websocket = __commonJS({
|
|
|
2279
2279
|
var http = __require("http");
|
|
2280
2280
|
var net = __require("net");
|
|
2281
2281
|
var tls = __require("tls");
|
|
2282
|
-
var { randomBytes: randomBytes7, createHash:
|
|
2282
|
+
var { randomBytes: randomBytes7, createHash: createHash7 } = __require("crypto");
|
|
2283
2283
|
var { Duplex, Readable } = __require("stream");
|
|
2284
2284
|
var { URL: URL2 } = __require("url");
|
|
2285
2285
|
var PerMessageDeflate2 = require_permessage_deflate();
|
|
@@ -2960,7 +2960,7 @@ var require_websocket = __commonJS({
|
|
|
2960
2960
|
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
2961
2961
|
return;
|
|
2962
2962
|
}
|
|
2963
|
-
const digest =
|
|
2963
|
+
const digest = createHash7("sha1").update(key + GUID).digest("base64");
|
|
2964
2964
|
if (res.headers["sec-websocket-accept"] !== digest) {
|
|
2965
2965
|
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
2966
2966
|
return;
|
|
@@ -3329,7 +3329,7 @@ var require_websocket_server = __commonJS({
|
|
|
3329
3329
|
var EventEmitter = __require("events");
|
|
3330
3330
|
var http = __require("http");
|
|
3331
3331
|
var { Duplex } = __require("stream");
|
|
3332
|
-
var { createHash:
|
|
3332
|
+
var { createHash: createHash7 } = __require("crypto");
|
|
3333
3333
|
var extension2 = require_extension();
|
|
3334
3334
|
var PerMessageDeflate2 = require_permessage_deflate();
|
|
3335
3335
|
var subprotocol2 = require_subprotocol();
|
|
@@ -3636,7 +3636,7 @@ var require_websocket_server = __commonJS({
|
|
|
3636
3636
|
);
|
|
3637
3637
|
}
|
|
3638
3638
|
if (this._state > RUNNING) return abortHandshake(socket, 503);
|
|
3639
|
-
const digest =
|
|
3639
|
+
const digest = createHash7("sha1").update(key + GUID).digest("base64");
|
|
3640
3640
|
const headers = [
|
|
3641
3641
|
"HTTP/1.1 101 Switching Protocols",
|
|
3642
3642
|
"Upgrade: websocket",
|
|
@@ -40258,6 +40258,17 @@ async function fileBlob(path, opts = {}) {
|
|
|
40258
40258
|
return blob;
|
|
40259
40259
|
}
|
|
40260
40260
|
|
|
40261
|
+
// node_modules/@chrischall/mcp-utils/dist/internal/headers.js
|
|
40262
|
+
function responseHeader(res, name) {
|
|
40263
|
+
return getHeader(res?.headers, name);
|
|
40264
|
+
}
|
|
40265
|
+
function getHeader(headers, name) {
|
|
40266
|
+
if (!headers || typeof headers.get !== "function")
|
|
40267
|
+
return null;
|
|
40268
|
+
const value = headers.get.call(headers, name);
|
|
40269
|
+
return typeof value === "string" ? value : null;
|
|
40270
|
+
}
|
|
40271
|
+
|
|
40261
40272
|
// node_modules/@chrischall/mcp-utils/dist/internal/ascii.js
|
|
40262
40273
|
function asciiLower(s) {
|
|
40263
40274
|
return s.replace(/[A-Z]+/g, (m) => m.toLowerCase());
|
|
@@ -40366,6 +40377,144 @@ function parseContentDispositionFilename(header) {
|
|
|
40366
40377
|
return rawExt;
|
|
40367
40378
|
}
|
|
40368
40379
|
|
|
40380
|
+
// node_modules/@chrischall/mcp-utils/dist/http/body-limit.js
|
|
40381
|
+
var ResponseTooLargeError = class extends McpToolError {
|
|
40382
|
+
maxBytes;
|
|
40383
|
+
constructor(service, maxBytes) {
|
|
40384
|
+
super(`Response from ${service} is larger than the ${maxBytes}-byte limit.`, {
|
|
40385
|
+
hint: "Raise maxBytes (or the client's maxResponseBytes) if a response this large is expected.",
|
|
40386
|
+
kind: "too_large"
|
|
40387
|
+
});
|
|
40388
|
+
this.name = "ResponseTooLargeError";
|
|
40389
|
+
this.maxBytes = maxBytes;
|
|
40390
|
+
}
|
|
40391
|
+
};
|
|
40392
|
+
async function readBytesCapped(res, maxBytes, service, bounded) {
|
|
40393
|
+
if (maxBytes !== void 0) {
|
|
40394
|
+
const declared = Number(responseHeader(res, "content-length") ?? NaN);
|
|
40395
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
40396
|
+
cancelStream(res.body);
|
|
40397
|
+
throw new ResponseTooLargeError(service, maxBytes);
|
|
40398
|
+
}
|
|
40399
|
+
}
|
|
40400
|
+
if (!res.body)
|
|
40401
|
+
return new Uint8Array(0);
|
|
40402
|
+
const reader = res.body.getReader();
|
|
40403
|
+
const chunks = [];
|
|
40404
|
+
let total = 0;
|
|
40405
|
+
try {
|
|
40406
|
+
for (; ; ) {
|
|
40407
|
+
const { done, value } = await bounded(reader.read());
|
|
40408
|
+
if (done)
|
|
40409
|
+
break;
|
|
40410
|
+
total += value.byteLength;
|
|
40411
|
+
if (maxBytes !== void 0 && total > maxBytes)
|
|
40412
|
+
throw new ResponseTooLargeError(service, maxBytes);
|
|
40413
|
+
chunks.push(value);
|
|
40414
|
+
}
|
|
40415
|
+
} catch (err) {
|
|
40416
|
+
reader.cancel().catch(() => {
|
|
40417
|
+
});
|
|
40418
|
+
throw err;
|
|
40419
|
+
}
|
|
40420
|
+
const out = new Uint8Array(total);
|
|
40421
|
+
let offset = 0;
|
|
40422
|
+
for (const c of chunks) {
|
|
40423
|
+
out.set(c, offset);
|
|
40424
|
+
offset += c.byteLength;
|
|
40425
|
+
}
|
|
40426
|
+
return out;
|
|
40427
|
+
}
|
|
40428
|
+
function cancelStream(body) {
|
|
40429
|
+
try {
|
|
40430
|
+
body?.cancel().catch(() => {
|
|
40431
|
+
});
|
|
40432
|
+
} catch {
|
|
40433
|
+
}
|
|
40434
|
+
}
|
|
40435
|
+
|
|
40436
|
+
// node_modules/@chrischall/mcp-utils/dist/http/fetch-bounded.js
|
|
40437
|
+
async function fetchBounded(url2, init, opts = {}) {
|
|
40438
|
+
const doFetch = opts.fetchImpl ?? fetch;
|
|
40439
|
+
const service = opts.service ?? hostOf(url2);
|
|
40440
|
+
const read = opts.read ?? "text";
|
|
40441
|
+
const timeoutMs = opts.timeoutMs === false ? 0 : opts.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
40442
|
+
const caller = withAmbientCancellation(init?.signal ?? void 0);
|
|
40443
|
+
if (caller?.aborted)
|
|
40444
|
+
throw reasonOf(caller);
|
|
40445
|
+
const timer = timeoutMs > 0 ? new AbortController() : void 0;
|
|
40446
|
+
const signal = combine(timer?.signal, caller);
|
|
40447
|
+
let handle;
|
|
40448
|
+
let detach = () => {
|
|
40449
|
+
};
|
|
40450
|
+
const stop = signal ? new Promise((_resolve, reject) => {
|
|
40451
|
+
const onAbort = () => reject(timer?.signal.aborted ? new RequestTimeoutError(service, timeoutMs) : reasonOf(caller));
|
|
40452
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
40453
|
+
detach = () => signal.removeEventListener("abort", onAbort);
|
|
40454
|
+
}) : void 0;
|
|
40455
|
+
stop?.catch(() => {
|
|
40456
|
+
});
|
|
40457
|
+
const bounded = (p) => stop ? Promise.race([p, stop]) : p;
|
|
40458
|
+
if (timer)
|
|
40459
|
+
handle = setTimeout(() => timer.abort(), timeoutMs);
|
|
40460
|
+
try {
|
|
40461
|
+
let res;
|
|
40462
|
+
try {
|
|
40463
|
+
res = await bounded(doFetch(url2, { ...init, ...signal ? { signal } : {} }));
|
|
40464
|
+
} catch (err) {
|
|
40465
|
+
if (timer?.signal.aborted)
|
|
40466
|
+
throw new RequestTimeoutError(service, timeoutMs);
|
|
40467
|
+
if (caller?.aborted)
|
|
40468
|
+
throw reasonOf(caller);
|
|
40469
|
+
throw err;
|
|
40470
|
+
}
|
|
40471
|
+
if (read === "none") {
|
|
40472
|
+
cancelStream(res.body);
|
|
40473
|
+
return done(res, void 0);
|
|
40474
|
+
}
|
|
40475
|
+
const bytes = await readBytesCapped(res, opts.maxBytes, service, bounded);
|
|
40476
|
+
if (read === "bytes")
|
|
40477
|
+
return done(res, bytes);
|
|
40478
|
+
const text = new TextDecoder().decode(bytes);
|
|
40479
|
+
if (read === "text")
|
|
40480
|
+
return done(res, text);
|
|
40481
|
+
if (text.length === 0)
|
|
40482
|
+
return done(res, void 0);
|
|
40483
|
+
try {
|
|
40484
|
+
return done(res, JSON.parse(text));
|
|
40485
|
+
} catch (cause) {
|
|
40486
|
+
const type = res.headers.get("content-type") ?? "no content-type";
|
|
40487
|
+
throw new McpToolError(`${service} returned a non-JSON response (HTTP ${res.status}, ${type}).`, {
|
|
40488
|
+
hint: "The upstream may have served an error or sign-in page instead of data.",
|
|
40489
|
+
cause,
|
|
40490
|
+
status: res.status
|
|
40491
|
+
});
|
|
40492
|
+
}
|
|
40493
|
+
} finally {
|
|
40494
|
+
clearTimeout(handle);
|
|
40495
|
+
detach();
|
|
40496
|
+
}
|
|
40497
|
+
function done(res, body) {
|
|
40498
|
+
return { res, status: res.status, ok: res.ok, headers: res.headers, body };
|
|
40499
|
+
}
|
|
40500
|
+
}
|
|
40501
|
+
function combine(a, b) {
|
|
40502
|
+
if (a && b)
|
|
40503
|
+
return AbortSignal.any([a, b]);
|
|
40504
|
+
return a ?? b;
|
|
40505
|
+
}
|
|
40506
|
+
function reasonOf(signal) {
|
|
40507
|
+
const reason = signal.reason;
|
|
40508
|
+
return reason instanceof Error ? reason : new Error(String(reason));
|
|
40509
|
+
}
|
|
40510
|
+
function hostOf(url2) {
|
|
40511
|
+
try {
|
|
40512
|
+
return new URL(url2).host;
|
|
40513
|
+
} catch {
|
|
40514
|
+
return String(url2);
|
|
40515
|
+
}
|
|
40516
|
+
}
|
|
40517
|
+
|
|
40369
40518
|
// node_modules/@chrischall/mcp-utils/dist/netguard/address.js
|
|
40370
40519
|
function parseIPv4(text) {
|
|
40371
40520
|
if (!/^(?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3}$/.test(text))
|
|
@@ -40449,6 +40598,7 @@ var NAT64 = V6("64:ff9b::");
|
|
|
40449
40598
|
var SIX_TO_FOUR = V6("2002::");
|
|
40450
40599
|
|
|
40451
40600
|
// node_modules/@chrischall/mcp-utils/dist/http/index.js
|
|
40601
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
|
|
40452
40602
|
var RateLimitedError = class extends Error {
|
|
40453
40603
|
status = 429;
|
|
40454
40604
|
/** `'http'`: the far side answered, with a 429 (see `status`). */
|
|
@@ -47702,7 +47852,7 @@ function describeTokenlessLogin(record2) {
|
|
|
47702
47852
|
|
|
47703
47853
|
// src/version.ts
|
|
47704
47854
|
var SERVER_NAME = "ofw-mcp";
|
|
47705
|
-
var VERSION = "2.
|
|
47855
|
+
var VERSION = "2.27.0";
|
|
47706
47856
|
|
|
47707
47857
|
// src/auth.ts
|
|
47708
47858
|
function fetchproxyDisabled() {
|
|
@@ -49098,6 +49248,12 @@ function getAttachmentsDir() {
|
|
|
49098
49248
|
function getDefaultAttachmentsDir() {
|
|
49099
49249
|
return join10(homedir4(), "Downloads", "ofw-mcp");
|
|
49100
49250
|
}
|
|
49251
|
+
function isHostedDeployment(env = process.env) {
|
|
49252
|
+
return readEnvVar("MCP_DATA_DIR", { env }) !== void 0 || readEnvVar("MCP_BLOB_BASE_URL", { env }) !== void 0;
|
|
49253
|
+
}
|
|
49254
|
+
function hasBlobStoreEnv(env = process.env) {
|
|
49255
|
+
return readEnvVar("MCP_BLOB_BASE_URL", { env }) !== void 0 && readEnvVar("MCP_BLOB_SIGNING_KEY", { env }) !== void 0;
|
|
49256
|
+
}
|
|
49101
49257
|
function getUploadDir() {
|
|
49102
49258
|
const override = process.env.OFW_UPLOAD_DIR;
|
|
49103
49259
|
if (override && override.trim().length > 0) return override.trim();
|
|
@@ -49663,6 +49819,555 @@ function stateRevision(value) {
|
|
|
49663
49819
|
return `s1:${fnv1a64(JSON.stringify(value))}`;
|
|
49664
49820
|
}
|
|
49665
49821
|
|
|
49822
|
+
// src/tools/attachments.ts
|
|
49823
|
+
import { chmodSync as chmodSync3, readFileSync as readFileSync4, realpathSync as realpathSync3, statSync as statSync3, mkdirSync as mkdirSync5, unlinkSync as unlinkSync5 } from "node:fs";
|
|
49824
|
+
import { basename as basename2, dirname as dirname6, extname, isAbsolute as isAbsolute6, join as join11, relative as relative2, resolve as resolve5, sep as sep2 } from "node:path";
|
|
49825
|
+
function isWithin(root, candidate) {
|
|
49826
|
+
const rel = relative2(root, candidate);
|
|
49827
|
+
return rel !== "" && !rel.startsWith("..") && !isAbsolute6(rel);
|
|
49828
|
+
}
|
|
49829
|
+
function resolveSaveDest(root, saveTo, defaultName) {
|
|
49830
|
+
if (!saveTo) return join11(root, defaultName);
|
|
49831
|
+
const isDirArg = saveTo.endsWith("/") || saveTo.endsWith("\\");
|
|
49832
|
+
const abs = resolve5(root, saveTo.startsWith("~") ? expandPath(saveTo) : saveTo);
|
|
49833
|
+
const dest = isDirArg ? join11(abs, defaultName) : abs;
|
|
49834
|
+
if (!isWithin(root, dest)) {
|
|
49835
|
+
throw new Error(`Refusing to save to ${dest}: it is outside the attachments directory (${root}). Files can only be written inside it \u2014 pass a path or subdirectory under it, or set OFW_ATTACHMENTS_DIR to move it.`);
|
|
49836
|
+
}
|
|
49837
|
+
return dest;
|
|
49838
|
+
}
|
|
49839
|
+
var MIME_BY_EXT = {
|
|
49840
|
+
".pdf": "application/pdf",
|
|
49841
|
+
".png": "image/png",
|
|
49842
|
+
".jpg": "image/jpeg",
|
|
49843
|
+
".jpeg": "image/jpeg",
|
|
49844
|
+
".gif": "image/gif",
|
|
49845
|
+
".webp": "image/webp",
|
|
49846
|
+
".heic": "image/heic",
|
|
49847
|
+
".txt": "text/plain",
|
|
49848
|
+
".md": "text/markdown",
|
|
49849
|
+
".csv": "text/csv",
|
|
49850
|
+
".html": "text/html",
|
|
49851
|
+
".htm": "text/html",
|
|
49852
|
+
".json": "application/json",
|
|
49853
|
+
".xml": "application/xml",
|
|
49854
|
+
".doc": "application/msword",
|
|
49855
|
+
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
49856
|
+
".xls": "application/vnd.ms-excel",
|
|
49857
|
+
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
49858
|
+
".ppt": "application/vnd.ms-powerpoint",
|
|
49859
|
+
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
49860
|
+
".zip": "application/zip",
|
|
49861
|
+
".ics": "text/calendar"
|
|
49862
|
+
};
|
|
49863
|
+
function mimeFromName(name) {
|
|
49864
|
+
return MIME_BY_EXT[extname(name).toLowerCase()] ?? "application/octet-stream";
|
|
49865
|
+
}
|
|
49866
|
+
var OCTET_STREAM = "application/octet-stream";
|
|
49867
|
+
var HOST_RENDERABLE_IMAGE_MIMES = /* @__PURE__ */ new Set([
|
|
49868
|
+
"image/png",
|
|
49869
|
+
"image/jpeg",
|
|
49870
|
+
"image/gif",
|
|
49871
|
+
"image/webp"
|
|
49872
|
+
]);
|
|
49873
|
+
function normalizeMimeType(raw) {
|
|
49874
|
+
if (!raw) return OCTET_STREAM;
|
|
49875
|
+
const bare = raw.split(";", 1)[0].trim().toLowerCase();
|
|
49876
|
+
return bare || OCTET_STREAM;
|
|
49877
|
+
}
|
|
49878
|
+
function sniffImageMime(bytes) {
|
|
49879
|
+
const sniffed = sniffMimeBytes(bytes);
|
|
49880
|
+
return sniffed !== void 0 && HOST_RENDERABLE_IMAGE_MIMES.has(sniffed) ? sniffed : null;
|
|
49881
|
+
}
|
|
49882
|
+
function resolveDownloadMime(bytes, headerMime, fileName) {
|
|
49883
|
+
const sniffed = sniffImageMime(bytes);
|
|
49884
|
+
if (sniffed) return sniffed;
|
|
49885
|
+
const fromHeader = normalizeMimeType(headerMime);
|
|
49886
|
+
if (fromHeader !== OCTET_STREAM) return fromHeader;
|
|
49887
|
+
return mimeFromName(fileName);
|
|
49888
|
+
}
|
|
49889
|
+
function isHostRenderableImage(mime) {
|
|
49890
|
+
return HOST_RENDERABLE_IMAGE_MIMES.has(mime);
|
|
49891
|
+
}
|
|
49892
|
+
var MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
|
|
49893
|
+
function hostedPathRefusal(hasBlobStore) {
|
|
49894
|
+
return new Error(
|
|
49895
|
+
"This server is remote and can't read files on your machine, so `path` cannot work here. " + (hasBlobStore ? "Upload the bytes instead: call ofw_upload_attachment with uploadSlots:[{filename}] to get a signed upload URL, PUT the file to it (the response includes a ready curl command), then call it again with blobKeys. For a small file you can instead pass `inline` with base64 content." : "Pass the bytes with `inline` ({filename, contentBase64}) instead.")
|
|
49896
|
+
);
|
|
49897
|
+
}
|
|
49898
|
+
var NodeAttachmentIO = class {
|
|
49899
|
+
supportsDisk = true;
|
|
49900
|
+
async resolveUpload(path) {
|
|
49901
|
+
if (isHostedDeployment()) throw hostedPathRefusal(hasBlobStoreEnv());
|
|
49902
|
+
const root = resolve5(getUploadDir());
|
|
49903
|
+
mkdirSync5(root, { recursive: true, mode: 448 });
|
|
49904
|
+
const abs = resolve5(root, path.startsWith("~") ? expandPath(path) : path);
|
|
49905
|
+
const outside = new Error(`Refusing to upload ${abs}: it is outside the upload directory (${root}). Only files placed in that directory can be uploaded \u2014 ask the user to copy the file there, or set OFW_UPLOAD_DIR.`);
|
|
49906
|
+
if (!isWithin(root, abs)) throw outside;
|
|
49907
|
+
let real;
|
|
49908
|
+
try {
|
|
49909
|
+
real = realpathSync3(abs);
|
|
49910
|
+
} catch (e) {
|
|
49911
|
+
if (e.code !== "ENOENT") throw e;
|
|
49912
|
+
throw new Error(`File not found in the upload directory (${root}): ${abs}. Copy the file there first, or pass its bytes with \`inline\`.`);
|
|
49913
|
+
}
|
|
49914
|
+
const realRoot = realpathSync3(root);
|
|
49915
|
+
try {
|
|
49916
|
+
assertPathWithinRoots(real, [realRoot]);
|
|
49917
|
+
} catch {
|
|
49918
|
+
throw outside;
|
|
49919
|
+
}
|
|
49920
|
+
if (relative2(realRoot, real).split(sep2).some((segment) => segment.startsWith("."))) {
|
|
49921
|
+
throw new Error(`Refusing to upload ${abs}: hidden files and files in hidden directories (dotfiles, credential stores) are never uploaded.`);
|
|
49922
|
+
}
|
|
49923
|
+
const stat = statSync3(real);
|
|
49924
|
+
if (!stat.isFile()) throw new Error(`Not a file: ${abs}`);
|
|
49925
|
+
if (stat.size > MAX_UPLOAD_BYTES) {
|
|
49926
|
+
throw new Error(`Refusing to upload ${abs}: it is too large (${stat.size} bytes; the limit is ${MAX_UPLOAD_BYTES}).`);
|
|
49927
|
+
}
|
|
49928
|
+
const fileName = basename2(abs);
|
|
49929
|
+
const mimeType = mimeFromName(fileName);
|
|
49930
|
+
const blob = await fileBlob(real, { type: mimeType, allowedRoots: [realRoot] });
|
|
49931
|
+
return { blob, fileName, mimeType, sizeBytes: stat.size };
|
|
49932
|
+
}
|
|
49933
|
+
readDownloaded(path) {
|
|
49934
|
+
try {
|
|
49935
|
+
return readFileSync4(path);
|
|
49936
|
+
} catch {
|
|
49937
|
+
return null;
|
|
49938
|
+
}
|
|
49939
|
+
}
|
|
49940
|
+
async writeDownload(dest, bytes, { root, overwrite }) {
|
|
49941
|
+
mkdirSync5(root, { recursive: true, mode: 448 });
|
|
49942
|
+
if (resolve5(root) === resolve5(getDefaultAttachmentsDir())) chmodSync3(root, 448);
|
|
49943
|
+
const realRoot = realpathSync3(root);
|
|
49944
|
+
const parent = dirname6(dest);
|
|
49945
|
+
const outside = () => new Error(`Refusing to write ${dest}: it resolves outside the attachments directory (${root}).`);
|
|
49946
|
+
try {
|
|
49947
|
+
assertPathWithinRoots(parent, [realRoot]);
|
|
49948
|
+
} catch {
|
|
49949
|
+
throw outside();
|
|
49950
|
+
}
|
|
49951
|
+
mkdirSync5(parent, { recursive: true, mode: 448 });
|
|
49952
|
+
if (overwrite) {
|
|
49953
|
+
try {
|
|
49954
|
+
unlinkSync5(dest);
|
|
49955
|
+
} catch {
|
|
49956
|
+
}
|
|
49957
|
+
}
|
|
49958
|
+
try {
|
|
49959
|
+
await writeFileSafe(dest, bytes, { mode: 384, allowedRoots: [realRoot] });
|
|
49960
|
+
} catch (e) {
|
|
49961
|
+
if (e instanceof FileWriteRefusedError) {
|
|
49962
|
+
if (e.reason === "outside-roots") throw outside();
|
|
49963
|
+
throw new Error(`Refusing to overwrite ${dest}: a file already exists there. Pass force:true to replace it, or choose another saveTo.`);
|
|
49964
|
+
}
|
|
49965
|
+
throw e;
|
|
49966
|
+
}
|
|
49967
|
+
}
|
|
49968
|
+
};
|
|
49969
|
+
|
|
49970
|
+
// node_modules/@chrischall/mcp-utils/dist/export/blob.js
|
|
49971
|
+
import { createHmac as createHmac4 } from "node:crypto";
|
|
49972
|
+
var BLOB_DEFAULT_TTL_MS = 60 * 60 * 1e3;
|
|
49973
|
+
var BLOB_MAX_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
49974
|
+
var BLOB_MAX_OBJECT_BYTES = 100 * 1024 * 1024;
|
|
49975
|
+
var MAX_KEY_LENGTH = 1024;
|
|
49976
|
+
var SAFE_SEGMENT = /^[A-Za-z0-9._~-]+$/;
|
|
49977
|
+
function configError(reason) {
|
|
49978
|
+
return new McpToolError(`MCP_BLOB_BASE_URL is not usable: ${reason}.`, {
|
|
49979
|
+
hint: "It should look like https://<host>/b/<registrationId> \u2014 check the deployment's environment.",
|
|
49980
|
+
kind: "unknown"
|
|
49981
|
+
});
|
|
49982
|
+
}
|
|
49983
|
+
function parseBase(baseUrl) {
|
|
49984
|
+
let parsed;
|
|
49985
|
+
try {
|
|
49986
|
+
parsed = new URL(baseUrl);
|
|
49987
|
+
} catch {
|
|
49988
|
+
throw configError("not a valid URL");
|
|
49989
|
+
}
|
|
49990
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:")
|
|
49991
|
+
throw configError("scheme must be http(s)");
|
|
49992
|
+
if (parsed.username || parsed.password)
|
|
49993
|
+
throw configError("must not contain credentials");
|
|
49994
|
+
if (parsed.search || parsed.hash)
|
|
49995
|
+
throw configError("must not contain a query or fragment");
|
|
49996
|
+
const path = parsed.pathname.replace(/^\/+|\/+$/g, "");
|
|
49997
|
+
const prefix = path.startsWith("b/") ? path.slice(2) : path;
|
|
49998
|
+
if (!prefix || prefix === "b")
|
|
49999
|
+
throw configError("has no registration path");
|
|
50000
|
+
return { base: `${parsed.origin}/${path}`, prefix };
|
|
50001
|
+
}
|
|
50002
|
+
function badInput(message) {
|
|
50003
|
+
return new McpToolError(message, { kind: "unknown" });
|
|
50004
|
+
}
|
|
50005
|
+
function encodeKey(key) {
|
|
50006
|
+
if (typeof key !== "string" || key.length === 0)
|
|
50007
|
+
throw badInput("Blob key must be a non-empty string.");
|
|
50008
|
+
if (key.length > MAX_KEY_LENGTH)
|
|
50009
|
+
throw badInput(`Blob key is longer than ${MAX_KEY_LENGTH} characters.`);
|
|
50010
|
+
const segments = key.split("/");
|
|
50011
|
+
for (const seg of segments) {
|
|
50012
|
+
if (seg === "" || seg === "." || seg === ".." || !SAFE_SEGMENT.test(seg)) {
|
|
50013
|
+
throw badInput('Blob key must be relative, slash-separated segments of [A-Za-z0-9._~-] with no empty, "." or ".." segment.');
|
|
50014
|
+
}
|
|
50015
|
+
}
|
|
50016
|
+
return segments.map(encodeURIComponent).join("/");
|
|
50017
|
+
}
|
|
50018
|
+
function checkContentType(contentType) {
|
|
50019
|
+
if (typeof contentType !== "string" || contentType.length === 0 || /[\x00-\x1f\x7f]/.test(contentType)) {
|
|
50020
|
+
throw badInput("Blob content type must be a non-empty string without control characters.");
|
|
50021
|
+
}
|
|
50022
|
+
}
|
|
50023
|
+
function expiry(opts) {
|
|
50024
|
+
const ttl = opts?.ttlMs ?? BLOB_DEFAULT_TTL_MS;
|
|
50025
|
+
if (!Number.isFinite(ttl) || ttl <= 0 || ttl > BLOB_MAX_TTL_MS) {
|
|
50026
|
+
throw badInput(`Blob link TTL must be between 1 ms and ${BLOB_MAX_TTL_MS} ms (24h); the gateway refuses longer.`);
|
|
50027
|
+
}
|
|
50028
|
+
return Math.floor((opts?.now ?? Date.now()) + ttl);
|
|
50029
|
+
}
|
|
50030
|
+
function toArrayBuffer(view) {
|
|
50031
|
+
const buf = view.buffer;
|
|
50032
|
+
if (buf instanceof ArrayBuffer && view.byteOffset === 0 && view.byteLength === buf.byteLength)
|
|
50033
|
+
return buf;
|
|
50034
|
+
return view.slice().buffer;
|
|
50035
|
+
}
|
|
50036
|
+
function createBlobStore(opts) {
|
|
50037
|
+
const { base, prefix } = parseBase(opts.baseUrl);
|
|
50038
|
+
const signingKey = opts.signingKey;
|
|
50039
|
+
const sign2 = (payload) => createHmac4("sha256", signingKey).update(payload).digest("base64url");
|
|
50040
|
+
const link2 = (encodedKey, exp, sig) => `${base}/${encodedKey}?exp=${exp}&sig=${encodeURIComponent(sig)}`;
|
|
50041
|
+
const signGetUrl = (key, o) => {
|
|
50042
|
+
const encoded = encodeKey(key);
|
|
50043
|
+
const exp = expiry(o);
|
|
50044
|
+
return { url: link2(encoded, exp, sign2(`${prefix}/${key}
|
|
50045
|
+
${exp}`)), expiresAtMs: exp };
|
|
50046
|
+
};
|
|
50047
|
+
const signPutUrl = (key, contentType, o) => {
|
|
50048
|
+
const encoded = encodeKey(key);
|
|
50049
|
+
checkContentType(contentType);
|
|
50050
|
+
const exp = expiry(o);
|
|
50051
|
+
return { url: link2(encoded, exp, sign2(`put\0${prefix}/${key}\0${contentType}\0${exp}`)), expiresAtMs: exp };
|
|
50052
|
+
};
|
|
50053
|
+
const put = async (key, body, contentType, o = {}) => {
|
|
50054
|
+
const { url: url2 } = signPutUrl(key, contentType, o);
|
|
50055
|
+
const bytes = typeof body === "string" ? new TextEncoder().encode(body) : body;
|
|
50056
|
+
const doFetch = o.fetchImpl ?? fetch;
|
|
50057
|
+
let res;
|
|
50058
|
+
try {
|
|
50059
|
+
res = await doFetch(url2, {
|
|
50060
|
+
method: "PUT",
|
|
50061
|
+
headers: { "content-type": contentType },
|
|
50062
|
+
body: toArrayBuffer(bytes),
|
|
50063
|
+
...o.signal ? { signal: o.signal } : {}
|
|
50064
|
+
});
|
|
50065
|
+
} catch (cause) {
|
|
50066
|
+
if (o.signal?.aborted)
|
|
50067
|
+
throw cause;
|
|
50068
|
+
throw new McpToolError(`Blob store upload of ${key} did not complete (network error).`, {
|
|
50069
|
+
kind: "transport"
|
|
50070
|
+
});
|
|
50071
|
+
}
|
|
50072
|
+
if (!res.ok) {
|
|
50073
|
+
throw new McpToolError(`Blob store upload of ${key} failed (HTTP ${res.status}).`, {
|
|
50074
|
+
kind: "http",
|
|
50075
|
+
status: res.status
|
|
50076
|
+
});
|
|
50077
|
+
}
|
|
50078
|
+
return { key, bytes: bytes.byteLength };
|
|
50079
|
+
};
|
|
50080
|
+
const signDeleteUrl = (key, o) => {
|
|
50081
|
+
const encoded = encodeKey(key);
|
|
50082
|
+
const exp = expiry(o);
|
|
50083
|
+
return { url: link2(encoded, exp, sign2(`del\0${prefix}/${key}\0${exp}`)), expiresAtMs: exp };
|
|
50084
|
+
};
|
|
50085
|
+
const exchange = async (what, url2, method, read, o) => {
|
|
50086
|
+
try {
|
|
50087
|
+
return await fetchBounded(url2, { method, ...o.signal ? { signal: o.signal } : {} }, {
|
|
50088
|
+
read,
|
|
50089
|
+
service: "the blob store",
|
|
50090
|
+
...read === "bytes" ? { maxBytes: o.maxBytes ?? BLOB_MAX_OBJECT_BYTES } : {},
|
|
50091
|
+
...o.timeoutMs !== void 0 ? { timeoutMs: o.timeoutMs } : {},
|
|
50092
|
+
...o.fetchImpl ? { fetchImpl: o.fetchImpl } : {}
|
|
50093
|
+
});
|
|
50094
|
+
} catch (cause) {
|
|
50095
|
+
if (o.signal?.aborted || cause instanceof McpToolError || cause instanceof RequestTimeoutError)
|
|
50096
|
+
throw cause;
|
|
50097
|
+
throw new McpToolError(`Blob store ${what} did not complete (network error).`, { kind: "transport" });
|
|
50098
|
+
}
|
|
50099
|
+
};
|
|
50100
|
+
const get = async (key, o = {}) => {
|
|
50101
|
+
const { url: url2 } = signGetUrl(key, o);
|
|
50102
|
+
const res = await exchange(`read of ${key}`, url2, "GET", "bytes", o);
|
|
50103
|
+
if (!res.ok) {
|
|
50104
|
+
const why = res.status === 404 ? " \u2014 not found (never uploaded, expired, or already consumed)" : "";
|
|
50105
|
+
throw new McpToolError(`Blob store read of ${key} failed (HTTP ${res.status})${why}.`, {
|
|
50106
|
+
kind: "http",
|
|
50107
|
+
status: res.status
|
|
50108
|
+
});
|
|
50109
|
+
}
|
|
50110
|
+
const contentType = res.headers.get("content-type") ?? void 0;
|
|
50111
|
+
return { key, bytes: res.body, ...contentType !== void 0 ? { contentType } : {} };
|
|
50112
|
+
};
|
|
50113
|
+
const del = async (key, o = {}) => {
|
|
50114
|
+
const { url: url2 } = signDeleteUrl(key, o);
|
|
50115
|
+
const res = await exchange(`delete of ${key}`, url2, "DELETE", "none", o);
|
|
50116
|
+
if (!res.ok) {
|
|
50117
|
+
throw new McpToolError(`Blob store delete of ${key} failed (HTTP ${res.status}).`, {
|
|
50118
|
+
kind: "http",
|
|
50119
|
+
status: res.status
|
|
50120
|
+
});
|
|
50121
|
+
}
|
|
50122
|
+
};
|
|
50123
|
+
const consume = async (key, use, o = {}) => {
|
|
50124
|
+
const object2 = await get(key, o);
|
|
50125
|
+
const result = await use(object2);
|
|
50126
|
+
try {
|
|
50127
|
+
await del(key, o);
|
|
50128
|
+
return { result, deleted: true };
|
|
50129
|
+
} catch (e) {
|
|
50130
|
+
return { result, deleted: false, deleteError: e instanceof Error ? e.message : String(e) };
|
|
50131
|
+
}
|
|
50132
|
+
};
|
|
50133
|
+
return { baseUrl: base, prefix, signGetUrl, signPutUrl, put, signDeleteUrl, get, delete: del, consume };
|
|
50134
|
+
}
|
|
50135
|
+
function blobStoreFromEnv(env = process.env) {
|
|
50136
|
+
const baseUrl = readEnvVar("MCP_BLOB_BASE_URL", { env });
|
|
50137
|
+
const signingKey = readEnvVar("MCP_BLOB_SIGNING_KEY", { env });
|
|
50138
|
+
if (!baseUrl || !signingKey)
|
|
50139
|
+
return void 0;
|
|
50140
|
+
return createBlobStore({ baseUrl, signingKey });
|
|
50141
|
+
}
|
|
50142
|
+
|
|
50143
|
+
// node_modules/@chrischall/mcp-utils/dist/export/zip.js
|
|
50144
|
+
var CRC_TABLE = (() => {
|
|
50145
|
+
const table = new Uint32Array(256);
|
|
50146
|
+
for (let n = 0; n < 256; n++) {
|
|
50147
|
+
let c = n;
|
|
50148
|
+
for (let k = 0; k < 8; k++)
|
|
50149
|
+
c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
|
|
50150
|
+
table[n] = c >>> 0;
|
|
50151
|
+
}
|
|
50152
|
+
return table;
|
|
50153
|
+
})();
|
|
50154
|
+
|
|
50155
|
+
// node_modules/@chrischall/mcp-utils/dist/export/sink.js
|
|
50156
|
+
var EXPORT_BLOB_MAX_BYTES = 256 * 1024 * 1024;
|
|
50157
|
+
|
|
50158
|
+
// src/tools/uploads.ts
|
|
50159
|
+
import { createHash as createHash6, randomUUID as randomUUID2 } from "node:crypto";
|
|
50160
|
+
var MAX_FILES_PER_CALL = 10;
|
|
50161
|
+
var UPLOAD_SLOT_TTL_MS = 30 * 60 * 1e3;
|
|
50162
|
+
var UPLOAD_BLOB_PREFIX = "uploads";
|
|
50163
|
+
var MIB = 1024 * 1024;
|
|
50164
|
+
var LIMIT_TEXT = `${MAX_UPLOAD_BYTES / MIB} MiB (${MAX_UPLOAD_BYTES} bytes)`;
|
|
50165
|
+
var inlineFileSchema = external_exports.object({
|
|
50166
|
+
filename: external_exports.string().describe('Filename OFW will show, e.g. "Finn_Think_Sheet_2026-11-03.jpg" \u2014 a bare name, no path, not starting with a dot. Its extension sets the MIME type when mimeType is omitted.'),
|
|
50167
|
+
contentBase64: external_exports.string().describe(`The file's bytes, standard base64 (line breaks and a "data:<type>;base64," prefix are tolerated).`),
|
|
50168
|
+
mimeType: external_exports.string().describe('MIME type, e.g. "image/jpeg". Default: inferred from the filename extension (jpg/jpeg, png, heic, pdf, docx, \u2026).').optional()
|
|
50169
|
+
});
|
|
50170
|
+
var uploadSlotRequestSchema = external_exports.object({
|
|
50171
|
+
filename: external_exports.string().describe("Filename OFW will show \u2014 a bare name, no path, not starting with a dot."),
|
|
50172
|
+
mimeType: external_exports.string().describe("MIME type. Default: inferred from the filename extension. The PUT must send exactly this Content-Type.").optional()
|
|
50173
|
+
});
|
|
50174
|
+
function sanitizeUploadFilename(raw) {
|
|
50175
|
+
const name = raw.trim();
|
|
50176
|
+
if (name.length === 0) throw new Error("filename is empty.");
|
|
50177
|
+
if (/[/\\]/.test(name)) {
|
|
50178
|
+
throw new Error(`filename ${JSON.stringify(name)} must be a bare filename, not a path \u2014 pass just the name OFW should show, e.g. "photo.jpg".`);
|
|
50179
|
+
}
|
|
50180
|
+
if (/[\x00-\x1f\x7f]/.test(name)) throw new Error(`filename ${JSON.stringify(name)} contains control characters.`);
|
|
50181
|
+
if (name.startsWith(".")) {
|
|
50182
|
+
throw new Error(`filename ${JSON.stringify(name)} must not start with a dot (hidden files are never uploaded).`);
|
|
50183
|
+
}
|
|
50184
|
+
if (name.length > 200) throw new Error("filename is longer than 200 characters.");
|
|
50185
|
+
return name;
|
|
50186
|
+
}
|
|
50187
|
+
var MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/;
|
|
50188
|
+
function resolveUploadMime(fileName, mimeType) {
|
|
50189
|
+
if (mimeType === void 0) return mimeFromName(fileName);
|
|
50190
|
+
const bare = normalizeMimeType(mimeType);
|
|
50191
|
+
if (!MEDIA_TYPE.test(bare)) {
|
|
50192
|
+
throw new Error(`mimeType ${JSON.stringify(mimeType)} is not a type/subtype media type such as "image/jpeg".`);
|
|
50193
|
+
}
|
|
50194
|
+
return bare;
|
|
50195
|
+
}
|
|
50196
|
+
function checkUploadSize(fileName, size) {
|
|
50197
|
+
if (size === 0) throw new Error(`${fileName} is empty (0 bytes); nothing to upload.`);
|
|
50198
|
+
if (size > MAX_UPLOAD_BYTES) {
|
|
50199
|
+
throw new Error(`${fileName} is too large (${size} bytes); the upload limit is ${LIMIT_TEXT}.`);
|
|
50200
|
+
}
|
|
50201
|
+
}
|
|
50202
|
+
var BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
50203
|
+
function decodeBase64Content(content, fileName) {
|
|
50204
|
+
const compact = content.replace(/^data:[^,]*;base64,/i, "").replace(/\s+/g, "");
|
|
50205
|
+
if (compact.length === 0) throw new Error(`${fileName} is empty (0 bytes); nothing to upload.`);
|
|
50206
|
+
const invalid = () => new Error(`${fileName}: contentBase64 is not valid base64 (standard alphabet A-Z a-z 0-9 + /, padded with = to a multiple of 4 characters). It may have been truncated.`);
|
|
50207
|
+
if (compact.length % 4 !== 0 || !BASE64.test(compact)) throw invalid();
|
|
50208
|
+
const padding = compact.endsWith("==") ? 2 : compact.endsWith("=") ? 1 : 0;
|
|
50209
|
+
checkUploadSize(fileName, compact.length / 4 * 3 - padding);
|
|
50210
|
+
const bytes = Buffer.from(compact, "base64");
|
|
50211
|
+
if (bytes.toString("base64") !== compact) throw invalid();
|
|
50212
|
+
return bytes;
|
|
50213
|
+
}
|
|
50214
|
+
function resolveInlineUpload(file2) {
|
|
50215
|
+
const fileName = sanitizeUploadFilename(file2.filename);
|
|
50216
|
+
const mimeType = resolveUploadMime(fileName, file2.mimeType);
|
|
50217
|
+
const bytes = decodeBase64Content(file2.contentBase64, fileName);
|
|
50218
|
+
return { blob: new Blob([new Uint8Array(bytes)], { type: mimeType }), fileName, mimeType, sizeBytes: bytes.length };
|
|
50219
|
+
}
|
|
50220
|
+
var UPLOAD_KEY = new RegExp(
|
|
50221
|
+
`^${UPLOAD_BLOB_PREFIX}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/([A-Za-z0-9_-]+)$`
|
|
50222
|
+
);
|
|
50223
|
+
function fileNameFromBlobKey(key) {
|
|
50224
|
+
const match = UPLOAD_KEY.exec(key);
|
|
50225
|
+
if (!match) {
|
|
50226
|
+
throw new Error(`blobKey ${JSON.stringify(key)} is not an upload key. Pass the blobKey exactly as ofw_upload_attachment's uploadSlots returned it.`);
|
|
50227
|
+
}
|
|
50228
|
+
return sanitizeUploadFilename(Buffer.from(match[1], "base64url").toString("utf8"));
|
|
50229
|
+
}
|
|
50230
|
+
function mintUploadSlot(store, req) {
|
|
50231
|
+
const filename = sanitizeUploadFilename(req.filename);
|
|
50232
|
+
const mimeType = resolveUploadMime(filename, req.mimeType);
|
|
50233
|
+
const blobKey = `${UPLOAD_BLOB_PREFIX}/${randomUUID2()}/${Buffer.from(filename, "utf8").toString("base64url")}`;
|
|
50234
|
+
const { url: url2, expiresAtMs } = store.signPutUrl(blobKey, mimeType, { ttlMs: UPLOAD_SLOT_TTL_MS });
|
|
50235
|
+
const shellName = filename.replace(/'/g, `'\\''`);
|
|
50236
|
+
return {
|
|
50237
|
+
filename,
|
|
50238
|
+
mimeType,
|
|
50239
|
+
blobKey,
|
|
50240
|
+
method: "PUT",
|
|
50241
|
+
uploadUrl: url2,
|
|
50242
|
+
expiresAt: formatInstant(new Date(expiresAtMs)).iso,
|
|
50243
|
+
// The signature commits to the Content-Type, so the header must match it
|
|
50244
|
+
// byte for byte; --fail turns a refused PUT into a non-zero exit.
|
|
50245
|
+
curl: `curl -sS --fail -X PUT -H 'Content-Type: ${mimeType}' --data-binary @'<path to ${shellName}>' '${url2}'`
|
|
50246
|
+
};
|
|
50247
|
+
}
|
|
50248
|
+
function blobObjectToUpload(key, object2) {
|
|
50249
|
+
const fileName = fileNameFromBlobKey(key);
|
|
50250
|
+
checkUploadSize(fileName, object2.bytes.length);
|
|
50251
|
+
const mimeType = normalizeMimeType(object2.contentType ?? mimeFromName(fileName));
|
|
50252
|
+
return {
|
|
50253
|
+
blob: new Blob([object2.bytes], { type: mimeType }),
|
|
50254
|
+
fileName,
|
|
50255
|
+
mimeType,
|
|
50256
|
+
sizeBytes: object2.bytes.length
|
|
50257
|
+
};
|
|
50258
|
+
}
|
|
50259
|
+
var UploadedFileSchema = external_exports.looseObject({
|
|
50260
|
+
fileId: external_exports.number(),
|
|
50261
|
+
fileName: external_exports.string().optional(),
|
|
50262
|
+
label: external_exports.string().optional(),
|
|
50263
|
+
fileType: external_exports.string().optional(),
|
|
50264
|
+
sizeInBytes: external_exports.number().optional(),
|
|
50265
|
+
shareClass: external_exports.string().optional()
|
|
50266
|
+
});
|
|
50267
|
+
async function uploadToMyFiles(client2, cache, upload, opts) {
|
|
50268
|
+
const { blob, fileName, mimeType, sizeBytes } = upload;
|
|
50269
|
+
const form = new FormData();
|
|
50270
|
+
form.append("file", blob, fileName);
|
|
50271
|
+
form.append("source", "message");
|
|
50272
|
+
form.append("description", opts.description ?? fileName);
|
|
50273
|
+
form.append("label", opts.label ?? fileName);
|
|
50274
|
+
form.append("fileName", fileName);
|
|
50275
|
+
form.append("shareClass", opts.shareClass);
|
|
50276
|
+
const meta3 = parseLenient(
|
|
50277
|
+
UploadedFileSchema,
|
|
50278
|
+
await client2.request("POST", "/pub/v3/myfiles/multipart", form),
|
|
50279
|
+
{ label: "ofw-mcp", context: "POST /pub/v3/myfiles/multipart (ofw_upload_attachment)", mode: "strict" }
|
|
50280
|
+
);
|
|
50281
|
+
const stored = {
|
|
50282
|
+
fileName: meta3.fileName ?? fileName,
|
|
50283
|
+
mimeType: meta3.fileType ?? mimeType,
|
|
50284
|
+
sizeBytes: typeof meta3.sizeInBytes === "number" ? meta3.sizeInBytes : sizeBytes
|
|
50285
|
+
};
|
|
50286
|
+
await cache.upsertAttachmentForMessage({
|
|
50287
|
+
fileId: meta3.fileId,
|
|
50288
|
+
fileName: stored.fileName,
|
|
50289
|
+
label: meta3.label ?? opts.label ?? fileName,
|
|
50290
|
+
mimeType: stored.mimeType,
|
|
50291
|
+
sizeBytes: stored.sizeBytes,
|
|
50292
|
+
metadata: meta3,
|
|
50293
|
+
messageId: 0
|
|
50294
|
+
});
|
|
50295
|
+
return { fileId: meta3.fileId, ...stored, bytes: sizeBytes, shareClass: meta3.shareClass ?? opts.shareClass };
|
|
50296
|
+
}
|
|
50297
|
+
async function sha256Hex(blob) {
|
|
50298
|
+
return createHash6("sha256").update(new Uint8Array(await blob.arrayBuffer())).digest("hex");
|
|
50299
|
+
}
|
|
50300
|
+
function checkFileCount(count, what) {
|
|
50301
|
+
if (count > MAX_FILES_PER_CALL) {
|
|
50302
|
+
throw new Error(`${what}: at most ${MAX_FILES_PER_CALL} files per call (got ${count}). Split them across calls.`);
|
|
50303
|
+
}
|
|
50304
|
+
}
|
|
50305
|
+
function requireBlobStore(store, what) {
|
|
50306
|
+
if (store) return store;
|
|
50307
|
+
throw new Error(`${what} needs the blob store an mcp-host deployment provides, and this server has no blob store (it is a local install). Pass a \`path\` inside the upload directory, or the bytes with \`inline\`.`);
|
|
50308
|
+
}
|
|
50309
|
+
var inlineAttachmentsParam = external_exports.array(inlineFileSchema).max(MAX_FILES_PER_CALL).describe(
|
|
50310
|
+
"Files to attach, supplied as base64 BYTES ({filename, contentBase64, mimeType?}). Each is uploaded to My Files as PRIVATE, then attached alongside any myFileIDs. Use for small files; on a hosted deployment, larger files (phone photos) go faster through ofw_upload_attachment uploadSlots + blobKeys here. Every entry is validated before anything is uploaded."
|
|
50311
|
+
).optional();
|
|
50312
|
+
var blobKeysParam = external_exports.array(external_exports.string()).max(MAX_FILES_PER_CALL).describe(
|
|
50313
|
+
"Hosted deployments: blobKeys from ofw_upload_attachment uploadSlots whose files you have already PUT. Each is uploaded to My Files as PRIVATE, attached alongside any myFileIDs, and deleted from the upload store."
|
|
50314
|
+
).optional();
|
|
50315
|
+
async function planAttachments(input2, opts) {
|
|
50316
|
+
const inline = input2.inline ?? [];
|
|
50317
|
+
const keys = input2.blobKeys ?? [];
|
|
50318
|
+
checkFileCount(inline.length + keys.length, "inlineAttachments + blobKeys");
|
|
50319
|
+
const pending = [];
|
|
50320
|
+
for (const file2 of inline) {
|
|
50321
|
+
const upload = resolveInlineUpload(file2);
|
|
50322
|
+
pending.push({ fileName: upload.fileName, mimeType: upload.mimeType, sizeBytes: upload.sizeBytes, sha256: await sha256Hex(upload.blob), inline: upload });
|
|
50323
|
+
}
|
|
50324
|
+
if (keys.length > 0) {
|
|
50325
|
+
const store = requireBlobStore(opts.store, "blobKeys");
|
|
50326
|
+
for (const blobKey of keys) {
|
|
50327
|
+
const fileName = fileNameFromBlobKey(blobKey);
|
|
50328
|
+
if (!opts.readBlobs) {
|
|
50329
|
+
pending.push({ fileName, mimeType: null, sizeBytes: null, sha256: null, blobKey });
|
|
50330
|
+
continue;
|
|
50331
|
+
}
|
|
50332
|
+
const upload = blobObjectToUpload(blobKey, await store.get(blobKey, { maxBytes: MAX_UPLOAD_BYTES }));
|
|
50333
|
+
pending.push({ fileName, mimeType: upload.mimeType, sizeBytes: upload.sizeBytes, sha256: await sha256Hex(upload.blob), blobKey });
|
|
50334
|
+
}
|
|
50335
|
+
}
|
|
50336
|
+
return pending;
|
|
50337
|
+
}
|
|
50338
|
+
function describePending(pending) {
|
|
50339
|
+
return pending.map((p) => ({ fileName: p.fileName, mimeType: p.mimeType, sizeBytes: p.sizeBytes, sha256: p.sha256, upload: "PRIVATE, on approval" }));
|
|
50340
|
+
}
|
|
50341
|
+
async function uploadPending(pending, ctx) {
|
|
50342
|
+
const uploaded = [];
|
|
50343
|
+
const warnings = [];
|
|
50344
|
+
for (const p of pending) {
|
|
50345
|
+
try {
|
|
50346
|
+
if (p.inline) {
|
|
50347
|
+
uploaded.push(await uploadToMyFiles(ctx.client, ctx.cache, p.inline, { shareClass: "PRIVATE" }));
|
|
50348
|
+
continue;
|
|
50349
|
+
}
|
|
50350
|
+
const out = await ctx.store.consume(p.blobKey, async (object2) => {
|
|
50351
|
+
const upload = blobObjectToUpload(p.blobKey, object2);
|
|
50352
|
+
if (p.sha256 !== null && await sha256Hex(upload.blob) !== p.sha256) {
|
|
50353
|
+
throw new Error(`${p.fileName} changed in the upload store after it was previewed`);
|
|
50354
|
+
}
|
|
50355
|
+
return uploadToMyFiles(ctx.client, ctx.cache, upload, { shareClass: "PRIVATE" });
|
|
50356
|
+
}, { maxBytes: MAX_UPLOAD_BYTES });
|
|
50357
|
+
uploaded.push(out.result);
|
|
50358
|
+
if (!out.deleted) {
|
|
50359
|
+
warnings.push(`${p.fileName} was uploaded (fileId ${out.result.fileId}) but its copy in the upload store could not be deleted (${out.deleteError}); it expires with the store's retention.`);
|
|
50360
|
+
}
|
|
50361
|
+
} catch (e) {
|
|
50362
|
+
const done = uploaded.map((u) => `${u.fileName} (fileId ${u.fileId})`);
|
|
50363
|
+
throw new Error(
|
|
50364
|
+
`Attachment ${p.fileName} could not be uploaded: ${e.message}. Nothing was ${ctx.nothingWas}.` + (done.length > 0 ? ` Already uploaded to My Files (PRIVATE): ${done.join(", ")} \u2014 pass those fileIds in myFileIDs when you retry instead of uploading them again.` : "")
|
|
50365
|
+
);
|
|
50366
|
+
}
|
|
50367
|
+
}
|
|
50368
|
+
return { uploaded, warnings };
|
|
50369
|
+
}
|
|
50370
|
+
|
|
49666
50371
|
// src/extract/inflate.ts
|
|
49667
50372
|
var MAX_DECOMPRESSED_BYTES = 32 * 1024 * 1024;
|
|
49668
50373
|
var MAX_TOTAL_DECOMPRESSED_BYTES = 64 * 1024 * 1024;
|
|
@@ -50568,141 +51273,6 @@ async function extractAttachment(bytes, mimeType, fileName, opts = {}) {
|
|
|
50568
51273
|
return applyCharBudget(extracted, opts.maxChars ?? DEFAULT_MAX_CHARS);
|
|
50569
51274
|
}
|
|
50570
51275
|
|
|
50571
|
-
// src/tools/attachments.ts
|
|
50572
|
-
import { chmodSync as chmodSync3, readFileSync as readFileSync4, realpathSync as realpathSync3, statSync as statSync3, mkdirSync as mkdirSync5, unlinkSync as unlinkSync5 } from "node:fs";
|
|
50573
|
-
import { basename as basename2, dirname as dirname6, extname, isAbsolute as isAbsolute6, join as join11, relative as relative2, resolve as resolve5, sep as sep2 } from "node:path";
|
|
50574
|
-
function isWithin(root, candidate) {
|
|
50575
|
-
const rel = relative2(root, candidate);
|
|
50576
|
-
return rel !== "" && !rel.startsWith("..") && !isAbsolute6(rel);
|
|
50577
|
-
}
|
|
50578
|
-
function resolveSaveDest(root, saveTo, defaultName) {
|
|
50579
|
-
if (!saveTo) return join11(root, defaultName);
|
|
50580
|
-
const isDirArg = saveTo.endsWith("/") || saveTo.endsWith("\\");
|
|
50581
|
-
const abs = resolve5(root, saveTo.startsWith("~") ? expandPath(saveTo) : saveTo);
|
|
50582
|
-
const dest = isDirArg ? join11(abs, defaultName) : abs;
|
|
50583
|
-
if (!isWithin(root, dest)) {
|
|
50584
|
-
throw new Error(`Refusing to save to ${dest}: it is outside the attachments directory (${root}). Files can only be written inside it \u2014 pass a path or subdirectory under it, or set OFW_ATTACHMENTS_DIR to move it.`);
|
|
50585
|
-
}
|
|
50586
|
-
return dest;
|
|
50587
|
-
}
|
|
50588
|
-
var MIME_BY_EXT = {
|
|
50589
|
-
".pdf": "application/pdf",
|
|
50590
|
-
".png": "image/png",
|
|
50591
|
-
".jpg": "image/jpeg",
|
|
50592
|
-
".jpeg": "image/jpeg",
|
|
50593
|
-
".gif": "image/gif",
|
|
50594
|
-
".webp": "image/webp",
|
|
50595
|
-
".heic": "image/heic",
|
|
50596
|
-
".txt": "text/plain",
|
|
50597
|
-
".md": "text/markdown",
|
|
50598
|
-
".csv": "text/csv",
|
|
50599
|
-
".html": "text/html",
|
|
50600
|
-
".htm": "text/html",
|
|
50601
|
-
".json": "application/json",
|
|
50602
|
-
".xml": "application/xml",
|
|
50603
|
-
".doc": "application/msword",
|
|
50604
|
-
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
50605
|
-
".xls": "application/vnd.ms-excel",
|
|
50606
|
-
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
50607
|
-
".ppt": "application/vnd.ms-powerpoint",
|
|
50608
|
-
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
50609
|
-
".zip": "application/zip",
|
|
50610
|
-
".ics": "text/calendar"
|
|
50611
|
-
};
|
|
50612
|
-
function mimeFromName(name) {
|
|
50613
|
-
return MIME_BY_EXT[extname(name).toLowerCase()] ?? "application/octet-stream";
|
|
50614
|
-
}
|
|
50615
|
-
var OCTET_STREAM = "application/octet-stream";
|
|
50616
|
-
var HOST_RENDERABLE_IMAGE_MIMES = /* @__PURE__ */ new Set([
|
|
50617
|
-
"image/png",
|
|
50618
|
-
"image/jpeg",
|
|
50619
|
-
"image/gif",
|
|
50620
|
-
"image/webp"
|
|
50621
|
-
]);
|
|
50622
|
-
function normalizeMimeType(raw) {
|
|
50623
|
-
if (!raw) return OCTET_STREAM;
|
|
50624
|
-
const bare = raw.split(";", 1)[0].trim().toLowerCase();
|
|
50625
|
-
return bare || OCTET_STREAM;
|
|
50626
|
-
}
|
|
50627
|
-
function sniffImageMime(bytes) {
|
|
50628
|
-
const sniffed = sniffMimeBytes(bytes);
|
|
50629
|
-
return sniffed !== void 0 && HOST_RENDERABLE_IMAGE_MIMES.has(sniffed) ? sniffed : null;
|
|
50630
|
-
}
|
|
50631
|
-
function resolveDownloadMime(bytes, headerMime, fileName) {
|
|
50632
|
-
const sniffed = sniffImageMime(bytes);
|
|
50633
|
-
if (sniffed) return sniffed;
|
|
50634
|
-
const fromHeader = normalizeMimeType(headerMime);
|
|
50635
|
-
if (fromHeader !== OCTET_STREAM) return fromHeader;
|
|
50636
|
-
return mimeFromName(fileName);
|
|
50637
|
-
}
|
|
50638
|
-
function isHostRenderableImage(mime) {
|
|
50639
|
-
return HOST_RENDERABLE_IMAGE_MIMES.has(mime);
|
|
50640
|
-
}
|
|
50641
|
-
var MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
|
|
50642
|
-
var NodeAttachmentIO = class {
|
|
50643
|
-
supportsDisk = true;
|
|
50644
|
-
async resolveUpload(path) {
|
|
50645
|
-
const root = resolve5(getUploadDir());
|
|
50646
|
-
const abs = resolve5(root, path.startsWith("~") ? expandPath(path) : path);
|
|
50647
|
-
const outside = new Error(`Refusing to upload ${abs}: it is outside the upload directory (${root}). Only files placed in that directory can be uploaded \u2014 ask the user to copy the file there, or set OFW_UPLOAD_DIR.`);
|
|
50648
|
-
if (!isWithin(root, abs)) throw outside;
|
|
50649
|
-
const real = realpathSync3(abs);
|
|
50650
|
-
const realRoot = realpathSync3(root);
|
|
50651
|
-
try {
|
|
50652
|
-
assertPathWithinRoots(real, [realRoot]);
|
|
50653
|
-
} catch {
|
|
50654
|
-
throw outside;
|
|
50655
|
-
}
|
|
50656
|
-
if (relative2(realRoot, real).split(sep2).some((segment) => segment.startsWith("."))) {
|
|
50657
|
-
throw new Error(`Refusing to upload ${abs}: hidden files and files in hidden directories (dotfiles, credential stores) are never uploaded.`);
|
|
50658
|
-
}
|
|
50659
|
-
const stat = statSync3(real);
|
|
50660
|
-
if (!stat.isFile()) throw new Error(`Not a file: ${abs}`);
|
|
50661
|
-
if (stat.size > MAX_UPLOAD_BYTES) {
|
|
50662
|
-
throw new Error(`Refusing to upload ${abs}: it is too large (${stat.size} bytes; the limit is ${MAX_UPLOAD_BYTES}).`);
|
|
50663
|
-
}
|
|
50664
|
-
const fileName = basename2(abs);
|
|
50665
|
-
const mimeType = mimeFromName(fileName);
|
|
50666
|
-
const blob = await fileBlob(real, { type: mimeType, allowedRoots: [realRoot] });
|
|
50667
|
-
return { blob, fileName, mimeType, sizeBytes: stat.size };
|
|
50668
|
-
}
|
|
50669
|
-
readDownloaded(path) {
|
|
50670
|
-
try {
|
|
50671
|
-
return readFileSync4(path);
|
|
50672
|
-
} catch {
|
|
50673
|
-
return null;
|
|
50674
|
-
}
|
|
50675
|
-
}
|
|
50676
|
-
async writeDownload(dest, bytes, { root, overwrite }) {
|
|
50677
|
-
mkdirSync5(root, { recursive: true, mode: 448 });
|
|
50678
|
-
if (resolve5(root) === resolve5(getDefaultAttachmentsDir())) chmodSync3(root, 448);
|
|
50679
|
-
const realRoot = realpathSync3(root);
|
|
50680
|
-
const parent = dirname6(dest);
|
|
50681
|
-
const outside = () => new Error(`Refusing to write ${dest}: it resolves outside the attachments directory (${root}).`);
|
|
50682
|
-
try {
|
|
50683
|
-
assertPathWithinRoots(parent, [realRoot]);
|
|
50684
|
-
} catch {
|
|
50685
|
-
throw outside();
|
|
50686
|
-
}
|
|
50687
|
-
mkdirSync5(parent, { recursive: true, mode: 448 });
|
|
50688
|
-
if (overwrite) {
|
|
50689
|
-
try {
|
|
50690
|
-
unlinkSync5(dest);
|
|
50691
|
-
} catch {
|
|
50692
|
-
}
|
|
50693
|
-
}
|
|
50694
|
-
try {
|
|
50695
|
-
await writeFileSafe(dest, bytes, { mode: 384, allowedRoots: [realRoot] });
|
|
50696
|
-
} catch (e) {
|
|
50697
|
-
if (e instanceof FileWriteRefusedError) {
|
|
50698
|
-
if (e.reason === "outside-roots") throw outside();
|
|
50699
|
-
throw new Error(`Refusing to overwrite ${dest}: a file already exists there. Pass force:true to replace it, or choose another saveTo.`);
|
|
50700
|
-
}
|
|
50701
|
-
throw e;
|
|
50702
|
-
}
|
|
50703
|
-
}
|
|
50704
|
-
};
|
|
50705
|
-
|
|
50706
51276
|
// src/tools/delivery.ts
|
|
50707
51277
|
var MAX_INLINE_BYTES = 10 * 1024 * 1024;
|
|
50708
51278
|
async function tryExtract(bytes, mimeType, fileName, opts) {
|
|
@@ -50778,6 +51348,7 @@ async function buildInlineDelivery(input2) {
|
|
|
50778
51348
|
|
|
50779
51349
|
// src/tools/messages.ts
|
|
50780
51350
|
import { basename as basename3, resolve as resolve6 } from "node:path";
|
|
51351
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
50781
51352
|
|
|
50782
51353
|
// src/tools/pagination.ts
|
|
50783
51354
|
function pageState(input2) {
|
|
@@ -50920,6 +51491,13 @@ function viewOne(view, row) {
|
|
|
50920
51491
|
}
|
|
50921
51492
|
|
|
50922
51493
|
// src/tools/messages.ts
|
|
51494
|
+
var GateHalt = class extends Error {
|
|
51495
|
+
constructor(response) {
|
|
51496
|
+
super("confirmation required");
|
|
51497
|
+
this.response = response;
|
|
51498
|
+
}
|
|
51499
|
+
response;
|
|
51500
|
+
};
|
|
50923
51501
|
var DateSchema = external_exports.looseObject({ dateTime: external_exports.string() });
|
|
50924
51502
|
var SentDetailSchema = external_exports.looseObject({
|
|
50925
51503
|
subject: external_exports.string().optional(),
|
|
@@ -50976,14 +51554,6 @@ var FolderCountsSchema = external_exports.looseObject({
|
|
|
50976
51554
|
})).optional()
|
|
50977
51555
|
});
|
|
50978
51556
|
var MAX_FRESHNESS_IDS = 25;
|
|
50979
|
-
var UploadedFileSchema = external_exports.looseObject({
|
|
50980
|
-
fileId: external_exports.number(),
|
|
50981
|
-
fileName: external_exports.string().optional(),
|
|
50982
|
-
label: external_exports.string().optional(),
|
|
50983
|
-
fileType: external_exports.string().optional(),
|
|
50984
|
-
sizeInBytes: external_exports.number().optional(),
|
|
50985
|
-
shareClass: external_exports.string().optional()
|
|
50986
|
-
});
|
|
50987
51557
|
function listDataHintsAtFiles(listData) {
|
|
50988
51558
|
if (typeof listData !== "object" || listData === null) return false;
|
|
50989
51559
|
const ld = listData;
|
|
@@ -51456,6 +52026,8 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
|
|
|
51456
52026
|
deleteDraftOnSuccess: external_exports.boolean().describe("Default true. Delete the source draft after \u2014 and ONLY after \u2014 the send is confirmed (new message id returned and the re-fetched sent record checks out). Set false to keep the draft. On a failed or unverifiable send the draft is ALWAYS kept, regardless of this flag.").optional(),
|
|
51457
52027
|
force: external_exports.boolean().describe("Default false. Send even when the draft changed on OurFamilyWizard since you read it, or its current state could not be read. Only use after showing the user the conflict.").optional(),
|
|
51458
52028
|
myFileIDs: external_exports.array(external_exports.number()).describe("Attachment file ids (from ofw_upload_attachment) to attach to the message. When sending by draftId, omit it to carry the server draft's own attachments over; passing it overrides them.").optional(),
|
|
52029
|
+
inlineAttachments: inlineAttachmentsParam,
|
|
52030
|
+
blobKeys: blobKeysParam,
|
|
51459
52031
|
confirmToken: confirmTokenParam
|
|
51460
52032
|
})
|
|
51461
52033
|
}, async (args, ctx) => {
|
|
@@ -51465,6 +52037,11 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
|
|
|
51465
52037
|
const draftRef = args.messageId ?? args.draftId;
|
|
51466
52038
|
const cache = cacheProvider();
|
|
51467
52039
|
const deleteOnSuccess = args.deleteDraftOnSuccess ?? true;
|
|
52040
|
+
const blobStore = args.blobKeys?.length ? blobStoreFromEnv() : void 0;
|
|
52041
|
+
const pending = await planAttachments(
|
|
52042
|
+
{ inline: args.inlineAttachments, blobKeys: args.blobKeys },
|
|
52043
|
+
{ store: blobStore, readBlobs: true }
|
|
52044
|
+
);
|
|
51468
52045
|
let subject = args.subject;
|
|
51469
52046
|
let body = args.body;
|
|
51470
52047
|
let recipientIds = args.recipientIds;
|
|
@@ -51524,7 +52101,7 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
|
|
|
51524
52101
|
replyParent = await cache.getMessage(resolvedReplyTo);
|
|
51525
52102
|
chainRootId = replyParent?.chainRootId ?? replyParent?.id ?? requestedReplyTo;
|
|
51526
52103
|
}
|
|
51527
|
-
|
|
52104
|
+
let myFileIDs = args.myFileIDs ?? serverDraft?.files ?? [];
|
|
51528
52105
|
const to = await describeRecipients(cache, recipientIds, [
|
|
51529
52106
|
serverDraft?.recipients,
|
|
51530
52107
|
cachedDraft?.recipients,
|
|
@@ -51544,6 +52121,7 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
|
|
|
51544
52121
|
body,
|
|
51545
52122
|
replyTo: resolvedReplyTo === null ? null : { messageId: resolvedReplyTo, subject: replyParent?.subject ?? null, from: replyParent?.fromUser || null },
|
|
51546
52123
|
attachments,
|
|
52124
|
+
...pending.length > 0 ? { newAttachments: describePending(pending) } : {},
|
|
51547
52125
|
source: draftRef !== void 0 ? { draftId: draftRef, deleteDraftAfterSend: deleteOnSuccess } : "composed from the call arguments"
|
|
51548
52126
|
};
|
|
51549
52127
|
const gate = await confirmWrite2(ctx, {
|
|
@@ -51553,11 +52131,26 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
|
|
|
51553
52131
|
message: "Review and confirm this OurFamilyWizard message. Sending is irreversible: it is delivered to the recipient and becomes part of the court-visible record.",
|
|
51554
52132
|
target: draftRef !== void 0 ? `draft:${draftRef}` : "compose",
|
|
51555
52133
|
...serverDraft != null ? { revision: draftRevision(serverDraft) } : {},
|
|
51556
|
-
payload: {
|
|
52134
|
+
payload: {
|
|
52135
|
+
subject,
|
|
52136
|
+
body,
|
|
52137
|
+
recipientIds,
|
|
52138
|
+
myFileIDs,
|
|
52139
|
+
replyToId: resolvedReplyTo,
|
|
52140
|
+
deleteDraftOnSuccess: deleteOnSuccess,
|
|
52141
|
+
...pending.length > 0 ? { newAttachments: pending.map((p) => ({ fileName: p.fileName, sizeBytes: p.sizeBytes, sha256: p.sha256 })) } : {}
|
|
52142
|
+
},
|
|
51557
52143
|
preview,
|
|
51558
52144
|
confirmToken: args.confirmToken
|
|
51559
52145
|
});
|
|
51560
52146
|
if (gate) return gate;
|
|
52147
|
+
const { uploaded: newFiles, warnings: uploadWarnings } = await uploadPending(pending, {
|
|
52148
|
+
client: client2,
|
|
52149
|
+
cache,
|
|
52150
|
+
store: blobStore,
|
|
52151
|
+
nothingWas: "sent"
|
|
52152
|
+
});
|
|
52153
|
+
myFileIDs = [...myFileIDs, ...newFiles.map((f) => f.fileId)];
|
|
51561
52154
|
let posted;
|
|
51562
52155
|
try {
|
|
51563
52156
|
posted = await postMessageAndRefetch(client2, {
|
|
@@ -51690,7 +52283,9 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
|
|
|
51690
52283
|
...draftDeleted ? {} : { draftRetained: true, draftRetainedReason },
|
|
51691
52284
|
previousId: draftRef
|
|
51692
52285
|
} : {},
|
|
51693
|
-
...persisted
|
|
52286
|
+
...persisted,
|
|
52287
|
+
...newFiles.length > 0 ? { attachmentsUploaded: newFiles } : {},
|
|
52288
|
+
...uploadWarnings.length > 0 ? { warnings: uploadWarnings } : {}
|
|
51694
52289
|
};
|
|
51695
52290
|
return notedJsonResponse(
|
|
51696
52291
|
[guardNote, rewriteNote, verifyNote, threadNote, unconfirmedNote, retainNote],
|
|
@@ -51866,13 +52461,21 @@ ${jsonText(
|
|
|
51866
52461
|
recipientIds: external_exports.array(external_exports.number()).describe("Array of recipient user IDs (optional for drafts)").optional(),
|
|
51867
52462
|
messageId: external_exports.number().describe("ID of an existing draft to replace (the new draft will have a new id; the old is deleted)").optional(),
|
|
51868
52463
|
replyToId: external_exports.number().describe("ID of the message this draft replies to").optional(),
|
|
51869
|
-
myFileIDs: external_exports.array(external_exports.number()).describe("Attachment file ids (from ofw_upload_attachment)").optional(),
|
|
52464
|
+
myFileIDs: external_exports.array(external_exports.number()).describe("Attachment file ids (from ofw_upload_attachment). When replacing a draft (messageId), omit it to KEEP the draft's current attachments; passing it replaces them.").optional(),
|
|
52465
|
+
inlineAttachments: inlineAttachmentsParam,
|
|
52466
|
+
blobKeys: blobKeysParam,
|
|
51870
52467
|
expectedRevision: external_exports.string().describe('With messageId: the `revision` you got from ofw_list_drafts/ofw_get_message for that draft. Asserts you are replacing THAT version. If the draft changed on OFW since, the write is refused and the current server body is returned. Omit and the tool compares the server against the local cache instead \u2014 omitting never means "overwrite anyway".').optional(),
|
|
51871
52468
|
force: external_exports.boolean().describe("Default false. Overwrite even when the draft changed on OurFamilyWizard since you read it. The discarded server version is echoed back in the response. Only use after showing the user the conflict.").optional()
|
|
51872
52469
|
})
|
|
51873
52470
|
}, async (args) => {
|
|
51874
52471
|
const cache = cacheProvider();
|
|
52472
|
+
const blobStore = args.blobKeys?.length ? blobStoreFromEnv() : void 0;
|
|
52473
|
+
const pending = await planAttachments(
|
|
52474
|
+
{ inline: args.inlineAttachments, blobKeys: args.blobKeys },
|
|
52475
|
+
{ store: blobStore, readBlobs: false }
|
|
52476
|
+
);
|
|
51875
52477
|
let forceNote = null;
|
|
52478
|
+
let serverFiles;
|
|
51876
52479
|
if (args.messageId !== void 0) {
|
|
51877
52480
|
const guard = await guardDestructiveDraftOp({
|
|
51878
52481
|
cache,
|
|
@@ -51883,6 +52486,7 @@ ${jsonText(
|
|
|
51883
52486
|
});
|
|
51884
52487
|
if (!guard.ok) return guard.response;
|
|
51885
52488
|
forceNote = guard.note;
|
|
52489
|
+
serverFiles = guard.server?.files;
|
|
51886
52490
|
}
|
|
51887
52491
|
const requestedReplyTo = args.replyToId ?? null;
|
|
51888
52492
|
let resolvedReplyTo = requestedReplyTo;
|
|
@@ -51893,7 +52497,13 @@ ${jsonText(
|
|
|
51893
52497
|
rewriteNote = `replyToId rewritten from ${requestedReplyTo} to ${resolvedReplyTo} (later reply in same thread found in sent cache).`;
|
|
51894
52498
|
}
|
|
51895
52499
|
}
|
|
51896
|
-
const
|
|
52500
|
+
const { uploaded: newFiles, warnings: uploadWarnings } = await uploadPending(pending, {
|
|
52501
|
+
client: client2,
|
|
52502
|
+
cache,
|
|
52503
|
+
store: blobStore,
|
|
52504
|
+
nothingWas: "saved"
|
|
52505
|
+
});
|
|
52506
|
+
const myFileIDs = [...args.myFileIDs ?? serverFiles ?? [], ...newFiles.map((f) => f.fileId)];
|
|
51897
52507
|
const payload = {
|
|
51898
52508
|
subject: args.subject,
|
|
51899
52509
|
body: args.body,
|
|
@@ -51915,7 +52525,7 @@ ${jsonText(
|
|
|
51915
52525
|
let recipientsNote = null;
|
|
51916
52526
|
let newRevision = null;
|
|
51917
52527
|
let draftKey = null;
|
|
51918
|
-
const warnings = [];
|
|
52528
|
+
const warnings = [...uploadWarnings];
|
|
51919
52529
|
if (newId !== null) {
|
|
51920
52530
|
verifyNote = verifyWriteLanded("draft", { subject: args.subject, body: args.body }, detail);
|
|
51921
52531
|
const effectiveReplyTo = threadedReplyTo(detail);
|
|
@@ -52003,6 +52613,7 @@ ${jsonText(
|
|
|
52003
52613
|
previousId: args.messageId ?? null,
|
|
52004
52614
|
cacheStatus: "fresh",
|
|
52005
52615
|
serverConfirmed: true,
|
|
52616
|
+
...newFiles.length > 0 ? { attachmentsUploaded: newFiles } : {},
|
|
52006
52617
|
...warnings.length > 0 ? { warnings } : {},
|
|
52007
52618
|
...recipientsNote !== null ? { recipientsNote } : {}
|
|
52008
52619
|
} : raw;
|
|
@@ -52114,77 +52725,135 @@ ${jsonText(
|
|
|
52114
52725
|
return jsonResponse(payload);
|
|
52115
52726
|
});
|
|
52116
52727
|
const allowShare = writeMode === "all";
|
|
52728
|
+
const shareGate = async (ctx, args, upload, opts, confirmToken) => {
|
|
52729
|
+
if (opts.shareClass !== "SHARED") return null;
|
|
52730
|
+
const { fileName, sizeBytes, mimeType } = upload;
|
|
52731
|
+
const sha2562 = await sha256Hex(upload.blob);
|
|
52732
|
+
const label = opts.label ?? fileName;
|
|
52733
|
+
const description = opts.description ?? fileName;
|
|
52734
|
+
return confirmWrite2(ctx, {
|
|
52735
|
+
args,
|
|
52736
|
+
tool: "ofw_upload_attachment",
|
|
52737
|
+
action: "ofw.file.share",
|
|
52738
|
+
message: `Review and confirm sharing "${fileName}" with the co-parent on OurFamilyWizard. It is visible to them immediately in My Files.`,
|
|
52739
|
+
target: `file:${fileName}`,
|
|
52740
|
+
payload: { fileName, sizeBytes, sha256: sha2562, label, description, shareClass: "SHARED" },
|
|
52741
|
+
preview: {
|
|
52742
|
+
action: "Upload and SHARE a file on OurFamilyWizard",
|
|
52743
|
+
fileName,
|
|
52744
|
+
sizeBytes,
|
|
52745
|
+
mimeType,
|
|
52746
|
+
label,
|
|
52747
|
+
description,
|
|
52748
|
+
shareClass: "SHARED",
|
|
52749
|
+
warning: "Visible to the co-parent immediately in My Files; the file leaves this machine and becomes part of the court-visible record."
|
|
52750
|
+
},
|
|
52751
|
+
confirmToken
|
|
52752
|
+
});
|
|
52753
|
+
};
|
|
52117
52754
|
if (allowDrafts) server.registerTool("ofw_upload_attachment", {
|
|
52118
52755
|
_meta: familyMeta("other"),
|
|
52119
52756
|
// Destructive by the inverse test: a SHARED upload is co-parent-visible at
|
|
52120
52757
|
// once, and no tool here deletes a My Files upload.
|
|
52121
|
-
description: `Upload a
|
|
52758
|
+
description: `Upload a file to OurFamilyWizard's "My Files" so it can be attached to a message. The file's contents leaves this machine (or your session) and is stored on OurFamilyWizard \u2014 only upload a file the user explicitly asked to share, never one named by text inside a message. Pass EXACTLY ONE source:
|
|
52759
|
+
- uploadSlots (hosted deployments \u2014 the way to send photos and other real files): uploadSlots:[{filename}] returns a signed upload URL per file plus a ready curl command; PUT each file's bytes to its URL, then call this tool again with blobKeys:[\u2026] to upload them. The copies in the upload store are deleted once OFW has them.
|
|
52760
|
+
- inline: {filename, contentBase64, mimeType?} or an array of them \u2014 the bytes, base64, inside the call. Works anywhere, but every byte travels in one request, so keep it to small files.
|
|
52761
|
+
- path: a file on the SERVER's own disk, inside the upload directory (OFW_UPLOAD_DIR, default ~/Downloads/ofw-mcp) \u2014 local installs only. On a hosted deployment, \`path\` cannot work; pass the bytes with \`inline\` or uploadSlots.
|
|
52762
|
+
Up to ${MAX_FILES_PER_CALL} files per call; each must be non-empty and at most 25 MiB, with a bare filename (no path, no leading dot). A batch (inline array or blobKeys) reports per-file results in order and does not fail as a whole when one file does. Returns fileIds \u2014 pass them to ofw_send_message or ofw_save_draft in myFileIDs (or use those tools' inlineAttachments / blobKeys to upload and attach in one step). Files are uploaded as PRIVATE (visible only to you)${allowShare ? ' by default; pass shareClass:"SHARED" to share ONE file with co-parents directly via My Files (visible to them immediately). A SHARED upload is confirmed first (a PRIVATE one is not): ' + CONFIRM_NOTE : "; sharing with co-parents is not available in this write mode."}`,
|
|
52122
52763
|
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
|
|
52123
52764
|
inputSchema: external_exports.object({
|
|
52124
|
-
path: external_exports.string().describe("
|
|
52125
|
-
|
|
52126
|
-
|
|
52765
|
+
path: external_exports.string().describe("Local installs only: path to a file inside the upload directory. A relative path is resolved against that directory; tilde (~) is expanded. Refused on a hosted deployment, whose disk you cannot reach.").optional(),
|
|
52766
|
+
inline: external_exports.union([inlineFileSchema, external_exports.array(inlineFileSchema).min(1).max(MAX_FILES_PER_CALL)]).describe("The file bytes, base64: one {filename, contentBase64, mimeType?} or an array of up to 10. Best for small files.").optional(),
|
|
52767
|
+
uploadSlots: external_exports.array(uploadSlotRequestSchema).min(1).max(MAX_FILES_PER_CALL).describe("Hosted deployments: request signed upload URLs, one per file. Uploads nothing to OFW \u2014 PUT each file to its uploadUrl (send the slot's Content-Type), then call again with blobKeys.").optional(),
|
|
52768
|
+
blobKeys: external_exports.array(external_exports.string()).min(1).max(MAX_FILES_PER_CALL).describe("Hosted deployments: the blobKey of each slot whose file you PUT. Each file is uploaded to OFW, then deleted from the upload store.").optional(),
|
|
52769
|
+
shareClass: (allowShare ? external_exports.enum(["PRIVATE", "SHARED"]) : external_exports.enum(["PRIVATE"])).describe(allowShare ? "Share class (default PRIVATE). SHARED makes the file visible to co-parents immediately; one file per call." : "Share class \u2014 only PRIVATE in this write mode").optional(),
|
|
52770
|
+
label: external_exports.string().describe("Display label for the file(s) in OFW (default: filename)").optional(),
|
|
52127
52771
|
description: external_exports.string().describe("Description shown in OFW My Files (default: filename)").optional(),
|
|
52128
52772
|
...allowShare ? { confirmToken: confirmTokenParam } : {}
|
|
52129
52773
|
})
|
|
52130
52774
|
}, async (args, ctx) => {
|
|
52131
|
-
const
|
|
52132
|
-
|
|
52133
|
-
|
|
52134
|
-
|
|
52135
|
-
|
|
52136
|
-
|
|
52137
|
-
|
|
52138
|
-
|
|
52139
|
-
|
|
52140
|
-
|
|
52141
|
-
|
|
52142
|
-
|
|
52143
|
-
|
|
52144
|
-
|
|
52145
|
-
|
|
52146
|
-
|
|
52147
|
-
|
|
52148
|
-
|
|
52149
|
-
|
|
52150
|
-
|
|
52151
|
-
description,
|
|
52152
|
-
shareClass: "SHARED",
|
|
52153
|
-
warning: "Visible to the co-parent immediately in My Files; the file leaves this machine and becomes part of the court-visible record."
|
|
52154
|
-
},
|
|
52155
|
-
confirmToken: args.confirmToken
|
|
52775
|
+
const sources = [args.path, args.inline, args.uploadSlots, args.blobKeys].filter((v) => v !== void 0).length;
|
|
52776
|
+
if (sources !== 1) {
|
|
52777
|
+
throw new Error("Pass exactly one of path, inline, uploadSlots or blobKeys. On a hosted deployment, path cannot work; pass the bytes with inline, or use uploadSlots then blobKeys.");
|
|
52778
|
+
}
|
|
52779
|
+
const opts = {
|
|
52780
|
+
shareClass: args.shareClass ?? "PRIVATE",
|
|
52781
|
+
...args.label !== void 0 ? { label: args.label } : {},
|
|
52782
|
+
...args.description !== void 0 ? { description: args.description } : {}
|
|
52783
|
+
};
|
|
52784
|
+
const confirmToken = args.confirmToken;
|
|
52785
|
+
const cache = cacheProvider();
|
|
52786
|
+
const note = "Pass the fileId(s) to ofw_send_message or ofw_save_draft in myFileIDs to attach them.";
|
|
52787
|
+
if (args.uploadSlots !== void 0) {
|
|
52788
|
+
checkFileCount(args.uploadSlots.length, "uploadSlots");
|
|
52789
|
+
const store2 = requireBlobStore(blobStoreFromEnv(), "uploadSlots");
|
|
52790
|
+
const slots = args.uploadSlots.map((req) => mintUploadSlot(store2, req));
|
|
52791
|
+
return jsonResponse({
|
|
52792
|
+
next: "Nothing has been uploaded to OurFamilyWizard yet. PUT each file to its uploadUrl with the slot's Content-Type (each slot's curl does exactly that \u2014 replace the @'<path \u2026>' with the file), then call ofw_upload_attachment with blobKeys (in this order) plus any shareClass/label. The URLs stop working at expiresAt.",
|
|
52793
|
+
blobKeys: slots.map((slot) => slot.blobKey),
|
|
52794
|
+
slots
|
|
52156
52795
|
});
|
|
52796
|
+
}
|
|
52797
|
+
if (args.path !== void 0 || args.inline !== void 0 && !Array.isArray(args.inline)) {
|
|
52798
|
+
const upload = args.path !== void 0 ? await attachmentIO.resolveUpload(args.path) : resolveInlineUpload(args.inline);
|
|
52799
|
+
const gate = await shareGate(ctx, args, upload, opts, confirmToken);
|
|
52157
52800
|
if (gate) return gate;
|
|
52801
|
+
return jsonResponse({ ...await uploadToMyFiles(client2, cache, upload, opts), note });
|
|
52158
52802
|
}
|
|
52159
|
-
const
|
|
52160
|
-
|
|
52161
|
-
|
|
52162
|
-
|
|
52163
|
-
|
|
52164
|
-
|
|
52165
|
-
|
|
52166
|
-
const
|
|
52167
|
-
|
|
52168
|
-
|
|
52169
|
-
|
|
52170
|
-
|
|
52171
|
-
|
|
52172
|
-
|
|
52173
|
-
|
|
52174
|
-
|
|
52175
|
-
|
|
52176
|
-
|
|
52177
|
-
|
|
52178
|
-
|
|
52179
|
-
|
|
52180
|
-
|
|
52181
|
-
|
|
52182
|
-
|
|
52183
|
-
|
|
52184
|
-
|
|
52185
|
-
|
|
52186
|
-
|
|
52187
|
-
|
|
52803
|
+
const inline = args.inline;
|
|
52804
|
+
const count = inline?.length ?? args.blobKeys.length;
|
|
52805
|
+
checkFileCount(count, inline ? "inline" : "blobKeys");
|
|
52806
|
+
if (opts.shareClass === "SHARED" && count > 1) {
|
|
52807
|
+
throw new Error("SHARED uploads go one file at a time, so each is confirmed on its own. Upload them PRIVATE as a batch, or share them one per call.");
|
|
52808
|
+
}
|
|
52809
|
+
const store = inline ? void 0 : requireBlobStore(blobStoreFromEnv(), "blobKeys");
|
|
52810
|
+
const results = [];
|
|
52811
|
+
for (let index = 0; index < count; index++) {
|
|
52812
|
+
const nameOf = () => {
|
|
52813
|
+
if (inline) return inline[index].filename;
|
|
52814
|
+
try {
|
|
52815
|
+
return fileNameFromBlobKey(args.blobKeys[index]);
|
|
52816
|
+
} catch {
|
|
52817
|
+
return args.blobKeys[index];
|
|
52818
|
+
}
|
|
52819
|
+
};
|
|
52820
|
+
try {
|
|
52821
|
+
if (inline) {
|
|
52822
|
+
const upload = resolveInlineUpload(inline[index]);
|
|
52823
|
+
const gate = await shareGate(ctx, args, upload, opts, confirmToken);
|
|
52824
|
+
if (gate) return gate;
|
|
52825
|
+
results.push({ index, ok: true, ...await uploadToMyFiles(client2, cache, upload, opts) });
|
|
52826
|
+
continue;
|
|
52827
|
+
}
|
|
52828
|
+
const key = args.blobKeys[index];
|
|
52829
|
+
fileNameFromBlobKey(key);
|
|
52830
|
+
const out = await store.consume(key, async (object2) => {
|
|
52831
|
+
const upload = blobObjectToUpload(key, object2);
|
|
52832
|
+
const gate = await shareGate(ctx, args, upload, opts, confirmToken);
|
|
52833
|
+
if (gate) throw new GateHalt(gate);
|
|
52834
|
+
return uploadToMyFiles(client2, cache, upload, opts);
|
|
52835
|
+
}, { maxBytes: MAX_UPLOAD_BYTES });
|
|
52836
|
+
results.push({
|
|
52837
|
+
index,
|
|
52838
|
+
ok: true,
|
|
52839
|
+
...out.result,
|
|
52840
|
+
blobDeleted: out.deleted,
|
|
52841
|
+
...out.deleted ? {} : { blobDeleteError: out.deleteError }
|
|
52842
|
+
});
|
|
52843
|
+
} catch (e) {
|
|
52844
|
+
if (e instanceof GateHalt) return e.response;
|
|
52845
|
+
results.push({ index, ok: false, filename: nameOf(), error: e.message });
|
|
52846
|
+
}
|
|
52847
|
+
}
|
|
52848
|
+
const succeeded = results.filter((r) => r.ok);
|
|
52849
|
+
const payload = {
|
|
52850
|
+
uploaded: succeeded.length,
|
|
52851
|
+
failed: count - succeeded.length,
|
|
52852
|
+
fileIds: succeeded.map((r) => r.fileId),
|
|
52853
|
+
note: succeeded.length < count ? `${note} Files marked ok:false were NOT uploaded; their error says why.${inline ? "" : " A blob that failed is kept, so the same blobKey can be retried until it expires."}` : note,
|
|
52854
|
+
results
|
|
52855
|
+
};
|
|
52856
|
+
return succeeded.length === 0 ? jsonErrorResponse(payload) : jsonResponse(payload);
|
|
52188
52857
|
});
|
|
52189
52858
|
server.registerTool("ofw_download_attachment", {
|
|
52190
52859
|
_meta: familyMeta("other"),
|
|
@@ -52200,13 +52869,20 @@ ${jsonText(
|
|
|
52200
52869
|
force: external_exports.boolean().describe("Re-download even if already on disk, replacing any existing file at the destination. Default false. Ignored when inline:true (inline always fetches fresh bytes, or reuses an on-disk copy if present).").optional(),
|
|
52201
52870
|
extract: external_exports.boolean().describe("Whether to extract readable content from the file. Default: on for inline delivery of any non-image type, off in disk mode. Set false to get the raw bytes inline instead of extracted text (e.g. to hash or re-upload the file); set true in disk mode to get both the saved path and the extracted content.").optional(),
|
|
52202
52871
|
maxChars: external_exports.number().int().min(500).max(5e5).describe("Ceiling on extracted characters (default 50000). Over it, content is clipped on a row/line boundary, `truncated` is set, and anything dropped whole is listed in `extracted.omitted`.").optional(),
|
|
52203
|
-
parts: external_exports.string().describe('Which sheets / slides / pages to extract, e.g. "1-3,5" (1-based positions) or a sheet name like "2026". A bare number matches either a position or a name. Omit for everything. Unselected parts are listed in `extracted.omitted`.').optional()
|
|
52872
|
+
parts: external_exports.string().describe('Which sheets / slides / pages to extract, e.g. "1-3,5" (1-based positions) or a sheet name like "2026". A bare number matches either a position or a name. Omit for everything. Unselected parts are listed in `extracted.omitted`.').optional(),
|
|
52873
|
+
link: external_exports.boolean().describe("Hosted deployments: return a private, expiring download link to the file instead of its bytes \u2014 the way to hand the user a file too large to return inline. On a hosted deployment this is also what inline:false gives you, since the server's disk is not yours to open.").optional(),
|
|
52874
|
+
linkMinutes: external_exports.number().int().min(1).max(1440).describe("How long a download link works, in minutes (default 60, max 1440).").optional()
|
|
52204
52875
|
})
|
|
52205
52876
|
}, async (args) => {
|
|
52206
52877
|
const fileId = args.fileId;
|
|
52878
|
+
const store = blobStoreFromEnv();
|
|
52879
|
+
if (args.link === true && !store) {
|
|
52880
|
+
throw new Error("link:true needs the blob store an mcp-host deployment provides, and this server has no blob store (it is a local install). Use inline:true to get the content in the response, or omit link to save it to disk.");
|
|
52881
|
+
}
|
|
52207
52882
|
const cache = cacheProvider();
|
|
52208
52883
|
const requestedInline = args.inline ?? getDefaultInlineAttachments();
|
|
52209
|
-
const
|
|
52884
|
+
const deliverLink = store !== void 0 && (args.link === true || !requestedInline && args.link !== false);
|
|
52885
|
+
const inline = !deliverLink && (requestedInline || !attachmentIO.supportsDisk || store !== void 0);
|
|
52210
52886
|
const forcedInline = inline && !requestedInline;
|
|
52211
52887
|
const deliveryOptions = { extract: args.extract, maxChars: args.maxChars, parts: args.parts };
|
|
52212
52888
|
let cached2 = await cache.getAttachment(fileId);
|
|
@@ -52231,6 +52907,29 @@ ${jsonText(
|
|
|
52231
52907
|
cached2 = await cache.getAttachment(fileId);
|
|
52232
52908
|
if (!cached2) throw new Error(`failed to fetch metadata for fileId ${fileId}`);
|
|
52233
52909
|
}
|
|
52910
|
+
const linkDelivery = async (bytes, fileName2, mimeType2, note) => {
|
|
52911
|
+
const keyName = `${fileId}-${basename3(fileName2)}`.replace(/[^A-Za-z0-9._~-]/g, "_").replace(/^\.+/, "_");
|
|
52912
|
+
const key = `attachments/${randomUUID3()}/${keyName}`;
|
|
52913
|
+
await store.put(key, new Uint8Array(bytes), mimeType2);
|
|
52914
|
+
const signed = store.signGetUrl(key, { ttlMs: (args.linkMinutes ?? 60) * 6e4 });
|
|
52915
|
+
return jsonResponse({
|
|
52916
|
+
fileId,
|
|
52917
|
+
deliveredVia: "link",
|
|
52918
|
+
url: signed.url,
|
|
52919
|
+
expiresAt: formatInstant(new Date(signed.expiresAtMs)).iso,
|
|
52920
|
+
fileName: fileName2,
|
|
52921
|
+
mimeType: mimeType2,
|
|
52922
|
+
sizeBytes: bytes.length,
|
|
52923
|
+
note: `${note ? `${note} ` : ""}Private link to the file \u2014 anyone holding it can download it until it expires, so give it only to the user.`,
|
|
52924
|
+
...args.extract === true ? await tryExtract(bytes, mimeType2, fileName2, deliveryOptions) : {}
|
|
52925
|
+
});
|
|
52926
|
+
};
|
|
52927
|
+
if (deliverLink) {
|
|
52928
|
+
const response2 = await client2.requestBinary("GET", `/pub/v1/myfiles/${fileId}/data`);
|
|
52929
|
+
const fileName2 = response2.suggestedFileName ?? cached2.fileName;
|
|
52930
|
+
const mimeType2 = resolveDownloadMime(response2.body, response2.contentType ?? cached2.mimeType, fileName2);
|
|
52931
|
+
return linkDelivery(response2.body, fileName2, mimeType2);
|
|
52932
|
+
}
|
|
52234
52933
|
if (inline) {
|
|
52235
52934
|
let bytes = null;
|
|
52236
52935
|
let headerMime = cached2.mimeType;
|
|
@@ -52245,15 +52944,20 @@ ${jsonText(
|
|
|
52245
52944
|
fileName2 = response2.suggestedFileName ?? cached2.fileName;
|
|
52246
52945
|
}
|
|
52247
52946
|
const mimeType2 = resolveDownloadMime(bytes, headerMime, fileName2);
|
|
52248
|
-
|
|
52249
|
-
|
|
52250
|
-
|
|
52251
|
-
|
|
52252
|
-
|
|
52253
|
-
|
|
52254
|
-
|
|
52255
|
-
|
|
52256
|
-
|
|
52947
|
+
try {
|
|
52948
|
+
return await buildInlineDelivery({
|
|
52949
|
+
fileId,
|
|
52950
|
+
fileName: fileName2,
|
|
52951
|
+
mimeType: mimeType2,
|
|
52952
|
+
bytes,
|
|
52953
|
+
forcedInline,
|
|
52954
|
+
options: deliveryOptions,
|
|
52955
|
+
diskAvailable: attachmentIO.supportsDisk
|
|
52956
|
+
});
|
|
52957
|
+
} catch (e) {
|
|
52958
|
+
if (store === void 0 || bytes.length <= MAX_INLINE_BYTES) throw e;
|
|
52959
|
+
return linkDelivery(bytes, fileName2, mimeType2, `The file is ${bytes.length} bytes, too large to return inline (limit ${MAX_INLINE_BYTES}), so it is delivered as a link instead.`);
|
|
52960
|
+
}
|
|
52257
52961
|
}
|
|
52258
52962
|
const safeName = basename3(cached2.fileName);
|
|
52259
52963
|
const root = resolve6(getAttachmentsDir());
|
|
@@ -52565,142 +53269,8 @@ async function deleteOFWMessages(client2, ids) {
|
|
|
52565
53269
|
return client2.request("DELETE", "/pub/v1/messages", form);
|
|
52566
53270
|
}
|
|
52567
53271
|
|
|
52568
|
-
// node_modules/@chrischall/mcp-utils/dist/export/blob.js
|
|
52569
|
-
import { createHmac as createHmac4 } from "node:crypto";
|
|
52570
|
-
var BLOB_DEFAULT_TTL_MS = 60 * 60 * 1e3;
|
|
52571
|
-
var BLOB_MAX_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
52572
|
-
var MAX_KEY_LENGTH = 1024;
|
|
52573
|
-
var SAFE_SEGMENT = /^[A-Za-z0-9._~-]+$/;
|
|
52574
|
-
function configError(reason) {
|
|
52575
|
-
return new McpToolError(`MCP_BLOB_BASE_URL is not usable: ${reason}.`, {
|
|
52576
|
-
hint: "It should look like https://<host>/b/<registrationId> \u2014 check the deployment's environment.",
|
|
52577
|
-
kind: "unknown"
|
|
52578
|
-
});
|
|
52579
|
-
}
|
|
52580
|
-
function parseBase(baseUrl) {
|
|
52581
|
-
let parsed;
|
|
52582
|
-
try {
|
|
52583
|
-
parsed = new URL(baseUrl);
|
|
52584
|
-
} catch {
|
|
52585
|
-
throw configError("not a valid URL");
|
|
52586
|
-
}
|
|
52587
|
-
if (parsed.protocol !== "https:" && parsed.protocol !== "http:")
|
|
52588
|
-
throw configError("scheme must be http(s)");
|
|
52589
|
-
if (parsed.username || parsed.password)
|
|
52590
|
-
throw configError("must not contain credentials");
|
|
52591
|
-
if (parsed.search || parsed.hash)
|
|
52592
|
-
throw configError("must not contain a query or fragment");
|
|
52593
|
-
const path = parsed.pathname.replace(/^\/+|\/+$/g, "");
|
|
52594
|
-
const prefix = path.startsWith("b/") ? path.slice(2) : path;
|
|
52595
|
-
if (!prefix || prefix === "b")
|
|
52596
|
-
throw configError("has no registration path");
|
|
52597
|
-
return { base: `${parsed.origin}/${path}`, prefix };
|
|
52598
|
-
}
|
|
52599
|
-
function badInput(message) {
|
|
52600
|
-
return new McpToolError(message, { kind: "unknown" });
|
|
52601
|
-
}
|
|
52602
|
-
function encodeKey(key) {
|
|
52603
|
-
if (typeof key !== "string" || key.length === 0)
|
|
52604
|
-
throw badInput("Blob key must be a non-empty string.");
|
|
52605
|
-
if (key.length > MAX_KEY_LENGTH)
|
|
52606
|
-
throw badInput(`Blob key is longer than ${MAX_KEY_LENGTH} characters.`);
|
|
52607
|
-
const segments = key.split("/");
|
|
52608
|
-
for (const seg of segments) {
|
|
52609
|
-
if (seg === "" || seg === "." || seg === ".." || !SAFE_SEGMENT.test(seg)) {
|
|
52610
|
-
throw badInput('Blob key must be relative, slash-separated segments of [A-Za-z0-9._~-] with no empty, "." or ".." segment.');
|
|
52611
|
-
}
|
|
52612
|
-
}
|
|
52613
|
-
return segments.map(encodeURIComponent).join("/");
|
|
52614
|
-
}
|
|
52615
|
-
function checkContentType(contentType) {
|
|
52616
|
-
if (typeof contentType !== "string" || contentType.length === 0 || /[\x00-\x1f\x7f]/.test(contentType)) {
|
|
52617
|
-
throw badInput("Blob content type must be a non-empty string without control characters.");
|
|
52618
|
-
}
|
|
52619
|
-
}
|
|
52620
|
-
function expiry(opts) {
|
|
52621
|
-
const ttl = opts?.ttlMs ?? BLOB_DEFAULT_TTL_MS;
|
|
52622
|
-
if (!Number.isFinite(ttl) || ttl <= 0 || ttl > BLOB_MAX_TTL_MS) {
|
|
52623
|
-
throw badInput(`Blob link TTL must be between 1 ms and ${BLOB_MAX_TTL_MS} ms (24h); the gateway refuses longer.`);
|
|
52624
|
-
}
|
|
52625
|
-
return Math.floor((opts?.now ?? Date.now()) + ttl);
|
|
52626
|
-
}
|
|
52627
|
-
function toArrayBuffer(view) {
|
|
52628
|
-
const buf = view.buffer;
|
|
52629
|
-
if (buf instanceof ArrayBuffer && view.byteOffset === 0 && view.byteLength === buf.byteLength)
|
|
52630
|
-
return buf;
|
|
52631
|
-
return view.slice().buffer;
|
|
52632
|
-
}
|
|
52633
|
-
function createBlobStore(opts) {
|
|
52634
|
-
const { base, prefix } = parseBase(opts.baseUrl);
|
|
52635
|
-
const signingKey = opts.signingKey;
|
|
52636
|
-
const sign2 = (payload) => createHmac4("sha256", signingKey).update(payload).digest("base64url");
|
|
52637
|
-
const link2 = (encodedKey, exp, sig) => `${base}/${encodedKey}?exp=${exp}&sig=${encodeURIComponent(sig)}`;
|
|
52638
|
-
const signGetUrl = (key, o) => {
|
|
52639
|
-
const encoded = encodeKey(key);
|
|
52640
|
-
const exp = expiry(o);
|
|
52641
|
-
return { url: link2(encoded, exp, sign2(`${prefix}/${key}
|
|
52642
|
-
${exp}`)), expiresAtMs: exp };
|
|
52643
|
-
};
|
|
52644
|
-
const signPutUrl = (key, contentType, o) => {
|
|
52645
|
-
const encoded = encodeKey(key);
|
|
52646
|
-
checkContentType(contentType);
|
|
52647
|
-
const exp = expiry(o);
|
|
52648
|
-
return { url: link2(encoded, exp, sign2(`put\0${prefix}/${key}\0${contentType}\0${exp}`)), expiresAtMs: exp };
|
|
52649
|
-
};
|
|
52650
|
-
const put = async (key, body, contentType, o = {}) => {
|
|
52651
|
-
const { url: url2 } = signPutUrl(key, contentType, o);
|
|
52652
|
-
const bytes = typeof body === "string" ? new TextEncoder().encode(body) : body;
|
|
52653
|
-
const doFetch = o.fetchImpl ?? fetch;
|
|
52654
|
-
let res;
|
|
52655
|
-
try {
|
|
52656
|
-
res = await doFetch(url2, {
|
|
52657
|
-
method: "PUT",
|
|
52658
|
-
headers: { "content-type": contentType },
|
|
52659
|
-
body: toArrayBuffer(bytes),
|
|
52660
|
-
...o.signal ? { signal: o.signal } : {}
|
|
52661
|
-
});
|
|
52662
|
-
} catch (cause) {
|
|
52663
|
-
if (o.signal?.aborted)
|
|
52664
|
-
throw cause;
|
|
52665
|
-
throw new McpToolError(`Blob store upload of ${key} did not complete (network error).`, {
|
|
52666
|
-
kind: "transport"
|
|
52667
|
-
});
|
|
52668
|
-
}
|
|
52669
|
-
if (!res.ok) {
|
|
52670
|
-
throw new McpToolError(`Blob store upload of ${key} failed (HTTP ${res.status}).`, {
|
|
52671
|
-
kind: "http",
|
|
52672
|
-
status: res.status
|
|
52673
|
-
});
|
|
52674
|
-
}
|
|
52675
|
-
return { key, bytes: bytes.byteLength };
|
|
52676
|
-
};
|
|
52677
|
-
return { baseUrl: base, prefix, signGetUrl, signPutUrl, put };
|
|
52678
|
-
}
|
|
52679
|
-
function blobStoreFromEnv(env = process.env) {
|
|
52680
|
-
const baseUrl = readEnvVar("MCP_BLOB_BASE_URL", { env });
|
|
52681
|
-
const signingKey = readEnvVar("MCP_BLOB_SIGNING_KEY", { env });
|
|
52682
|
-
if (!baseUrl || !signingKey)
|
|
52683
|
-
return void 0;
|
|
52684
|
-
return createBlobStore({ baseUrl, signingKey });
|
|
52685
|
-
}
|
|
52686
|
-
|
|
52687
|
-
// node_modules/@chrischall/mcp-utils/dist/export/zip.js
|
|
52688
|
-
var CRC_TABLE = (() => {
|
|
52689
|
-
const table = new Uint32Array(256);
|
|
52690
|
-
for (let n = 0; n < 256; n++) {
|
|
52691
|
-
let c = n;
|
|
52692
|
-
for (let k = 0; k < 8; k++)
|
|
52693
|
-
c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
|
|
52694
|
-
table[n] = c >>> 0;
|
|
52695
|
-
}
|
|
52696
|
-
return table;
|
|
52697
|
-
})();
|
|
52698
|
-
|
|
52699
|
-
// node_modules/@chrischall/mcp-utils/dist/export/sink.js
|
|
52700
|
-
var EXPORT_BLOB_MAX_BYTES = 256 * 1024 * 1024;
|
|
52701
|
-
|
|
52702
53272
|
// src/tools/calendar.ts
|
|
52703
|
-
import { randomUUID as
|
|
53273
|
+
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
52704
53274
|
import { resolve as resolve7 } from "node:path";
|
|
52705
53275
|
|
|
52706
53276
|
// src/tools/calendar-ics.ts
|
|
@@ -53107,7 +53677,7 @@ function registerCalendarTools(server, client2, attachmentIO = new NodeAttachmen
|
|
|
53107
53677
|
const fileName = `ofw-calendar-${args.startDate}_${args.endDate}-${now.toISOString().replace(/[-:]/g, "").slice(0, 15)}Z.ics`;
|
|
53108
53678
|
const blob = blobStoreFromEnv();
|
|
53109
53679
|
if (blob) {
|
|
53110
|
-
const key = `calendar/${
|
|
53680
|
+
const key = `calendar/${randomUUID4()}/${fileName}`;
|
|
53111
53681
|
await blob.put(key, built.ics, "text/calendar");
|
|
53112
53682
|
const link2 = blob.signGetUrl(key, { ttlMs: (args.linkMinutes ?? 60) * 6e4 });
|
|
53113
53683
|
return jsonResponse({
|