earnrate 0.1.0 → 0.1.2

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.
@@ -103,6 +103,7 @@ export const WalletSummarySchema = z.object({
103
103
  lastVerified: z.string(),
104
104
  verifiedBy: z.string(),
105
105
  dataIsStale: z.boolean(),
106
+ rotationGap: z.string().nullable(),
106
107
  caps: z.array(z.object({
107
108
  key: z.string(),
108
109
  rules: z.array(z.string()),
@@ -172,3 +173,48 @@ export const OfferComparisonSchema = z.object({
172
173
  withoutOffer: z.array(z.string()),
173
174
  notes: z.array(z.string()),
174
175
  });
176
+ export const CardSearchSchema = z.object({
177
+ exact: z.boolean(),
178
+ cards: z.array(z.object({
179
+ id: z.string(),
180
+ name: z.string(),
181
+ issuer: z.string(),
182
+ network: CardNetwork,
183
+ currency: z.string(),
184
+ annualFee: z.number().nullable(),
185
+ business: z.boolean(),
186
+ onlyAt: z.array(z.string()).nullable(),
187
+ held: z.boolean(),
188
+ choices: z.array(z.object({
189
+ id: z.string(),
190
+ pick: z.number(),
191
+ period: z.enum([
192
+ 'month',
193
+ 'quarter',
194
+ 'calendar_year',
195
+ 'until_changed',
196
+ ]),
197
+ options: z.array(z.string()),
198
+ default: z.array(z.string()).nullable(),
199
+ })),
200
+ memberships: z.array(z.string()),
201
+ activation: z.array(z.string()),
202
+ needsAnniversary: z.boolean(),
203
+ })),
204
+ });
205
+ export const WalletChangeSchema = z.object({
206
+ message: z.string(),
207
+ created: z.boolean(),
208
+ cardIds: z.array(z.string()),
209
+ memberships: z.array(z.string()),
210
+ notes: z.array(z.object({
211
+ kind: z.enum([
212
+ 'pick',
213
+ 'membership',
214
+ 'activation',
215
+ 'anniversary',
216
+ 'rotation',
217
+ ]),
218
+ text: z.string(),
219
+ })),
220
+ });
@@ -1,19 +1,22 @@
1
1
  import { McpServer } from '@modelcontextprotocol/server';
2
2
  import { z } from 'zod';
3
3
  import { MCP_SERVER_NAME } from "../brand.js";
4
+ import { formatCardInfo, formatNotes } from "../cli/cards.js";
4
5
  import { formatRecommendation } from "../cli/format.js";
5
6
  import { formatOffers } from "../cli/offers.js";
6
7
  import { walletProblems } from "../data/integrity.js";
7
8
  import { loadWallet } from "../data/load.js";
8
9
  import { withWalletLock, writeBonusSpent, writeCapBooking, } from "../data/wallet-write.js";
10
+ import { addCard, removeCard, setMemberships, updateCard, } from "../data/wallet-setup.js";
9
11
  import { bonusStatus, countsTowardBonus } from "../engine/bonus.js";
10
12
  import { compareOffers } from "../engine/offers.js";
11
13
  import { capBooking } from "../engine/record.js";
12
14
  import { recommend } from "../engine/recommend.js";
15
+ import { knownMemberships, searchCards } from "../engine/setup.js";
13
16
  import { walletSummary } from "../engine/wallet-summary.js";
14
17
  import { resolveMerchant, withCallerCategory } from "../merchants/resolve.js";
15
18
  import { IsoDate } from "../schema/common.js";
16
- import { MerchantResolutionSchema, RecommendationSchema, OfferComparisonSchema, RecordResultSchema, WalletSummarySchema, } from "./schemas.js";
19
+ import { CardSearchSchema, MerchantResolutionSchema, RecommendationSchema, OfferComparisonSchema, RecordResultSchema, WalletChangeSchema, WalletSummarySchema, } from "./schemas.js";
17
20
  const Merchant = z
18
21
  .string()
19
22
  .min(1)
@@ -23,13 +26,16 @@ const ChannelInput = z
23
26
  .optional()
24
27
  .describe('How the purchase is made. Omit if unknown; the answer says what it assumed.');
25
28
  const DateInput = IsoDate.optional().describe('Purchase date, YYYY-MM-DD. Defaults to today.');
29
+ const INSTRUCTIONS = `earnrate picks which of the user's credit cards earns the most for a purchase. Its wallet lists the cards they hold by product id, never card numbers; never ask for card numbers, expiry dates or security codes.
30
+
31
+ If a tool says there's no wallet yet, ask the user which cards they have, find each with search_cards, and add it with add_card. add_card and update_card reply with what a card still needs, such as category picks, memberships like Amazon Prime, or activated bonus categories. Ask the user about those and set them with update_card or set_memberships.`;
26
32
  const fail = (text) => ({
27
33
  content: [{ type: 'text', text }],
28
34
  isError: true,
29
35
  });
30
36
  const dollars = (n) => `$${n.toLocaleString('en-US', { maximumFractionDigits: 2 })}`;
31
37
  export function createEarnrateServer(deps) {
32
- const server = new McpServer({ name: MCP_SERVER_NAME, version: deps.version });
38
+ const server = new McpServer({ name: MCP_SERVER_NAME, version: deps.version }, { instructions: INSTRUCTIONS });
33
39
  const { catalog } = deps;
34
40
  // Read on every call, so edits to the wallet file apply without a restart.
35
41
  async function wallet() {
@@ -38,6 +44,9 @@ export function createEarnrateServer(deps) {
38
44
  loaded = await loadWallet(deps.walletFile);
39
45
  }
40
46
  catch (e) {
47
+ if (e instanceof Error && 'code' in e && e.code === 'ENOENT') {
48
+ return `There's no wallet yet (${deps.walletFile}). Ask the user which credit cards they have, find each one with search_cards, and add it with add_card.`;
49
+ }
41
50
  return `Couldn't read the wallet at ${deps.walletFile}: ${e instanceof Error ? e.message : String(e)}`;
42
51
  }
43
52
  const problems = walletProblems(loaded, catalog);
@@ -145,13 +154,16 @@ export function createEarnrateServer(deps) {
145
154
  ? `; chosen categories for ${c.chosen.period}${c.chosen.current ? '' : ' (out of date)'}`
146
155
  : '';
147
156
  const onlyAt = c.onlyAt ? `; works only at ${c.onlyAt.join(', ')}` : '';
157
+ const rotation = c.rotationGap === null
158
+ ? ''
159
+ : `; rotating categories for ${c.rotationGap} not in earnrate yet`;
148
160
  const b = c.bonus;
149
161
  const bonus = b?.state === 'open' && b.spend !== null
150
162
  ? `; welcome bonus ${dollars(b.spent)} of ${dollars(b.spend)} spent, due ${b.deadline ?? ''}`
151
163
  : b
152
164
  ? `; welcome bonus ${b.state}`
153
165
  : '';
154
- return `- ${c.checkoutLabel ?? c.cardName} (${c.cardId}): ${c.currency} at ${String(c.centsPerUnit)}¢${caps.length > 0 ? `; ${caps.join(', ')}` : ''}${chosen}${onlyAt}${bonus}`;
166
+ return `- ${c.checkoutLabel ?? c.cardName} (${c.cardId}): ${c.currency} at ${String(c.centsPerUnit)}¢${caps.length > 0 ? `; ${caps.join(', ')}` : ''}${chosen}${rotation}${onlyAt}${bonus}`;
155
167
  });
156
168
  return {
157
169
  content: [{ type: 'text', text: lines.join('\n') }],
@@ -304,5 +316,149 @@ export function createEarnrateServer(deps) {
304
316
  structuredContent: output,
305
317
  };
306
318
  }));
319
+ const CardId = z
320
+ .string()
321
+ .min(1)
322
+ .describe('The card id from search_cards, e.g. chase-sapphire-preferred.');
323
+ const cardFields = {
324
+ checkoutLabel: z
325
+ .string()
326
+ .min(1)
327
+ .optional()
328
+ .describe('How the card appears at checkout or in a browser wallet, e.g. "Amex Gold". Optional.'),
329
+ picks: z
330
+ .record(z.string(), z.array(z.string()).min(1))
331
+ .optional()
332
+ .describe('For cards where the cardholder picks bonus categories: choice id → option ids, from search_cards, e.g. {"five-percent": ["tv-internet-streaming", "fast-food"]}. Saved for the current period. Ask the user; don\'t guess.'),
333
+ anniversary: z
334
+ .string()
335
+ .regex(/^\d{2}-\d{2}$/)
336
+ .optional()
337
+ .describe("The account's anniversary as MM-DD, for cards whose cap resets on it."),
338
+ activated: z
339
+ .array(z.string())
340
+ .optional()
341
+ .describe('Rule ids the user has activated with the issuer, such as rotating categories. Replaces the current list.'),
342
+ };
343
+ // A card change reports what that card still needs; other changes don't.
344
+ function changed(result, message, cardChange = true) {
345
+ if (!result.ok)
346
+ return fail(result.error);
347
+ const output = {
348
+ message,
349
+ created: result.created,
350
+ cardIds: result.wallet.cards.map((c) => c.id),
351
+ memberships: result.wallet.memberships,
352
+ notes: result.notes,
353
+ };
354
+ const text = [
355
+ message,
356
+ `Wallet: ${output.cardIds.join(', ')}.`,
357
+ ...(cardChange ? [formatNotes(result.notes)] : []),
358
+ ].join('\n');
359
+ return {
360
+ content: [{ type: 'text', text }],
361
+ structuredContent: output,
362
+ };
363
+ }
364
+ const cardInput = (args) => ({
365
+ id: args.cardId,
366
+ ...(args.checkoutLabel === undefined
367
+ ? {}
368
+ : { checkoutLabel: args.checkoutLabel }),
369
+ ...(args.picks === undefined ? {} : { picks: args.picks }),
370
+ ...(args.anniversary === undefined
371
+ ? {}
372
+ : { anniversary: args.anniversary }),
373
+ ...(args.activated === undefined ? {} : { activated: args.activated }),
374
+ });
375
+ const cardName = (id) => catalog.cards.find((c) => c.id === id)?.name ?? id;
376
+ server.registerTool('search_cards', {
377
+ title: 'Search cards',
378
+ description: 'Finds credit cards in earnrate\'s catalog by name or issuer, e.g. "sapphire", "amex gold" or "bofa". Returns each card\'s id (for add_card), network, annual fee, whether it\'s already in the wallet, and what it needs set up: category picks and their options, memberships, activations. Leave the query out to list every card. US cards only.',
379
+ inputSchema: z.object({
380
+ query: z
381
+ .string()
382
+ .optional()
383
+ .describe('Card name or issuer, as the user said it.'),
384
+ }),
385
+ outputSchema: CardSearchSchema,
386
+ annotations: { readOnlyHint: true, openWorldHint: false },
387
+ }, async ({ query }) => {
388
+ const held = await loadWallet(deps.walletFile).catch(() => null);
389
+ const result = searchCards(catalog, query ?? '', held, deps.today());
390
+ const header = result.exact
391
+ ? ''
392
+ : result.cards.length > 0
393
+ ? 'No card matched every word. Closest:\n'
394
+ : `No card matched "${query ?? ''}". earnrate covers ${String(catalog.cards.length)} US cards; list them all by leaving the query out.`;
395
+ return {
396
+ content: [
397
+ {
398
+ type: 'text',
399
+ text: header + result.cards.map(formatCardInfo).join('\n'),
400
+ },
401
+ ],
402
+ structuredContent: result,
403
+ };
404
+ });
405
+ server.registerTool('add_card', {
406
+ title: 'Add a card',
407
+ description: "Adds a card the user holds to their wallet by its id from search_cards, creating the wallet if there isn't one. The reply says what the card still needs (category picks, memberships, activations); ask the user about those. Stores only the card's product id and settings, never card numbers.",
408
+ inputSchema: z.object({ cardId: CardId, ...cardFields }),
409
+ outputSchema: WalletChangeSchema,
410
+ annotations: {
411
+ readOnlyHint: false,
412
+ destructiveHint: false,
413
+ idempotentHint: false,
414
+ openWorldHint: false,
415
+ },
416
+ }, (args) => withWalletLock(deps.walletFile, async () => {
417
+ const result = await addCard(deps.walletFile, catalog, cardInput(args), deps.today());
418
+ return changed(result, `Added ${cardName(args.cardId)} (${args.cardId})${result.ok && result.created ? `, starting a new wallet at ${deps.walletFile}` : ''}.`);
419
+ }));
420
+ server.registerTool('update_card', {
421
+ title: 'Update a card',
422
+ description: 'Changes settings on a card already in the wallet: its category picks for this period, checkout label, anniversary or activated categories. Picks for the current period are merged with the ones already saved. Use it when the user picks new categories, such as each quarter on U.S. Bank Cash+.',
423
+ inputSchema: z.object({ cardId: CardId, ...cardFields }),
424
+ outputSchema: WalletChangeSchema,
425
+ annotations: {
426
+ readOnlyHint: false,
427
+ destructiveHint: false,
428
+ idempotentHint: true,
429
+ openWorldHint: false,
430
+ },
431
+ }, (args) => withWalletLock(deps.walletFile, async () => changed(await updateCard(deps.walletFile, catalog, cardInput(args), deps.today()), `Updated ${cardName(args.cardId)} (${args.cardId}).`)));
432
+ server.registerTool('remove_card', {
433
+ title: 'Remove a card',
434
+ description: "Removes a card from the wallet, with its tracked cap usage and bonus progress. Only when the user says they no longer have it or don't want it considered.",
435
+ inputSchema: z.object({ cardId: CardId }),
436
+ outputSchema: WalletChangeSchema,
437
+ annotations: {
438
+ readOnlyHint: false,
439
+ destructiveHint: true,
440
+ idempotentHint: true,
441
+ openWorldHint: false,
442
+ },
443
+ }, ({ cardId }) => withWalletLock(deps.walletFile, async () => changed(await removeCard(deps.walletFile, catalog, cardId), `Removed ${cardName(cardId)} (${cardId}).`, false)));
444
+ const memberships = knownMemberships(catalog);
445
+ server.registerTool('set_memberships', {
446
+ title: 'Set memberships',
447
+ description: "Sets the memberships that unlock some cards' rates, such as amazon-prime for Prime Visa's 5% or a Bank of America Preferred Rewards tier. Replaces the whole list, so include the ones to keep.",
448
+ inputSchema: z.object({
449
+ memberships: z
450
+ .array(z.enum(memberships))
451
+ .describe(`Every membership the user has. Known: ${memberships.join(', ')}.`),
452
+ }),
453
+ outputSchema: WalletChangeSchema,
454
+ annotations: {
455
+ readOnlyHint: false,
456
+ destructiveHint: false,
457
+ idempotentHint: true,
458
+ openWorldHint: false,
459
+ },
460
+ }, (args) => withWalletLock(deps.walletFile, async () => changed(await setMemberships(deps.walletFile, catalog, args.memberships), args.memberships.length > 0
461
+ ? `Memberships set to ${args.memberships.join(', ')}.`
462
+ : 'Memberships cleared.', false)));
307
463
  return server;
308
464
  }
@@ -12,7 +12,13 @@ export const CapSchema = z.strictObject({
12
12
  period: CapPeriod,
13
13
  then_rate: z.number().nonnegative(),
14
14
  });
15
- export const SharedCapSchema = CapSchema.extend({ id: KebabId });
15
+ export const SharedCapSchema = CapSchema.extend({
16
+ id: KebabId,
17
+ // Rotating categories (Freedom Flex): every rule on this cap covers one
18
+ // dated period, and a period with no rule means the issuer's categories
19
+ // aren't in the data yet, not that there's no bonus.
20
+ rotating: z.literal(true).optional(),
21
+ });
16
22
  const hasAny = (m) => Object.values(m).some((v) => v === true || (v !== undefined && v.length > 0));
17
23
  // Kinds combine with AND, values within a kind with OR: `{ merchants:
18
24
  // [lyft], categories: [transit] }` is a Lyft purchase that codes as transit.
@@ -75,21 +81,40 @@ export const WelcomeOfferSchema = z
75
81
  export const ChoiceSchema = z.strictObject({
76
82
  id: KebabId,
77
83
  pick: z.number().int().positive(),
78
- period: z.enum(['month', 'quarter', 'calendar_year']),
84
+ // `until_changed`: the pick carries over until the cardholder changes it,
85
+ // so a pick made in an earlier period is still current.
86
+ period: z.enum(['month', 'quarter', 'calendar_year', 'until_changed']),
79
87
  // Option ids that apply when the wallet hasn't picked, e.g. Bilt's dining.
80
88
  default: z.array(KebabId).min(1).optional(),
81
- // Option id → what that option covers: a list of categories, or, when the
82
- // issuer publishes the only qualifying stores, `{ merchants: [...] }`.
89
+ // Option id → what that option covers: a list of categories; or, when the
90
+ // issuer publishes the only qualifying stores, `{ merchants: [...] }`; or,
91
+ // for "online shopping" picks, `{ channel: online, exclude: [...] }`, any
92
+ // online purchase outside the excluded categories.
83
93
  options: z.record(KebabId, z.union([
84
94
  z
85
95
  .array(CategoryId)
86
96
  .min(1)
87
- .transform((categories) => ({ categories, merchants: [] })),
97
+ .transform((categories) => ({
98
+ categories,
99
+ merchants: [],
100
+ online: null,
101
+ })),
88
102
  z
89
103
  .strictObject({ merchants: z.array(KebabId).min(1) })
90
104
  .transform(({ merchants }) => ({
91
105
  categories: [],
92
106
  merchants,
107
+ online: null,
108
+ })),
109
+ z
110
+ .strictObject({
111
+ channel: z.literal('online'),
112
+ exclude: z.array(CategoryId).default([]),
113
+ })
114
+ .transform(({ exclude }) => ({
115
+ categories: [],
116
+ merchants: [],
117
+ online: { exclude },
93
118
  })),
94
119
  ])),
95
120
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "earnrate",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Picks the best credit card from your wallet for a merchant, and explains why",
5
5
  "keywords": [
6
6
  "credit cards",
@@ -21,7 +21,7 @@
21
21
  "mcpName": "io.github.cwasley/earnrate",
22
22
  "type": "module",
23
23
  "engines": {
24
- "node": ">=24"
24
+ "node": ">=22"
25
25
  },
26
26
  "bin": {
27
27
  "earnrate": "./dist/cli/bin.js",