@chrischall/hellofresh-mcp 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js CHANGED
@@ -53,6 +53,12 @@ export class HelloFreshClient {
53
53
  route: `/api/subscriptions/{id}/delivery_dates/${week}`,
54
54
  });
55
55
  }
56
+ /** A box's carrier tracking, by the public id at the end of the delivery's `tracking.tracking_link`. */
57
+ getTracking(publicId) {
58
+ return this.request('GET', apiPath `/scm/tracking-ids/track/public-id/${publicId}`, {
59
+ route: '/scm/tracking-ids/track/public-id/{id}',
60
+ });
61
+ }
56
62
  getProductOptions(subscriptionId) {
57
63
  return this.request('GET', apiPath `/api/subscriptions/${subscriptionId}/product_options`, {
58
64
  route: '/api/subscriptions/{id}/product_options',
package/dist/normalize.js CHANGED
@@ -85,6 +85,56 @@ export function projectDelivery(d) {
85
85
  oneOffDaySlots: (d.availableOneOffOptions ?? []).map((o) => ({ handle: o.handle, deliveryDate: o.deliveryDate })),
86
86
  };
87
87
  }
88
+ // ---- tracking --------------------------------------------------------------------
89
+ /** The public id a delivery's HelloFresh tracking link ends in (only a www.hellofresh.com link counts). */
90
+ export function trackingPublicId(t) {
91
+ const m = /^https:\/\/www\.hellofresh\.com\/delivery-tracking\/([0-9a-f-]{8,64})\/?$/i.exec(t?.tracking_link ?? '');
92
+ return m?.[1];
93
+ }
94
+ const opt = (key, value) => (value === undefined || value === null || value === '' ? {} : { [key]: value });
95
+ const step = (s) => ({
96
+ ...opt('status', s.status),
97
+ ...opt('statusDetail', s.status_detail),
98
+ ...opt('at', s.datetime),
99
+ ...opt('message', s.message),
100
+ });
101
+ /**
102
+ * Carrier tracking, allowlisted: carrier, code, live status (HelloFresh's and
103
+ * its internal one) and the status history. Never the signer's name, the box's
104
+ * external id, its lane or the proof-of-delivery photo URLs (only their count).
105
+ */
106
+ export function projectTracking(raw) {
107
+ const boxes = (raw.boxes ?? []).filter((b) => !!b && typeof b === 'object');
108
+ return {
109
+ boxes: boxes.map((b) => {
110
+ const last = b.last_status ?? {};
111
+ const photos = Array.isArray(b.proof_of_delivery_photo_urls) ? b.proof_of_delivery_photo_urls.length : 0;
112
+ const history = (b.statuses ?? []).filter((s) => !!s && typeof s === 'object').map(step);
113
+ const lastAt = Date.parse(last.datetime ?? '');
114
+ const newer = history
115
+ .filter((h) => Date.parse(h.at ?? '') > (Number.isNaN(lastAt) ? -Infinity : lastAt))
116
+ .sort((a, z) => Date.parse(z.at) - Date.parse(a.at))[0];
117
+ return {
118
+ ...opt('carrier', b.carrier),
119
+ ...opt('trackingCode', b.tracking_code),
120
+ ...opt('status', last.status),
121
+ ...opt('statusDetail', last.status_detail),
122
+ ...opt('internalStatus', b.internal_status ?? last.internal_status),
123
+ ...opt('internalStatusDetail', b.internal_status_detail ?? last.internal_status_detail),
124
+ ...opt('statusMessage', last.message),
125
+ ...opt('statusAt', last.datetime),
126
+ ...opt('estimatedDelivery', last.est_delivery_time),
127
+ ...opt('carrierTrackingUrl', b.carrier_tracking_url ?? b.public_url),
128
+ ...opt('trackingUrl', b.hf_tracking_url),
129
+ ...opt('deliveryDate', b.delivery_date),
130
+ delivered: last.status === 'delivered' || newer?.status === 'delivered',
131
+ ...(newer ? { latestEvent: newer } : {}),
132
+ ...(photos > 0 ? { proofOfDeliveryPhotos: photos } : {}),
133
+ history,
134
+ };
135
+ }),
136
+ };
137
+ }
88
138
  const QUICK_TAGS = new Set(['quick', 'easy-prep']);
89
139
  const QUICK_MINUTES = 30;
90
140
  function isSeafoodCategory(category) {
@@ -0,0 +1,256 @@
1
+ // HelloFresh customer-support chat ("FreshBot") — docs/HELLOFRESH-API.md
2
+ // "Support chat (Sierra)".
3
+ //
4
+ // The chat on www.hellofresh.com/contact-us is NOT a /gw endpoint: it is a
5
+ // Sierra AI agent (eu.sierra.chat) that a person can take over. Three calls:
6
+ //
7
+ // 1. POST {SIERRA_API}/graphql embedChatRefreshWindowTokenQuery → a window
8
+ // token for a client-chosen window id (no HelloFresh credential needed);
9
+ // 2. POST {SIERRA_API}/chat one client event (`start` opens a
10
+ // conversation, `message` sends text) → a stream of
11
+ // `BOT_CHAT_EVENT_BEGIN{json}BOT_CHAT_EVENT_END` frames: the conversation
12
+ // id and its encryption key (on start), streamed reply text, and `state`
13
+ // snapshots of the whole transcript;
14
+ // 3. POST {SIERRA_API}/chat/live/poll — a long-poll the site runs only while
15
+ // a human agent is involved; with none it answers 204 after ~48 s.
16
+ //
17
+ // The request carries `memory.secrets.CUSTOMER_JWT` = the HelloFresh access
18
+ // token (exactly as the site sends it — that is how FreshBot reads the
19
+ // account). It is never logged, returned or put in an error.
20
+ //
21
+ // Everything here is pure or takes an injected fetch: the tools own the
22
+ // conversation store and the token.
23
+ import { McpToolError, messageOf, truncateErrorMessage } from '@chrischall/mcp-utils';
24
+ export const SIERRA_API = 'https://eu.sierra.chat/-/api';
25
+ /** HelloFresh US's public chat-agent key (it is in the widget's script URL on every page). */
26
+ export const SIERRA_AGENT_KEY = 'rEVzK9YBnPzNiWEBnPzNic4p0Ya-JWIRjGNmiP8amMI';
27
+ export const SUPPORT_SERVICE = 'HelloFresh support chat';
28
+ /** The entry reason the site sends from its "Chat now" button (the one value observed). */
29
+ export const ENTRY_REASON = 'unknown-from_chat_now_button';
30
+ export const CHAT_LOCALE = 'en-US';
31
+ export const DEFAULT_TIME_ZONE = 'America/New_York';
32
+ /** Bound on a start / message turn (the reply streams in the same response). */
33
+ export const TURN_TIMEOUT_MS = 90_000;
34
+ const WINDOW_TOKEN_QUERY = 'query embedChatRefreshWindowTokenQuery($token:String!$userIdentityToken:String$windowId:String){embedBotByToken(token:$token fullscreen:false userIdentityToken:$userIdentityToken windowId:$windowId){__typename ...on EmbedBot{windowToken}...on Node{__isNode:__typename id}}}';
35
+ // ---- the stream -----------------------------------------------------------------
36
+ /** Every frame of a chat answer, in order. A frame that is not JSON is skipped. */
37
+ export function parseChatStream(text) {
38
+ const frames = [];
39
+ for (const m of text.matchAll(/BOT_CHAT_EVENT_BEGIN([\s\S]*?)BOT_CHAT_EVENT_END/g)) {
40
+ try {
41
+ const value = JSON.parse(m[1]);
42
+ if (value && typeof value === 'object' && !Array.isArray(value))
43
+ frames.push(value);
44
+ }
45
+ catch {
46
+ // A malformed frame is skipped: the state snapshots repeat the transcript.
47
+ }
48
+ }
49
+ return frames;
50
+ }
51
+ const META_KEYS = new Set(['timestamp', 'idempotencyKey', 'tags', 'encryptedFullRedactionMode', 'eventId', 'agentInvocationId']);
52
+ const SPEAKER = { USER: 'user', AGENT: 'bot', HUMAN_AGENT: 'human_agent' };
53
+ const str = (v) => (typeof v === 'string' && v !== '' ? v : undefined);
54
+ function linksOf(attachments) {
55
+ if (!Array.isArray(attachments))
56
+ return undefined;
57
+ const links = attachments.flatMap((a) => {
58
+ const data = a?.data;
59
+ const url = str(data?.path);
60
+ return url && /^https:\/\//.test(url) ? [{ ...(str(data?.label) ? { label: str(data?.label) } : {}), url }] : [];
61
+ });
62
+ return links.length > 0 ? links : undefined;
63
+ }
64
+ /** The state snapshot's events, projected: who said what and when. Unknown shapes are skipped, never guessed at. */
65
+ export function projectEvents(raw) {
66
+ const out = [];
67
+ for (const e of raw) {
68
+ if (!e || typeof e !== 'object' || Array.isArray(e))
69
+ continue;
70
+ const ev = e;
71
+ const kind = Object.keys(ev).find((k) => !META_KEYS.has(k));
72
+ if (!kind)
73
+ continue;
74
+ const base = { ...(str(ev.timestamp) ? { at: str(ev.timestamp) } : {}), ...(str(ev.eventId) ? { id: str(ev.eventId) } : {}) };
75
+ if (kind === 'message') {
76
+ const m = ev.message;
77
+ const text = str(m?.text);
78
+ if (!m || !text || m.isProgressIndicator === true)
79
+ continue;
80
+ const from = SPEAKER[String(m.author)];
81
+ const links = linksOf(m.attachments);
82
+ out.push({
83
+ kind,
84
+ ...(from ? { from } : {}),
85
+ ...(from === 'human_agent' && str(m.displayName) ? { name: str(m.displayName) } : {}),
86
+ text,
87
+ ...base,
88
+ ...(links ? { links } : {}),
89
+ });
90
+ continue;
91
+ }
92
+ if (kind === 'humanAgentParticipation') {
93
+ const type = ev.humanAgentParticipation?.type;
94
+ out.push({ kind: type === 'JOIN' ? 'agentJoined' : type === 'LEAVE' ? 'agentLeft' : kind, ...base });
95
+ continue;
96
+ }
97
+ // humanAgentTyping is transient UI state, not part of the record.
98
+ if (kind === 'humanAgentTyping')
99
+ continue;
100
+ const detail = kind === 'queueInfo' ? ev.queueInfo : undefined;
101
+ out.push({ kind, ...base, ...(detail !== undefined ? { detail } : {}) });
102
+ }
103
+ return out;
104
+ }
105
+ const stateEvents = (frame) => {
106
+ const events = frame.state?.events;
107
+ return Array.isArray(events) ? events : undefined;
108
+ };
109
+ /** The conversation id + key (sent on start) and the transcript of the last state frame. */
110
+ export function readTurn(frames) {
111
+ const turn = {};
112
+ for (const f of frames) {
113
+ if (typeof f.conversationID === 'string')
114
+ turn.conversationID = f.conversationID;
115
+ if (typeof f.encryptionKey === 'string')
116
+ turn.encryptionKey = f.encryptionKey;
117
+ if (f.type === 'state') {
118
+ const events = stateEvents(f);
119
+ if (events)
120
+ turn.events = projectEvents(events);
121
+ }
122
+ }
123
+ return turn;
124
+ }
125
+ // ---- request bodies (the site's own shapes) -------------------------------------------
126
+ export function chatRequestBody(r) {
127
+ const clientEvent = r.event.type === 'start'
128
+ ? { type: 'start', idempotencyKey: r.idempotencyKey }
129
+ : { type: 'message', message: { content: r.event.text }, idempotencyKey: r.idempotencyKey, idempotencyReplayResponse: true };
130
+ return {
131
+ token: SIERRA_AGENT_KEY,
132
+ releaseHash: 'production',
133
+ ...(r.conversation ? { conversationID: r.conversation.conversationID, encryptionKey: r.conversation.encryptionKey } : {}),
134
+ clientEvent,
135
+ userMessageText: r.event.type === 'message' ? r.event.text : '',
136
+ memory: r.memory,
137
+ locale: CHAT_LOCALE,
138
+ timeZone: r.timeZone ?? DEFAULT_TIME_ZONE,
139
+ userMessageIndex: 0,
140
+ windowId: r.windowId,
141
+ };
142
+ }
143
+ export function livePollBody(r) {
144
+ return {
145
+ token: SIERRA_AGENT_KEY,
146
+ releaseHash: 'production',
147
+ conversationID: r.conversation.conversationID,
148
+ encryptionKey: r.conversation.encryptionKey,
149
+ memory: r.memory,
150
+ locale: CHAT_LOCALE,
151
+ timeZone: r.timeZone ?? DEFAULT_TIME_ZONE,
152
+ windowId: r.windowId,
153
+ };
154
+ }
155
+ export class SierraChat {
156
+ fetchImpl;
157
+ redact;
158
+ timeoutMs;
159
+ constructor(opts) {
160
+ this.fetchImpl = opts.fetchImpl;
161
+ this.redact = opts.redact ?? ((t) => t);
162
+ this.timeoutMs = opts.timeoutMs ?? TURN_TIMEOUT_MS;
163
+ }
164
+ /** A window token for `windowId` (the `x-window-token` every chat call carries). */
165
+ async windowToken(windowId) {
166
+ const res = await this.post('/graphql', 'application/json', {
167
+ query: WINDOW_TOKEN_QUERY,
168
+ variables: { token: SIERRA_AGENT_KEY, userIdentityToken: null, windowId },
169
+ });
170
+ const text = await res.text();
171
+ let token;
172
+ try {
173
+ token = JSON.parse(text).data?.embedBotByToken?.windowToken;
174
+ }
175
+ catch {
176
+ // handled below
177
+ }
178
+ if (typeof token !== 'string' || token === '') {
179
+ throw new McpToolError(`${SUPPORT_SERVICE} did not issue a window token (HTTP ${res.status}).`, { kind: 'http', status: res.status });
180
+ }
181
+ return token;
182
+ }
183
+ /** One client event; the reply streams back in the same response. */
184
+ async turn(body, windowToken) {
185
+ const res = await this.post('/chat', 'text/plain', body, { 'x-window-token': windowToken });
186
+ const text = await res.text();
187
+ const frames = parseChatStream(text);
188
+ if (frames.length === 0) {
189
+ throw new McpToolError(`${SUPPORT_SERVICE} answered HTTP ${res.status} with no chat events.`, { kind: 'http', status: res.status });
190
+ }
191
+ return readTurn(frames);
192
+ }
193
+ /** Wait up to `waitMs` for new live-agent events. Running out of time is "nothing new". */
194
+ async poll(body, windowToken, waitMs) {
195
+ let res;
196
+ try {
197
+ res = await this.post('/chat/live/poll', 'text/plain', body, { 'x-window-token': windowToken }, waitMs, true);
198
+ }
199
+ catch (err) {
200
+ if (err instanceof WaitElapsed)
201
+ return { status: 'nothing_new' };
202
+ throw err;
203
+ }
204
+ if (res.status === 204)
205
+ return { status: 'nothing_new' };
206
+ let parsed;
207
+ try {
208
+ parsed = JSON.parse(await res.text());
209
+ }
210
+ catch {
211
+ throw new McpToolError(`${SUPPORT_SERVICE}'s live poll answered something that is not JSON.`, { kind: 'http', status: res.status });
212
+ }
213
+ const se = parsed.streamEvent;
214
+ const events = Array.isArray(se?.state?.events) ? projectEvents(se.state.events) : [];
215
+ return {
216
+ status: 'events',
217
+ events,
218
+ isDelta: se?.isDelta === true,
219
+ ...(typeof se?.stateCursor === 'string' ? { stateCursor: se.stateCursor } : {}),
220
+ };
221
+ }
222
+ async post(path, contentType, body, extraHeaders = {}, timeoutMs = this.timeoutMs, waitIsNormal = false) {
223
+ const signal = AbortSignal.timeout(timeoutMs);
224
+ let res;
225
+ try {
226
+ res = await this.fetchImpl(`${SIERRA_API}${path}`, {
227
+ method: 'POST',
228
+ headers: { 'content-type': contentType, accept: '*/*', ...extraHeaders },
229
+ body: JSON.stringify(body),
230
+ signal,
231
+ });
232
+ }
233
+ catch (err) {
234
+ if (signal.aborted && waitIsNormal)
235
+ throw new WaitElapsed();
236
+ if (signal.aborted) {
237
+ throw new McpToolError(`${SUPPORT_SERVICE} did not answer in time (${timeoutMs} ms).`, { kind: 'timeout', cause: err });
238
+ }
239
+ throw new McpToolError(`Could not reach ${SUPPORT_SERVICE}: ${truncateErrorMessage(this.redact(messageOf(err)), 200)}`, {
240
+ kind: 'transport',
241
+ cause: err,
242
+ });
243
+ }
244
+ if (!res.ok && res.status !== 204) {
245
+ const text = await res.text();
246
+ throw new McpToolError(`${SUPPORT_SERVICE} answered HTTP ${res.status} on ${path}: ${truncateErrorMessage(this.redact(text), 200)}`, {
247
+ kind: res.status === 401 || res.status === 403 ? 'credential_rejected' : 'http',
248
+ status: res.status,
249
+ });
250
+ }
251
+ return res;
252
+ }
253
+ }
254
+ /** The long-poll's own wait ran out (internal: answered as "nothing new"). */
255
+ class WaitElapsed extends Error {
256
+ }
@@ -7,6 +7,7 @@ import { registerHealthcheckTool } from './healthcheck.js';
7
7
  import { registerPlannerTools } from './planner.js';
8
8
  import { registerPromoTools } from './promo.js';
9
9
  import { registerReadTools } from './reads.js';
10
+ import { registerSupportTools } from './support.js';
10
11
  import { registerWriteTools } from './writes/index.js';
11
12
  export const TOOL_REGISTRARS = [
12
13
  registerHealthcheckTool,
@@ -16,4 +17,5 @@ export const TOOL_REGISTRARS = [
16
17
  registerCookingTools,
17
18
  registerFavoriteTools,
18
19
  registerPromoTools,
20
+ registerSupportTools,
19
21
  ];
@@ -5,7 +5,7 @@
5
5
  // payment token, none of which is ever returned.
6
6
  import { z } from 'zod';
7
7
  import { mapWithConcurrency, minifiedResult, resolveView, todayIso, toolAnnotations } from '@chrischall/mcp-utils';
8
- import { parseSku, projectDelivery, projectSubscription, } from '../normalize.js';
8
+ import { parseSku, projectDelivery, projectTracking, trackingPublicId, projectSubscription, } from '../normalize.js';
9
9
  import { isoWeekOf, shiftWeek } from '../weeks.js';
10
10
  import { LOOKUP, foodMeta } from './hints.js';
11
11
  import { HF_VIEWS, PRICE_CONCURRENCY, attempt, boxNumbering, boxNumbers, calculatorGate, briefLine, byWeek, compactSelection, dateOf, estimateFor, estimatedPrice, hellofreshPrice, hfView, loadAccount, nextBoxNumberParam, premiumCentsOf, readMenu, readPicks, weekParam, } from './shared.js';
@@ -85,6 +85,26 @@ function applyFilters(meals, f) {
85
85
  // ---- registration -------------------------------------------------------------------
86
86
  export function registerReadTools(server, deps) {
87
87
  const { client } = deps;
88
+ /**
89
+ * The box's carrier tracking, best effort: none before the box is labelled
90
+ * (no HelloFresh tracking link yet); a failed read keeps the delivery's own
91
+ * code and link and says why.
92
+ */
93
+ const readTracking = async (raw, full) => {
94
+ const publicId = trackingPublicId(raw.tracking);
95
+ if (!publicId)
96
+ return {};
97
+ const read = await attempt(async () => projectTracking(await client.getTracking(publicId)));
98
+ if (!read.ok || read.value.boxes.length === 0) {
99
+ return {
100
+ tracking: { trackingCode: raw.tracking?.tracking_code || undefined, trackingUrl: raw.tracking?.tracking_link },
101
+ trackingError: read.ok ? 'HelloFresh returned no tracked box for this delivery.' : read.reason,
102
+ };
103
+ }
104
+ const [first, ...more] = read.value.boxes;
105
+ const shape = (b) => (full ? b : { ...b, history: undefined });
106
+ return { tracking: shape(first), ...(more.length > 0 ? { moreBoxes: more.map(shape) } : {}) };
107
+ };
88
108
  const now = deps.now ?? Date.now;
89
109
  server.registerTool('hf_get_subscription', {
90
110
  description: 'Read the HelloFresh meal-kit subscription: the plan’s box size (meals × people, SKU), price per box, ' +
@@ -181,9 +201,10 @@ export function registerReadTools(server, deps) {
181
201
  });
182
202
  server.registerTool('hf_get_delivery', {
183
203
  description: 'Read one HelloFresh delivery week: delivery date and slot, meal-pick cutoff, status, box size, the meals ' +
184
- 'currently picked (with any premium upcharge), allowed actions, alternative delivery days, and the box price ' +
204
+ 'currently picked (with any premium upcharge), allowed actions, alternative delivery days, the box price ' +
185
205
  '— HelloFresh’s own checkout total plus the picked meals’ premium upcharge, or a labelled local estimate ' +
186
- 'when that cannot be read.',
206
+ 'when that cannot be read — and, once the box is labelled, its carrier tracking: carrier, tracking code, ' +
207
+ 'live status (e.g. delayed / shortage, delivered) and, in the full view, the status history.',
187
208
  annotations: readOnly('HelloFresh: get delivery'),
188
209
  _meta: LOOKUP,
189
210
  inputSchema: z.object({
@@ -201,10 +222,12 @@ export function registerReadTools(server, deps) {
201
222
  }),
202
223
  }, async ({ week, box_number, next_box_number, view }) => {
203
224
  const account = await loadAccount(client);
204
- const delivery = projectDelivery(await client.getDelivery(account.subscriptionId, week));
225
+ const raw = await client.getDelivery(account.subscriptionId, week);
226
+ const delivery = projectDelivery(raw);
205
227
  const menu = delivery.status === 'skipped' ? undefined : await attempt(() => readMenu(client, account, delivery, week));
206
228
  const selected = menu?.ok ? menu.value.selected : undefined;
207
229
  const full = resolveView(view, HF_VIEWS) === 'full';
230
+ const tracking = await readTracking(raw, full);
208
231
  let boxNumberNote;
209
232
  // The upcoming list is read only when the estimate needs a derived box number.
210
233
  const fallbackBoxNumber = async () => {
@@ -231,6 +254,7 @@ export function registerReadTools(server, deps) {
231
254
  ...(menu && !menu.ok ? { selectionError: menu.reason } : {}),
232
255
  ...(price ? { price } : {}),
233
256
  ...(boxNumberNote ? { boxNumberNote } : {}),
257
+ ...tracking,
234
258
  });
235
259
  });
236
260
  server.registerTool('hf_get_menu', {