@chrischall/hellofresh-mcp 0.0.0-stage → 0.1.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,572 @@
1
+ // The write tools (docs/HELLOFRESH-API.md "Writes" 1–5), each confirm-gated:
2
+ //
3
+ // plan — validate the arguments against a FRESH read (status, cutoff,
4
+ // allowed actions, menu indexes, offered sizes/slots) and build the
5
+ // exact request with the client's own builder, so the preview IS
6
+ // what is sent;
7
+ // gate — `confirmWrite` (elicitation, or a phase-1 preview + confirmToken);
8
+ // execute — send it, then RE-READ and compare, answering
9
+ // `{status: 'verified' | 'unverified', before, after}` honestly.
10
+ //
11
+ // A write that was sent and then timed out / dropped / got a 5xx answers
12
+ // `status: 'unknown'` (not an error), so the model checks before repeating it.
13
+ // Cancelling the subscription and the meal-preference preset are deliberately
14
+ // not exposed (see the API doc).
15
+ //
16
+ // `registerWrite` from mcp-utils cannot carry `_meta`, which the context-group
17
+ // hints need, so `registerGated` below is the same plan → confirmWrite →
18
+ // execute flow with `_meta`.
19
+ import { z } from 'zod';
20
+ import { CONFIRM_FLOW_SENTENCE, CONFIRM_INJECTION_RULE, McpToolError, confirmTokenParam, confirmWrite, minifiedResult, toolAnnotations, writeOrUnknown, } from '@chrischall/mcp-utils';
21
+ import { deliveryStatusRequest, oneOffRequest, weekSizeRequest, planDeliveryDetailsRequest, planProductRequest, selectMealsRequest, } from '../client.js';
22
+ import { projectDelivery } from '../normalize.js';
23
+ import { foodMeta } from './hints.js';
24
+ import { attempt, compactSelection, customerPlanIdOf, dateOf, isUnresizableFirstBox, loadAccount, readMenu, sleepMs, weekParam, } from './shared.js';
25
+ function registerGated(server, def) {
26
+ server.registerTool(def.name, {
27
+ description: `${def.description} ${CONFIRM_FLOW_SENTENCE} ${CONFIRM_INJECTION_RULE}`,
28
+ annotations: toolAnnotations({ title: def.title, readOnly: false, destructive: def.destructive, idempotent: true, openWorld: true }),
29
+ _meta: def.meta,
30
+ inputSchema: z.object({ ...def.input, confirmToken: confirmTokenParam }),
31
+ }, async (input, ctx) => {
32
+ const { confirmToken, ...args } = input;
33
+ const { gate, state } = await def.plan(args);
34
+ const blocked = await confirmWrite(ctx, { ...gate, tool: def.name, confirmToken, args });
35
+ if (blocked)
36
+ return blocked;
37
+ return def.execute(state);
38
+ });
39
+ }
40
+ /** A write as `confirmWrite` previews and binds it: the path as sent on www.hellofresh.com. */
41
+ const shown = (w) => ({ method: w.method, path: `/gw${w.path}`, query: w.query, body: w.body });
42
+ const CHANGE = (aliases) => foodMeta('change', { aliases });
43
+ /**
44
+ * Send `send`, then re-read with `verify`. A send whose outcome is unknown
45
+ * answers `status: 'unknown'`; a re-read that fails answers `unverified` with
46
+ * the reason.
47
+ */
48
+ async function sendAndVerify(opts) {
49
+ const sent = await writeOrUnknown(opts.send, (_err, reason) => minifiedResult({
50
+ status: 'unknown',
51
+ before: opts.before,
52
+ warning: `HelloFresh did not confirm this change (${reason}), so it may already have happened. ` +
53
+ `Check with ${opts.checkWith} before repeating it; do not repeat it blindly.`,
54
+ }));
55
+ if (!sent.ok)
56
+ return sent.result;
57
+ const extra = opts.extra?.(sent.value) ?? {};
58
+ const check = await attempt(opts.verify);
59
+ if (!check.ok) {
60
+ return minifiedResult({
61
+ status: 'unverified',
62
+ before: opts.before,
63
+ ...extra,
64
+ verifyError: check.reason,
65
+ warning: `HelloFresh accepted the request, but re-reading it failed. Check with ${opts.checkWith}.`,
66
+ });
67
+ }
68
+ return minifiedResult({
69
+ status: check.value.ok ? 'verified' : 'unverified',
70
+ before: opts.before,
71
+ after: check.value.after,
72
+ ...extra,
73
+ ...check.value.extra,
74
+ ...(check.value.ok ? {} : { warning: `${opts.mismatch} Check with ${opts.checkWith} before trying again.` }),
75
+ });
76
+ }
77
+ /** The week, refused when its cutoff has passed. */
78
+ async function openWeek(client, account, week, now) {
79
+ const raw = await client.getDelivery(account.subscriptionId, week);
80
+ const delivery = projectDelivery(raw);
81
+ if (delivery.cutoffDate && Date.parse(delivery.cutoffDate) <= now) {
82
+ throw new McpToolError(`The cutoff for ${week} passed at ${delivery.cutoffDate}; HelloFresh no longer accepts changes to it.`);
83
+ }
84
+ return { raw, delivery };
85
+ }
86
+ /** Refuse a change HelloFresh marks as not allowed for the week. */
87
+ function requireAllowed(raw, week, action) {
88
+ if (raw.allowedActions?.[action] === false) {
89
+ throw new McpToolError(`HelloFresh does not allow this change for ${week} (${action} is not allowed for it).`);
90
+ }
91
+ }
92
+ /** Refuse a week that is not running (skipped → unskip first). */
93
+ function requireRunning(delivery, week, what) {
94
+ if (delivery.status === 'skipped') {
95
+ throw new McpToolError(`${week} is skipped, so you cannot ${what}. Unskip it first with hf_unskip_week.`);
96
+ }
97
+ if (delivery.status !== 'running')
98
+ throw new McpToolError(`${week} is ${delivery.status}, so you cannot ${what}.`);
99
+ }
100
+ /** The SKUs this subscription can switch to; refuses one not among them. */
101
+ async function requireOfferedSku(client, account, sku) {
102
+ const options = await client.getProductOptions(account.subscriptionId);
103
+ const offered = (options.items ?? []).flatMap((g) => (g.products ?? []).flatMap((p) => (p.handle ? [p.handle] : [])));
104
+ if (!offered.includes(sku)) {
105
+ throw new McpToolError(`This subscription cannot switch to ${sku}. Sizes offered: ${offered.join(', ')}.`, {
106
+ hint: 'hf_list_box_sizes lists them as meals × people.',
107
+ });
108
+ }
109
+ }
110
+ /** Re-reads after a one-week size change before calling it unverified, and the wait between them. */
111
+ export const SIZE_VERIFY_READS = 3;
112
+ export const SIZE_VERIFY_DELAY_MS = 1500;
113
+ const skuOf = (meals, people) => `US-CBU-${meals}-${people}-0`;
114
+ const boxOf = (d) => ({
115
+ sku: d.sku,
116
+ meals: d.meals,
117
+ people: d.servings,
118
+ deliveryOption: d.deliveryOption,
119
+ });
120
+ const peopleParam = z
121
+ .union([z.literal(2), z.literal(3), z.literal(4), z.literal(6)])
122
+ .describe('People (servings per meal): 2, 3, 4 or 6.');
123
+ const mealsCountParam = (what) => z.number().int().min(1).max(6).describe(`Meals per week ${what}.`);
124
+ const SLOT = /^US-[1-7]-\d{4}-\d{4}$/;
125
+ // ---- registration ---------------------------------------------------------------------
126
+ export function registerWriteTools(server, deps) {
127
+ const { client } = deps;
128
+ const now = deps.now ?? Date.now;
129
+ const sleep = deps.sleep ?? sleepMs;
130
+ registerGated(server, {
131
+ name: 'hf_select_meals',
132
+ title: 'HelloFresh: pick meals for a week',
133
+ description: 'Pick the meals for one HelloFresh delivery week, replacing the current picks. Give the menu indexes from ' +
134
+ 'hf_get_menu (a protein swap’s index works too); the count (with quantities) must equal the box’s meals per ' +
135
+ 'week, and only before the week’s cutoff. Re-reads the menu afterwards to verify the picks.',
136
+ destructive: false,
137
+ meta: CHANGE(['pick hellofresh meals', 'choose meals', 'select recipes']),
138
+ input: {
139
+ week: weekParam,
140
+ meals: z
141
+ .array(z.union([
142
+ z.number().int().positive(),
143
+ z.object({ index: z.number().int().positive(), quantity: z.number().int().min(1).max(6) }),
144
+ ]))
145
+ .min(1)
146
+ .max(12)
147
+ .describe('The COMPLETE selection: menu indexes, or {index, quantity} for more than one of a meal. A repeated index adds up.'),
148
+ },
149
+ async plan({ week, meals }) {
150
+ const account = await loadAccount(client);
151
+ const { raw, delivery } = await openWeek(client, account, week, now());
152
+ requireRunning(delivery, week, 'pick its meals');
153
+ requireAllowed(raw, week, 'mealSwap');
154
+ if (!delivery.meals || !delivery.sku)
155
+ throw new McpToolError(`HelloFresh returned no meal count for ${week}'s box.`);
156
+ const menu = await readMenu(client, account, delivery, week);
157
+ const quantities = new Map();
158
+ for (const m of meals) {
159
+ const { index, quantity } = typeof m === 'number' ? { index: m, quantity: 1 } : m;
160
+ quantities.set(index, (quantities.get(index) ?? 0) + quantity);
161
+ }
162
+ const cart = [...quantities].map(([index, quantity]) => ({ index, quantity }));
163
+ const names = namesOf(menu);
164
+ const unknown = cart.filter((m) => !names.has(m.index)).map((m) => m.index);
165
+ if (unknown.length > 0) {
166
+ throw new McpToolError(`Meal ${unknown.join(', ')} is not on the ${week} menu.`, { hint: `hf_get_menu {week: "${week}"} lists the indexes.` });
167
+ }
168
+ const total = cart.reduce((n, m) => n + m.quantity, 0);
169
+ if (total !== delivery.meals) {
170
+ throw new McpToolError(`The ${week} box takes ${delivery.meals} meals; you picked ${total}.`, {
171
+ hint: 'Pick exactly that many (quantities count), or change the box with hf_set_week_size first.',
172
+ });
173
+ }
174
+ const customerId = account.subscription.customer?.id;
175
+ if (customerId === undefined)
176
+ throw new McpToolError('HelloFresh returned no customer id on the subscription, which the cart needs.');
177
+ const preference = account.subscription.preset;
178
+ if (!preference)
179
+ throw new McpToolError('HelloFresh returned no meal-preference preset on the subscription, which the cart needs.');
180
+ const request = { week, subscriptionId: account.subscriptionId, customerId, sku: delivery.sku, preference, meals: cart };
181
+ const before = menu.selected.map(compactSelection);
182
+ return {
183
+ gate: {
184
+ action: 'hellofresh.meals.select',
185
+ summary: `Pick ${total} meal(s) for the ${week} box (${delivery.meals}×${delivery.servings}), replacing the current picks`,
186
+ account: account.subscriptionId,
187
+ target: week,
188
+ revision: JSON.stringify(before.map((s) => [s.index, s.quantity])),
189
+ request: shown(selectMealsRequest(request)),
190
+ preview: {
191
+ currentPicks: before.map((s) => s.name),
192
+ newPicks: cart.map((m) => ({ ...m, name: names.get(m.index) })),
193
+ },
194
+ },
195
+ state: { account, delivery, week, meals: cart, request, before },
196
+ };
197
+ },
198
+ execute: (s) => sendAndVerify({
199
+ send: () => client.selectMeals(s.request),
200
+ before: s.before,
201
+ checkWith: `hf_get_delivery {week: "${s.week}"}`,
202
+ mismatch: 'HelloFresh accepted the request, but the re-read menu does not show exactly these picks.',
203
+ extra: (r) => (r.hasSeamlessDowngraded ? { hasSeamlessDowngraded: true } : {}),
204
+ verify: async () => {
205
+ const menu = await readMenu(client, s.account, s.delivery, s.week);
206
+ const after = menu.selected.map(compactSelection);
207
+ const key = (l) => JSON.stringify([...l].sort((a, b) => a.index - b.index).map((m) => [m.index, m.quantity]));
208
+ return { ok: key(after) === key(s.meals), after };
209
+ },
210
+ }),
211
+ });
212
+ registerGated(server, {
213
+ name: 'hf_set_week_size',
214
+ title: 'HelloFresh: change one week’s box size',
215
+ description: 'Change the box size (people, and optionally meals) of ONE HelloFresh delivery week only — the plan stays as it ' +
216
+ 'is (hf_change_plan_size changes it for good, and resets these one-week sizes). Keeps the week’s delivery day. ' +
217
+ 'The subscription’s first box cannot be resized (a HelloFresh rule) and is refused. HelloFresh may reset that ' +
218
+ 'week’s meal picks; the result says so, and hf_select_meals re-picks.',
219
+ destructive: false,
220
+ meta: CHANGE(['hellofresh box size this week', 'servings this week', 'change people']),
221
+ input: {
222
+ week: weekParam,
223
+ people: peopleParam,
224
+ meals: mealsCountParam('for this week (default: the week’s current count)').optional(),
225
+ },
226
+ async plan({ week, people, meals }) {
227
+ const account = await loadAccount(client);
228
+ if (isUnresizableFirstBox(account.subscription, week)) {
229
+ throw new McpToolError(`${week} is this subscription’s first box, and HelloFresh does not allow resizing the first box.`, {
230
+ hint: 'It keeps the size it was ordered with; every later week can be resized with hf_set_week_size.',
231
+ });
232
+ }
233
+ const { raw, delivery } = await openWeek(client, account, week, now());
234
+ requireRunning(delivery, week, 'change its box size');
235
+ requireAllowed(raw, week, 'oneOffChange');
236
+ const count = meals ?? delivery.meals;
237
+ if (!count)
238
+ throw new McpToolError(`HelloFresh returned no meal count for ${week}'s box; pass meals.`);
239
+ const sku = skuOf(count, people);
240
+ if (sku === delivery.sku)
241
+ throw new McpToolError(`${week} is already a ${count}-meal box for ${people}.`);
242
+ await requireOfferedSku(client, account, sku);
243
+ const picks = await attempt(() => readMenu(client, account, delivery, week));
244
+ const currentPicks = picks.ok ? picks.value.selected.map(compactSelection) : undefined;
245
+ const request = { subscriptionId: account.subscriptionId, week, sku };
246
+ const from = { sku: delivery.sku, meals: delivery.meals, people: delivery.servings };
247
+ return {
248
+ gate: {
249
+ action: 'hellofresh.week.size',
250
+ summary: `Change the ${week} box to ${count} meals for ${people} people (this week only)`,
251
+ account: account.subscriptionId,
252
+ target: week,
253
+ request: shown(weekSizeRequest(request)),
254
+ preview: {
255
+ from,
256
+ to: { sku, meals: count, people },
257
+ ...(currentPicks ? { currentPicks: currentPicks.map((p) => p.name) } : {}),
258
+ warning: 'HelloFresh may reset this week’s meal picks when the size changes; re-pick with hf_select_meals if so.',
259
+ },
260
+ },
261
+ state: { account, week, request, before: boxOf(delivery), beforePicks: currentPicks?.length },
262
+ };
263
+ },
264
+ execute: (s) => sendAndVerify({
265
+ send: () => client.setWeekSize(s.request),
266
+ before: s.before,
267
+ checkWith: `hf_get_delivery {week: "${s.week}"}`,
268
+ mismatch: `HelloFresh accepted the request, but ${SIZE_VERIFY_READS} re-reads of the week do not show the new box size.`,
269
+ verify: async () => {
270
+ // The new size can take a moment to show: re-read a few times before calling it unverified.
271
+ let delivery = projectDelivery(await client.getDelivery(s.account.subscriptionId, s.week));
272
+ for (let read = 1; read < SIZE_VERIFY_READS && delivery.sku !== s.request.sku; read++) {
273
+ await sleep(SIZE_VERIFY_DELAY_MS);
274
+ delivery = projectDelivery(await client.getDelivery(s.account.subscriptionId, s.week));
275
+ }
276
+ const ok = delivery.sku === s.request.sku;
277
+ const picks = await attempt(() => readMenu(client, s.account, delivery, s.week));
278
+ const extra = picks.ok
279
+ ? { picksAfter: picks.value.selected.map(compactSelection) }
280
+ : { picksError: picks.reason };
281
+ if (picks.ok && picks.value.selected.length === 0 && (s.beforePicks ?? 0) > 0) {
282
+ extra.warning = 'The meal picks were reset by the size change; pick again with hf_select_meals.';
283
+ }
284
+ return { ok, after: boxOf(delivery), extra };
285
+ },
286
+ }),
287
+ });
288
+ registerGated(server, {
289
+ name: 'hf_set_week_delivery_day',
290
+ title: 'HelloFresh: move one week’s delivery day',
291
+ description: 'Move ONE HelloFresh delivery week to another delivery day/slot offered for that week (the week’s ' +
292
+ 'oneOffDaySlots from hf_get_delivery). Keeps the box size; the plan’s regular day is unchanged ' +
293
+ '(hf_change_delivery_schedule changes it for good).',
294
+ destructive: false,
295
+ meta: CHANGE(['hellofresh delivery day', 'move delivery', 'deliver on another day']),
296
+ input: {
297
+ week: weekParam,
298
+ slot: z
299
+ .string()
300
+ .trim()
301
+ .regex(SLOT, 'a slot handle like US-2-0800-2000')
302
+ .describe('The slot handle from the week’s oneOffDaySlots, e.g. US-2-0800-2000 (weekday 1=Mon…7=Sun, then from/to HHMM).'),
303
+ },
304
+ async plan({ week, slot }) {
305
+ const account = await loadAccount(client);
306
+ const { raw, delivery } = await openWeek(client, account, week, now());
307
+ requireRunning(delivery, week, 'move its delivery day');
308
+ requireAllowed(raw, week, 'oneOffChange');
309
+ if (slot === delivery.deliveryOption)
310
+ throw new McpToolError(`${week} is already delivered in slot ${slot}.`);
311
+ const offered = delivery.oneOffDaySlots;
312
+ const target = offered.find((o) => o.handle === slot);
313
+ if (!target) {
314
+ const list = offered.map((o) => `${o.handle} (${dateOf(o.deliveryDate)})`).join(', ');
315
+ throw new McpToolError(list ? `${slot} is not offered for ${week}. Offered: ${list}.` : `HelloFresh offers no alternative delivery day for ${week}.`);
316
+ }
317
+ if (!delivery.sku)
318
+ throw new McpToolError(`HelloFresh returned no box size for ${week}, which the change must keep.`);
319
+ const request = { subscriptionId: account.subscriptionId, week, sku: delivery.sku, deliveryOption: slot };
320
+ return {
321
+ gate: {
322
+ action: 'hellofresh.week.day',
323
+ summary: `Deliver the ${week} box in slot ${slot} on ${dateOf(target.deliveryDate)} (this week only)`,
324
+ account: account.subscriptionId,
325
+ target: week,
326
+ request: shown(oneOffRequest(request)),
327
+ preview: {
328
+ from: { deliveryOption: delivery.deliveryOption, deliveryDate: dateOf(delivery.deliveryDate) },
329
+ to: { deliveryOption: slot, deliveryDate: dateOf(target.deliveryDate) },
330
+ },
331
+ },
332
+ state: { account, week, request, before: slotOf(delivery) },
333
+ };
334
+ },
335
+ execute: (s) => sendAndVerify({
336
+ send: () => client.changeOneOff(s.request),
337
+ before: s.before,
338
+ checkWith: `hf_get_delivery {week: "${s.week}"}`,
339
+ mismatch: 'HelloFresh accepted the request, but the re-read week does not show the new delivery slot.',
340
+ verify: async () => {
341
+ const delivery = projectDelivery(await client.getDelivery(s.account.subscriptionId, s.week));
342
+ return { ok: delivery.deliveryOption === s.request.deliveryOption && delivery.sku === s.request.sku, after: slotOf(delivery) };
343
+ },
344
+ }),
345
+ });
346
+ // ---- hf_skip_week / hf_unskip_week (write 2) ----
347
+ const statusWrite = (skip) => {
348
+ const name = skip ? 'hf_skip_week' : 'hf_unskip_week';
349
+ registerGated(server, {
350
+ name,
351
+ title: skip ? 'HelloFresh: skip a week' : 'HelloFresh: unskip a week',
352
+ description: skip
353
+ ? 'Skip one HelloFresh delivery week: no box is delivered or charged that week. Only before the week’s cutoff; ' +
354
+ 'undo with hf_unskip_week.'
355
+ : 'Unskip one skipped HelloFresh delivery week, so its box is delivered and charged again. Only before the week’s ' +
356
+ 'cutoff; HelloFresh may pick meals for it — check with hf_get_delivery and pick with hf_select_meals.',
357
+ destructive: false,
358
+ meta: CHANGE(skip ? ['skip hellofresh', 'pause hellofresh week', 'no box this week'] : ['unskip hellofresh', 'resume hellofresh week']),
359
+ input: { week: weekParam },
360
+ async plan({ week }) {
361
+ const account = await loadAccount(client);
362
+ const { raw, delivery } = await openWeek(client, account, week, now());
363
+ if (skip && delivery.status === 'skipped')
364
+ throw new McpToolError(`${week} is already skipped.`);
365
+ if (skip)
366
+ requireRunning(delivery, week, 'skip it');
367
+ if (!skip && delivery.status !== 'skipped')
368
+ throw new McpToolError(`${week} is not skipped (it is ${delivery.status}).`);
369
+ requireAllowed(raw, week, 'pause');
370
+ if (!delivery.deliveryDate || !delivery.cutoffDate) {
371
+ throw new McpToolError(`HelloFresh returned no delivery/cutoff dates for ${week}, which the change must send back.`);
372
+ }
373
+ const request = {
374
+ subscriptionId: account.subscriptionId,
375
+ week,
376
+ deliveryDate: delivery.deliveryDate,
377
+ cutoffDate: delivery.cutoffDate,
378
+ status: skip ? 'PAUSED' : 'RUNNING',
379
+ };
380
+ return {
381
+ gate: {
382
+ action: skip ? 'hellofresh.week.skip' : 'hellofresh.week.unskip',
383
+ summary: skip
384
+ ? `Skip the ${week} box (delivery ${dateOf(delivery.deliveryDate)}): nothing delivered or charged`
385
+ : `Unskip the ${week} box (delivery ${dateOf(delivery.deliveryDate)}): it will be delivered and charged`,
386
+ account: account.subscriptionId,
387
+ target: week,
388
+ request: shown(deliveryStatusRequest(request)),
389
+ },
390
+ state: { account, week, request, before: { status: delivery.status } },
391
+ };
392
+ },
393
+ execute: (s) => sendAndVerify({
394
+ send: () => client.setDeliveryStatus(s.request),
395
+ before: s.before,
396
+ checkWith: `hf_get_delivery {week: "${s.week}"}`,
397
+ mismatch: `HelloFresh accepted the request, but the re-read week is not ${skip ? 'skipped' : 'running'}.`,
398
+ verify: async () => {
399
+ const delivery = projectDelivery(await client.getDelivery(s.account.subscriptionId, s.week));
400
+ return { ok: delivery.status === (skip ? 'skipped' : 'running'), after: { status: delivery.status } };
401
+ },
402
+ }),
403
+ });
404
+ };
405
+ statusWrite(true);
406
+ statusWrite(false);
407
+ /** Upcoming running weeks still open for changes whose size differs from the plan's: week-only overrides. */
408
+ const overridesOf = (deliveries, planSku, at, subscription) => deliveries.flatMap((d) => d.status === 'running' &&
409
+ !(d.week && isUnresizableFirstBox(subscription, d.week)) &&
410
+ d.week &&
411
+ d.sku &&
412
+ d.sku !== planSku &&
413
+ !(d.cutoffDate && Date.parse(d.cutoffDate) <= at)
414
+ ? [{ week: d.week, sku: d.sku }]
415
+ : []);
416
+ /** Which overrides the plan change reverted to `sku` (re-read best effort). */
417
+ const overrideReport = async (overrides, sku) => {
418
+ if (overrides.length === 0)
419
+ return {};
420
+ const read = await attempt(async () => ((await client.listDeliveries()).items ?? []).map(projectDelivery));
421
+ if (!read.ok)
422
+ return { overridesError: read.reason, overridesNote: overridesNote(overrides) };
423
+ const now = new Map(read.value.map((d) => [d.week, d.sku]));
424
+ const reverted = overrides.filter((o) => now.get(o.week) === sku && o.sku !== sku).map((o) => ({ week: o.week, from: o.sku, to: sku }));
425
+ const kept = overrides.filter((o) => now.has(o.week) && now.get(o.week) !== sku).map((o) => ({ week: o.week, sku: now.get(o.week) }));
426
+ const unread = overrides.filter((o) => !now.has(o.week)).map((o) => o.week);
427
+ return {
428
+ ...(reverted.length > 0 ? { overridesReverted: reverted } : {}),
429
+ ...(kept.length > 0 ? { overridesKept: kept } : {}),
430
+ ...(unread.length > 0 ? { overridesUnread: unread } : {}),
431
+ overridesNote: overridesNote(overrides),
432
+ };
433
+ };
434
+ const overridesNote = (overrides) => 'A plan size change resets one-week sizes. To keep one, re-apply it with hf_set_week_size ' +
435
+ `(the weeks were: ${overrides.map((o) => `${o.week} ${o.sku}`).join(', ')}).`;
436
+ registerGated(server, {
437
+ name: 'hf_change_plan_size',
438
+ title: 'HelloFresh: change the plan’s box size',
439
+ description: 'Permanently change the HelloFresh plan’s box size (meals per week × people) for every future week. Warning: ' +
440
+ 'this RESETS every one-week size set with hf_set_week_size — those weeks revert to the new plan size. The ' +
441
+ 'preview lists them, and the result says which reverted so they can be re-applied with hf_set_week_size. ' +
442
+ 'Re-reads the plan to verify.',
443
+ destructive: true,
444
+ meta: CHANGE(['hellofresh plan size', 'change hellofresh plan', 'permanent box size']),
445
+ input: { meals: mealsCountParam('on the plan'), people: peopleParam },
446
+ async plan({ meals, people }) {
447
+ const account = await loadAccount(client);
448
+ const planId = await customerPlanIdOf(client, account);
449
+ const plans = await client.listPlans();
450
+ const current = plans.find((p) => p.id === planId)?.planItems?.[0]?.productHandle ?? account.subscription.product?.sku;
451
+ const sku = skuOf(meals, people);
452
+ if (sku === current)
453
+ throw new McpToolError(`The plan is already ${meals} meals for ${people} people (${sku}).`);
454
+ await requireOfferedSku(client, account, sku);
455
+ const size = current ? /-(\d+)-(\d+)-\d+$/.exec(current) : null;
456
+ const upcoming = await attempt(async () => ((await client.listDeliveries()).items ?? []).map(projectDelivery));
457
+ const overrides = upcoming.ok ? overridesOf(upcoming.value, current, now(), account.subscription) : [];
458
+ return {
459
+ gate: {
460
+ action: 'hellofresh.plan.size',
461
+ summary: `Permanently change the plan to ${meals} meals for ${people} people (${sku})`,
462
+ account: account.subscriptionId,
463
+ target: planId,
464
+ request: shown(planProductRequest(planId, sku)),
465
+ preview: {
466
+ from: { sku: current, ...(size ? { meals: Number(size[1]), people: Number(size[2]) } : {}) },
467
+ to: { sku, meals, people },
468
+ note: 'Permanent: applies to every future week, and resets any one-week size (hf_set_week_size) to the new plan size.',
469
+ ...(overrides.length > 0
470
+ ? {
471
+ overriddenWeeks: overrides.map((o) => ({ ...o, revertsTo: sku })),
472
+ warning: `${overrides.map((o) => `${o.week} (now ${o.sku})`).join(', ')} will revert to ${sku}: a plan size change ` +
473
+ 'resets one-week sizes. Re-apply any you want to keep with hf_set_week_size afterwards.',
474
+ }
475
+ : {}),
476
+ ...(upcoming.ok
477
+ ? {}
478
+ : { overridesUnknown: `Could not read the upcoming weeks (${upcoming.reason}), so one-week sizes that would revert are not listed.` }),
479
+ },
480
+ },
481
+ state: { planId, sku, before: { sku: current }, overrides },
482
+ };
483
+ },
484
+ execute: (s) => sendAndVerify({
485
+ send: () => client.setPlanProduct(s.planId, s.sku),
486
+ before: s.before,
487
+ checkWith: 'hf_get_subscription',
488
+ mismatch: 'HelloFresh accepted the request, but the re-read plan does not show the new box size.',
489
+ verify: async () => {
490
+ const sku = (await client.listPlans()).find((p) => p.id === s.planId)?.planItems?.[0]?.productHandle;
491
+ return { ok: sku === s.sku, after: { sku }, extra: await overrideReport(s.overrides, s.sku) };
492
+ },
493
+ }),
494
+ });
495
+ registerGated(server, {
496
+ name: 'hf_change_delivery_schedule',
497
+ title: 'HelloFresh: change the delivery schedule',
498
+ description: 'Permanently change the HelloFresh plan’s regular delivery slot (day + time window) and/or frequency (every 1–4 ' +
499
+ 'weeks). Give either or both; the other keeps its current value. Re-reads the subscription to verify.',
500
+ destructive: true,
501
+ meta: CHANGE(['hellofresh delivery schedule', 'delivery frequency', 'every other week']),
502
+ input: {
503
+ delivery_option: z
504
+ .string()
505
+ .trim()
506
+ .regex(SLOT, 'a slot handle like US-1-0800-2000')
507
+ .optional()
508
+ .describe('The regular slot handle, e.g. US-1-0800-2000 = Mondays 8AM–8PM (weekday 1=Mon…7=Sun, then from/to HHMM).'),
509
+ interval_weeks: z.number().int().min(1).max(4).optional().describe('Deliver every N weeks (1–4).'),
510
+ },
511
+ async plan({ delivery_option, interval_weeks }) {
512
+ if (delivery_option === undefined && interval_weeks === undefined) {
513
+ throw new McpToolError('Give delivery_option or interval_weeks (or both).');
514
+ }
515
+ const account = await loadAccount(client);
516
+ const sub = account.subscription;
517
+ const currentOption = sub.deliveryOption?.handle ?? sub.deliveryTime;
518
+ const currentInterval = sub.deliveryInterval;
519
+ if (!currentOption)
520
+ throw new McpToolError('HelloFresh returned no current delivery slot, which must be sent with the change.');
521
+ if (currentInterval === undefined) {
522
+ throw new McpToolError('HelloFresh returned no current delivery frequency, which must be sent with the change.');
523
+ }
524
+ const details = { deliveryOption: delivery_option ?? currentOption, deliveryInterval: interval_weeks ?? currentInterval };
525
+ const before = { deliveryOption: currentOption, deliveryInterval: currentInterval };
526
+ if (details.deliveryOption === currentOption && details.deliveryInterval === currentInterval) {
527
+ throw new McpToolError(`The schedule is already slot ${currentOption}, every ${currentInterval} week(s).`);
528
+ }
529
+ const planId = await customerPlanIdOf(client, account);
530
+ let caveat;
531
+ if (details.deliveryOption !== currentOption) {
532
+ const seen = ((await client.listDeliveries()).items ?? []).flatMap((d) => (d.availableOneOffOptions ?? []).map((o) => o.handle));
533
+ if (!seen.includes(details.deliveryOption)) {
534
+ caveat = `${details.deliveryOption} is not one this account has been offered (not among the upcoming weeks’ alternative slots); HelloFresh may refuse it.`;
535
+ }
536
+ }
537
+ return {
538
+ gate: {
539
+ action: 'hellofresh.plan.schedule',
540
+ summary: `Permanently deliver in slot ${details.deliveryOption}, every ${details.deliveryInterval} week(s)`,
541
+ account: account.subscriptionId,
542
+ target: planId,
543
+ request: shown(planDeliveryDetailsRequest(planId, details)),
544
+ preview: { from: before, to: details, ...(caveat ? { caveat } : {}) },
545
+ },
546
+ state: { account, planId, details, before },
547
+ };
548
+ },
549
+ execute: (s) => sendAndVerify({
550
+ send: () => client.changePlanDeliveryDetails(s.planId, s.details),
551
+ before: s.before,
552
+ checkWith: 'hf_get_subscription',
553
+ mismatch: 'HelloFresh accepted the request, but the re-read subscription does not show the new schedule.',
554
+ verify: async () => {
555
+ const sub = await client.getSubscription(s.account.subscriptionId);
556
+ const after = { deliveryOption: sub.deliveryOption?.handle ?? sub.deliveryTime, deliveryInterval: sub.deliveryInterval };
557
+ return { ok: after.deliveryOption === s.details.deliveryOption && after.deliveryInterval === s.details.deliveryInterval, after };
558
+ },
559
+ }),
560
+ });
561
+ }
562
+ /** Every index on the menu (base courses and their protein swaps) → its name. */
563
+ function namesOf(menu) {
564
+ const names = new Map();
565
+ for (const m of menu.meals) {
566
+ names.set(m.index, m.name);
567
+ for (const v of m.variants)
568
+ names.set(v.index, v.name ?? v.title);
569
+ }
570
+ return names;
571
+ }
572
+ const slotOf = (d) => ({ deliveryOption: d.deliveryOption, deliveryDate: dateOf(d.deliveryDate), sku: d.sku });
@@ -0,0 +1,81 @@
1
+ // The ContextMint Bridge, used ONLY to bootstrap the session (the fleet's
2
+ // "bootstrap" archetype): it reads the `apiV2Auth` cookie from the user's
3
+ // signed-in www.hellofresh.com tab, and writes a refreshed token set back to
4
+ // it (HelloFresh ROTATES the refresh token on every refresh and sets no cookie,
5
+ // so without the write-back the browser keeps a spent refresh token and is
6
+ // signed out). Every API call is a plain Node fetch with a Bearer token.
7
+ //
8
+ // `@chrischall/mcp-utils/fetchproxy` eagerly imports `@fetchproxy/server`, so it
9
+ // is imported lazily here (type imports are erased): nothing on the boot path
10
+ // depends on the bridge package resolving.
11
+ import { parseCookieHeader } from '@chrischall/mcp-utils';
12
+ /** The cookie domain the bridge is scoped to. */
13
+ export const BRIDGE_DOMAIN = 'hellofresh.com';
14
+ /**
15
+ * The one cookie this MCP reads, declared up front: the pair grant is
16
+ * per-scope, so changing it strands every paired user until they re-approve.
17
+ */
18
+ export const AUTH_COOKIE = 'apiV2Auth';
19
+ /** The cookie is host-only on www.hellofresh.com. */
20
+ export const AUTH_SUBDOMAIN = 'www';
21
+ export function createHelloFreshBridge(opts) {
22
+ // The library's build-once / start-once wrapper. `ready()` single-flights the
23
+ // start and FORGETS a rejected one, so a start failure surfaces from the next
24
+ // use instead of crashing boot — and that use retries it.
25
+ let lazy;
26
+ let lastReady;
27
+ const lazyTransport = () => (lazy ??= import('@chrischall/mcp-utils/fetchproxy').then((fp) => fp.createLazyTransport(() => fp.createFetchproxyTransport({
28
+ serverName: 'hellofresh-mcp',
29
+ version: opts.version,
30
+ port: opts.port,
31
+ ...withCookieWrite(fp.createBootstrapOpts({
32
+ domains: [BRIDGE_DOMAIN],
33
+ bootstrap: { cookieKeys: [AUTH_COOKIE] },
34
+ })),
35
+ debugEnvVar: 'HELLOFRESH_DEBUG',
36
+ logListening: true,
37
+ createServer: opts.createServer,
38
+ }))));
39
+ const ensureStarted = () => (lastReady = lazyTransport().then((l) => l.ready()));
40
+ return {
41
+ async start() {
42
+ await ensureStarted();
43
+ },
44
+ async close() {
45
+ const transport = await lastReady?.catch(() => undefined);
46
+ await transport?.close();
47
+ },
48
+ async readAuthCookie() {
49
+ const transport = await ensureStarted();
50
+ const header = await transport.server.readCookies({
51
+ domain: BRIDGE_DOMAIN,
52
+ subdomain: AUTH_SUBDOMAIN,
53
+ keys: [AUTH_COOKIE],
54
+ });
55
+ return parseCookieHeader(header)[AUTH_COOKIE] || undefined;
56
+ },
57
+ async writeAuthCookie(value) {
58
+ const transport = await ensureStarted();
59
+ const written = await transport.server.writeCookies({
60
+ domain: BRIDGE_DOMAIN,
61
+ subdomain: AUTH_SUBDOMAIN,
62
+ cookies: { [AUTH_COOKIE]: value },
63
+ });
64
+ if (!written.includes(AUTH_COOKIE)) {
65
+ throw new Error(`the browser did not confirm writing the ${AUTH_COOKIE} cookie`);
66
+ }
67
+ },
68
+ async healthTransport() {
69
+ return (await lazyTransport()).transport();
70
+ },
71
+ };
72
+ }
73
+ /**
74
+ * `createBootstrapOpts` derives the READ capabilities from the declarations;
75
+ * the write verb is declared here, on top. It is approved at pair time as its
76
+ * own line, so adding or dropping it later forces every user to re-pair.
77
+ */
78
+ function withCookieWrite(opts) {
79
+ // Always set here: a cookie declaration yields ['fetch', 'read_cookies'].
80
+ return { ...opts, capabilities: [...opts.capabilities, 'write_cookies'] };
81
+ }
package/dist/types.js ADDED
@@ -0,0 +1,6 @@
1
+ // Raw HelloFresh web-API shapes, as documented in docs/HELLOFRESH-API.md.
2
+ // Only the fields this server reads are typed; everything is optional because
3
+ // the API is undocumented and may drop a field at any time. Subscriptions also
4
+ // carry the customer's name, email, addresses and payment token — those are
5
+ // deliberately NOT typed here, and src/normalize.ts projects to an allowlist.
6
+ export {};