@chrischall/hellofresh-mcp 0.0.0-stage → 0.0.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,71 @@
1
+ // hf_healthcheck — the bridge is on the auth path (it holds the session cookie),
2
+ // so this reports the bridge state AND probes the API from Node with the
3
+ // session's bearer: `GET /api/customers/me/subscriptions`, returning only the
4
+ // status (never the body, which carries the customer's name and address).
5
+ // The body is the library's bridge healthcheck; this adds the session block
6
+ // (minutes to expiry, the write-back warning) and HelloFresh's error kinds.
7
+ import { z } from 'zod';
8
+ import { EdgeBlockedError, McpToolError, detectEdgeBlock, errorKindOf, minifiedResult, toolAnnotations, } from '@chrischall/mcp-utils';
9
+ import { HelloFreshBridgeError, HelloFreshSessionError, WEB_ORIGIN, signInHint } from '../session.js';
10
+ export const PROBE_PATH = '/gw/api/customers/me/subscriptions?country=US&locale=en-US';
11
+ const HOST_LABEL = 'www.hellofresh.com';
12
+ const PROBE_TIMEOUT_MS = 30_000;
13
+ /** GET the subscriptions list with the session's bearer; resolve to '' (status only) or throw. */
14
+ async function probe(deps) {
15
+ const res = await deps.session.withAuth((token) => deps.fetchImpl(`${WEB_ORIGIN}${PROBE_PATH}`, {
16
+ headers: { authorization: `Bearer ${token}`, accept: 'application/json' },
17
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
18
+ }));
19
+ const body = await res.text();
20
+ if (res.ok)
21
+ return '';
22
+ const edge = detectEdgeBlock({ status: res.status, headers: res.headers, body });
23
+ if (edge)
24
+ throw new EdgeBlockedError(res.status, edge.vendor, { service: 'HelloFresh', method: 'GET', path: PROBE_PATH });
25
+ throw new McpToolError(`HelloFresh answered HTTP ${res.status} for the subscriptions probe.`, {
26
+ status: res.status,
27
+ kind: res.status === 401 ? 'credential_rejected' : 'http',
28
+ });
29
+ }
30
+ function classify(err) {
31
+ if (err instanceof HelloFreshSessionError)
32
+ return { kind: 'session_expired', hint: err.hint };
33
+ if (err instanceof HelloFreshBridgeError)
34
+ return { kind: 'bridge', hint: err.hint };
35
+ if (errorKindOf(err) === 'credential_rejected')
36
+ return { kind: 'credential_rejected', hint: signInHint() };
37
+ return undefined;
38
+ }
39
+ export function registerHealthcheckTool(server, deps) {
40
+ server.registerTool('hf_healthcheck', {
41
+ description: 'Check the HelloFresh connection end to end: the ContextMint Bridge link to your signed-in ' +
42
+ 'www.hellofresh.com tab (which holds the session), the session token (minutes to expiry, and a warning ' +
43
+ 'if a refreshed session could not be written back to the browser), and a probe of the HelloFresh ' +
44
+ 'subscriptions endpoint that returns only its status. Call it when another hf_ tool fails, to learn ' +
45
+ 'which hop broke (bridge, sign-in, or HelloFresh itself).',
46
+ annotations: toolAnnotations({ title: 'HelloFresh: healthcheck', readOnly: true, idempotent: true, openWorld: true }),
47
+ inputSchema: z.object({}),
48
+ }, async () => {
49
+ // Lazy, like transport.ts: the fetchproxy subpath eagerly loads @fetchproxy/server.
50
+ const { runBridgeHealthcheck } = await import('@chrischall/mcp-utils/fetchproxy');
51
+ const raw = await runBridgeHealthcheck({
52
+ server,
53
+ prefix: 'hf',
54
+ hostLabel: HOST_LABEL,
55
+ probePath: PROBE_PATH,
56
+ transport: await deps.bridge.healthTransport(),
57
+ probeFn: () => probe(deps),
58
+ classifyThrown: classify,
59
+ });
60
+ const result = JSON.parse(raw.content[0].text);
61
+ const minutes = deps.session.expiresInMinutes();
62
+ const warning = deps.session.warning();
63
+ result['session'] = {
64
+ ...(minutes !== undefined ? { expires_in_minutes: minutes } : {}),
65
+ ...(warning !== undefined ? { warning } : {}),
66
+ };
67
+ if (result.ok && warning !== undefined)
68
+ result.hint = warning;
69
+ return minifiedResult(result);
70
+ });
71
+ }
@@ -0,0 +1,14 @@
1
+ // Context-group hints, published on each tool as `_meta.mint` (the mcp-host
2
+ // context-groups contract, `mintHintSchema`). Inert data: a host that does not
3
+ // read them sees an extra `_meta` key and nothing else. The shape is fixed by
4
+ // the host's contract, so it is restated here rather than imported — this
5
+ // server takes no dependency on mcp-host.
6
+ //
7
+ // Every tool but hf_healthcheck sits in the `food` domain. `aliases` are
8
+ // lowercase, at most 8, each ≤ 40 chars.
9
+ /** `_meta` for a HelloFresh tool. */
10
+ export function foodMeta(intent, extra = {}) {
11
+ return { mint: { domain: 'food', intent, ...extra } };
12
+ }
13
+ /** A read of one record or a reference list. */
14
+ export const LOOKUP = foodMeta('lookup');
@@ -0,0 +1,13 @@
1
+ // The one list of tool registrars. `src/index.ts` registers exactly these, and
2
+ // the manifest-roster and annotation tests drive the same list, so a registrar
3
+ // can never be wired into the server but missed by the tests (or vice versa).
4
+ import { registerHealthcheckTool } from './healthcheck.js';
5
+ import { registerPlannerTools } from './planner.js';
6
+ import { registerReadTools } from './reads.js';
7
+ import { registerWriteTools } from './writes.js';
8
+ export const TOOL_REGISTRARS = [
9
+ registerHealthcheckTool,
10
+ registerReadTools,
11
+ registerWriteTools,
12
+ registerPlannerTools,
13
+ ];
@@ -0,0 +1,281 @@
1
+ // The planner tools: hf_list_profiles (the configured planner profiles),
2
+ // hf_suggest_meals (ranked picks for a week and a profile) and hf_weekly_plan
3
+ // (everything to approve in one read — box size needed, picks, estimated
4
+ // total, the approval line and the exact confirm-gated write calls to make
5
+ // next). All are READ-ONLY: they never change the box. The scoring itself is
6
+ // pure and lives in src/planner.ts; profiles load from local config
7
+ // (src/profiles.ts) on first use.
8
+ import { z } from 'zod';
9
+ import { minifiedResult, toolAnnotations } from '@chrischall/mcp-utils';
10
+ import { projectDelivery } from '../normalize.js';
11
+ import { suggestMeals, summaryText } from '../planner.js';
12
+ import { BUILTIN_PROFILES, DEFAULT_PROFILES_FILE, PROFILES_ENV, PROFILES_FILE_ENV, createProfileStore, profileLabel, profileSku, resolveProfile, } from '../profiles.js';
13
+ import { shiftWeek } from '../weeks.js';
14
+ import { foodMeta } from './hints.js';
15
+ import { boxNumbering, boxNumbers, compactEstimate, compactSelection, dateOf, estimateFor, isUnresizableFirstBox, loadAccount, nextBoxNumberParam, readMenu, readPicks, weekParam, } from './shared.js';
16
+ const readOnly = (title) => toolAnnotations({ title, readOnly: true, idempotent: true, openWorld: true });
17
+ // ---- parameters -----------------------------------------------------------------------
18
+ const builtinNames = BUILTIN_PROFILES.map((p) => `"${p.name}"`).join(', ');
19
+ const profileParam = z
20
+ .string()
21
+ .trim()
22
+ .min(1)
23
+ .max(40)
24
+ .describe(`The planner profile to plan for, by name (hf_list_profiles lists them; the built-ins are ${builtinNames}). ` +
25
+ 'A profile sets the servings and meal count, the allowed recipe categories, and what to favour ' +
26
+ '(kid friendly, quick, adventurous) and the premium cap. Decide which profile applies to the week before calling.');
27
+ const suggestInput = {
28
+ week: weekParam,
29
+ profile: profileParam,
30
+ people: z
31
+ .union([z.literal(2), z.literal(3), z.literal(4), z.literal(6)])
32
+ .optional()
33
+ .describe('Servings for this week only, overriding the profile’s people (2, 3, 4 or 6).'),
34
+ avoid_indexes: z
35
+ .array(z.number().int().positive())
36
+ .max(50)
37
+ .optional()
38
+ .describe('Menu indexes never to suggest (e.g. a recipe someone dislikes).'),
39
+ avoid_recent_weeks: z
40
+ .number()
41
+ .int()
42
+ .min(0)
43
+ .max(12)
44
+ .optional()
45
+ .describe('Skip recipes picked in this many weeks before the week (default: the profile’s avoidRepeatWeeks, usually 4; ' +
46
+ '0 allows repeats). ' +
47
+ 'Read best effort, like hf_recent_picks.'),
48
+ max_premium_per_serving_cents: z
49
+ .number()
50
+ .int()
51
+ .min(0)
52
+ .optional()
53
+ .describe('Highest premium upcharge per serving, in US cents (default: the profile’s premiumCapCents; 0 = no premiums).'),
54
+ };
55
+ async function plan(client, account, delivery, profile, args) {
56
+ const back = args.avoid_recent_weeks ?? profile.avoidRepeatWeeks;
57
+ const weeks = Array.from({ length: back }, (_, i) => shiftWeek(args.week, i - back));
58
+ const [menu, picks] = await Promise.all([
59
+ readMenu(client, account, delivery, args.week),
60
+ back > 0 ? readPicks(client, account, weeks) : undefined,
61
+ ]);
62
+ const suggestion = suggestMeals(menu, {
63
+ profile,
64
+ people: args.people,
65
+ avoidIndexes: args.avoid_indexes,
66
+ avoidNames: picks?.recipeNames,
67
+ maxPremiumPerServingCents: args.max_premium_per_serving_cents,
68
+ });
69
+ return {
70
+ menu,
71
+ suggestion,
72
+ ...(picks
73
+ ? {
74
+ recent: {
75
+ weeks,
76
+ avoidedNames: picks.recipeNames,
77
+ ...(picks.unreadable.length > 0 ? { unreadable: picks.unreadable } : {}),
78
+ },
79
+ }
80
+ : {}),
81
+ };
82
+ }
83
+ function compactCandidate(c) {
84
+ return {
85
+ index: c.index,
86
+ name: c.name,
87
+ category: c.category,
88
+ protein: c.protein,
89
+ ...(c.baseIndex !== undefined ? { baseIndex: c.baseIndex } : {}),
90
+ kidFriendly: c.kidFriendly,
91
+ totalMinutes: c.totalMinutes,
92
+ ...(c.premiumPerServingCents > 0 ? { premiumPerServingCents: c.premiumPerServingCents, premiumBoxCents: c.premiumBoxCents } : {}),
93
+ ...(c.selected ? { selected: true } : {}),
94
+ score: c.score,
95
+ reasons: c.reasons,
96
+ };
97
+ }
98
+ function suggestionFields(s) {
99
+ return {
100
+ maxPremiumPerServingCents: s.maxPremiumPerServingCents,
101
+ picks: s.picks.map(compactCandidate),
102
+ alternates: s.alternates.map((a) => ({ slot: a.slot, for: a.for, options: a.options.map(compactCandidate) })),
103
+ ...(s.excluded.length > 0 ? { excluded: s.excluded } : {}),
104
+ ...(s.warning ? { warning: s.warning } : {}),
105
+ };
106
+ }
107
+ // ---- weekly-plan helpers ---------------------------------------------------------------------
108
+ /** The product price/fees for `sku`: this week's own, another upcoming week's at that size, or the plan's unit price. */
109
+ function priceFor(sku, delivery, upcoming, account) {
110
+ const fees = { feeCents: delivery.feeCents, shippingCents: delivery.shippingCents };
111
+ if (delivery.sku === sku && delivery.priceCents !== undefined)
112
+ return { priceCents: delivery.priceCents, ...fees, priceFrom: 'this week' };
113
+ const other = upcoming.find((d) => d.sku === sku && d.priceCents !== undefined);
114
+ if (other)
115
+ return { priceCents: other.priceCents, ...fees, priceFrom: `${other.week} (same box size)` };
116
+ const product = account.subscription.product;
117
+ if (product?.sku === sku && product.unitPrice !== undefined)
118
+ return { priceCents: product.unitPrice, ...fees, priceFrom: 'the plan price' };
119
+ return undefined;
120
+ }
121
+ /** Why the week can no longer be changed, if it cannot. */
122
+ function lockedReason(delivery, week, now) {
123
+ if (delivery.status !== 'running' && delivery.status !== 'skipped')
124
+ return `${week} is ${delivery.status}: it can no longer be changed.`;
125
+ if (delivery.cutoffDate && Date.parse(delivery.cutoffDate) <= now) {
126
+ return `The cutoff for ${week} passed at ${delivery.cutoffDate}: its box and picks can no longer be changed.`;
127
+ }
128
+ return undefined;
129
+ }
130
+ // ---- registration ------------------------------------------------------------------------------
131
+ export function registerPlannerTools(server, deps) {
132
+ const { client } = deps;
133
+ const now = deps.now ?? Date.now;
134
+ const profiles = deps.profiles ?? createProfileStore();
135
+ /** The named profile — loading the config on first use, so a bad config is a tool error, never a boot failure. */
136
+ const profileFor = (name) => resolveProfile(profiles(), name);
137
+ server.registerTool('hf_list_profiles', {
138
+ description: 'List the meal-planner profiles hf_suggest_meals and hf_weekly_plan accept (e.g. a 2-person adventurous ' +
139
+ 'week, a 4-person kid-friendly week): each one’s servings, meals, box SKU, allowed recipe categories, ' +
140
+ 'preferences and premium cap, and where the profiles were loaded from (HELLOFRESH_PROFILES, a profiles ' +
141
+ 'file, or the built-in defaults). Local config only: no HelloFresh call.',
142
+ annotations: toolAnnotations({ title: 'HelloFresh: list planner profiles', readOnly: true, idempotent: true, openWorld: false }),
143
+ _meta: foodMeta('lookup', { aliases: ['hellofresh profiles', 'meal plan profiles', 'who is the box for'] }),
144
+ inputSchema: z.object({}),
145
+ }, async () => {
146
+ const loaded = profiles();
147
+ return minifiedResult({
148
+ source: loaded.source,
149
+ profiles: loaded.profiles.map((p) => ({ ...p, label: profileLabel(p), sku: profileSku(p) })),
150
+ configure: `Set ${PROFILES_ENV} to a JSON array of profiles, or point ${PROFILES_FILE_ENV} at a JSON file ` +
151
+ `(default ${DEFAULT_PROFILES_FILE}). Each: name, people (2/3/4/6), premiumCapCents; optional label, meals ` +
152
+ '(2–6), categories, kidFriendly, maxMinutes, adventurous, avoidRepeatWeeks. Restart the server after a change.',
153
+ });
154
+ });
155
+ server.registerTool('hf_suggest_meals', {
156
+ description: 'Suggest the dinners to pick for a HelloFresh delivery week for a planner profile (hf_list_profiles): ranks ' +
157
+ 'every dish and protein swap on the week’s menu in the profile’s allowed categories by its preferences ' +
158
+ '(kid friendly, quick, adventurous) and premium cap, skips recipes picked in recent weeks, prefers varied ' +
159
+ 'proteins (e.g. one shrimp + one fish), and returns the top picks plus 2 alternates per slot, each with its ' +
160
+ 'reasons. Read-only: pick with hf_select_meals.',
161
+ annotations: readOnly('HelloFresh: suggest meals'),
162
+ _meta: foodMeta('other', { aliases: ['what should we have', 'hellofresh suggestions', 'seafood dinners', 'pick dinners'] }),
163
+ inputSchema: z.object(suggestInput),
164
+ }, async (args) => {
165
+ const profile = profileFor(args.profile);
166
+ const account = await loadAccount(client);
167
+ const delivery = projectDelivery(await client.getDelivery(account.subscriptionId, args.week));
168
+ const { suggestion, recent } = await plan(client, account, delivery, profile, args);
169
+ return minifiedResult({
170
+ week: args.week,
171
+ profile: profile.name,
172
+ servings: suggestion.people,
173
+ box: { current: delivery.sku, required: profileSku(profile, suggestion.people) },
174
+ ...suggestionFields(suggestion),
175
+ ...(recent ? { recentPicks: recent } : {}),
176
+ next: `hf_weekly_plan {week: "${args.week}", profile: "${profile.name}"} prices it and lists the writes; hf_select_meals picks.`,
177
+ });
178
+ });
179
+ server.registerTool('hf_weekly_plan', {
180
+ description: 'Plan one HelloFresh delivery week for a planner profile (hf_list_profiles — e.g. a 4-person family week) in ' +
181
+ 'one read: the box size the week needs versus what it has, suggested picks with alternates, the estimated ' +
182
+ 'box total with the voucher discount (and a warning when the voucher stops applying), a one-line summary ' +
183
+ 'for the user to approve, and the exact follow-up write calls (hf_unskip_week, hf_set_week_size, ' +
184
+ 'hf_select_meals) in order. The subscription’s first box cannot be resized, so for it no size change is ' +
185
+ 'proposed (notes say so). Read-only: it changes nothing.',
186
+ annotations: readOnly('HelloFresh: weekly plan'),
187
+ _meta: foodMeta('other', { aliases: ['plan hellofresh week', 'weekly meal plan', 'hellofresh plan this week'] }),
188
+ inputSchema: z.object({
189
+ ...suggestInput,
190
+ box_number: z
191
+ .number()
192
+ .int()
193
+ .min(1)
194
+ .max(1000)
195
+ .optional()
196
+ .describe('This box’s number, counting every box ever delivered — overrides the number derived from next_box_number.'),
197
+ next_box_number: nextBoxNumberParam,
198
+ }),
199
+ }, async (args) => {
200
+ const { week } = args;
201
+ const profile = profileFor(args.profile);
202
+ const account = await loadAccount(client);
203
+ const [raw, list] = await Promise.all([client.getDelivery(account.subscriptionId, week), client.listDeliveries()]);
204
+ const delivery = projectDelivery(raw);
205
+ const upcoming = (list.items ?? []).map(projectDelivery);
206
+ // The first box cannot be resized (a HelloFresh rule): plan for the box as it is, and say so.
207
+ const wanted = profileSku(profile, args.people ?? profile.people);
208
+ const firstBoxFixed = isUnresizableFirstBox(account.subscription, week) && !!delivery.sku && !!delivery.servings && !!delivery.meals;
209
+ const firstBoxDiffers = firstBoxFixed && delivery.sku !== wanted;
210
+ const planProfile = firstBoxDiffers ? { ...profile, meals: delivery.meals } : profile;
211
+ const planArgs = firstBoxDiffers ? { ...args, people: delivery.servings } : args;
212
+ const { menu, suggestion, recent } = await plan(client, account, delivery, planProfile, planArgs);
213
+ const { picks, people } = suggestion;
214
+ const sku = firstBoxDiffers ? delivery.sku : profileSku(profile, people);
215
+ const notes = firstBoxDiffers
216
+ ? [
217
+ `${week} is the first box of this subscription, which HelloFresh says cannot be resized: it keeps ` +
218
+ `${delivery.sku} (the ${profile.name} profile would want ${wanted}), so the picks and estimate are for it as it is.`,
219
+ ]
220
+ : [];
221
+ const sizeChangeNeeded = delivery.sku !== sku;
222
+ const skipped = delivery.status === 'skipped';
223
+ const locked = lockedReason(delivery, week, now());
224
+ // Box number as if the week runs (an unskip makes it count).
225
+ const numbering = boxNumbering(account.subscription, args.next_box_number);
226
+ const boxNumber = args.box_number ??
227
+ boxNumbers(upcoming.map((d) => (d.week === week ? { ...d, status: 'running' } : d)), numbering.next).get(week);
228
+ const price = priceFor(sku, delivery, upcoming, account);
229
+ const estimate = price
230
+ ? estimateFor({ ...delivery, ...price }, picks.map((p) => ({ premiumBoxCents: p.premiumBoxCents, quantity: 1 })), account, boxNumber)
231
+ : undefined;
232
+ const chosen = new Set(picks.map((p) => p.index));
233
+ const alreadyPicked = !sizeChangeNeeded &&
234
+ !skipped &&
235
+ picks.length > 0 &&
236
+ menu.selected.length === picks.length &&
237
+ menu.selected.every((s) => chosen.has(s.index));
238
+ const followUp = locked
239
+ ? []
240
+ : [
241
+ ...(skipped ? [{ tool: 'hf_unskip_week', arguments: { week }, why: `${week} is skipped.` }] : []),
242
+ ...(sizeChangeNeeded
243
+ ? [
244
+ {
245
+ tool: 'hf_set_week_size',
246
+ arguments: { week, people, meals: profile.meals },
247
+ why: `${week} is ${delivery.sku}; the ${profile.name} profile needs ${sku}.`,
248
+ },
249
+ ]
250
+ : []),
251
+ ...(picks.length > 0 && !alreadyPicked
252
+ ? [{ tool: 'hf_select_meals', arguments: { week, meals: picks.map((p) => p.index) }, why: 'Pick the suggested meals.' }]
253
+ : []),
254
+ ];
255
+ return minifiedResult({
256
+ week,
257
+ profile: profile.name,
258
+ servings: people,
259
+ delivery: { deliveryDate: dateOf(delivery.deliveryDate), cutoffDate: delivery.cutoffDate, status: delivery.status },
260
+ box: { current: delivery.sku, required: sku, sizeChangeNeeded },
261
+ currentPicks: menu.selected.map(compactSelection),
262
+ ...suggestionFields(suggestion),
263
+ ...(estimate
264
+ ? { estimate: { ...compactEstimate(estimate), ...(estimate.voucher ? { voucher: estimate.voucher.code } : {}), priceFrom: price.priceFrom } }
265
+ : { estimateWarning: `HelloFresh shows no price for ${sku} on this account, so the box total is not estimated.` }),
266
+ ...(estimate && args.box_number === undefined ? { boxNumberNote: numbering.note } : {}),
267
+ summary: summaryText({ profile, people, deliveryDate: delivery.deliveryDate, picks, estimate }),
268
+ ...(locked ? { locked } : {}),
269
+ ...(alreadyPicked ? { note: 'The suggested meals are already picked for this week; nothing to change.' } : {}),
270
+ ...(notes.length > 0 ? { notes } : {}),
271
+ followUp,
272
+ ...(followUp.length > 0
273
+ ? {
274
+ followUpNote: 'Run these in order once the user approves the summary. Each is confirm-gated: call it without ' +
275
+ 'confirmToken to preview, then again with the token. A size change may reset the picks, so pick last.',
276
+ }
277
+ : {}),
278
+ ...(recent ? { recentPicks: recent } : {}),
279
+ });
280
+ });
281
+ }