ofw-mcp 2.26.0 → 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.
@@ -0,0 +1,311 @@
1
+ // Getting a file's bytes to OurFamilyWizard from a caller that shares no
2
+ // filesystem with this server.
3
+ //
4
+ // `ofw_upload_attachment` used to accept only a `path` on the SERVER's disk.
5
+ // On mcp-host the caller is a claude.ai session somewhere else entirely, so no
6
+ // path it can name exists here, and every upload failed — first as a raw
7
+ // ENOENT on an upload directory nobody had created, and even with that
8
+ // directory there was no way for the caller to put a file in it.
9
+ //
10
+ // Two ways in, by size:
11
+ //
12
+ // - **Blob upload slots** (hosted, the main path). The server mints a signed
13
+ // PUT URL on mcp-host's per-registration blob store (`uploadSlots`); the
14
+ // caller `curl`s the file to it; the server reads the object back
15
+ // (`blobKeys`) and DELETES it once OFW has the file (`BlobStore.consume`).
16
+ // No base64 in the tool call, so no request-size ceiling, and no photo
17
+ // left sitting in the bucket until the 30-day retention prune.
18
+ // - **Inline base64** (`inline`). Works on any deployment, but every byte
19
+ // rides inside one JSON-RPC request — mcp-host caps that at ~9.9 MiB — and
20
+ // a model must emit the base64 as tool-call text. Fine for a small file or
21
+ // a client with no shell; wrong for a batch of phone photos.
22
+ //
23
+ // Both converge on a {@link ResolvedUpload}, the same shape a disk `path`
24
+ // resolves to, so everything after this point — the My Files POST, the
25
+ // SHARED confirmation, the attachment cache — is one code path.
26
+ import { createHash, randomUUID } from 'node:crypto';
27
+ import { z } from 'zod';
28
+ import { parseLenient } from '@chrischall/mcp-utils';
29
+ import { MAX_UPLOAD_BYTES, mimeFromName, normalizeMimeType } from './attachments.js';
30
+ import { formatInstant } from '../timestamps.js';
31
+ /** Most files one call may upload (inline array, blobKeys, uploadSlots). */
32
+ export const MAX_FILES_PER_CALL = 10;
33
+ /**
34
+ * How long an upload slot's PUT URL works. Long enough to find the file and
35
+ * run a curl; short, because the URL is a credential to write this key.
36
+ */
37
+ export const UPLOAD_SLOT_TTL_MS = 30 * 60 * 1000;
38
+ /** Object-key prefix for caller uploads — the only keys `blobKeys` accepts. */
39
+ export const UPLOAD_BLOB_PREFIX = 'uploads';
40
+ const MIB = 1024 * 1024;
41
+ const LIMIT_TEXT = `${MAX_UPLOAD_BYTES / MIB} MiB (${MAX_UPLOAD_BYTES} bytes)`;
42
+ export const inlineFileSchema = z.object({
43
+ filename: z.string().describe('Filename OFW will show, e.g. "Finn_Think_Sheet_2026-11-03.jpg" — a bare name, no path, not starting with a dot. Its extension sets the MIME type when mimeType is omitted.'),
44
+ contentBase64: z.string().describe('The file\'s bytes, standard base64 (line breaks and a "data:<type>;base64," prefix are tolerated).'),
45
+ mimeType: z.string().describe('MIME type, e.g. "image/jpeg". Default: inferred from the filename extension (jpg/jpeg, png, heic, pdf, docx, …).').optional(),
46
+ });
47
+ export const uploadSlotRequestSchema = z.object({
48
+ filename: z.string().describe('Filename OFW will show — a bare name, no path, not starting with a dot.'),
49
+ mimeType: z.string().describe('MIME type. Default: inferred from the filename extension. The PUT must send exactly this Content-Type.').optional(),
50
+ });
51
+ /**
52
+ * A caller-supplied filename, as the name OFW will show. It must be ONE
53
+ * plain segment: it names the file in the co-parent's view, so a path or a
54
+ * hidden-file name has no legitimate use and is refused rather than repaired.
55
+ */
56
+ export function sanitizeUploadFilename(raw) {
57
+ const name = raw.trim();
58
+ if (name.length === 0)
59
+ throw new Error('filename is empty.');
60
+ if (/[/\\]/.test(name)) {
61
+ throw new Error(`filename ${JSON.stringify(name)} must be a bare filename, not a path — pass just the name OFW should show, e.g. "photo.jpg".`);
62
+ }
63
+ // eslint-disable-next-line no-control-regex
64
+ if (/[\x00-\x1f\x7f]/.test(name))
65
+ throw new Error(`filename ${JSON.stringify(name)} contains control characters.`);
66
+ if (name.startsWith('.')) {
67
+ throw new Error(`filename ${JSON.stringify(name)} must not start with a dot (hidden files are never uploaded).`);
68
+ }
69
+ if (name.length > 200)
70
+ throw new Error('filename is longer than 200 characters.');
71
+ return name;
72
+ }
73
+ const MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/;
74
+ /** The MIME type to upload under: an explicit one (bare, validated), else the extension's. */
75
+ export function resolveUploadMime(fileName, mimeType) {
76
+ if (mimeType === undefined)
77
+ return mimeFromName(fileName);
78
+ const bare = normalizeMimeType(mimeType);
79
+ if (!MEDIA_TYPE.test(bare)) {
80
+ throw new Error(`mimeType ${JSON.stringify(mimeType)} is not a type/subtype media type such as "image/jpeg".`);
81
+ }
82
+ return bare;
83
+ }
84
+ /** Refuse an empty file or one over the upload cap, naming the limit. */
85
+ export function checkUploadSize(fileName, size) {
86
+ if (size === 0)
87
+ throw new Error(`${fileName} is empty (0 bytes); nothing to upload.`);
88
+ if (size > MAX_UPLOAD_BYTES) {
89
+ throw new Error(`${fileName} is too large (${size} bytes); the upload limit is ${LIMIT_TEXT}.`);
90
+ }
91
+ }
92
+ const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
93
+ /**
94
+ * Decode caller base64 STRICTLY. `Buffer.from(s, 'base64')` never throws — it
95
+ * silently drops what it does not recognise — so a truncated or mangled
96
+ * payload would otherwise be uploaded as a corrupt file and only discovered
97
+ * by the co-parent. The size is checked from the encoded length before any
98
+ * allocation, so an oversized payload costs nothing to refuse.
99
+ */
100
+ export function decodeBase64Content(content, fileName) {
101
+ const compact = content.replace(/^data:[^,]*;base64,/i, '').replace(/\s+/g, '');
102
+ if (compact.length === 0)
103
+ throw new Error(`${fileName} is empty (0 bytes); nothing to upload.`);
104
+ 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.`);
105
+ if (compact.length % 4 !== 0 || !BASE64.test(compact))
106
+ throw invalid();
107
+ const padding = compact.endsWith('==') ? 2 : compact.endsWith('=') ? 1 : 0;
108
+ checkUploadSize(fileName, (compact.length / 4) * 3 - padding);
109
+ const bytes = Buffer.from(compact, 'base64');
110
+ // Non-canonical trailing bits decode to the same bytes as a different
111
+ // string; the round trip refuses them rather than guessing intent.
112
+ if (bytes.toString('base64') !== compact)
113
+ throw invalid();
114
+ return bytes;
115
+ }
116
+ /** An `inline` entry → the upload it describes, validated end to end. */
117
+ export function resolveInlineUpload(file) {
118
+ const fileName = sanitizeUploadFilename(file.filename);
119
+ const mimeType = resolveUploadMime(fileName, file.mimeType);
120
+ const bytes = decodeBase64Content(file.contentBase64, fileName);
121
+ return { blob: new Blob([new Uint8Array(bytes)], { type: mimeType }), fileName, mimeType, sizeBytes: bytes.length };
122
+ }
123
+ // ── Blob upload slots ────────────────────────────────────────────────────
124
+ // The filename rides in the key, base64url-encoded: the blob store only
125
+ // accepts [A-Za-z0-9._~-] segments, and a photo name routinely has spaces.
126
+ // A random UUID segment makes the key unguessable and per-slot unique.
127
+ const UPLOAD_KEY = new RegExp(`^${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_-]+)$`);
128
+ /**
129
+ * The filename an upload key was minted for. Only keys of the shape
130
+ * {@link mintUploadSlot} produces are accepted, so `blobKeys` can never be
131
+ * pointed at another object in this registration's store (a calendar export,
132
+ * an export zip) and pass it off as an upload.
133
+ */
134
+ export function fileNameFromBlobKey(key) {
135
+ const match = UPLOAD_KEY.exec(key);
136
+ if (!match) {
137
+ throw new Error(`blobKey ${JSON.stringify(key)} is not an upload key. Pass the blobKey exactly as ofw_upload_attachment's uploadSlots returned it.`);
138
+ }
139
+ return sanitizeUploadFilename(Buffer.from(match[1], 'base64url').toString('utf8'));
140
+ }
141
+ /** Mint one signed PUT slot for a caller upload. */
142
+ export function mintUploadSlot(store, req) {
143
+ const filename = sanitizeUploadFilename(req.filename);
144
+ const mimeType = resolveUploadMime(filename, req.mimeType);
145
+ const blobKey = `${UPLOAD_BLOB_PREFIX}/${randomUUID()}/${Buffer.from(filename, 'utf8').toString('base64url')}`;
146
+ const { url, expiresAtMs } = store.signPutUrl(blobKey, mimeType, { ttlMs: UPLOAD_SLOT_TTL_MS });
147
+ const shellName = filename.replace(/'/g, `'\\''`);
148
+ return {
149
+ filename,
150
+ mimeType,
151
+ blobKey,
152
+ method: 'PUT',
153
+ uploadUrl: url,
154
+ expiresAt: formatInstant(new Date(expiresAtMs)).iso,
155
+ // The signature commits to the Content-Type, so the header must match it
156
+ // byte for byte; --fail turns a refused PUT into a non-zero exit.
157
+ curl: `curl -sS --fail -X PUT -H 'Content-Type: ${mimeType}' --data-binary @'<path to ${shellName}>' '${url}'`,
158
+ };
159
+ }
160
+ /** A consumed blob object → the upload it holds. */
161
+ export function blobObjectToUpload(key, object) {
162
+ const fileName = fileNameFromBlobKey(key);
163
+ checkUploadSize(fileName, object.bytes.length);
164
+ // The stored type is the one the PUT signature committed to, i.e. the one
165
+ // this server minted the slot for.
166
+ const mimeType = normalizeMimeType(object.contentType ?? mimeFromName(fileName));
167
+ return {
168
+ blob: new Blob([object.bytes], { type: mimeType }),
169
+ fileName,
170
+ mimeType,
171
+ sizeBytes: object.bytes.length,
172
+ };
173
+ }
174
+ // ── The My Files upload ──────────────────────────────────────────────────
175
+ export const UploadedFileSchema = z.looseObject({
176
+ fileId: z.number(),
177
+ fileName: z.string().optional(),
178
+ label: z.string().optional(),
179
+ fileType: z.string().optional(),
180
+ sizeInBytes: z.number().optional(),
181
+ shareClass: z.string().optional(),
182
+ });
183
+ /**
184
+ * POST one resolved upload to OFW's My Files, the multipart shape of the OFW
185
+ * web UI's own request, and cache its metadata under the not-yet-linked
186
+ * `messageId: 0` sentinel so a later download or send can name it. The
187
+ * response is parsed STRICTLY: an unusable fileId cached here would be
188
+ * attached to a message later.
189
+ */
190
+ export async function uploadToMyFiles(client, cache, upload, opts) {
191
+ const { blob, fileName, mimeType, sizeBytes } = upload;
192
+ const form = new FormData();
193
+ form.append('file', blob, fileName);
194
+ form.append('source', 'message');
195
+ form.append('description', opts.description ?? fileName);
196
+ form.append('label', opts.label ?? fileName);
197
+ form.append('fileName', fileName);
198
+ form.append('shareClass', opts.shareClass);
199
+ 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' });
200
+ const stored = {
201
+ fileName: meta.fileName ?? fileName,
202
+ mimeType: meta.fileType ?? mimeType,
203
+ sizeBytes: typeof meta.sizeInBytes === 'number' ? meta.sizeInBytes : sizeBytes,
204
+ };
205
+ await cache.upsertAttachmentForMessage({
206
+ fileId: meta.fileId,
207
+ fileName: stored.fileName,
208
+ label: meta.label ?? opts.label ?? fileName,
209
+ mimeType: stored.mimeType,
210
+ sizeBytes: stored.sizeBytes,
211
+ metadata: meta,
212
+ messageId: 0,
213
+ });
214
+ return { fileId: meta.fileId, ...stored, bytes: sizeBytes, shareClass: meta.shareClass ?? opts.shareClass };
215
+ }
216
+ /** SHA-256 of an upload's bytes, hex — what a confirmation binds. */
217
+ export async function sha256Hex(blob) {
218
+ return createHash('sha256').update(new Uint8Array(await blob.arrayBuffer())).digest('hex');
219
+ }
220
+ /** Refuse a call naming more than {@link MAX_FILES_PER_CALL} files. */
221
+ export function checkFileCount(count, what) {
222
+ if (count > MAX_FILES_PER_CALL) {
223
+ throw new Error(`${what}: at most ${MAX_FILES_PER_CALL} files per call (got ${count}). Split them across calls.`);
224
+ }
225
+ }
226
+ /** The blob store, or a refusal that says what to use instead. */
227
+ export function requireBlobStore(store, what) {
228
+ if (store)
229
+ return store;
230
+ 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\`.`);
231
+ }
232
+ // ── Attaching in one step (ofw_save_draft / ofw_send_message) ────────────
233
+ export const inlineAttachmentsParam = z.array(inlineFileSchema).max(MAX_FILES_PER_CALL).describe('Files to attach, supplied as base64 BYTES ({filename, contentBase64, mimeType?}). Each is uploaded to My Files as PRIVATE, '
234
+ + 'then attached alongside any myFileIDs. Use for small files; on a hosted deployment, larger files (phone photos) go faster '
235
+ + 'through ofw_upload_attachment uploadSlots + blobKeys here. Every entry is validated before anything is uploaded.').optional();
236
+ export const blobKeysParam = z.array(z.string()).max(MAX_FILES_PER_CALL).describe('Hosted deployments: blobKeys from ofw_upload_attachment uploadSlots whose files you have already PUT. Each is uploaded to '
237
+ + 'My Files as PRIVATE, attached alongside any myFileIDs, and deleted from the upload store.').optional();
238
+ /**
239
+ * Validate every new attachment BEFORE anything is uploaded, so a bad entry
240
+ * fails the call with nothing half-done. With `readBlobs`, blob objects are
241
+ * read (not consumed) so a confirmation can bind their exact bytes.
242
+ */
243
+ export async function planAttachments(input, opts) {
244
+ const inline = input.inline ?? [];
245
+ const keys = input.blobKeys ?? [];
246
+ checkFileCount(inline.length + keys.length, 'inlineAttachments + blobKeys');
247
+ const pending = [];
248
+ for (const file of inline) {
249
+ const upload = resolveInlineUpload(file);
250
+ pending.push({ fileName: upload.fileName, mimeType: upload.mimeType, sizeBytes: upload.sizeBytes, sha256: await sha256Hex(upload.blob), inline: upload });
251
+ }
252
+ if (keys.length > 0) {
253
+ const store = requireBlobStore(opts.store, 'blobKeys');
254
+ for (const blobKey of keys) {
255
+ const fileName = fileNameFromBlobKey(blobKey);
256
+ if (!opts.readBlobs) {
257
+ pending.push({ fileName, mimeType: null, sizeBytes: null, sha256: null, blobKey });
258
+ continue;
259
+ }
260
+ const upload = blobObjectToUpload(blobKey, await store.get(blobKey, { maxBytes: MAX_UPLOAD_BYTES }));
261
+ pending.push({ fileName, mimeType: upload.mimeType, sizeBytes: upload.sizeBytes, sha256: await sha256Hex(upload.blob), blobKey });
262
+ }
263
+ }
264
+ return pending;
265
+ }
266
+ /** What a preview shows of the new attachments. */
267
+ export function describePending(pending) {
268
+ return pending.map((p) => ({ fileName: p.fileName, mimeType: p.mimeType, sizeBytes: p.sizeBytes, sha256: p.sha256, upload: 'PRIVATE, on approval' }));
269
+ }
270
+ /**
271
+ * Upload the planned attachments PRIVATE, in order. A blob is consumed —
272
+ * deleted once OFW has it; a failed delete is a warning, never a failure. Any
273
+ * upload failure stops the batch and throws, naming what DID upload, so the
274
+ * caller can retry with those fileIds instead of uploading them twice.
275
+ */
276
+ export async function uploadPending(pending, ctx) {
277
+ const uploaded = [];
278
+ const warnings = [];
279
+ for (const p of pending) {
280
+ try {
281
+ if (p.inline) {
282
+ uploaded.push(await uploadToMyFiles(ctx.client, ctx.cache, p.inline, { shareClass: 'PRIVATE' }));
283
+ continue;
284
+ }
285
+ const out = await ctx.store.consume(p.blobKey, async (object) => {
286
+ const upload = blobObjectToUpload(p.blobKey, object);
287
+ if (p.sha256 !== null && (await sha256Hex(upload.blob)) !== p.sha256) {
288
+ throw new Error(`${p.fileName} changed in the upload store after it was previewed`);
289
+ }
290
+ return uploadToMyFiles(ctx.client, ctx.cache, upload, { shareClass: 'PRIVATE' });
291
+ }, { maxBytes: MAX_UPLOAD_BYTES });
292
+ uploaded.push(out.result);
293
+ if (!out.deleted) {
294
+ 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.`);
295
+ }
296
+ }
297
+ catch (e) {
298
+ const done = uploaded.map((u) => `${u.fileName} (fileId ${u.fileId})`);
299
+ throw new Error(`Attachment ${p.fileName} could not be uploaded: ${e.message}. Nothing was ${ctx.nothingWas}.`
300
+ + (done.length > 0
301
+ ? ` Already uploaded to My Files (PRIVATE): ${done.join(', ')} — pass those fileIds in myFileIDs when you retry instead of uploading them again.`
302
+ : ''));
303
+ }
304
+ }
305
+ return { uploaded, warnings };
306
+ }
307
+ // ── Hosted detection ─────────────────────────────────────────────────────
308
+ // Defined beside the code that needs them without importing this module
309
+ // (config.ts, attachments.ts), re-exported here as part of the upload surface.
310
+ export { hasBlobStoreEnv, isHostedDeployment } from '../config.js';
311
+ export { hostedPathRefusal } from './attachments.js';
package/dist/version.js CHANGED
@@ -4,4 +4,4 @@
4
4
  // package.json drift. Importing these instead of package.json keeps the whole
5
5
  // manifest — npm scripts included — out of dist/bundle.js.
6
6
  export const SERVER_NAME = 'ofw-mcp';
7
- export const VERSION = '2.26.0'; // x-release-please-version
7
+ export const VERSION = '2.27.0'; // x-release-please-version
package/mint.yaml CHANGED
@@ -207,3 +207,8 @@ egress:
207
207
  # file URL (no OFW credential is sent there; every redirect hop is
208
208
  # re-checked against this suffix in src/tools/expenses.ts).
209
209
  - "*.oaiusercontent.com"
210
+ # Not listed: mcp-host's own blob store (MCP_BLOB_BASE_URL, the gateway
211
+ # serving this connector — its host differs per deployment). The server
212
+ # PUTs .ics exports and download links there, and GETs + DELETEs files the
213
+ # caller uploaded through ofw_upload_attachment uploadSlots. Signed
214
+ # requests only; no OFW credential is ever sent.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ofw-mcp",
3
- "version": "2.26.0",
3
+ "version": "2.27.0",
4
4
  "license": "MIT",
5
5
  "mcpName": "io.github.chrischall/ofw-mcp",
6
6
  "description": "OurFamilyWizard MCP server for Claude — developed and maintained by AI (Claude Code)",
@@ -34,7 +34,7 @@
34
34
  "typecheck": "tsc -p tsconfig.json --noEmit"
35
35
  },
36
36
  "dependencies": {
37
- "@chrischall/mcp-utils": "^3.1.0",
37
+ "@chrischall/mcp-utils": "^3.5.0",
38
38
  "@fetchproxy/bootstrap": "^3.6.2",
39
39
  "@modelcontextprotocol/server": "^2.3.0",
40
40
  "dotenv": "^18.0.0",
package/server.json CHANGED
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/chrischall/ofw-mcp",
7
7
  "source": "github"
8
8
  },
9
- "version": "2.26.0",
9
+ "version": "2.27.0",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "ofw-mcp",
14
- "version": "2.26.0",
14
+ "version": "2.27.0",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },
@@ -94,13 +94,13 @@ Always pass `--config ~/.mcporter/mcporter.json` unless a local `config/mcporter
94
94
  | `ofw_list_message_folders` | List OFW folders with unread counts. Most reads use the cache; this is mainly for folder IDs and live unread counts. |
95
95
  | `ofw_list_messages(folderId?, since?, until?, q?, sort?, page?, size?, autoRefresh?, view?)` | Cache-backed list. Supports folder ("inbox"/"sent"/"both"), date range, and substring search. `sort:"oldest"` starts at the old end of a range instead of paging to it (default `"newest"`). Returns `complete` for the RESULT SET plus **`nextPage`** (null when done) — and the paging keys come FIRST in the JSON, before `messages`. `returned` carries the record count as a scalar, beside `total`. An **empty** result from a non-fresh cache is refused (`UNVERIFIED_EMPTY`) — pass `autoRefresh:true` to sync and answer instead. |
96
96
  | `ofw_get_message(messageId, allowMarkRead?, view?)` | Read a message OR draft body. Cache-first. Ids in the drafts cache return `folder: "drafts"`. ⚠️ Falls through to OFW for unread inbox messages, which marks them read AND stamps a "First Viewed" time the co-parent can see — irreversible. Pass `allowMarkRead:false` to refuse that fetch instead; cached, sent and already-read messages are unaffected. If the server runs with `OFW_CONFIRM_MARK_READ`, the first call returns a preview (subject, sender, sent time) instead of the body: show it to the user and repeat the call with its `confirmToken` only after they say yes. On a server-configured no-read day (`readingBlocked` / `READING_BLOCKED` in the response) the body is withheld (`bodyWithheld: true`) — report the sender, date and subject, say when `nextReadableDay` is, and do not try to work around it. |
97
- | `ofw_send_message(draftId?, subject?, body?, recipientIds?, replyToId?, expectedRevision?, deleteDraftOnSuccess?, myFileIDs?, force?)` | Send a message — **the one irreversible operation**. Preferred path: pass `draftId` (+ `expectedRevision`) to send an existing draft **as it exists on the server** — the tool re-reads it from OFW first and refuses if it changed since you read it (or was already sent/deleted); `subject`/`body` become optional overrides. `recipientIds` is usually still required: OFW does not store recipients on drafts. After a **confirmed** send the draft is auto-deleted (`deleteDraftOnSuccess:false` to keep it); on any failure or ambiguity it is retained and the response says why (`draftRetained`). Response leads with `sentMessageId`, `draftKey`, `threaded`, `draftDeleted`. Compose from scratch by passing `subject`/`body`/`recipientIds` with no `draftId`. |
97
+ | `ofw_send_message(draftId?, subject?, body?, recipientIds?, replyToId?, expectedRevision?, deleteDraftOnSuccess?, myFileIDs?, inlineAttachments?, blobKeys?, force?)` | Send a message — **the one irreversible operation**. Preferred path: pass `draftId` (+ `expectedRevision`) to send an existing draft **as it exists on the server** — the tool re-reads it from OFW first and refuses if it changed since you read it (or was already sent/deleted); `subject`/`body` become optional overrides. `recipientIds` is usually still required: OFW does not store recipients on drafts. After a **confirmed** send the draft is auto-deleted (`deleteDraftOnSuccess:false` to keep it); on any failure or ambiguity it is retained and the response says why (`draftRetained`). Response leads with `sentMessageId`, `draftKey`, `threaded`, `draftDeleted`. Compose from scratch by passing `subject`/`body`/`recipientIds` with no `draftId`. `inlineAttachments`/`blobKeys` upload new files (PRIVATE) only after approval and attach them alongside `myFileIDs`. |
98
98
  | `ofw_get_unread_sent(page?, size?, autoRefresh?)` | Sent messages your co-parent hasn't read yet (from cache). Leads with `complete`/`hasMore`/`nextPage`, then `scanned`/`total`, then `unread`; an empty sent cache that is not fresh is refused rather than reported as "nothing sent". |
99
99
  | `ofw_list_drafts(page?, size?, verify?, autoRefresh?, view?)` | Leads with `complete`/`hasMore`/`nextPage`; `drafts` comes last. List saved drafts, **auto-verified**: when the cache is not verified-fresh a cheap drafts sync runs first (default `verify:true`), so one call answers server-confirmed. `verify:false` serves straight from cache. Each draft carries `serverConfirmed`, `revision` and `draftKey`. Returns `complete` — **check it before saying "you have N drafts"**. See [Freshness](#freshness). |
100
- | `ofw_save_draft(subject, body, recipientIds?, messageId?, replyToId?, myFileIDs?, expectedRevision?, force?)` | Create a new draft. Pass `messageId` to **replace** an existing draft: the tool creates a fresh draft and deletes the old one (OFW's update-in-place endpoint silently no-ops). The returned `id` is the NEW id; the response leads with `draftKey`, which stays the same across every edit — **track that, not the id**. Note: OFW does **not** store recipients on drafts — `recipientIds` are accepted but come back empty (a one-line NOTE says so; supply them at send time instead). Threading warnings fire only on genuine drops — a draft echoing `inReplyTo`/`showContext` IS threaded. |
100
+ | `ofw_save_draft(subject, body, recipientIds?, messageId?, replyToId?, myFileIDs?, inlineAttachments?, blobKeys?, expectedRevision?, force?)` | Create a new draft. Pass `messageId` to **replace** an existing draft: the tool creates a fresh draft and deletes the old one (OFW's update-in-place endpoint silently no-ops). The returned `id` is the NEW id; the response leads with `draftKey`, which stays the same across every edit — **track that, not the id**. Note: OFW does **not** store recipients on drafts — `recipientIds` are accepted but come back empty (a one-line NOTE says so; supply them at send time instead). Threading warnings fire only on genuine drops — a draft echoing `inReplyTo`/`showContext` IS threaded. Replacing a draft KEEPS its attachments unless you pass `myFileIDs`; `inlineAttachments`/`blobKeys` upload and add new files in the same call. |
101
101
  | `ofw_delete_draft(messageId)` | Delete a draft. |
102
- | `ofw_upload_attachment(path, shareClass?, label?, description?)` | Upload a local file to My Files; returns a fileId to pass into `myFileIDs`. Only files inside the upload directory (`OFW_UPLOAD_DIR`, default `~/Downloads/ofw-mcp`) can be uploaded; hidden files are refused. `shareClass:"SHARED"` needs write mode `all`. |
103
- | `ofw_download_attachment(fileId, inline?, saveTo?, force?, extract?, maxChars?, parts?)` | Download an attachment. Inline delivery returns the first rung that works: image → `ImageContent`; .xlsx/.csv/.pdf/.docx/.pptx/text → **extracted content** under `extracted` (per-sheet CSV, per-page/slide text); anything else → raw bytes. Default writes to `~/Downloads/ofw-mcp/` (add `extract:true` for content too). Use `parts:"1-2"` / a sheet name and `maxChars` on large files. Images and raw bytes over 10 MiB are not returned inline (tool error) — use disk mode or open the file in OFW. |
102
+ | `ofw_upload_attachment(path \| inline \| uploadSlots \| blobKeys, shareClass?, label?, description?)` | Upload to My Files; returns fileIds for `myFileIDs`. Exactly one source. **Hosted connector (claude.ai): `path` cannot work.** For real files (photos), call `uploadSlots:[{filename}]`, run each slot's `curl` with the file, then call again with `blobKeys`; for a small file pass `inline:{filename, contentBase64}`. Local installs: `path` inside the upload directory (`OFW_UPLOAD_DIR`). Up to 10 files per call, 25 MiB each; a batch reports per-file `results`. `shareClass:"SHARED"` is one file, confirm-gated, mode `all`. |
103
+ | `ofw_download_attachment(fileId, inline?, saveTo?, force?, extract?, maxChars?, parts?, link?, linkMinutes?)` | Download an attachment. Inline delivery returns the first rung that works: image → `ImageContent`; .xlsx/.csv/.pdf/.docx/.pptx/text → **extracted content** under `extracted` (per-sheet CSV, per-page/slide text); anything else → raw bytes. Default writes to `~/Downloads/ofw-mcp/` (add `extract:true` for content too). Use `parts:"1-2"` / a sheet name and `maxChars` on large files. Images and raw bytes over 10 MiB are not returned inline (tool error) — use disk mode or open the file in OFW. On a hosted connector, `inline:false`/`link:true` returns a private expiring download link instead, and an over-10-MiB inline image falls back to one. |
104
104
  | `ofw_check_freshness(folders?, messageIds?, allowMarkRead?)` | Cheap live check that the cache still matches OFW — one request for folder counts plus one per id, no bodies, no sync. Each id gets a live `state` (`draft`/`sent`/`received`/`deleted`/`unknown`) plus `folder` and `sentAt`. Probes ids cached as drafts, as sent, or as already-read inbox messages freely; anything else needs `allowMarkRead:true` (it would mark an inbox message read). |
105
105
  | `ofw_status(ids?, draftKeys?, includeDraftInventory?, allowMarkRead?)` | **The status call.** One live round trip. With no arguments: the full, server-verified draft inventory. With `ids`/`draftKeys`: each one's live lifecycle state. Top-level `complete` is true only when every part was verified live. |
106
106
 
@@ -193,11 +193,14 @@ projection.
193
193
  Every tool except `ofw_healthcheck` carries a `_meta.mint` hint in the
194
194
  **family** group, so a host such as mcp-host can answer a "what's going on
195
195
  with the family" ask across OFW and its sibling connectors. Two reads are
196
- canonical, and both take `view: "brief"` (plain text, one line per item,
197
- `title — <ISO date | no date> — <status>`). A line starting with `-- ` is a
198
- note, not an item: `-- N of M shown` ends a page that is not the whole result
199
- (walk `page`, or narrow the range), and `-- none` is the whole answer when
200
- nothing matched:
196
+ canonical, and both take `view: "brief"` (one line per item,
197
+ `title — <ISO date | no date> — <status>`, at most 120 chars). The lines carry
198
+ text other people wrote, so they arrive inside the untrusted-data envelope as
199
+ `data` (`{"untrusted_content":true,"note":…,"data":[…]}`). A line starting
200
+ with `-- ` is a note, not an item: `-- N of M shown` ends a page that is not
201
+ the whole result (walk `page`, or narrow the range), and `-- none` is the
202
+ whole answer when nothing matched. A title that itself starts with `-- ` or
203
+ `\` is escaped with one leading `\`:
201
204
 
202
205
  - **What's new:** `ofw_list_messages`, its range on `since` / `until`. A line
203
206
  is `sender: subject — sent — unread|read|sent`. It reads the local cache, so