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/dist/config.js CHANGED
@@ -38,6 +38,18 @@ export function getAttachmentsDir() {
38
38
  export function getDefaultAttachmentsDir() {
39
39
  return join(homedir(), 'Downloads', 'ofw-mcp');
40
40
  }
41
+ /**
42
+ * True on mcp-host: it injects `MCP_DATA_DIR` (the per-registration state
43
+ * dir) and, with a blob store, `MCP_BLOB_BASE_URL`. A local stdio install has
44
+ * neither. Read through `readEnvVar`, so an unexpanded placeholder is unset.
45
+ */
46
+ export function isHostedDeployment(env = process.env) {
47
+ return readEnvVar('MCP_DATA_DIR', { env }) !== undefined || readEnvVar('MCP_BLOB_BASE_URL', { env }) !== undefined;
48
+ }
49
+ /** True when mcp-host lent this process a blob store (without validating it). */
50
+ export function hasBlobStoreEnv(env = process.env) {
51
+ return readEnvVar('MCP_BLOB_BASE_URL', { env }) !== undefined && readEnvVar('MCP_BLOB_SIGNING_KEY', { env }) !== undefined;
52
+ }
41
53
  /**
42
54
  * The only directory tree ofw_upload_attachment may read from. Uploading sends
43
55
  * a local file to OurFamilyWizard (and, when shared, straight to the
@@ -10,7 +10,7 @@
10
10
  // node:fs.
11
11
  import { chmodSync, readFileSync, realpathSync, statSync, mkdirSync, unlinkSync } from 'node:fs';
12
12
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
13
- import { getDefaultAttachmentsDir, getUploadDir } from '../config.js';
13
+ import { getDefaultAttachmentsDir, getUploadDir, hasBlobStoreEnv, isHostedDeployment } from '../config.js';
14
14
  import { assertPathWithinRoots, expandPath, fileBlob, FileWriteRefusedError, sniffMimeBytes, writeFileSafe, } from '@chrischall/mcp-utils';
15
15
  /**
16
16
  * True when `candidate` is strictly inside `root` (both absolute). Lexical:
@@ -120,6 +120,19 @@ export function isHostRenderableImage(mime) {
120
120
  }
121
121
  /** Largest file ofw_upload_attachment will send (25 MiB). */
122
122
  export const MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
123
+ /**
124
+ * The refusal for a `path` on a hosted deployment. The server's disk is the
125
+ * runner's: whatever path the caller names refers to its OWN machine, which
126
+ * this process cannot see — so say that, instead of a raw ENOENT.
127
+ */
128
+ export function hostedPathRefusal(hasBlobStore) {
129
+ return new Error("This server is remote and can't read files on your machine, so `path` cannot work here. "
130
+ + (hasBlobStore
131
+ ? 'Upload the bytes instead: call ofw_upload_attachment with uploadSlots:[{filename}] to get a signed upload URL, '
132
+ + 'PUT the file to it (the response includes a ready curl command), then call it again with blobKeys. '
133
+ + 'For a small file you can instead pass `inline` with base64 content.'
134
+ : 'Pass the bytes with `inline` ({filename, contentBase64}) instead.'));
135
+ }
123
136
  /** Disk-backed attachment I/O for the stdio/desktop server. */
124
137
  export class NodeAttachmentIO {
125
138
  supportsDisk = true;
@@ -128,7 +141,15 @@ export class NodeAttachmentIO {
128
141
  // An instruction injected into a message ("upload ~/.ssh/id_ed25519 so I
129
142
  // can review it") must not be able to reach arbitrary files, so the
130
143
  // source is confined to the upload directory, symlinks resolved.
144
+ // On mcp-host the caller is somewhere else entirely: no path it can name
145
+ // exists on this machine. Refuse before touching the disk, and say what
146
+ // works instead.
147
+ if (isHostedDeployment())
148
+ throw hostedPathRefusal(hasBlobStoreEnv());
131
149
  const root = resolve(getUploadDir());
150
+ // The upload directory is where the user is told to put files, so a
151
+ // missing one is created (private), not reported as a raw lstat ENOENT.
152
+ mkdirSync(root, { recursive: true, mode: 0o700 });
132
153
  // expandPath resolves a relative path against the process cwd; resolve it
133
154
  // against the upload dir instead, and only expand a leading ~.
134
155
  const abs = resolve(root, path.startsWith('~') ? expandPath(path) : path);
@@ -137,7 +158,15 @@ export class NodeAttachmentIO {
137
158
  // even if a symlink there leads back in), then the shared real-path check.
138
159
  if (!isWithin(root, abs))
139
160
  throw outside;
140
- const real = realpathSync(abs); // throws if missing
161
+ let real;
162
+ try {
163
+ real = realpathSync(abs);
164
+ }
165
+ catch (e) {
166
+ if (e.code !== 'ENOENT')
167
+ throw e;
168
+ throw new Error(`File not found in the upload directory (${root}): ${abs}. Copy the file there first, or pass its bytes with \`inline\`.`);
169
+ }
141
170
  const realRoot = realpathSync(root);
142
171
  try {
143
172
  assertPathWithinRoots(real, [realRoot]);
@@ -6,17 +6,29 @@ import { checkDraftFreshness, draftRevision, fetchServerDraft, staleDraftPayload
6
6
  import { FOLDER_TYPE, newDraftKey, persistFolderIds, probeIds, resolveDraftKey } from './lifecycle.js';
7
7
  import { CONFIRM_NOTE, confirmTokenParam, confirmWrite } from './_confirm.js';
8
8
  import { getFolderVerifiedAt } from '../sync.js';
9
- import { buildInlineDelivery, tryExtract } from './delivery.js';
9
+ import { MAX_UPLOAD_BYTES } from './attachments.js';
10
+ import { blobStoreFromEnv } from '@chrischall/mcp-utils/export';
11
+ import { blobKeysParam, blobObjectToUpload, checkFileCount, describePending, fileNameFromBlobKey, inlineAttachmentsParam, inlineFileSchema, MAX_FILES_PER_CALL, mintUploadSlot, planAttachments, requireBlobStore, resolveInlineUpload, sha256Hex, uploadPending, uploadSlotRequestSchema, uploadToMyFiles, } from './uploads.js';
12
+ import { buildInlineDelivery, MAX_INLINE_BYTES, tryExtract } from './delivery.js';
10
13
  import { resolveDownloadMime, resolveSaveDest } from './attachments.js';
11
14
  import { getAllowMarkRead, getConfirmMarkRead, getAttachmentsDir, getAutoRefreshStaleReads, getDefaultInlineAttachments, getFetchUnreadBodies, getSyncMaxRequests, getWriteMode, } from '../config.js';
12
15
  import { basename, resolve } from 'node:path';
16
+ import { randomUUID } from 'node:crypto';
13
17
  import { ApiRecipientSchema, deriveRead, hasRealView, jsonErrorResponse, jsonResponse, jsonText, mapRecipients, notedJsonResponse, postMessageAndRefetch, reportsThreaded, UnconfirmedWriteError, reportsUnthreaded, threadedReplyTo, verifyWriteLanded, withReadState } from './_shared.js';
14
18
  import { parseLenient } from '@chrischall/mcp-utils';
15
19
  import { pageState } from './pagination.js';
16
20
  import { MESSAGE_VIEWS, senderOf, viewDrafts, viewMessages, viewOne } from './project.js';
17
21
  import { resolveView, viewParam } from '@chrischall/mcp-utils';
18
- import { displayTimeZone, normalizeTimestampsInValue, nowNaiveWallClock, toNaiveWallClock } from '../timestamps.js';
22
+ import { displayTimeZone, formatInstant, normalizeTimestampsInValue, nowNaiveWallClock, toNaiveWallClock } from '../timestamps.js';
19
23
  import { readingBlockedToday } from '../read-days.js';
24
+ /** A confirmation preview raised from inside a blob consume — carries it out. */
25
+ class GateHalt extends Error {
26
+ response;
27
+ constructor(response) {
28
+ super('confirmation required');
29
+ this.response = response;
30
+ }
31
+ }
20
32
  // Schemas for the load-bearing fields of each /pub/v3 response this file
21
33
  // reads (issue #83). Loose: unknown keys pass through into cached listData.
22
34
  const DateSchema = z.looseObject({ dateTime: z.string() });
@@ -96,14 +108,6 @@ const FolderCountsSchema = z.looseObject({
96
108
  const MAX_FRESHNESS_IDS = 25;
97
109
  // Upload response — STRICT: fileId is the whole point of the call; caching
98
110
  // or returning an undefined/mistyped fileId produces an unusable attachment.
99
- const UploadedFileSchema = z.looseObject({
100
- fileId: z.number(),
101
- fileName: z.string().optional(),
102
- label: z.string().optional(),
103
- fileType: z.string().optional(),
104
- sizeInBytes: z.number().optional(),
105
- shareClass: z.string().optional(),
106
- });
107
111
  // The list endpoint payload (cached as `listData`) reports attachments via
108
112
  // `files: <count>` (a number) — the actual fileIds only appear on the detail
109
113
  // endpoint as `files: [number, ...]`. Some intermediate shapes return an
@@ -799,6 +803,8 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
799
803
  deleteDraftOnSuccess: z.boolean().describe('Default true. Delete the source draft after — and ONLY after — 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(),
800
804
  force: z.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(),
801
805
  myFileIDs: z.array(z.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(),
806
+ inlineAttachments: inlineAttachmentsParam,
807
+ blobKeys: blobKeysParam,
802
808
  confirmToken: confirmTokenParam,
803
809
  }),
804
810
  }, async (args, ctx) => {
@@ -808,6 +814,11 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
808
814
  const draftRef = args.messageId ?? args.draftId;
809
815
  const cache = cacheProvider();
810
816
  const deleteOnSuccess = args.deleteDraftOnSuccess ?? true;
817
+ // New attachments are validated — and blob ones READ, so the approval can
818
+ // bind their exact bytes — before anything else. They are uploaded only
819
+ // after the send is approved: a preview never puts a file on OFW.
820
+ const blobStore = args.blobKeys?.length ? blobStoreFromEnv() : undefined;
821
+ const pending = await planAttachments({ inline: args.inlineAttachments, blobKeys: args.blobKeys }, { store: blobStore, readBlobs: true });
811
822
  let subject = args.subject;
812
823
  let body = args.body;
813
824
  let recipientIds = args.recipientIds;
@@ -889,7 +900,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
889
900
  // Attachments carry over from the SERVER draft the guard read — sending
890
901
  // "the draft as it exists on the server" includes its files, or the send
891
902
  // would silently strip them. Explicit myFileIDs still overrides.
892
- const myFileIDs = args.myFileIDs ?? serverDraft?.files ?? [];
903
+ let myFileIDs = args.myFileIDs ?? serverDraft?.files ?? [];
893
904
  // ── Confirmation gate ────────────────────────────────────────────────
894
905
  // Everything above this line is a read. This is the ONE irreversible
895
906
  // operation in the server, and until here the only things between a
@@ -923,6 +934,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
923
934
  ? null
924
935
  : { messageId: resolvedReplyTo, subject: replyParent?.subject ?? null, from: replyParent?.fromUser || null },
925
936
  attachments,
937
+ ...(pending.length > 0 ? { newAttachments: describePending(pending) } : {}),
926
938
  source: draftRef !== undefined
927
939
  ? { draftId: draftRef, deleteDraftAfterSend: deleteOnSuccess }
928
940
  : 'composed from the call arguments',
@@ -934,12 +946,23 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
934
946
  message: 'Review and confirm this OurFamilyWizard message. Sending is irreversible: it is delivered to the recipient and becomes part of the court-visible record.',
935
947
  target: draftRef !== undefined ? `draft:${draftRef}` : 'compose',
936
948
  ...(serverDraft != null ? { revision: draftRevision(serverDraft) } : {}),
937
- payload: { subject, body, recipientIds, myFileIDs, replyToId: resolvedReplyTo, deleteDraftOnSuccess: deleteOnSuccess },
949
+ payload: {
950
+ subject, body, recipientIds, myFileIDs, replyToId: resolvedReplyTo, deleteDraftOnSuccess: deleteOnSuccess,
951
+ ...(pending.length > 0
952
+ ? { newAttachments: pending.map((p) => ({ fileName: p.fileName, sizeBytes: p.sizeBytes, sha256: p.sha256 })) }
953
+ : {}),
954
+ },
938
955
  preview,
939
956
  confirmToken: args.confirmToken,
940
957
  });
941
958
  if (gate)
942
959
  return gate;
960
+ // Approved. Upload the new files (PRIVATE) now; a failure stops here,
961
+ // before the send, naming whatever did upload.
962
+ const { uploaded: newFiles, warnings: uploadWarnings } = await uploadPending(pending, {
963
+ client, cache, store: blobStore, nothingWas: 'sent',
964
+ });
965
+ myFileIDs = [...myFileIDs, ...newFiles.map((f) => f.fileId)];
943
966
  let posted;
944
967
  try {
945
968
  posted = await postMessageAndRefetch(client, {
@@ -1126,6 +1149,8 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1126
1149
  }
1127
1150
  : {}),
1128
1151
  ...persisted,
1152
+ ...(newFiles.length > 0 ? { attachmentsUploaded: newFiles } : {}),
1153
+ ...(uploadWarnings.length > 0 ? { warnings: uploadWarnings } : {}),
1129
1154
  };
1130
1155
  return notedJsonResponse([guardNote, rewriteNote, verifyNote, threadNote, unconfirmedNote, retainNote], responseObj, 'Message sent successfully.');
1131
1156
  });
@@ -1330,15 +1355,22 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1330
1355
  recipientIds: z.array(z.number()).describe('Array of recipient user IDs (optional for drafts)').optional(),
1331
1356
  messageId: z.number().describe('ID of an existing draft to replace (the new draft will have a new id; the old is deleted)').optional(),
1332
1357
  replyToId: z.number().describe('ID of the message this draft replies to').optional(),
1333
- myFileIDs: z.array(z.number()).describe('Attachment file ids (from ofw_upload_attachment)').optional(),
1358
+ myFileIDs: z.array(z.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(),
1359
+ inlineAttachments: inlineAttachmentsParam,
1360
+ blobKeys: blobKeysParam,
1334
1361
  expectedRevision: z.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 — omitting never means "overwrite anyway".').optional(),
1335
1362
  force: z.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(),
1336
1363
  }),
1337
1364
  }, async (args) => {
1338
1365
  const cache = cacheProvider();
1366
+ // New attachments are validated before ANYTHING happens, so a bad entry
1367
+ // fails the call with nothing uploaded and nothing saved.
1368
+ const blobStore = args.blobKeys?.length ? blobStoreFromEnv() : undefined;
1369
+ const pending = await planAttachments({ inline: args.inlineAttachments, blobKeys: args.blobKeys }, { store: blobStore, readBlobs: false });
1339
1370
  // Guard BEFORE the POST: refusing after creating a replacement would leave
1340
1371
  // a stray draft behind for a write we then decline to finish.
1341
1372
  let forceNote = null;
1373
+ let serverFiles;
1342
1374
  if (args.messageId !== undefined) {
1343
1375
  const guard = await guardDestructiveDraftOp({
1344
1376
  cache,
@@ -1350,6 +1382,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1350
1382
  if (!guard.ok)
1351
1383
  return guard.response;
1352
1384
  forceNote = guard.note;
1385
+ serverFiles = guard.server?.files;
1353
1386
  }
1354
1387
  const requestedReplyTo = args.replyToId ?? null;
1355
1388
  let resolvedReplyTo = requestedReplyTo;
@@ -1360,7 +1393,15 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1360
1393
  rewriteNote = `replyToId rewritten from ${requestedReplyTo} to ${resolvedReplyTo} (later reply in same thread found in sent cache).`;
1361
1394
  }
1362
1395
  }
1363
- const myFileIDs = args.myFileIDs ?? [];
1396
+ // Replacing a draft creates a NEW one, so its files must be posted again
1397
+ // or the edit silently strips them: they carry over from the server copy
1398
+ // the guard just read (an explicit myFileIDs still replaces them, as on
1399
+ // send). New uploads go on top, after the guard, so a refused replace
1400
+ // uploads nothing.
1401
+ const { uploaded: newFiles, warnings: uploadWarnings } = await uploadPending(pending, {
1402
+ client, cache, store: blobStore, nothingWas: 'saved',
1403
+ });
1404
+ const myFileIDs = [...(args.myFileIDs ?? serverFiles ?? []), ...newFiles.map((f) => f.fileId)];
1364
1405
  // Deliberately do NOT pass `args.messageId` to OFW's POST payload.
1365
1406
  // OFW's update-by-messageId path silently no-ops on subsequent
1366
1407
  // updates while echoing the posted body in the immediate GET — so
@@ -1385,7 +1426,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1385
1426
  let draftKey = null;
1386
1427
  // Fields accepted on the write that the saved draft must carry — or their
1387
1428
  // loss must be reported. Never a silent drop (Defect 3).
1388
- const warnings = [];
1429
+ const warnings = [...uploadWarnings];
1389
1430
  if (newId !== null) {
1390
1431
  verifyNote = verifyWriteLanded('draft', { subject: args.subject, body: args.body }, detail);
1391
1432
  // Trust the re-fetched server detail as the source of truth for the stored
@@ -1519,6 +1560,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1519
1560
  previousId: args.messageId ?? null,
1520
1561
  cacheStatus: 'fresh',
1521
1562
  serverConfirmed: true,
1563
+ ...(newFiles.length > 0 ? { attachmentsUploaded: newFiles } : {}),
1522
1564
  ...(warnings.length > 0 ? { warnings } : {}),
1523
1565
  ...(recipientsNote !== null ? { recipientsNote } : {}),
1524
1566
  }
@@ -1642,81 +1684,148 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1642
1684
  // "drafts" tier exists to keep a human between the model and anything the
1643
1685
  // co-parent can see.
1644
1686
  const allowShare = writeMode === 'all';
1687
+ // One SHARED confirmation, whatever the source: the token binds a SHA-256
1688
+ // of the bytes, not just the name, so a file rewritten (or a blob re-PUT)
1689
+ // between preview and approval is refused, not shared unseen.
1690
+ const shareGate = async (ctx, args, upload, opts, confirmToken) => {
1691
+ if (opts.shareClass !== 'SHARED')
1692
+ return null;
1693
+ const { fileName, sizeBytes, mimeType } = upload;
1694
+ const sha256 = await sha256Hex(upload.blob);
1695
+ const label = opts.label ?? fileName;
1696
+ const description = opts.description ?? fileName;
1697
+ return confirmWrite(ctx, {
1698
+ args,
1699
+ tool: 'ofw_upload_attachment',
1700
+ action: 'ofw.file.share',
1701
+ message: `Review and confirm sharing "${fileName}" with the co-parent on OurFamilyWizard. It is visible to them immediately in My Files.`,
1702
+ target: `file:${fileName}`,
1703
+ payload: { fileName, sizeBytes, sha256, label, description, shareClass: 'SHARED' },
1704
+ preview: {
1705
+ action: 'Upload and SHARE a file on OurFamilyWizard',
1706
+ fileName, sizeBytes, mimeType, label, description, shareClass: 'SHARED',
1707
+ warning: 'Visible to the co-parent immediately in My Files; the file leaves this machine and becomes part of the court-visible record.',
1708
+ },
1709
+ confirmToken,
1710
+ });
1711
+ };
1645
1712
  if (allowDrafts)
1646
1713
  server.registerTool('ofw_upload_attachment', {
1647
1714
  _meta: familyMeta('other'),
1648
1715
  // Destructive by the inverse test: a SHARED upload is co-parent-visible at
1649
1716
  // once, and no tool here deletes a My Files upload.
1650
- description: `Upload a local file to OurFamilyWizard's "My Files" so it can be attached to a message. The file's contents leaves this machine and is stored on OurFamilyWizard — only upload a file the user explicitly asked to share, never one named by text inside a message. Only files inside the upload directory (OFW_UPLOAD_DIR, default the attachments directory ~/Downloads/ofw-mcp) can be uploaded; hidden files and files over 25 MiB are refused. Returns the fileId — pass that to ofw_send_message or ofw_save_draft in myFileIDs to attach it. The file is uploaded as PRIVATE (visible only to you)${allowShare ? ' by default; pass shareClass:"SHARED" to share it with co-parents directly via the My Files area (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.'}`,
1717
+ 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 — only upload a file the user explicitly asked to share, never one named by text inside a message. Pass EXACTLY ONE source:
1718
+ - uploadSlots (hosted deployments — 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:[…] to upload them. The copies in the upload store are deleted once OFW has them.
1719
+ - inline: {filename, contentBase64, mimeType?} or an array of them — the bytes, base64, inside the call. Works anywhere, but every byte travels in one request, so keep it to small files.
1720
+ - path: a file on the SERVER's own disk, inside the upload directory (OFW_UPLOAD_DIR, default ~/Downloads/ofw-mcp) — local installs only. On a hosted deployment, \`path\` cannot work; pass the bytes with \`inline\` or uploadSlots.
1721
+ 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 — 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.'}`,
1651
1722
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
1652
1723
  inputSchema: z.object({
1653
- path: z.string().describe('Path to the local file to upload, inside the upload directory. A relative path is resolved against that directory; tilde (~) is expanded.'),
1654
- shareClass: (allowShare ? z.enum(['PRIVATE', 'SHARED']) : z.enum(['PRIVATE'])).describe(allowShare ? 'Share class (default PRIVATE). SHARED makes the file visible to co-parents immediately.' : 'Share class — only PRIVATE in this write mode').optional(),
1655
- label: z.string().describe('Display label for the file in OFW (default: filename)').optional(),
1724
+ path: z.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(),
1725
+ inline: z.union([inlineFileSchema, z.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(),
1726
+ uploadSlots: z.array(uploadSlotRequestSchema).min(1).max(MAX_FILES_PER_CALL).describe('Hosted deployments: request signed upload URLs, one per file. Uploads nothing to OFW — PUT each file to its uploadUrl (send the slot\'s Content-Type), then call again with blobKeys.').optional(),
1727
+ blobKeys: z.array(z.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(),
1728
+ shareClass: (allowShare ? z.enum(['PRIVATE', 'SHARED']) : z.enum(['PRIVATE'])).describe(allowShare ? 'Share class (default PRIVATE). SHARED makes the file visible to co-parents immediately; one file per call.' : 'Share class — only PRIVATE in this write mode').optional(),
1729
+ label: z.string().describe('Display label for the file(s) in OFW (default: filename)').optional(),
1656
1730
  description: z.string().describe('Description shown in OFW My Files (default: filename)').optional(),
1657
1731
  ...(allowShare ? { confirmToken: confirmTokenParam } : {}),
1658
1732
  }),
1659
1733
  }, async (args, ctx) => {
1660
- // Resolve the upload source through the injected attachment-I/O boundary
1661
- // (disk read on node; an in-memory source on a hosted deployment).
1662
- const { blob, fileName, mimeType: mime, sizeBytes } = await attachmentIO.resolveUpload(args.path);
1663
- // A SHARED upload puts the file in front of the co-parent at once, with
1664
- // no send step to review it in — so it is confirmed first. The token
1665
- // binds a SHA-256 of the bytes, not just the name: a file rewritten in
1666
- // place between preview and approval is refused, not shared unseen.
1734
+ const sources = [args.path, args.inline, args.uploadSlots, args.blobKeys].filter((v) => v !== undefined).length;
1735
+ if (sources !== 1) {
1736
+ 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.');
1737
+ }
1667
1738
  // (The schema is built per write mode, so TS sees only its narrower arm.)
1668
- const shareClass = args.shareClass;
1669
- if (shareClass === 'SHARED') {
1670
- const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', await blob.arrayBuffer()));
1671
- const sha256 = Array.from(digest, (b) => b.toString(16).padStart(2, '0')).join('');
1672
- const label = args.label ?? fileName;
1673
- const description = args.description ?? fileName;
1674
- const gate = await confirmWrite(ctx, {
1675
- args,
1676
- tool: 'ofw_upload_attachment',
1677
- action: 'ofw.file.share',
1678
- message: `Review and confirm sharing "${fileName}" with the co-parent on OurFamilyWizard. It is visible to them immediately in My Files.`,
1679
- target: `file:${fileName}`,
1680
- payload: { fileName, sizeBytes, sha256, label, description, shareClass: 'SHARED' },
1681
- preview: {
1682
- action: 'Upload and SHARE a file on OurFamilyWizard',
1683
- fileName, sizeBytes, mimeType: mime, label, description, shareClass: 'SHARED',
1684
- warning: 'Visible to the co-parent immediately in My Files; the file leaves this machine and becomes part of the court-visible record.',
1685
- },
1686
- confirmToken: args.confirmToken,
1739
+ const opts = {
1740
+ shareClass: args.shareClass ?? 'PRIVATE',
1741
+ ...(args.label !== undefined ? { label: args.label } : {}),
1742
+ ...(args.description !== undefined ? { description: args.description } : {}),
1743
+ };
1744
+ const confirmToken = args.confirmToken;
1745
+ const cache = cacheProvider();
1746
+ const note = 'Pass the fileId(s) to ofw_send_message or ofw_save_draft in myFileIDs to attach them.';
1747
+ if (args.uploadSlots !== undefined) {
1748
+ checkFileCount(args.uploadSlots.length, 'uploadSlots');
1749
+ const store = requireBlobStore(blobStoreFromEnv(), 'uploadSlots');
1750
+ const slots = args.uploadSlots.map((req) => mintUploadSlot(store, req));
1751
+ return jsonResponse({
1752
+ 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 — replace the @\'<path …>\' with the file), then call ofw_upload_attachment with blobKeys (in this order) plus any shareClass/label. The URLs stop working at expiresAt.',
1753
+ blobKeys: slots.map((slot) => slot.blobKey),
1754
+ slots,
1687
1755
  });
1756
+ }
1757
+ // A single file: the long-standing response shape, plus `bytes`.
1758
+ if (args.path !== undefined || (args.inline !== undefined && !Array.isArray(args.inline))) {
1759
+ const upload = args.path !== undefined
1760
+ ? await attachmentIO.resolveUpload(args.path)
1761
+ : resolveInlineUpload(args.inline);
1762
+ const gate = await shareGate(ctx, args, upload, opts, confirmToken);
1688
1763
  if (gate)
1689
1764
  return gate;
1765
+ return jsonResponse({ ...(await uploadToMyFiles(client, cache, upload, opts)), note });
1690
1766
  }
1691
- // Build the multipart payload matching the OFW web UI's request shape.
1692
- const form = new FormData();
1693
- form.append('file', blob, fileName);
1694
- form.append('source', 'message');
1695
- form.append('description', args.description ?? fileName);
1696
- form.append('label', args.label ?? fileName);
1697
- form.append('fileName', fileName);
1698
- form.append('shareClass', args.shareClass ?? 'PRIVATE');
1699
- const meta = parseLenient(UploadedFileSchema, await client.request('POST', '/pub/v3/myfiles/multipart', form), { label: 'ofw-mcp', context: 'POST /pub/v3/myfiles/multipart (ofw_upload_attachment)', mode: 'strict' });
1700
- // Cache metadata so subsequent ofw_get_message calls can surface it and
1701
- // ofw_download_attachment can short-circuit. messageId is 0 (the
1702
- // not-yet-linked sentinel) until a message actually references this file.
1703
- await cacheProvider().upsertAttachmentForMessage({
1704
- fileId: meta.fileId,
1705
- fileName: meta.fileName ?? fileName,
1706
- label: meta.label ?? args.label ?? fileName,
1707
- mimeType: meta.fileType ?? mime,
1708
- sizeBytes: typeof meta.sizeInBytes === 'number' ? meta.sizeInBytes : sizeBytes,
1709
- metadata: meta,
1710
- messageId: 0,
1711
- });
1712
- return jsonResponse({
1713
- fileId: meta.fileId,
1714
- fileName: meta.fileName ?? fileName,
1715
- mimeType: meta.fileType ?? mime,
1716
- sizeBytes: meta.sizeInBytes ?? sizeBytes,
1717
- shareClass: meta.shareClass ?? args.shareClass ?? 'PRIVATE',
1718
- note: 'Pass this fileId to ofw_send_message or ofw_save_draft in myFileIDs to attach it.',
1719
- });
1767
+ // A batch: an inline array, or blobKeys.
1768
+ const inline = args.inline;
1769
+ const count = inline?.length ?? args.blobKeys.length;
1770
+ checkFileCount(count, inline ? 'inline' : 'blobKeys');
1771
+ if (opts.shareClass === 'SHARED' && count > 1) {
1772
+ 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.');
1773
+ }
1774
+ const store = inline ? undefined : requireBlobStore(blobStoreFromEnv(), 'blobKeys');
1775
+ const results = [];
1776
+ for (let index = 0; index < count; index++) {
1777
+ const nameOf = () => {
1778
+ if (inline)
1779
+ return inline[index].filename;
1780
+ try {
1781
+ return fileNameFromBlobKey(args.blobKeys[index]);
1782
+ }
1783
+ catch {
1784
+ return args.blobKeys[index];
1785
+ }
1786
+ };
1787
+ try {
1788
+ if (inline) {
1789
+ const upload = resolveInlineUpload(inline[index]);
1790
+ const gate = await shareGate(ctx, args, upload, opts, confirmToken);
1791
+ if (gate)
1792
+ return gate;
1793
+ results.push({ index, ok: true, ...(await uploadToMyFiles(client, cache, upload, opts)) });
1794
+ continue;
1795
+ }
1796
+ const key = args.blobKeys[index];
1797
+ fileNameFromBlobKey(key); // a key we did not mint is refused before any read
1798
+ const out = await store.consume(key, async (object) => {
1799
+ const upload = blobObjectToUpload(key, object);
1800
+ const gate = await shareGate(ctx, args, upload, opts, confirmToken);
1801
+ // Thrown, not returned: consume keeps the blob when the handler
1802
+ // throws, so the confirmed call can still read it.
1803
+ if (gate)
1804
+ throw new GateHalt(gate);
1805
+ return uploadToMyFiles(client, cache, upload, opts);
1806
+ }, { maxBytes: MAX_UPLOAD_BYTES });
1807
+ results.push({
1808
+ index, ok: true, ...out.result, blobDeleted: out.deleted,
1809
+ ...(out.deleted ? {} : { blobDeleteError: out.deleteError }),
1810
+ });
1811
+ }
1812
+ catch (e) {
1813
+ if (e instanceof GateHalt)
1814
+ return e.response;
1815
+ results.push({ index, ok: false, filename: nameOf(), error: e.message });
1816
+ }
1817
+ }
1818
+ const succeeded = results.filter((r) => r.ok);
1819
+ const payload = {
1820
+ uploaded: succeeded.length,
1821
+ failed: count - succeeded.length,
1822
+ fileIds: succeeded.map((r) => r.fileId),
1823
+ note: succeeded.length < count
1824
+ ? `${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.'}`
1825
+ : note,
1826
+ results,
1827
+ };
1828
+ return succeeded.length === 0 ? jsonErrorResponse(payload) : jsonResponse(payload);
1720
1829
  });
1721
1830
  server.registerTool('ofw_download_attachment', {
1722
1831
  _meta: familyMeta('other'),
@@ -1733,16 +1842,28 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1733
1842
  extract: z.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(),
1734
1843
  maxChars: z.number().int().min(500).max(500_000).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(),
1735
1844
  parts: z.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(),
1845
+ link: z.boolean().describe('Hosted deployments: return a private, expiring download link to the file instead of its bytes — 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(),
1846
+ linkMinutes: z.number().int().min(1).max(1440).describe('How long a download link works, in minutes (default 60, max 1440).').optional(),
1736
1847
  }),
1737
1848
  }, async (args) => {
1738
1849
  const fileId = args.fileId;
1850
+ // mcp-host lends a hosted child a blob store; its disk is the runner's,
1851
+ // which nobody can open, so on a hosted deployment a link is the
1852
+ // deliverable wherever a local install would write a file.
1853
+ const store = blobStoreFromEnv();
1854
+ if (args.link === true && !store) {
1855
+ 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.');
1856
+ }
1739
1857
  const cache = cacheProvider();
1740
1858
  const requestedInline = args.inline ?? getDefaultInlineAttachments();
1741
1859
  // When the deployment has no filesystem, inline is the
1742
1860
  // ONLY path to the bytes — force it rather than erroring on a disk write.
1743
1861
  // `forcedInline` records that we overrode an explicit `inline:false` so the
1744
1862
  // response is honest about it instead of silently ignoring the argument.
1745
- const inline = requestedInline || !attachmentIO.supportsDisk;
1863
+ const deliverLink = store !== undefined && (args.link === true || (!requestedInline && args.link !== false));
1864
+ // A hosted deployment never writes a download to its own disk: with the
1865
+ // link declined, inline is the remaining route to the bytes.
1866
+ const inline = !deliverLink && (requestedInline || !attachmentIO.supportsDisk || store !== undefined);
1746
1867
  const forcedInline = inline && !requestedInline;
1747
1868
  const deliveryOptions = { extract: args.extract, maxChars: args.maxChars, parts: args.parts };
1748
1869
  let cached = await cache.getAttachment(fileId);
@@ -1776,6 +1897,32 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1776
1897
  if (!cached)
1777
1898
  throw new Error(`failed to fetch metadata for fileId ${fileId}`);
1778
1899
  }
1900
+ // A private, expiring link to the bytes in the blob store. The random
1901
+ // segment keeps the link unguessable; the readable last segment is the
1902
+ // name a browser saves it under (sanitized to the store's key alphabet).
1903
+ const linkDelivery = async (bytes, fileName, mimeType, note) => {
1904
+ const keyName = `${fileId}-${basename(fileName)}`.replace(/[^A-Za-z0-9._~-]/g, '_').replace(/^\.+/, '_');
1905
+ const key = `attachments/${randomUUID()}/${keyName}`;
1906
+ await store.put(key, new Uint8Array(bytes), mimeType);
1907
+ const signed = store.signGetUrl(key, { ttlMs: (args.linkMinutes ?? 60) * 60_000 });
1908
+ return jsonResponse({
1909
+ fileId,
1910
+ deliveredVia: 'link',
1911
+ url: signed.url,
1912
+ expiresAt: formatInstant(new Date(signed.expiresAtMs)).iso,
1913
+ fileName,
1914
+ mimeType,
1915
+ sizeBytes: bytes.length,
1916
+ note: `${note ? `${note} ` : ''}Private link to the file — anyone holding it can download it until it expires, so give it only to the user.`,
1917
+ ...(args.extract === true ? await tryExtract(bytes, mimeType, fileName, deliveryOptions) : {}),
1918
+ });
1919
+ };
1920
+ if (deliverLink) {
1921
+ const response = await client.requestBinary('GET', `/pub/v1/myfiles/${fileId}/data`);
1922
+ const fileName = response.suggestedFileName ?? cached.fileName;
1923
+ const mimeType = resolveDownloadMime(response.body, response.contentType ?? cached.mimeType, fileName);
1924
+ return linkDelivery(response.body, fileName, mimeType);
1925
+ }
1779
1926
  if (inline) {
1780
1927
  // Reuse on-disk bytes if we already have them; otherwise fetch fresh.
1781
1928
  let bytes = null;
@@ -1797,10 +1944,20 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1797
1944
  // The ladder decides between rendering, extracted content, and raw bytes
1798
1945
  // — see src/tools/delivery.ts. Whatever the host can draw, the caller
1799
1946
  // ends up holding something readable.
1800
- return await buildInlineDelivery({
1801
- fileId, fileName, mimeType, bytes, forcedInline, options: deliveryOptions,
1802
- diskAvailable: attachmentIO.supportsDisk,
1803
- });
1947
+ try {
1948
+ return await buildInlineDelivery({
1949
+ fileId, fileName, mimeType, bytes, forcedInline, options: deliveryOptions,
1950
+ diskAvailable: attachmentIO.supportsDisk,
1951
+ });
1952
+ }
1953
+ catch (e) {
1954
+ // Over the inline cap, a hosted deployment still has a route to the
1955
+ // bytes: the link. (Extractable files never get here — their text is
1956
+ // bounded by maxChars, not the byte cap.)
1957
+ if (store === undefined || bytes.length <= MAX_INLINE_BYTES)
1958
+ throw e;
1959
+ return linkDelivery(bytes, fileName, mimeType, `The file is ${bytes.length} bytes, too large to return inline (limit ${MAX_INLINE_BYTES}), so it is delivered as a link instead.`);
1960
+ }
1804
1961
  }
1805
1962
  // The filename comes from OFW file metadata — i.e. it is controlled by the
1806
1963
  // co-parent who uploaded the attachment. basename() it before interpolating