@chrischall/hellofresh-mcp 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +20 -9
- package/dist/bundle.js +1853 -711
- package/dist/client.js +123 -1
- package/dist/cooking.js +179 -0
- package/dist/index.js +5 -4
- package/dist/normalize.js +32 -0
- package/dist/planner.js +71 -16
- package/dist/session.js +47 -3
- package/dist/tools/cooking.js +216 -0
- package/dist/tools/favorites.js +164 -0
- package/dist/tools/index.js +7 -1
- package/dist/tools/planner.js +276 -83
- package/dist/tools/promo.js +108 -0
- package/dist/tools/reads.js +71 -40
- package/dist/tools/shared.js +210 -24
- package/dist/tools/writes/index.js +9 -0
- package/dist/tools/writes/plan.js +177 -0
- package/dist/tools/writes/shared.js +137 -0
- package/dist/tools/{writes.js → writes/week.js} +8 -290
- package/dist/transport.js +13 -1
- package/dist/version.js +1 -1
- package/manifest.json +47 -4
- package/mint.yaml +6 -0
- package/package.json +1 -1
- package/server.json +8 -2
- package/skills/hellofresh/SKILL.md +56 -12
- package/skills/hellofresh-fpx/SKILL.md +13 -5
- package/skills/hellofresh-fpx/references/requests.md +30 -10
package/dist/session.js
CHANGED
|
@@ -14,6 +14,20 @@
|
|
|
14
14
|
// surfaces WRITE_BACK_WARNING.
|
|
15
15
|
// 4. A 401 from any call invalidates the token, re-runs the lifecycle once
|
|
16
16
|
// (never trusting the rejected token again) and retries the call once.
|
|
17
|
+
// 5. When the browser cookie read FAILS (bridge down, tab closed, pairing
|
|
18
|
+
// pending) but the newest set this process knows is one it refreshed
|
|
19
|
+
// itself, it may stand in — how far depends on its write-back:
|
|
20
|
+
// - the write-back FAILED: the browser never received that refresh token,
|
|
21
|
+
// so only this process can have spent it. While it has not expired it
|
|
22
|
+
// is used, refreshed (and written back) as in 3 when stale.
|
|
23
|
+
// - the write-back SUCCEEDED: the browser holds that refresh token and
|
|
24
|
+
// may already have rotated it (POSTing a spent one can sign the browser
|
|
25
|
+
// out). Only its ACCESS token is used, while still valid (and not
|
|
26
|
+
// rejected); otherwise the original bridge error is rethrown, its
|
|
27
|
+
// pairing hint intact. /gw/refresh is never called.
|
|
28
|
+
// A set read from the browser is never a fallback: its refresh token may
|
|
29
|
+
// already be spent by the browser. A missing cookie (signed out) is NOT a
|
|
30
|
+
// read failure and still fails.
|
|
17
31
|
//
|
|
18
32
|
// No token value is ever logged, put in an error message or returned.
|
|
19
33
|
import { EdgeBlockedError, McpToolError, SessionNotAuthenticatedError, createCachedTokenSource, decodeJwtClaim, detectEdgeBlock, messageOf, parseJsonBody, redactValues, truncateErrorMessage, } from '@chrischall/mcp-utils';
|
|
@@ -139,6 +153,10 @@ export class HelloFreshSession {
|
|
|
139
153
|
/** An access token the API rejected: never trusted again, even if the cookie still holds it. */
|
|
140
154
|
rejected;
|
|
141
155
|
writeBackWarning;
|
|
156
|
+
/** The refresh token of this process's own latest refresh (the fallback when the cookie read fails). */
|
|
157
|
+
ownRefreshToken;
|
|
158
|
+
/** Whether that refresh was written back to the browser (which may then rotate it on its own). */
|
|
159
|
+
ownWrittenBack = false;
|
|
142
160
|
seen = [];
|
|
143
161
|
constructor(opts) {
|
|
144
162
|
this.opts = opts;
|
|
@@ -204,8 +222,28 @@ export class HelloFreshSession {
|
|
|
204
222
|
fresh(set) {
|
|
205
223
|
return set.access_token !== this.rejected && tokenExpiresAtMs(set) - this.now() > EXPIRY_SKEW_MS;
|
|
206
224
|
}
|
|
207
|
-
|
|
208
|
-
|
|
225
|
+
/** Whether `set`'s refresh token is still usable: its stated lifetime has not run out (unstated = try it). */
|
|
226
|
+
refreshable(set) {
|
|
227
|
+
if (typeof set.refresh_expires_in !== 'number')
|
|
228
|
+
return true;
|
|
229
|
+
return (set.issued_at + set.refresh_expires_in) * 1000 > this.now();
|
|
230
|
+
}
|
|
231
|
+
/** The newest token set: the browser cookie's or our own (lifecycle steps 2 and 5). */
|
|
232
|
+
async newestSet() {
|
|
233
|
+
let raw;
|
|
234
|
+
try {
|
|
235
|
+
raw = await this.bridged(() => this.opts.bridge.readAuthCookie());
|
|
236
|
+
}
|
|
237
|
+
catch (err) {
|
|
238
|
+
const ours = this.latest;
|
|
239
|
+
if (!ours || ours.refresh_token !== this.ownRefreshToken)
|
|
240
|
+
throw err;
|
|
241
|
+
// Written back: the browser may have rotated (spent) its refresh token — use the access token only.
|
|
242
|
+
if (this.ownWrittenBack ? !this.fresh(ours) : !this.refreshable(ours))
|
|
243
|
+
throw err;
|
|
244
|
+
console.error(`[hellofresh-mcp] could not read the browser session (${truncateErrorMessage(this.redact(messageOf(err)), 200)}); using this process's own refreshed session`);
|
|
245
|
+
return ours;
|
|
246
|
+
}
|
|
209
247
|
if (!raw)
|
|
210
248
|
throw new HelloFreshSessionError(`no ${AUTH_COOKIE} cookie was found on www.hellofresh.com`);
|
|
211
249
|
const browser = decodeAuthCookie(raw);
|
|
@@ -214,18 +252,24 @@ export class HelloFreshSession {
|
|
|
214
252
|
// then the cookie's refresh token is already spent and ours must be used.
|
|
215
253
|
const ours = this.latest;
|
|
216
254
|
const browserIsNewest = !ours || browser.issued_at >= ours.issued_at;
|
|
217
|
-
const newest = browserIsNewest ? browser : ours;
|
|
218
255
|
if (browserIsNewest)
|
|
219
256
|
this.writeBackWarning = undefined;
|
|
257
|
+
return browserIsNewest ? browser : ours;
|
|
258
|
+
}
|
|
259
|
+
async lifecycle() {
|
|
260
|
+
const newest = await this.newestSet();
|
|
220
261
|
if (this.fresh(newest)) {
|
|
221
262
|
this.latest = newest;
|
|
222
263
|
return newest;
|
|
223
264
|
}
|
|
224
265
|
const next = await this.refresh(newest);
|
|
225
266
|
this.latest = next;
|
|
267
|
+
this.ownRefreshToken = next.refresh_token;
|
|
268
|
+
this.ownWrittenBack = false;
|
|
226
269
|
this.remember(next);
|
|
227
270
|
try {
|
|
228
271
|
await this.opts.bridge.writeAuthCookie(encodeAuthCookie(next));
|
|
272
|
+
this.ownWrittenBack = true;
|
|
229
273
|
this.writeBackWarning = undefined;
|
|
230
274
|
}
|
|
231
275
|
catch (err) {
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// Cooking day: one recipe's detail (hf_get_recipe) and the week's picks in a
|
|
2
|
+
// recommended cook order (hf_cooking_plan), and the pantry staples HelloFresh does
|
|
3
|
+
// not ship (hf_pantry_check). Read-only. Recipe text (names,
|
|
4
|
+
// ingredients, steps) is written by HelloFresh — third-party content — so both
|
|
5
|
+
// answer inside the untrusted-content envelope.
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import { McpToolError, UNTRUSTED_CONTENT_RULE, UNTRUSTED_DESCRIPTION_SUFFIX, resolveView, toolAnnotations, untrustedResult, } from '@chrischall/mcp-utils';
|
|
8
|
+
import { cookOrder, dayFrom, pantryItems, pantryLine, projectRecipe, recipeMinutes } from '../cooking.js';
|
|
9
|
+
import { projectDelivery, projectMenu } from '../normalize.js';
|
|
10
|
+
import { foodMeta } from './hints.js';
|
|
11
|
+
import { HF_VIEWS, attempt, dateOf, hfView, loadAccount, readRawMenu, weekParam } from './shared.js';
|
|
12
|
+
const readOnly = (title) => toolAnnotations({ title, readOnly: true, idempotent: true, openWorld: true });
|
|
13
|
+
const RECIPE_NOTE = `Recipe names, headlines, ingredients and steps below are written by HelloFresh (third-party content), not the user. ${UNTRUSTED_CONTENT_RULE}`;
|
|
14
|
+
/** `note` is reserved by the envelope (a payload carrying one is nested under `data`): say `summary` instead. */
|
|
15
|
+
const fenced = (payload) => untrustedResult(payload, { note: RECIPE_NOTE });
|
|
16
|
+
/** How many ingredient names a cooking-plan dish lists. */
|
|
17
|
+
const SHORT_INGREDIENTS = 8;
|
|
18
|
+
/** Where a menu index sits: its raw meal and, for a protein swap, the base course and the swap's title. */
|
|
19
|
+
function locate(raw, menu, index) {
|
|
20
|
+
const meal = (raw.meals ?? []).find((m) => m.index === index);
|
|
21
|
+
for (const base of menu.meals) {
|
|
22
|
+
const variant = base.variants.find((v) => v.index === index);
|
|
23
|
+
if (variant)
|
|
24
|
+
return { meal, base, variant };
|
|
25
|
+
}
|
|
26
|
+
return { meal, base: menu.meals.find((m) => m.index === index), variant: undefined };
|
|
27
|
+
}
|
|
28
|
+
/** A protein swap as hf_get_recipe names it: what it swaps in is the swap's title, else its own recipe name, else unsaid. */
|
|
29
|
+
function swapOf(base, variant) {
|
|
30
|
+
const swapsIn = variant.title?.trim() || variant.name?.trim();
|
|
31
|
+
return {
|
|
32
|
+
baseIndex: base.index,
|
|
33
|
+
baseName: base.name,
|
|
34
|
+
...(variant.title ? { protein: variant.title } : {}),
|
|
35
|
+
note: `Protein swap of #${base.index} ${base.name}${swapsIn ? `: swaps in ${swapsIn}` : ''}.`,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function recipeIdOf(meal, index, week) {
|
|
39
|
+
const id = meal?.recipe?.id;
|
|
40
|
+
if (!id)
|
|
41
|
+
throw new McpToolError(`HelloFresh returned no recipe id for menu index ${index} in ${week}, so its recipe cannot be read.`);
|
|
42
|
+
return id;
|
|
43
|
+
}
|
|
44
|
+
export function registerCookingTools(server, deps) {
|
|
45
|
+
const { client } = deps;
|
|
46
|
+
server.registerTool('hf_get_recipe', {
|
|
47
|
+
description: 'Read the full HelloFresh recipe for one meal on a week’s menu (by menu index, a protein swap included): ' +
|
|
48
|
+
'total time, difficulty, allergens, nutrition per serving, ingredients with amounts for the week’s servings ' +
|
|
49
|
+
'(nearest listed yield otherwise, said so), the cooking steps as plain text, utensils, the printable recipe ' +
|
|
50
|
+
`card and web page. Answers "how do I cook this?". ${UNTRUSTED_DESCRIPTION_SUFFIX}`,
|
|
51
|
+
annotations: readOnly('HelloFresh: get recipe'),
|
|
52
|
+
_meta: foodMeta('lookup', { aliases: ['hellofresh recipe', 'recipe card', 'how to cook'] }),
|
|
53
|
+
inputSchema: z.object({
|
|
54
|
+
week: weekParam,
|
|
55
|
+
index: z.number().int().min(0).describe('The meal’s menu index (from hf_get_menu or hf_get_delivery; a protein swap has its own).'),
|
|
56
|
+
}),
|
|
57
|
+
}, async ({ week, index }) => {
|
|
58
|
+
const account = await loadAccount(client);
|
|
59
|
+
const delivery = projectDelivery(await client.getDelivery(account.subscriptionId, week));
|
|
60
|
+
const raw = await readRawMenu(client, account, delivery, week);
|
|
61
|
+
const { meal, base, variant } = locate(raw, projectMenu(raw), index);
|
|
62
|
+
if (!meal) {
|
|
63
|
+
throw new McpToolError(`There is no meal with index ${index} on the ${week} menu.`, {
|
|
64
|
+
hint: 'hf_get_menu lists the week’s menu indexes (protein swaps under each course).',
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
const detail = await client.getRecipe(recipeIdOf(meal, index, week));
|
|
68
|
+
const servings = delivery.servings;
|
|
69
|
+
const quantity = meal.selection?.quantity ?? 0;
|
|
70
|
+
return fenced({
|
|
71
|
+
week,
|
|
72
|
+
index,
|
|
73
|
+
servings,
|
|
74
|
+
...(quantity > 0 ? { selectedQuantity: quantity } : {}),
|
|
75
|
+
...(quantity > 1
|
|
76
|
+
? { quantityNote: `This meal is picked ${quantity}× this week: multiply the amounts by ${quantity}.` }
|
|
77
|
+
: {}),
|
|
78
|
+
...(variant && base ? { swap: swapOf(base, variant) } : {}),
|
|
79
|
+
recipe: projectRecipe(detail, servings),
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
server.registerTool('hf_cooking_plan', {
|
|
83
|
+
description: 'Plan cooking for a HelloFresh delivery week: the picked meals in a recommended cook order, most perishable ' +
|
|
84
|
+
'first (fish, then shellfish, other seafood, poultry, ground meat, whole cuts of beef/pork/lamb, vegetarian ' +
|
|
85
|
+
'last; ties by shorter total time), each with a suggested day counted from the delivery date, why, total ' +
|
|
86
|
+
'time, a short ingredient list, the pantry staples HelloFresh does not ship (salt, oil…) and the recipe card. ' +
|
|
87
|
+
`${UNTRUSTED_DESCRIPTION_SUFFIX}`,
|
|
88
|
+
annotations: readOnly('HelloFresh: cooking plan'),
|
|
89
|
+
_meta: foodMeta('whats-on', { aliases: ['what to cook', 'cooking order', 'dinner this week'] }),
|
|
90
|
+
inputSchema: z.object({ week: weekParam }),
|
|
91
|
+
}, async ({ week }) => {
|
|
92
|
+
const account = await loadAccount(client);
|
|
93
|
+
const delivery = projectDelivery(await client.getDelivery(account.subscriptionId, week));
|
|
94
|
+
const deliveryDate = dateOf(delivery.deliveryDate);
|
|
95
|
+
const head = { week, ...(deliveryDate ? { deliveryDate } : {}), status: delivery.status };
|
|
96
|
+
if (delivery.status === 'skipped') {
|
|
97
|
+
return fenced({ ...head, dishes: [], summary: `${week} is skipped: nothing is delivered, so there is nothing to cook.` });
|
|
98
|
+
}
|
|
99
|
+
const raw = await readRawMenu(client, account, delivery, week);
|
|
100
|
+
const menu = projectMenu(raw);
|
|
101
|
+
if (menu.selected.length === 0) {
|
|
102
|
+
return fenced({ ...head, dishes: [], summary: `No meals are picked for ${week} yet — pick them with hf_select_meals.` });
|
|
103
|
+
}
|
|
104
|
+
const servings = delivery.servings; // readRawMenu refuses a week without it
|
|
105
|
+
const dishes = await Promise.all(menu.selected.map(async (s) => {
|
|
106
|
+
const { meal, base, variant } = locate(raw, menu, s.index);
|
|
107
|
+
const recipe = meal?.recipe ?? {};
|
|
108
|
+
const read = await attempt(async () => projectRecipe(await client.getRecipe(recipeIdOf(meal, s.index, week)), servings));
|
|
109
|
+
const shipped = read.ok ? read.value.ingredients.filter((i) => !i.notInBox).map((i) => i.name) : [];
|
|
110
|
+
const pantry = read.ok ? read.value.ingredients.filter((i) => i.notInBox).map((i) => i.name) : [];
|
|
111
|
+
const dish = variant ?? base;
|
|
112
|
+
return {
|
|
113
|
+
index: s.index,
|
|
114
|
+
name: recipe.name,
|
|
115
|
+
quantity: s.quantity,
|
|
116
|
+
...(s.quantity > 1
|
|
117
|
+
? {
|
|
118
|
+
dinners: s.quantity,
|
|
119
|
+
quantityNote: `Picked ${s.quantity}× this week: this covers ${s.quantity} dinners (cook it on ${s.quantity} nights, or once at ${s.quantity}× the amounts).`,
|
|
120
|
+
}
|
|
121
|
+
: {}),
|
|
122
|
+
...(variant ? { swapOf: s.baseIndex } : {}),
|
|
123
|
+
category: dish?.category ?? recipe.category ?? null,
|
|
124
|
+
seafoodKind: dish?.seafoodKind ?? null,
|
|
125
|
+
totalMinutes: recipeMinutes(recipe),
|
|
126
|
+
text: [recipe.name, recipe.headline, ...shipped].join(' '),
|
|
127
|
+
...(read.ok
|
|
128
|
+
? {
|
|
129
|
+
ingredients: shipped.slice(0, SHORT_INGREDIENTS),
|
|
130
|
+
...(shipped.length > SHORT_INGREDIENTS ? { moreIngredients: shipped.length - SHORT_INGREDIENTS } : {}),
|
|
131
|
+
pantry,
|
|
132
|
+
...(read.value.cardLink ? { cardLink: read.value.cardLink } : {}),
|
|
133
|
+
}
|
|
134
|
+
: { ingredientsError: read.reason }),
|
|
135
|
+
};
|
|
136
|
+
}));
|
|
137
|
+
const ordered = cookOrder(dishes);
|
|
138
|
+
return fenced({
|
|
139
|
+
...head,
|
|
140
|
+
dishes: ordered.map(({ text: _text, category: _category, seafoodKind: _kind, rank, why, ...d }, i) => {
|
|
141
|
+
const tied = ordered.filter((o) => o.rank === rank && o.index !== d.index).map((o) => `#${o.index}`);
|
|
142
|
+
return {
|
|
143
|
+
order: i + 1,
|
|
144
|
+
...(deliveryDate ? dayFrom(deliveryDate, i) : {}),
|
|
145
|
+
...d,
|
|
146
|
+
why: tied.length > 0 ? `${why} Same perishability as ${tied.join(', ')}: shorter total time first.` : why,
|
|
147
|
+
};
|
|
148
|
+
}),
|
|
149
|
+
...(deliveryDate
|
|
150
|
+
? { dayNote: 'Days count from the delivery day (the most perishable dish that evening); shift them to fit your week.' }
|
|
151
|
+
: {}),
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
server.registerTool('hf_pantry_check', {
|
|
155
|
+
description: 'Check what to have in the pantry for a HelloFresh delivery week: the staples HelloFresh does NOT ship (salt, ' +
|
|
156
|
+
'pepper, cooking oil, often butter, eggs, sugar or flour) across the week’s picked meals, at the week’s servings ' +
|
|
157
|
+
'(nearest listed yield otherwise, said so) and × each meal’s quantity — summed per ingredient and unit, ' +
|
|
158
|
+
'"to taste" when no amount is listed, with the dishes that use each — plus a one-line summary. Answers ' +
|
|
159
|
+
`"what do I need from my pantry for HelloFresh this week?". ${UNTRUSTED_DESCRIPTION_SUFFIX}`,
|
|
160
|
+
annotations: readOnly('HelloFresh: pantry check'),
|
|
161
|
+
_meta: foodMeta('lookup', { aliases: ['pantry check', 'pantry staples', 'what do i need on hand', 'not in the box'] }),
|
|
162
|
+
inputSchema: z.object({
|
|
163
|
+
week: weekParam,
|
|
164
|
+
view: hfView('compact is the summed pantry list and summary; full adds each dish’s staples with their own amounts.'),
|
|
165
|
+
}),
|
|
166
|
+
}, async ({ week, view }) => {
|
|
167
|
+
const account = await loadAccount(client);
|
|
168
|
+
const delivery = projectDelivery(await client.getDelivery(account.subscriptionId, week));
|
|
169
|
+
const head = { week, status: delivery.status };
|
|
170
|
+
if (delivery.status === 'skipped') {
|
|
171
|
+
return fenced({ ...head, items: [], summary: `${week} is skipped: nothing is delivered, so nothing is needed from the pantry.` });
|
|
172
|
+
}
|
|
173
|
+
const raw = await readRawMenu(client, account, delivery, week);
|
|
174
|
+
const menu = projectMenu(raw);
|
|
175
|
+
if (menu.selected.length === 0) {
|
|
176
|
+
return fenced({ ...head, items: [], summary: `No meals are picked for ${week} yet — pick them with hf_select_meals, then check the pantry.` });
|
|
177
|
+
}
|
|
178
|
+
const servings = delivery.servings; // readRawMenu refuses a week without it
|
|
179
|
+
const reads = await Promise.all(menu.selected.map(async (s) => ({
|
|
180
|
+
s,
|
|
181
|
+
read: await attempt(async () => projectRecipe(await client.getRecipe(recipeIdOf(locate(raw, menu, s.index).meal, s.index, week)), servings)),
|
|
182
|
+
})));
|
|
183
|
+
const dishes = reads.flatMap(({ s, read }) => {
|
|
184
|
+
if (!read.ok)
|
|
185
|
+
return [];
|
|
186
|
+
const name = s.name ?? read.value.name ?? `#${s.index}`;
|
|
187
|
+
return [{ index: s.index, name, quantity: s.quantity, recipe: read.value }];
|
|
188
|
+
});
|
|
189
|
+
const unread = reads.flatMap(({ s, read }) => (read.ok ? [] : [{ index: s.index, reason: read.reason }]));
|
|
190
|
+
const items = pantryItems(dishes.map((d) => ({ name: d.name, quantity: d.quantity, ingredients: d.recipe.ingredients })));
|
|
191
|
+
const notes = dishes.flatMap((d) => d.recipe.yieldsNote ? [`${d.name === `#${d.index}` ? d.name : `#${d.index} ${d.name}`}: ${d.recipe.yieldsNote}`] : []);
|
|
192
|
+
const unreadLine = unread.length === 0
|
|
193
|
+
? ''
|
|
194
|
+
: ` ${unread.length} recipe${unread.length === 1 ? '' : 's'} could not be read (${unread.map((u) => `#${u.index}`).join(', ')}): their staples are missing.`;
|
|
195
|
+
const full = resolveView(view, HF_VIEWS) === 'full';
|
|
196
|
+
return fenced({
|
|
197
|
+
...head,
|
|
198
|
+
servings,
|
|
199
|
+
items,
|
|
200
|
+
summary: pantryLine(week, items) + unreadLine,
|
|
201
|
+
...(notes.length > 0 ? { notes } : {}),
|
|
202
|
+
...(unread.length > 0 ? { unread } : {}),
|
|
203
|
+
...(full
|
|
204
|
+
? {
|
|
205
|
+
dishes: dishes.map((d) => ({
|
|
206
|
+
index: d.index,
|
|
207
|
+
name: d.name,
|
|
208
|
+
quantity: d.quantity,
|
|
209
|
+
...(d.recipe.amountsForServings !== undefined ? { amountsForServings: d.recipe.amountsForServings } : {}),
|
|
210
|
+
pantry: d.recipe.ingredients.filter((i) => i.notInBox).map(({ notInBox: _n, ...i }) => i),
|
|
211
|
+
})),
|
|
212
|
+
}
|
|
213
|
+
: {}),
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// Favourites and ratings (docs/HELLOFRESH-API.md "Added 2026-11-12"):
|
|
2
|
+
//
|
|
3
|
+
// hf_list_favorites — read: the user's favourite recipe ids (never the
|
|
4
|
+
// customer uuid each item carries), named from a
|
|
5
|
+
// week's menu when one is given;
|
|
6
|
+
// hf_list_ratings — read: the user's own recipe ratings on the v2 and/or
|
|
7
|
+
// v3 (5-star) scale. The list's item shape is NOT yet
|
|
8
|
+
// observed, so items are parsed defensively and the
|
|
9
|
+
// unparseable ones are skipped and counted;
|
|
10
|
+
// hf_favorite_recipe /
|
|
11
|
+
// hf_unfavorite_recipe — confirm-gated writes (each the other's inverse, so
|
|
12
|
+
// neither is destructive), verified by re-reading the
|
|
13
|
+
// favourites list.
|
|
14
|
+
//
|
|
15
|
+
// There is deliberately NO rating write: the rate call is not verified live
|
|
16
|
+
// (it needs a delivered box), see the API doc.
|
|
17
|
+
import { z } from 'zod';
|
|
18
|
+
import { McpToolError, minifiedResult, toolAnnotations } from '@chrischall/mcp-utils';
|
|
19
|
+
import { addFavoriteRequest, removeFavoriteRequest } from '../client.js';
|
|
20
|
+
import { projectDelivery, projectFavorites } from '../normalize.js';
|
|
21
|
+
import { foodMeta } from './hints.js';
|
|
22
|
+
import { RATING_SCALES, attempt, loadAccount, readMenu, readRatings, weekParam } from './shared.js';
|
|
23
|
+
import { CHANGE, registerGated, sendAndVerify, shown } from './writes/shared.js';
|
|
24
|
+
const readOnly = (title) => toolAnnotations({ title, readOnly: true, idempotent: true, openWorld: true });
|
|
25
|
+
/** Every recipe on the menu (base courses and their protein swaps): recipe id → menu index + name. */
|
|
26
|
+
function recipesOf(menu) {
|
|
27
|
+
const recipes = new Map();
|
|
28
|
+
for (const m of menu.meals) {
|
|
29
|
+
if (m.recipeId)
|
|
30
|
+
recipes.set(m.recipeId, { index: m.index, name: m.name });
|
|
31
|
+
for (const v of m.variants)
|
|
32
|
+
if (v.recipeId)
|
|
33
|
+
recipes.set(v.recipeId, { index: v.index, name: v.name ?? v.title });
|
|
34
|
+
}
|
|
35
|
+
return recipes;
|
|
36
|
+
}
|
|
37
|
+
/** The week's menu, best effort: its recipes, or the reason it could not be read. */
|
|
38
|
+
async function weekRecipes(client, week) {
|
|
39
|
+
return attempt(async () => {
|
|
40
|
+
const account = await loadAccount(client);
|
|
41
|
+
const delivery = projectDelivery(await client.getDelivery(account.subscriptionId, week));
|
|
42
|
+
return recipesOf(await readMenu(client, account, delivery, week));
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
/** Name each item found on the week's menu (best effort); `menuError` when the menu could not be read. */
|
|
46
|
+
async function nameFromWeek(client, items, week) {
|
|
47
|
+
if (!week)
|
|
48
|
+
return { items, extra: {} };
|
|
49
|
+
const recipes = await weekRecipes(client, week);
|
|
50
|
+
if (!recipes.ok)
|
|
51
|
+
return { items, extra: { menuError: recipes.reason } };
|
|
52
|
+
const named = items.map((item) => {
|
|
53
|
+
const hit = recipes.value.get(item.recipeId);
|
|
54
|
+
return hit ? { ...item, menuWeek: week, index: hit.index, ...(hit.name ? { name: hit.name } : {}) } : item;
|
|
55
|
+
});
|
|
56
|
+
return { items: named, extra: { onMenu: named.filter((i) => 'index' in i).length } };
|
|
57
|
+
}
|
|
58
|
+
const optionalWeek = weekParam
|
|
59
|
+
.optional()
|
|
60
|
+
.describe('A delivery week (ISO, e.g. 2026-W49): items on that week’s menu are named with their menu index.');
|
|
61
|
+
export function registerFavoriteTools(server, deps) {
|
|
62
|
+
const { client } = deps;
|
|
63
|
+
server.registerTool('hf_list_favorites', {
|
|
64
|
+
description: 'List the recipes the user favourited on HelloFresh (recipe ids and when). Give a week to name the ones on ' +
|
|
65
|
+
'that week’s menu with their menu index (hf_favorite_recipe / hf_unfavorite_recipe take that index). ' +
|
|
66
|
+
'hf_suggest_meals and hf_weekly_plan already favour these recipes.',
|
|
67
|
+
annotations: readOnly('HelloFresh: list favourite recipes'),
|
|
68
|
+
_meta: foodMeta('lookup', { aliases: ['hellofresh favorites', 'favourite recipes', 'saved recipes'] }),
|
|
69
|
+
inputSchema: z.object({ week: optionalWeek }),
|
|
70
|
+
}, async ({ week }) => {
|
|
71
|
+
const { total, favorites } = projectFavorites(await client.listFavorites());
|
|
72
|
+
const { items, extra } = await nameFromWeek(client, favorites, week);
|
|
73
|
+
return minifiedResult({ ...(total !== undefined ? { total } : {}), favorites: items, ...extra });
|
|
74
|
+
});
|
|
75
|
+
server.registerTool('hf_list_ratings', {
|
|
76
|
+
description: 'List the user’s own HelloFresh recipe ratings (both rating scales by default: v2, and v3 = 5 stars). Give a ' +
|
|
77
|
+
'week to name the rated recipes on that week’s menu. The planner never suggests a recipe rated 2 or lower. ' +
|
|
78
|
+
'The ratings list’s item shape has not been observed yet, so items without a recipe id and a numeric rating ' +
|
|
79
|
+
'are skipped and counted, not guessed at. Read-only: rating a recipe is not supported.',
|
|
80
|
+
annotations: readOnly('HelloFresh: list recipe ratings'),
|
|
81
|
+
_meta: foodMeta('lookup', { aliases: ['hellofresh ratings', 'rated recipes', 'my recipe ratings'] }),
|
|
82
|
+
inputSchema: z.object({
|
|
83
|
+
week: optionalWeek,
|
|
84
|
+
scale: z.enum(['v2', 'v3']).optional().describe('One rating scale only (v3 = 5 stars). Default: both.'),
|
|
85
|
+
}),
|
|
86
|
+
}, async ({ week, scale }) => {
|
|
87
|
+
const scales = scale ? [scale] : RATING_SCALES;
|
|
88
|
+
const read = await readRatings(client, scales);
|
|
89
|
+
if (read.unreadable.length === scales.length) {
|
|
90
|
+
throw new McpToolError(`Could not read your HelloFresh ratings: ${read.unreadable.map((u) => `${u.source}: ${u.reason}`).join('; ')}`);
|
|
91
|
+
}
|
|
92
|
+
const { items, extra } = await nameFromWeek(client, read.ratings, week);
|
|
93
|
+
return minifiedResult({
|
|
94
|
+
ratings: items,
|
|
95
|
+
...(read.skipped > 0 ? { skipped: read.skipped } : {}),
|
|
96
|
+
...(read.unreadable.length > 0 ? { unreadable: read.unreadable } : {}),
|
|
97
|
+
...extra,
|
|
98
|
+
note: 'The ratings item shape is not yet observed live: an item counts when it has a recipe id (object_id) and ' +
|
|
99
|
+
'a numeric rating; any other item is skipped and counted.',
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
const favoriteWrite = (add) => {
|
|
103
|
+
const name = add ? 'hf_favorite_recipe' : 'hf_unfavorite_recipe';
|
|
104
|
+
registerGated(server, {
|
|
105
|
+
name,
|
|
106
|
+
title: add ? 'HelloFresh: favourite a recipe' : 'HelloFresh: un-favourite a recipe',
|
|
107
|
+
description: add
|
|
108
|
+
? 'Add a recipe from a week’s menu to the user’s HelloFresh favourites (the planner then favours it). Give ' +
|
|
109
|
+
'the week and the menu index from hf_get_menu (a protein swap favourites the swap’s own recipe). Undo with ' +
|
|
110
|
+
'hf_unfavorite_recipe. Re-reads the favourites to verify.'
|
|
111
|
+
: 'Remove a recipe on a week’s menu from the user’s HelloFresh favourites. Give the week and the menu index ' +
|
|
112
|
+
'(hf_list_favorites with the week shows which are favourites). Undo with hf_favorite_recipe. Re-reads the ' +
|
|
113
|
+
'favourites to verify.',
|
|
114
|
+
destructive: false,
|
|
115
|
+
meta: CHANGE(add ? ['favorite hellofresh recipe', 'save recipe', 'like this recipe'] : ['unfavorite hellofresh recipe', 'remove favorite']),
|
|
116
|
+
input: {
|
|
117
|
+
week: weekParam,
|
|
118
|
+
index: z.number().int().positive().describe('The recipe’s menu index for that week (from hf_get_menu).'),
|
|
119
|
+
},
|
|
120
|
+
async plan({ week, index }) {
|
|
121
|
+
const account = await loadAccount(client);
|
|
122
|
+
const delivery = projectDelivery(await client.getDelivery(account.subscriptionId, week));
|
|
123
|
+
const menu = await readMenu(client, account, delivery, week);
|
|
124
|
+
const entry = [...recipesOf(menu)].find(([, r]) => r.index === index);
|
|
125
|
+
if (!entry) {
|
|
126
|
+
const listed = menu.meals.some((m) => m.index === index || m.variants.some((v) => v.index === index));
|
|
127
|
+
throw new McpToolError(listed ? `HelloFresh returned no recipe id for meal ${index} on the ${week} menu.` : `Meal ${index} is not on the ${week} menu.`, { hint: `hf_get_menu {week: "${week}"} lists the indexes.` });
|
|
128
|
+
}
|
|
129
|
+
const [recipeId, recipe] = entry;
|
|
130
|
+
const favorites = projectFavorites(await client.listFavorites()).favorites;
|
|
131
|
+
const isFavorite = favorites.some((f) => f.recipeId === recipeId);
|
|
132
|
+
const label = `“${recipe.name ?? recipeId}” (menu #${index}, ${week})`;
|
|
133
|
+
if (add && isFavorite)
|
|
134
|
+
throw new McpToolError(`${label} is already one of your favorites.`);
|
|
135
|
+
if (!add && !isFavorite)
|
|
136
|
+
throw new McpToolError(`${label} is not one of your favorites.`);
|
|
137
|
+
const request = add ? addFavoriteRequest(recipeId, week) : removeFavoriteRequest(recipeId);
|
|
138
|
+
return {
|
|
139
|
+
gate: {
|
|
140
|
+
action: add ? 'hellofresh.recipe.favorite' : 'hellofresh.recipe.unfavorite',
|
|
141
|
+
summary: add ? `Add ${label} to your HelloFresh favorites` : `Remove ${label} from your HelloFresh favorites`,
|
|
142
|
+
account: account.subscriptionId,
|
|
143
|
+
target: recipeId,
|
|
144
|
+
request: shown(request),
|
|
145
|
+
preview: { recipe: { index, name: recipe.name, recipeId }, favoritesNow: favorites.length },
|
|
146
|
+
},
|
|
147
|
+
state: { recipeId, week },
|
|
148
|
+
};
|
|
149
|
+
},
|
|
150
|
+
execute: (s) => sendAndVerify({
|
|
151
|
+
send: () => (add ? client.addFavorite(s.recipeId, s.week) : client.removeFavorite(s.recipeId)),
|
|
152
|
+
before: { favorite: !add },
|
|
153
|
+
checkWith: `hf_list_favorites {week: "${s.week}"}`,
|
|
154
|
+
mismatch: `HelloFresh accepted the request, but the re-read favourites ${add ? 'do not include' : 'still include'} the recipe.`,
|
|
155
|
+
verify: async () => {
|
|
156
|
+
const favorite = projectFavorites(await client.listFavorites()).favorites.some((f) => f.recipeId === s.recipeId);
|
|
157
|
+
return { ok: favorite === add, after: { favorite } };
|
|
158
|
+
},
|
|
159
|
+
}),
|
|
160
|
+
});
|
|
161
|
+
};
|
|
162
|
+
favoriteWrite(true);
|
|
163
|
+
favoriteWrite(false);
|
|
164
|
+
}
|
package/dist/tools/index.js
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
// The one list of tool registrars. `src/index.ts` registers exactly these, and
|
|
2
2
|
// the manifest-roster and annotation tests drive the same list, so a registrar
|
|
3
3
|
// can never be wired into the server but missed by the tests (or vice versa).
|
|
4
|
+
import { registerCookingTools } from './cooking.js';
|
|
5
|
+
import { registerFavoriteTools } from './favorites.js';
|
|
4
6
|
import { registerHealthcheckTool } from './healthcheck.js';
|
|
5
7
|
import { registerPlannerTools } from './planner.js';
|
|
8
|
+
import { registerPromoTools } from './promo.js';
|
|
6
9
|
import { registerReadTools } from './reads.js';
|
|
7
|
-
import { registerWriteTools } from './writes.js';
|
|
10
|
+
import { registerWriteTools } from './writes/index.js';
|
|
8
11
|
export const TOOL_REGISTRARS = [
|
|
9
12
|
registerHealthcheckTool,
|
|
10
13
|
registerReadTools,
|
|
11
14
|
registerWriteTools,
|
|
12
15
|
registerPlannerTools,
|
|
16
|
+
registerCookingTools,
|
|
17
|
+
registerFavoriteTools,
|
|
18
|
+
registerPromoTools,
|
|
13
19
|
];
|