@expensebot/mcp-server-auth 0.5.1 → 0.6.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/README.md CHANGED
@@ -2,13 +2,17 @@
2
2
 
3
3
  Authenticated MCP (Model Context Protocol) server for [ExpenseBot](https://www.expensebot.ai). Lets Claude Desktop, Cursor, Claude Code, Continue, Cline, Windsurf, and any MCP-compatible AI assistant search receipts, submit photos, scan Gmail, create reports, and analyze spending using your real ExpenseBot account.
4
4
 
5
- **21 tools** across:
6
- - **Search & analytics** — `search_expenses`, `get_spending_summary`, `get_deep_analytics`, `list_categories`, `list_tags`, `search_knowledge`
7
- - **Receipt capture** — `submit_receipt` (photo/PDF), `add_cash_expense`, `add_mileage_entry`, `add_income`, `parse_expense`
5
+ **33 tools** across:
6
+ - **Search & analytics** — `search_expenses`, `get_spending_summary`, `get_deep_analytics`, `list_categories`, `list_tags`, `list_income_categories`, `search_knowledge`
7
+ - **Income & P&L** *(v0.6.0)* — `get_income_summary`, `get_pnl`, `get_per_tag_pnl`
8
+ - **Mileage & Subscriptions** *(v0.6.1)* — `get_mileage_summary`, `get_subscription_audit`
9
+ - **Receipt capture** — `submit_receipt` (photo/PDF), `add_cash_expense`, `add_mileage_entry`, `add_income`, `parse_expense`, `get_expense_by_id`
8
10
  - **Gmail** — `scan_gmail`, `process_gmail_receipts`
9
- - **Reports** — `create_report`, `list_reports`, `get_report_details`, `share_report`
11
+ - **Reports** — `create_report`, `list_reports`, `get_report_details`, `share_report`, `export_report`
10
12
  - **Compliance & tax** — `check_compliance`, `fix_compliance`, `check_tax_deductibility`
11
- - **Onboarding** — `get_signup_link`
13
+ - **Activity & onboarding** — `get_recent_activity`, `get_signup_link`, `get_pricing`, `check_feature`, `start_trial_link`
14
+
15
+ **Period comparison** — All analytics tools (spending, income, P&L, per-tag P&L, mileage) accept YoY / MoM / QoQ / same-month-prev-year phrasing in the `query` field. Margin is rendered loss-aware (multiplier when expenses exceed revenue) so AI clients see "expenses 5.4× revenue" instead of "-436.9% margin".
12
16
 
13
17
  ## Setup
14
18
 
@@ -78,9 +82,12 @@ Same `npx -y @expensebot/mcp-server-auth --token=...` command in your client's M
78
82
 
79
83
  ## Onboarding mode (no token)
80
84
 
81
- Running without a token exposes 2 read-only tools that help new users sign up:
85
+ Running without a token exposes 5 read-only tools that help new users discover ExpenseBot and sign up:
82
86
  - `get_signup_link` — returns ExpenseBot signup URL
83
87
  - `search_knowledge` — searches the public ExpenseBot knowledge base
88
+ - `get_pricing` — returns current pricing for all plans *(v0.7.0)*
89
+ - `check_feature` — answers "does ExpenseBot support X?" *(v0.7.0)*
90
+ - `start_trial_link` — UTM-tagged signup URL *(v0.7.0)*
84
91
 
85
92
  ```bash
86
93
  npx @expensebot/mcp-server-auth
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@expensebot/mcp-server-auth",
3
- "version": "0.5.1",
3
+ "version": "0.6.1",
4
4
  "mcpName": "io.github.TotesMagotes/mcp-server-auth",
5
5
  "description": "Authenticated MCP server for ExpenseBot — lets Claude Desktop, Cursor, and other AI assistants search your expenses, create reports, and analyze spending using your actual ExpenseBot data.",
6
6
  "bin": {
@@ -10,6 +10,7 @@
10
10
  "main": "./src/index.js",
11
11
  "files": [
12
12
  "src",
13
+ "scripts",
13
14
  "README.md"
14
15
  ],
15
16
  "keywords": [
@@ -30,7 +31,10 @@
30
31
  },
31
32
  "scripts": {
32
33
  "start": "node src/index.js",
33
- "test": "node src/test.js"
34
+ "test": "node src/test.js",
35
+ "sync-check": "node scripts/sync-check.js",
36
+ "gen-descriptions": "node scripts/generate-descriptions-from-kb.js",
37
+ "prepublishOnly": "node scripts/sync-check.js && node src/test.js"
34
38
  },
35
39
  "author": "ExpenseBot",
36
40
  "license": "MIT"
@@ -0,0 +1,10 @@
1
+ {
2
+ "_meta": {
3
+ "generatedAt": "2026-05-07T05:13:24.014Z",
4
+ "sourceKb": "../server/config/kb/entries/income-and-pnl-analytics.md",
5
+ "note": "Auto-generated from KB. Do NOT edit by hand — re-run `npm run gen-descriptions` after the KB changes."
6
+ },
7
+ "get_income_summary": "Get income totals and breakdowns from the Income tab — Schedule C / T2125 basis. Excludes Schedule B (interest, dividends), tax refunds, and security deposits (mirrors year-end report routing). Examples: \"How much income YTD?\", \"Income by source\", \"by month\", \"by payment method\".",
8
+ "get_pnl": "Compute Profit & Loss across the Income tab and expenses. Examples: \"Am I profitable this year?\", \"Net income last quarter\", \"What's my margin?\", \"P&L for Q1\".",
9
+ "get_per_tag_pnl": "Per-tag P&L — revenue, cost, profit, and margin grouped by tag. Requires both income AND expense rows to be tagged consistently. Examples: ."
10
+ }
@@ -0,0 +1,113 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * KB-derived tool descriptions (PROOF-OF-CONCEPT, opt-in)
4
+ *
5
+ * The drift problem: an analytics capability has its description live in
6
+ * 4 places — KB markdown, server enum, MCP TOOLS[], README. When we add
7
+ * a feature to the income tab, all four need to update or AI clients
8
+ * advertise stale capabilities. (See `reference_income_categories_drift.md`.)
9
+ *
10
+ * Long-term fix: derive the descriptive prose for income/P&L/per-tag tools
11
+ * from the canonical KB entry. This script scans the KB for tagged
12
+ * sections and emits a `descriptions.generated.json` that index.js can
13
+ * import. If the KB changes, re-run this script and the tool descriptions
14
+ * update automatically.
15
+ *
16
+ * STATUS: scaffold only. Actually wiring index.js to import the generated
17
+ * file is gated on a v0.8.0 cleanup. Today's v0.6.0 still hand-writes the
18
+ * descriptions in src/index.js to avoid a bigger refactor.
19
+ *
20
+ * Usage:
21
+ * npm run gen-descriptions # writes scripts/descriptions.generated.json
22
+ *
23
+ * Wire-in TODO (when ready):
24
+ * 1. Replace inline descriptions in src/index.js with `import desc from
25
+ * "../scripts/descriptions.generated.json" assert { type: "json" }`
26
+ * 2. Reference desc.get_income_summary etc. in TOOLS[]
27
+ * 3. Add a CI step that re-runs this script + diffs the generated file
28
+ * against the committed copy (drift check)
29
+ */
30
+
31
+ import fs from "node:fs";
32
+ import path from "node:path";
33
+ import { fileURLToPath } from "node:url";
34
+
35
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
36
+ const ROOT = path.resolve(__dirname, "..");
37
+
38
+ // Adjust if the repo layout changes
39
+ const KB_ENTRY = path.resolve(
40
+ ROOT,
41
+ "../server/config/kb/entries/income-and-pnl-analytics.md"
42
+ );
43
+
44
+ const OUT = path.join(__dirname, "descriptions.generated.json");
45
+
46
+ function loadKb() {
47
+ if (!fs.existsSync(KB_ENTRY)) {
48
+ console.error(`KB entry not found: ${KB_ENTRY}`);
49
+ process.exit(1);
50
+ }
51
+ return fs.readFileSync(KB_ENTRY, "utf8");
52
+ }
53
+
54
+ // Strip frontmatter, return body
55
+ function body(md) {
56
+ return md.replace(/^---[\s\S]*?---\s*/m, "").trim();
57
+ }
58
+
59
+ // Pull bullet lists under a bolded heading like "**Income (Schedule C / T2125 basis)**"
60
+ function extractSection(md, headingRe) {
61
+ const m = md.match(headingRe);
62
+ if (!m) return null;
63
+ // Read until next bolded line or end
64
+ const start = m.index + m[0].length;
65
+ const rest = md.slice(start);
66
+ const stop = rest.search(/\n\*\*[^*]+\*\*/);
67
+ return (stop === -1 ? rest : rest.slice(0, stop)).trim();
68
+ }
69
+
70
+ const md = body(loadKb());
71
+
72
+ const incomeSection =
73
+ extractSection(md, /\*\*Income \(Schedule C[^*]+\*\*/) || "";
74
+ const pnlSection = extractSection(md, /\*\*Profit & Loss\*\*/) || "";
75
+ const perTagSection = extractSection(md, /\*\*Per-Tag P&L[^*]+\*\*/) || "";
76
+
77
+ function summarize(s, header) {
78
+ const examples = (s.match(/"([^"]+)"/g) || []).slice(0, 4).join(", ");
79
+ return `${header} Examples: ${examples}.`;
80
+ }
81
+
82
+ const out = {
83
+ _meta: {
84
+ generatedAt: new Date().toISOString(),
85
+ sourceKb: path.relative(ROOT, KB_ENTRY),
86
+ note:
87
+ "Auto-generated from KB. Do NOT edit by hand — re-run " +
88
+ "`npm run gen-descriptions` after the KB changes.",
89
+ },
90
+ get_income_summary: summarize(
91
+ incomeSection,
92
+ "Get income totals and breakdowns from the Income tab — Schedule C / T2125 basis. Excludes Schedule B (interest, dividends), tax refunds, and security deposits (mirrors year-end report routing)."
93
+ ),
94
+ get_pnl: summarize(
95
+ pnlSection,
96
+ "Compute Profit & Loss across the Income tab and expenses."
97
+ ),
98
+ get_per_tag_pnl: summarize(
99
+ perTagSection,
100
+ "Per-tag P&L — revenue, cost, profit, and margin grouped by tag. Requires both income AND expense rows to be tagged consistently."
101
+ ),
102
+ };
103
+
104
+ fs.writeFileSync(OUT, JSON.stringify(out, null, 2) + "\n");
105
+ console.log(`✓ Wrote ${path.relative(ROOT, OUT)}`);
106
+ console.log(
107
+ ` Tools generated: ${Object.keys(out).filter((k) => k !== "_meta").length}`
108
+ );
109
+ console.log(` Source KB: ${path.relative(ROOT, KB_ENTRY)}`);
110
+ console.log(
111
+ "\nNote: this is a scaffold. index.js still uses inline descriptions in v0.6.0."
112
+ );
113
+ console.log("Wire-in plan documented in this file's header comment.");
@@ -0,0 +1,177 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Sync-check — verifies the MCP tool list is consistent across the files
4
+ * that need to agree. Runs as `npm run sync-check` and exits non-zero
5
+ * if drift is detected.
6
+ *
7
+ * Files validated:
8
+ * 1. src/index.js — TOOLS[] array + handleTool() switch (source of truth)
9
+ * 2. README.md — bullet-list tool inventory + total tool count
10
+ * 3. package.json — version
11
+ * 4. server.json — version (top-level + packages[].version)
12
+ * 5. src/client.js — User-Agent string version match
13
+ *
14
+ * Source of truth = src/index.js. README/package.json/server.json must
15
+ * agree with it. Add this to CI before publish to prevent the kind of
16
+ * silent drift that bit the income-categories enum across windows.
17
+ *
18
+ * Background: see reference_income_categories_drift.md
19
+ */
20
+
21
+ import fs from "node:fs";
22
+ import path from "node:path";
23
+ import { fileURLToPath } from "node:url";
24
+
25
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
26
+ const ROOT = path.resolve(__dirname, "..");
27
+
28
+ const errors = [];
29
+ const warnings = [];
30
+
31
+ function fail(msg) {
32
+ errors.push(msg);
33
+ }
34
+ function warn(msg) {
35
+ warnings.push(msg);
36
+ }
37
+
38
+ // ── 1. Parse src/index.js ────────────────────────────────────────────
39
+ const indexSrc = fs.readFileSync(path.join(ROOT, "src/index.js"), "utf8");
40
+
41
+ // Extract tool names from TOOLS = [ ... { name: "...", ... }, ... ]
42
+ const toolNameRe = /\bname:\s*"([a-z_][a-z0-9_]*)"/gi;
43
+ const tools = [];
44
+ let match;
45
+ const toolBlock = indexSrc.match(/const TOOLS = \[([\s\S]*?)\n\];\n/);
46
+ if (!toolBlock) {
47
+ fail("Could not find `const TOOLS = [ ... ];` in src/index.js");
48
+ } else {
49
+ while ((match = toolNameRe.exec(toolBlock[1])) !== null) {
50
+ tools.push(match[1]);
51
+ }
52
+ }
53
+
54
+ // Extract case-branch handlers from handleTool()
55
+ const caseRe = /\bcase\s+"([a-z_][a-z0-9_]*)":/g;
56
+ const cases = new Set();
57
+ while ((match = caseRe.exec(indexSrc)) !== null) {
58
+ cases.add(match[1]);
59
+ }
60
+
61
+ // Extract Server version (the MCP protocol-level version string)
62
+ const serverVersionMatch = indexSrc.match(
63
+ /name:\s*"expensebot-auth",\s*version:\s*"([^"]+)"/
64
+ );
65
+ const serverVersion = serverVersionMatch?.[1];
66
+
67
+ // Extract advertised tool count from get_signup_link message
68
+ const advertisedCountMatch = indexSrc.match(
69
+ /unlock all (\d+) tools/i
70
+ );
71
+ const advertisedCount = advertisedCountMatch?.[1]
72
+ ? parseInt(advertisedCountMatch[1], 10)
73
+ : null;
74
+
75
+ // ── 2. Cross-check: every tool has a case branch ────────────────────
76
+ const missingCases = tools.filter((t) => !cases.has(t));
77
+ if (missingCases.length) {
78
+ fail(
79
+ `${missingCases.length} tool(s) declared in TOOLS[] but missing a ` +
80
+ `handleTool() case branch: ${missingCases.join(", ")}`
81
+ );
82
+ }
83
+
84
+ // ── 3. README.md ────────────────────────────────────────────────────
85
+ const readme = fs.readFileSync(path.join(ROOT, "README.md"), "utf8");
86
+ const readmeCountMatch = readme.match(/\*\*(\d+)\s+tools\*\*/);
87
+ const readmeCount = readmeCountMatch ? parseInt(readmeCountMatch[1], 10) : null;
88
+ if (readmeCount === null) {
89
+ warn("README.md does not declare a tool count (looking for `**N tools**`)");
90
+ } else if (readmeCount !== tools.length) {
91
+ fail(
92
+ `README.md declares **${readmeCount} tools** but src/index.js has ${tools.length}`
93
+ );
94
+ }
95
+
96
+ // Check that every public tool name appears in the README inventory
97
+ const missingFromReadme = tools.filter(
98
+ (t) => !readme.includes("`" + t + "`")
99
+ );
100
+ if (missingFromReadme.length) {
101
+ fail(
102
+ `${missingFromReadme.length} tool(s) missing from README.md inventory: ` +
103
+ missingFromReadme.join(", ")
104
+ );
105
+ }
106
+
107
+ // ── 4. package.json ─────────────────────────────────────────────────
108
+ const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8"));
109
+ if (serverVersion && pkg.version !== serverVersion) {
110
+ fail(
111
+ `Version drift: package.json=${pkg.version} vs src/index.js Server=${serverVersion}`
112
+ );
113
+ }
114
+
115
+ // ── 5. server.json ──────────────────────────────────────────────────
116
+ const serverJson = JSON.parse(
117
+ fs.readFileSync(path.join(ROOT, "server.json"), "utf8")
118
+ );
119
+ if (serverJson.version !== pkg.version) {
120
+ fail(`Version drift: server.json=${serverJson.version} vs package.json=${pkg.version}`);
121
+ }
122
+ const pkgEntry = serverJson.packages?.find(
123
+ (p) => p.identifier === pkg.name
124
+ );
125
+ if (!pkgEntry) {
126
+ warn(
127
+ `server.json packages[] does not include identifier '${pkg.name}'`
128
+ );
129
+ } else if (pkgEntry.version !== pkg.version) {
130
+ fail(
131
+ `Version drift: server.json packages[].version=${pkgEntry.version} vs package.json=${pkg.version}`
132
+ );
133
+ }
134
+
135
+ // ── 6. client.js User-Agent ─────────────────────────────────────────
136
+ const clientSrc = fs.readFileSync(path.join(ROOT, "src/client.js"), "utf8");
137
+ const uaMatch = clientSrc.match(/expensebot-mcp-auth\/([^"]+)"/);
138
+ const uaVersion = uaMatch?.[1];
139
+ if (uaVersion && uaVersion !== pkg.version) {
140
+ fail(
141
+ `User-Agent drift: client.js says expensebot-mcp-auth/${uaVersion} ` +
142
+ `but package.json is ${pkg.version}`
143
+ );
144
+ }
145
+
146
+ // ── 7. Advertised tool count in get_signup_link message ─────────────
147
+ if (advertisedCount !== null && advertisedCount !== tools.length) {
148
+ fail(
149
+ `get_signup_link advertises ${advertisedCount} tools but src/index.js ` +
150
+ `actually declares ${tools.length}`
151
+ );
152
+ }
153
+
154
+ // ── Report ──────────────────────────────────────────────────────────
155
+ console.log(`\n=== MCP server-auth sync-check ===`);
156
+ console.log(`Tools declared: ${tools.length}`);
157
+ console.log(`Handler cases: ${cases.size} (filtered to tool names)`);
158
+ console.log(`README.md tool count: ${readmeCount ?? "n/a"}`);
159
+ console.log(`package.json version: ${pkg.version}`);
160
+ console.log(`server.json version: ${serverJson.version}`);
161
+ console.log(`Server version: ${serverVersion ?? "n/a"}`);
162
+ console.log(`User-Agent version: ${uaVersion ?? "n/a"}`);
163
+ console.log(`Advertised tool count: ${advertisedCount ?? "n/a"}`);
164
+ console.log("");
165
+
166
+ if (warnings.length) {
167
+ console.log("Warnings:");
168
+ warnings.forEach((w) => console.log(" ⚠ " + w));
169
+ console.log("");
170
+ }
171
+ if (errors.length) {
172
+ console.error("✘ Sync-check FAILED:");
173
+ errors.forEach((e) => console.error(" ✘ " + e));
174
+ console.error("");
175
+ process.exit(1);
176
+ }
177
+ console.log("✓ Sync-check PASSED — all manifests agree.\n");
package/src/client.js CHANGED
@@ -20,7 +20,7 @@ export class ExpenseBotClient {
20
20
  headers: {
21
21
  Authorization: `Bearer ${this.token}`,
22
22
  "Content-Type": "application/json",
23
- "User-Agent": "expensebot-mcp-auth/0.1.0",
23
+ "User-Agent": "expensebot-mcp-auth/0.6.1",
24
24
  ...options.headers,
25
25
  },
26
26
  body: options.body ? JSON.stringify(options.body) : undefined,
package/src/index.js CHANGED
@@ -94,15 +94,25 @@ const TOOLS = [
94
94
  {
95
95
  name: "get_spending_summary",
96
96
  description:
97
- "Get spending totals, breakdowns by category or merchant, and basic " +
98
- "expense analytics. For simple questions like 'how much did I spend " +
99
- "last month' or 'top merchants'.",
97
+ "Unified analytics endpoint — handles expenses, income, P&L, " +
98
+ "per-tag P&L (per-client / per-property / per-event), Schedule B " +
99
+ "drill-in (interest, dividends, tax refunds, security deposits), " +
100
+ "mileage, and subscription audits in ONE tool. Examples: 'how much " +
101
+ "did I spend last month', 'income YTD', 'rental income by " +
102
+ "property', 'P&L for Q1', 'profit by client', 'mileage this year', " +
103
+ "'recurring subscriptions', 'price increases', 'duplicate " +
104
+ "subscriptions', 'trial conversions'. Supports period comparison " +
105
+ "phrasing — 'this year vs last' (YoY), 'vs last month' (MoM), 'Q1 " +
106
+ "vs Q2' (QoQ), same-month-prev-year. Margin renders as multiplier " +
107
+ "('expenses 5.4× revenue') when in loss territory. Returns: " +
108
+ "{ message, data: { total, breakdown?, comparison?, sampleMeta? } }.",
100
109
  inputSchema: {
101
110
  type: "object",
102
111
  properties: {
103
112
  query: {
104
113
  type: "string",
105
- description: "Natural language analytics question (e.g., 'how much did I spend in March')",
114
+ description:
115
+ "Natural language question (e.g., 'how much did I spend in March', 'rental income by property')",
106
116
  },
107
117
  categories: { type: "array", items: { type: "string" } },
108
118
  dateRange: {
@@ -115,7 +125,7 @@ const TOOLS = [
115
125
  value: { type: "string" },
116
126
  },
117
127
  },
118
- groupBy: { type: "string", enum: ["category", "merchant", "month"] },
128
+ groupBy: { type: "string", enum: ["category", "merchant", "month", "tag", "source", "paymentMethod"] },
119
129
  metric: { type: "string", enum: ["total", "count", "average"] },
120
130
  },
121
131
  },
@@ -123,9 +133,12 @@ const TOOLS = [
123
133
  {
124
134
  name: "get_deep_analytics",
125
135
  description:
126
- "Run deep analytics on the user's expenses. Use for complex questions " +
127
- "like 'why did my spending increase', 'compare Q1 vs Q2', or 'find " +
128
- "unusual patterns'. Takes 10-30 seconds (runs in background).",
136
+ "Run deeper, multi-step analytics on the user's expenses. Use for " +
137
+ "explanatory questions like 'why did my spending increase' or " +
138
+ "'compare Q1 vs Q2'. Takes 10-30 seconds (runs as a background job, " +
139
+ "polled automatically). Returns: { message, data: { ..., sampleMeta? } } " +
140
+ "where sampleMeta.isTruncated indicates whether the agent saw the " +
141
+ "full dataset.",
129
142
  inputSchema: {
130
143
  type: "object",
131
144
  properties: {
@@ -256,14 +269,21 @@ const TOOLS = [
256
269
  {
257
270
  name: "check_tax_deductibility",
258
271
  description:
259
- "Check if a specific expense type or purchase is tax deductible. " +
260
- "Provides guidance based on the user's country/tax jurisdiction.",
272
+ "Look up whether a specific expense type or purchase is tax-DEDUCTIBLE " +
273
+ "(business write-off rules) based on the user's country/jurisdiction. " +
274
+ "This is a deductibility *advice* tool — use it for questions like " +
275
+ "'is Uber deductible', 'can I write off home office', 'are client " +
276
+ "dinners 50% or 100%'. Do NOT use it for questions about tax REFUNDS " +
277
+ "received as income (use get_spending_summary with a 'tax refunds' " +
278
+ "query for those — they're routed to the Income tab, not deduction " +
279
+ "rules).",
261
280
  inputSchema: {
262
281
  type: "object",
263
282
  properties: {
264
283
  query: {
265
284
  type: "string",
266
- description: "The tax question (e.g., 'is Uber tax deductible?')",
285
+ description:
286
+ "Deductibility question (e.g., 'is Uber tax deductible', 'home office write-off rules')",
267
287
  },
268
288
  category: { type: "string" },
269
289
  merchant: { type: "string" },
@@ -540,10 +560,350 @@ const TOOLS = [
540
560
  "valid tag names, not guesses.",
541
561
  inputSchema: { type: "object", properties: {} },
542
562
  },
563
+
564
+ // ── Income & P&L analytics (v0.6.0) ───────────────────────────────────
565
+ // These are first-class entry points for income / P&L / per-tag P&L
566
+ // questions. They proxy to the same query_analytics handler that powers
567
+ // get_spending_summary, but advertise themselves separately so AI clients
568
+ // surface them in completions when users ask income/profit questions.
569
+ {
570
+ name: "get_income_summary",
571
+ description:
572
+ "Get income totals, breakdowns, and analytics from the Income tab. " +
573
+ "Covers Schedule C / T2125 income, Schedule B drill-in (interest, " +
574
+ "dividends, tax refunds, security deposits), rental income, and " +
575
+ "per-source / per-payment-method / per-category / per-month / " +
576
+ "per-tag breakdowns. Schedule-C-style category exclusions match " +
577
+ "year-end T6 routing (security deposits, refunds excluded from " +
578
+ "taxable totals). Examples: 'income YTD', 'income by source', " +
579
+ "'rental income by property', 'interest income this year', " +
580
+ "'dividends YTD', 'tax refunds 2024', 'income this year vs last' " +
581
+ "(YoY). Supports period comparison phrasing — YoY ('vs last year'), " +
582
+ "MoM ('vs last month'), QoQ ('Q1 vs Q2'), same-month-prev-year. " +
583
+ "Returns: { message, data: { total, breakdown?, comparison?, " +
584
+ "sampleMeta? } }.",
585
+ inputSchema: {
586
+ type: "object",
587
+ properties: {
588
+ query: {
589
+ type: "string",
590
+ description:
591
+ "Natural language income question (e.g., 'income YTD by source', 'rental income last month')",
592
+ },
593
+ groupBy: {
594
+ type: "string",
595
+ enum: ["source", "category", "month", "paymentMethod", "tag"],
596
+ description: "How to group the breakdown",
597
+ },
598
+ dateRange: {
599
+ type: "object",
600
+ properties: {
601
+ type: { type: "string" },
602
+ month: { type: "string" },
603
+ year: { type: "integer" },
604
+ quarter: { type: "integer" },
605
+ value: { type: "string", description: "Relative date like 'YTD', 'last quarter'" },
606
+ },
607
+ },
608
+ incomeTagPrefix: {
609
+ type: "string",
610
+ description:
611
+ "Optional tag-prefix shortcut (e.g., 'Prop –' for rental income, 'Client –' for client billings, 'Wedding –' for events). When set, the tool filters to income rows tagged with this prefix.",
612
+ },
613
+ },
614
+ },
615
+ },
616
+ {
617
+ name: "get_pnl",
618
+ description:
619
+ "Compute Profit & Loss (P&L / net income / margin) by combining the " +
620
+ "Income tab with expense tabs. Examples: 'am I profitable this " +
621
+ "year', 'P&L for Q1', 'net income last quarter', 'what's my " +
622
+ "margin', 'P&L this year vs last' (YoY). Supports period comparison " +
623
+ "— YoY, MoM, QoQ, same-month-prev-year. Margin renders as " +
624
+ "multiplier in loss territory ('expenses 5.4× revenue') so the " +
625
+ "user gets a readable signal instead of '-436.9% margin'. Returns: " +
626
+ "{ message, data: { revenue, expenses, netIncome, margin, " +
627
+ "comparison?, sampleMeta? } }.",
628
+ inputSchema: {
629
+ type: "object",
630
+ properties: {
631
+ query: {
632
+ type: "string",
633
+ description: "Natural language P&L question (e.g., 'P&L for Q1 2025', 'am I profitable')",
634
+ },
635
+ dateRange: {
636
+ type: "object",
637
+ properties: {
638
+ type: { type: "string" },
639
+ month: { type: "string" },
640
+ year: { type: "integer" },
641
+ quarter: { type: "integer" },
642
+ value: { type: "string" },
643
+ },
644
+ },
645
+ },
646
+ },
647
+ },
648
+ {
649
+ name: "get_per_tag_pnl",
650
+ description:
651
+ "Per-tag P&L — revenue, cost, profit, and margin grouped by tag " +
652
+ "(per-client, per-property, per-event, per-realtor-deal). Requires " +
653
+ "both income AND expense rows to be tagged with matching labels. " +
654
+ "Common tag-prefix shortcuts: 'Prop –' (rentals), 'Client –' " +
655
+ "(client billings), 'Wedding –' (events), 'Realtor –' (real estate " +
656
+ "deals). Examples: 'per-tag P&L this year', 'profit by client', " +
657
+ "'profit by property', 'profit on the Smith wedding', 'per-client " +
658
+ "P&L this year vs last' (YoY). Supports YoY / MoM / QoQ comparison " +
659
+ "phrasing. Margin renders as multiplier in loss territory. " +
660
+ "Defaults to year-to-date if no date range given.",
661
+ inputSchema: {
662
+ type: "object",
663
+ properties: {
664
+ query: {
665
+ type: "string",
666
+ description: "Natural language per-tag P&L question",
667
+ },
668
+ tagPrefix: {
669
+ type: "string",
670
+ description:
671
+ "Optional prefix to limit which tags are bucketed (e.g., 'Prop –' for properties only, 'Client –' for clients only). When omitted, all tags are included.",
672
+ },
673
+ dateRange: {
674
+ type: "object",
675
+ properties: {
676
+ type: { type: "string" },
677
+ month: { type: "string" },
678
+ year: { type: "integer" },
679
+ quarter: { type: "integer" },
680
+ value: { type: "string" },
681
+ },
682
+ },
683
+ },
684
+ },
685
+ },
686
+ {
687
+ name: "list_income_categories",
688
+ description:
689
+ "List the user's configured income categories (mirrors " +
690
+ "list_categories for the Income tab). Use this BEFORE calling " +
691
+ "add_income with a category so you pass the user's actual income " +
692
+ "category names, not guesses. Returns the canonical INCOME_CATEGORIES " +
693
+ "enum (Service Revenue, Product Sales, Rental Income, Interest " +
694
+ "Income, Dividend Income, Tax Refund, Other Income, etc.).",
695
+ inputSchema: { type: "object", properties: {} },
696
+ },
697
+ {
698
+ name: "get_recent_activity",
699
+ description:
700
+ "Show what the user (or their AI assistants) has recently done in " +
701
+ "ExpenseBot via this MCP server: which tools were called, when, with " +
702
+ "what arguments, and whether they succeeded. Useful for ambient " +
703
+ "questions like 'what did I do this week', 'did my last receipt " +
704
+ "submission work', or to give the user transparency into AI-assisted " +
705
+ "actions. Returns the most recent N entries from the audit log " +
706
+ "(default 20, max 100).",
707
+ inputSchema: {
708
+ type: "object",
709
+ properties: {
710
+ limit: {
711
+ type: "integer",
712
+ minimum: 1,
713
+ maximum: 100,
714
+ default: 20,
715
+ },
716
+ sinceDays: {
717
+ type: "integer",
718
+ description: "Only show actions from the last N days (default 7)",
719
+ default: 7,
720
+ },
721
+ actionId: {
722
+ type: "string",
723
+ description: "Optional: filter to a single tool/action name",
724
+ },
725
+ },
726
+ },
727
+ },
728
+
729
+ // ── Mileage & Subscriptions (v0.6.1) ─────────────────────────────────
730
+ // Both proxy to the same query_analytics action that powers the chat
731
+ // widget — runtime is auto-routed via classifyMileageIntent /
732
+ // classifySubscriptionIntent. Registered as dedicated tools so AI
733
+ // clients pick them up in completions for "mileage" / "subscriptions"
734
+ // questions instead of the generic get_spending_summary.
735
+ {
736
+ name: "get_mileage_summary",
737
+ description:
738
+ "Mileage analytics — totals, breakdowns by month / client / " +
739
+ "purpose / category, plus deduction framing (cents-per-mile or " +
740
+ "cents-per-km × distance, country-aware IRS / CRA rates). " +
741
+ "Examples: 'mileage this year', 'miles driven for Acme', 'mileage " +
742
+ "by month', 'mileage deduction estimate', 'business miles last " +
743
+ "quarter'. Supports YoY / MoM / QoQ comparison phrasing. Returns: " +
744
+ "{ message, data: { totalDistance, deductionEstimate?, breakdown?, " +
745
+ "comparison?, sampleMeta? } }.",
746
+ inputSchema: {
747
+ type: "object",
748
+ properties: {
749
+ query: {
750
+ type: "string",
751
+ description:
752
+ "Natural language mileage question (e.g., 'mileage this year', 'miles driven for Acme client')",
753
+ },
754
+ groupBy: {
755
+ type: "string",
756
+ enum: ["month", "tag", "purpose", "category"],
757
+ description: "How to group the breakdown",
758
+ },
759
+ dateRange: {
760
+ type: "object",
761
+ properties: {
762
+ type: { type: "string" },
763
+ month: { type: "string" },
764
+ year: { type: "integer" },
765
+ quarter: { type: "integer" },
766
+ value: { type: "string" },
767
+ },
768
+ },
769
+ },
770
+ },
771
+ },
772
+ {
773
+ name: "get_subscription_audit",
774
+ description:
775
+ "Subscription audit — wraps the Subscription Auditor engine to " +
776
+ "find recurring charges, duplicates, price increases, and " +
777
+ "trial-conversion suspects in the user's expenses. Examples: " +
778
+ "'recurring subscriptions', 'duplicate subscriptions', 'price " +
779
+ "increases', 'trial conversions', 'subscriptions over $20/month'. " +
780
+ "Returns: { message, data: { recurring, duplicates, priceIncreases, " +
781
+ "trialConversions, totalMonthlyCost, sampleMeta? } }.",
782
+ inputSchema: {
783
+ type: "object",
784
+ properties: {
785
+ query: {
786
+ type: "string",
787
+ description:
788
+ "Natural language subscription question (e.g., 'find duplicate subscriptions', 'price increases this year')",
789
+ },
790
+ focus: {
791
+ type: "string",
792
+ enum: ["recurring", "duplicates", "price_increases", "trial_conversions", "all"],
793
+ description: "Narrow the audit to a single category (default: all)",
794
+ },
795
+ dateRange: {
796
+ type: "object",
797
+ properties: {
798
+ type: { type: "string" },
799
+ month: { type: "string" },
800
+ year: { type: "integer" },
801
+ quarter: { type: "integer" },
802
+ value: { type: "string" },
803
+ },
804
+ },
805
+ },
806
+ },
807
+ },
808
+
809
+ // ── Read-only mutation helpers + onboarding (v0.7.0) ─────────────────
810
+ {
811
+ name: "get_expense_by_id",
812
+ description:
813
+ "Fetch a single expense row by its sheet row number or by its " +
814
+ "ExpenseBot expenseId (the value in column J). Returns the row's " +
815
+ "headers + values + a labeled {header → value} map so you can refer " +
816
+ "to a specific expense the user mentioned. Read-only.",
817
+ inputSchema: {
818
+ type: "object",
819
+ properties: {
820
+ rowNumber: {
821
+ type: "integer",
822
+ minimum: 2,
823
+ description: "1-indexed sheet row (row 1 is headers, so ≥ 2)",
824
+ },
825
+ expenseId: {
826
+ type: "string",
827
+ description: "ExpenseBot expense ID (column J)",
828
+ },
829
+ },
830
+ },
831
+ },
832
+ {
833
+ name: "export_report",
834
+ description:
835
+ "Get download URLs for an expense report. Returns the Google Sheets " +
836
+ "view URL plus direct PDF / CSV / XLSX export URLs. The user needs to " +
837
+ "be signed into the Google account that owns the report to download " +
838
+ "(no separate auth from the AI client). Use list_reports first to find " +
839
+ "the reportId.",
840
+ inputSchema: {
841
+ type: "object",
842
+ properties: {
843
+ reportId: { type: "string", description: "Report ID from list_reports" },
844
+ },
845
+ required: ["reportId"],
846
+ },
847
+ },
848
+ {
849
+ name: "get_pricing",
850
+ description:
851
+ "Get current ExpenseBot pricing for all plans (Free Trial, Standard, " +
852
+ "Pro Add-On, Deep Scan, Accountants). Useful when the user asks 'how " +
853
+ "much does this cost' or 'what's the difference between plans'. Works " +
854
+ "with or without authentication.",
855
+ inputSchema: { type: "object", properties: {} },
856
+ },
857
+ {
858
+ name: "check_feature",
859
+ description:
860
+ "Check whether ExpenseBot supports a specific feature ('does ExpenseBot " +
861
+ "support X', 'can it integrate with Y'). Searches the public knowledge " +
862
+ "base and returns a confidence-scored answer + related questions. Works " +
863
+ "with or without authentication.",
864
+ inputSchema: {
865
+ type: "object",
866
+ properties: {
867
+ feature: {
868
+ type: "string",
869
+ description: "Feature or integration to check (e.g., 'Xero', 'mileage tracking', 'Plaid')",
870
+ },
871
+ },
872
+ required: ["feature"],
873
+ },
874
+ },
875
+ {
876
+ name: "start_trial_link",
877
+ description:
878
+ "Get a UTM-tagged signup URL for the 60-day free trial (no credit " +
879
+ "card required). Use this when an unauthenticated AI conversation " +
880
+ "wants to send the user to sign up. Returns a URL with attribution " +
881
+ "tags so we can track AI-assistant referrals.",
882
+ inputSchema: {
883
+ type: "object",
884
+ properties: {
885
+ utmSource: {
886
+ type: "string",
887
+ description: "UTM source override (default: 'mcp')",
888
+ },
889
+ utmCampaign: {
890
+ type: "string",
891
+ description: "UTM campaign override (default: 'ai-assistant')",
892
+ },
893
+ },
894
+ },
895
+ },
543
896
  ];
544
897
 
545
898
  // Tools available without authentication (onboarding mode)
546
- const PUBLIC_TOOLS = ["get_signup_link", "search_knowledge"];
899
+ const PUBLIC_TOOLS = [
900
+ "get_signup_link",
901
+ "search_knowledge",
902
+ // v0.7.0 — pre-sales discovery for unauthenticated AI agents
903
+ "get_pricing",
904
+ "check_feature",
905
+ "start_trial_link",
906
+ ];
547
907
 
548
908
  // ── Tool Handlers ──────────────────────────────────────────────────────
549
909
 
@@ -578,8 +938,8 @@ async function handleTool(name, args) {
578
938
  text:
579
939
  "**ExpenseBot — 60-day free trial, no credit card required**\n\n" +
580
940
  `Sign up: https://www.expensebot.ai?utm_source=${args?.utmSource || "mcp"}&utm_medium=ai-assistant\n\n` +
581
- "After signing up, generate an AI Assistant Token from Settings to unlock all 16 tools " +
582
- "(search expenses, submit receipts, scan Gmail, create reports, run analytics).\n\n" +
941
+ "After signing up, generate an AI Assistant Token from Settings to unlock all 33 tools " +
942
+ "(submit receipts, scan Gmail, search expenses, run income / P&L / per-tag P&L analytics, create reports).\n\n" +
583
943
  "Free for accountants forever. $10/month for everyone else.",
584
944
  },
585
945
  ],
@@ -710,6 +1070,172 @@ async function handleTool(name, args) {
710
1070
  case "list_tags":
711
1071
  return formatResult(await client.execute("list_tags", {}));
712
1072
 
1073
+ // ── Income & P&L analytics (v0.6.0) — proxy to query_analytics ──
1074
+ case "get_income_summary": {
1075
+ // Build a query that hints at income intent + optional tag filter
1076
+ let q = args.query || "income summary";
1077
+ if (args.incomeTagPrefix) {
1078
+ q = `${q} (filter to tag prefix '${args.incomeTagPrefix}')`;
1079
+ }
1080
+ if (args.groupBy) {
1081
+ q = `${q} grouped by ${args.groupBy}`;
1082
+ }
1083
+ return formatResult(
1084
+ await client.execute("query_analytics", {
1085
+ ...args,
1086
+ message: q,
1087
+ intent: "income",
1088
+ })
1089
+ );
1090
+ }
1091
+
1092
+ case "get_pnl":
1093
+ return formatResult(
1094
+ await client.execute("query_analytics", {
1095
+ ...args,
1096
+ message: args.query || "P&L summary",
1097
+ intent: "pnl",
1098
+ })
1099
+ );
1100
+
1101
+ case "get_per_tag_pnl": {
1102
+ let q = args.query || "per-tag P&L";
1103
+ if (args.tagPrefix) {
1104
+ q = `${q} (limit to tag prefix '${args.tagPrefix}')`;
1105
+ }
1106
+ return formatResult(
1107
+ await client.execute("query_analytics", {
1108
+ ...args,
1109
+ message: q,
1110
+ intent: "per_tag_pnl",
1111
+ })
1112
+ );
1113
+ }
1114
+
1115
+ case "list_income_categories":
1116
+ return formatResult(
1117
+ await client.execute("list_income_categories", {})
1118
+ );
1119
+
1120
+ case "get_recent_activity":
1121
+ return formatResult(
1122
+ await client.execute("get_recent_activity", {
1123
+ limit: args.limit || 20,
1124
+ sinceDays: args.sinceDays || 7,
1125
+ actionId: args.actionId,
1126
+ })
1127
+ );
1128
+
1129
+ // ── Mileage & Subscriptions (v0.6.1) ──
1130
+ // Both proxy to query_analytics; classifyMileageIntent /
1131
+ // classifySubscriptionIntent route to the correct helper server-side.
1132
+ case "get_mileage_summary": {
1133
+ let q = args.query || "mileage summary";
1134
+ if (args.groupBy) q = `${q} grouped by ${args.groupBy}`;
1135
+ return formatResult(
1136
+ await client.execute("query_analytics", {
1137
+ ...args,
1138
+ message: q,
1139
+ intent: "mileage",
1140
+ })
1141
+ );
1142
+ }
1143
+
1144
+ case "get_subscription_audit": {
1145
+ let q = args.query || "subscription audit";
1146
+ if (args.focus && args.focus !== "all") {
1147
+ q = `${q} (focus: ${args.focus})`;
1148
+ }
1149
+ return formatResult(
1150
+ await client.execute("query_analytics", {
1151
+ ...args,
1152
+ message: q,
1153
+ intent: "subscriptions",
1154
+ })
1155
+ );
1156
+ }
1157
+
1158
+ // ── Read-only mutation helpers (v0.7.0) ──
1159
+ case "get_expense_by_id":
1160
+ return formatResult(
1161
+ await client.execute("get_expense_by_id", {
1162
+ rowNumber: args.rowNumber,
1163
+ expenseId: args.expenseId,
1164
+ })
1165
+ );
1166
+
1167
+ case "export_report":
1168
+ return formatResult(
1169
+ await client.execute("export_report", { reportId: args.reportId })
1170
+ );
1171
+
1172
+ // ── Onboarding-mode tools (v0.7.0) — work with or without token ──
1173
+ case "get_pricing": {
1174
+ // Onboarding fallback: hardcoded snapshot so it works with no token
1175
+ if (onboardingMode) {
1176
+ return {
1177
+ content: [
1178
+ {
1179
+ type: "text",
1180
+ text:
1181
+ "**ExpenseBot pricing**\n\n" +
1182
+ "- **Free Trial** — 60 days, no credit card. Current year only.\n" +
1183
+ "- **Standard** — $10/month. Current + 1 year back.\n" +
1184
+ "- **Pro Add-On** — $20 one-time. Multi-inbox + alias forwarding.\n" +
1185
+ "- **Deep Scan Add-On** — $40 one-time. 5-year historical Gmail scan.\n" +
1186
+ "- **Accountants** — Free forever. Multi-client.\n\n" +
1187
+ "Sign up: https://www.expensebot.ai?utm_source=mcp&utm_medium=ai-assistant",
1188
+ },
1189
+ ],
1190
+ };
1191
+ }
1192
+ return formatResult(await client.execute("get_pricing", {}));
1193
+ }
1194
+
1195
+ case "check_feature": {
1196
+ if (onboardingMode) {
1197
+ // Use public /api/discover with feature query
1198
+ try {
1199
+ const url = new URL("/api/discover", "https://www.expensebot.ai");
1200
+ url.searchParams.set("query", args?.feature || "");
1201
+ url.searchParams.set("utm_source", "mcp-onboarding");
1202
+ const res = await fetch(url.toString(), {
1203
+ headers: { "User-Agent": "expensebot-mcp-auth/0.6.0" },
1204
+ });
1205
+ const data = await res.json();
1206
+ return formatResult(data);
1207
+ } catch (err) {
1208
+ return {
1209
+ content: [{ type: "text", text: `Feature check failed: ${err.message}` }],
1210
+ isError: true,
1211
+ };
1212
+ }
1213
+ }
1214
+ return formatResult(
1215
+ await client.execute("check_feature", { feature: args.feature })
1216
+ );
1217
+ }
1218
+
1219
+ case "start_trial_link": {
1220
+ const utmSource = args?.utmSource || "mcp";
1221
+ const utmCampaign = args?.utmCampaign || "ai-assistant";
1222
+ const url =
1223
+ `https://www.expensebot.ai?utm_source=${encodeURIComponent(utmSource)}` +
1224
+ `&utm_medium=ai-assistant&utm_campaign=${encodeURIComponent(utmCampaign)}`;
1225
+ return {
1226
+ content: [
1227
+ {
1228
+ type: "text",
1229
+ text:
1230
+ `**Start your 60-day free trial** (no credit card required)\n\n` +
1231
+ `${url}\n\n` +
1232
+ `After signup: Settings → AI Assistant Tokens → Generate to ` +
1233
+ `unlock all ${TOOLS.length} MCP tools.`,
1234
+ },
1235
+ ],
1236
+ };
1237
+ }
1238
+
713
1239
  default:
714
1240
  return {
715
1241
  content: [{ type: "text", text: `Unknown tool: ${name}` }],
@@ -719,24 +1245,56 @@ async function handleTool(name, args) {
719
1245
  }
720
1246
 
721
1247
  function formatResult(result) {
1248
+ // Structured error path (v0.7.0): backend may return { success: false,
1249
+ // error: { code, message, hint } }. Surface clean human text without
1250
+ // burying the AI in a raw stack trace.
1251
+ if (result?.success === false) {
1252
+ const err = result.error;
1253
+ let errText;
1254
+ if (err && typeof err === "object" && err.message) {
1255
+ errText = `Error (${err.code || "unknown"}): ${err.message}`;
1256
+ if (err.hint) errText += `\n\nHint: ${err.hint}`;
1257
+ } else if (typeof err === "string") {
1258
+ errText = `Error: ${err}`;
1259
+ } else {
1260
+ errText = `Error: ${result.message || "request failed"}`;
1261
+ }
1262
+ return { content: [{ type: "text", text: errText }], isError: true };
1263
+ }
1264
+
722
1265
  // Extract the meaningful content
723
1266
  let text;
724
- if (result.message && typeof result.message === "string") {
1267
+ if (result?.message && typeof result.message === "string") {
725
1268
  text = result.message;
726
- } else if (result.data) {
1269
+ } else if (result?.data) {
727
1270
  text = JSON.stringify(result.data, null, 2);
728
1271
  } else {
729
1272
  text = JSON.stringify(result, null, 2);
730
1273
  }
731
1274
 
1275
+ // Truncation banner (v0.6.0): when the analytics agent saw only a sample
1276
+ // of the user's expenses, prepend a clear note so the AI knows totals
1277
+ // remain accurate but row-level detail is partial. Looks at multiple
1278
+ // shapes since sampleMeta can sit at result.sampleMeta or result.data.sampleMeta.
1279
+ const sm = result?.sampleMeta || result?.data?.sampleMeta;
1280
+ if (sm?.isTruncated) {
1281
+ const seen = sm.sampleCount ?? "some";
1282
+ const total = sm.totalCount ?? "many";
1283
+ const banner =
1284
+ `⚠️ Truncated result: agent saw a sample of ${seen} of ${total} rows. ` +
1285
+ `Aggregate totals are accurate; row-level detail may be partial. ` +
1286
+ `Refine the date range or add filters to see all rows.`;
1287
+ text = `${banner}\n\n${text}`;
1288
+ }
1289
+
732
1290
  // Append structured data if present
733
- if (result.data && result.message) {
1291
+ if (result?.data && result?.message) {
734
1292
  text += "\n\n---\nRaw data:\n" + JSON.stringify(result.data, null, 2);
735
1293
  }
736
1294
 
737
1295
  return {
738
1296
  content: [{ type: "text", text }],
739
- isError: result.success === false,
1297
+ isError: false,
740
1298
  };
741
1299
  }
742
1300
 
@@ -744,7 +1302,7 @@ function formatResult(result) {
744
1302
 
745
1303
  async function main() {
746
1304
  const server = new Server(
747
- { name: "expensebot-auth", version: "0.1.0" },
1305
+ { name: "expensebot-auth", version: "0.6.1" },
748
1306
  { capabilities: { tools: {} } }
749
1307
  );
750
1308
 
@@ -772,7 +1330,9 @@ async function main() {
772
1330
  const transport = new StdioServerTransport();
773
1331
  await server.connect(transport);
774
1332
  console.error(
775
- `[expensebot-auth] MCP server ready. tools=${TOOLS.length}, base=${client.baseUrl}`
1333
+ `[expensebot-auth] MCP server ready. tools=${TOOLS.length}, ` +
1334
+ `mode=${onboardingMode ? "onboarding" : "authenticated"}, ` +
1335
+ `base=${client?.baseUrl || "https://www.expensebot.ai"}`
776
1336
  );
777
1337
  }
778
1338
 
package/src/test.js ADDED
@@ -0,0 +1,245 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Smoke test — boots the MCP server in onboarding mode (no token) and
4
+ * verifies via stdio that:
5
+ * 1. Server starts cleanly without throwing
6
+ * 2. tools/list returns the expected number of tools
7
+ * 3. All locally-handled tools (PUBLIC_TOOLS that don't need backend)
8
+ * respond without error
9
+ * 4. A token-gated tool returns the expected "requires account" error
10
+ *
11
+ * Run: npm test
12
+ *
13
+ * Does NOT hit the production backend. For that, see
14
+ * scripts/_test_mcp_e2e.js (uses a real PAT).
15
+ */
16
+
17
+ import { spawn } from "node:child_process";
18
+ import { fileURLToPath } from "node:url";
19
+ import path from "node:path";
20
+
21
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
22
+ const SERVER_PATH = path.join(__dirname, "index.js");
23
+
24
+ const EXPECTED_TOOL_COUNT = 33;
25
+ const REQUIRED_TOOLS = [
26
+ // v0.5.x
27
+ "search_expenses",
28
+ "submit_receipt",
29
+ "scan_gmail",
30
+ "create_report",
31
+ // v0.6.0
32
+ "get_income_summary",
33
+ "get_pnl",
34
+ "get_per_tag_pnl",
35
+ "list_income_categories",
36
+ "get_recent_activity",
37
+ // v0.6.1
38
+ "get_mileage_summary",
39
+ "get_subscription_audit",
40
+ // v0.7.0
41
+ "get_expense_by_id",
42
+ "export_report",
43
+ "get_pricing",
44
+ "check_feature",
45
+ "start_trial_link",
46
+ ];
47
+
48
+ const REQUESTS = [
49
+ {
50
+ jsonrpc: "2.0",
51
+ id: 1,
52
+ method: "initialize",
53
+ params: {
54
+ protocolVersion: "2024-11-05",
55
+ capabilities: {},
56
+ clientInfo: { name: "smoke-test", version: "1.0" },
57
+ },
58
+ },
59
+ { jsonrpc: "2.0", method: "notifications/initialized" },
60
+ { jsonrpc: "2.0", id: 2, method: "tools/list", params: {} },
61
+ {
62
+ jsonrpc: "2.0",
63
+ id: 3,
64
+ method: "tools/call",
65
+ params: { name: "get_pricing", arguments: {} },
66
+ },
67
+ {
68
+ jsonrpc: "2.0",
69
+ id: 4,
70
+ method: "tools/call",
71
+ params: { name: "start_trial_link", arguments: {} },
72
+ },
73
+ {
74
+ jsonrpc: "2.0",
75
+ id: 5,
76
+ method: "tools/call",
77
+ params: { name: "get_signup_link", arguments: {} },
78
+ },
79
+ {
80
+ // Token-gated tool — must return isError:true with onboarding message
81
+ jsonrpc: "2.0",
82
+ id: 6,
83
+ method: "tools/call",
84
+ params: { name: "search_expenses", arguments: {} },
85
+ },
86
+ ];
87
+
88
+ function runServer() {
89
+ return new Promise((resolve, reject) => {
90
+ const child = spawn("node", [SERVER_PATH], {
91
+ stdio: ["pipe", "pipe", "pipe"],
92
+ env: { ...process.env, EXPENSEBOT_TOKEN: "" },
93
+ });
94
+
95
+ const responses = [];
96
+ let stdoutBuf = "";
97
+
98
+ child.stdout.on("data", (chunk) => {
99
+ stdoutBuf += chunk.toString();
100
+ let nl;
101
+ while ((nl = stdoutBuf.indexOf("\n")) !== -1) {
102
+ const line = stdoutBuf.slice(0, nl).trim();
103
+ stdoutBuf = stdoutBuf.slice(nl + 1);
104
+ if (!line) continue;
105
+ try {
106
+ responses.push(JSON.parse(line));
107
+ } catch {
108
+ /* non-JSON stderr-ish line */
109
+ }
110
+ }
111
+ });
112
+
113
+ child.stderr.on("data", (d) => {
114
+ // Pass through banners only when running in verbose mode
115
+ if (process.env.MCP_TEST_VERBOSE) {
116
+ process.stderr.write(`[server] ${d}`);
117
+ }
118
+ });
119
+
120
+ child.on("error", reject);
121
+ child.on("exit", (code) => {
122
+ if (code !== 0 && code !== null) {
123
+ reject(new Error(`Server exited with code ${code}`));
124
+ return;
125
+ }
126
+ resolve(responses);
127
+ });
128
+
129
+ // Send all requests with small delays (server needs to ack between)
130
+ (async () => {
131
+ for (const req of REQUESTS) {
132
+ child.stdin.write(JSON.stringify(req) + "\n");
133
+ await new Promise((r) => setTimeout(r, 200));
134
+ }
135
+ // Wait for last responses, then close
136
+ await new Promise((r) => setTimeout(r, 500));
137
+ child.stdin.end();
138
+ // Server exits cleanly when stdin closes
139
+ setTimeout(() => child.kill("SIGTERM"), 1500);
140
+ })();
141
+ });
142
+ }
143
+
144
+ const failures = [];
145
+
146
+ function check(label, ok, details = "") {
147
+ const symbol = ok ? "✓" : "✘";
148
+ console.log(`${symbol} ${label}${details ? " — " + details : ""}`);
149
+ if (!ok) failures.push(label);
150
+ }
151
+
152
+ (async () => {
153
+ console.log("=== mcp-server-auth smoke test ===\n");
154
+ const responses = await runServer();
155
+ const byId = new Map(
156
+ responses.filter((r) => r.id != null).map((r) => [r.id, r])
157
+ );
158
+
159
+ // 1. tools/list shape
160
+ const listResp = byId.get(2);
161
+ const tools = listResp?.result?.tools;
162
+ check(
163
+ "tools/list returns an array",
164
+ Array.isArray(tools),
165
+ `(got ${typeof tools})`
166
+ );
167
+ if (Array.isArray(tools)) {
168
+ check(
169
+ `tools/list count = ${EXPECTED_TOOL_COUNT}`,
170
+ tools.length === EXPECTED_TOOL_COUNT,
171
+ `(got ${tools.length})`
172
+ );
173
+ const names = new Set(tools.map((t) => t.name));
174
+ const missing = REQUIRED_TOOLS.filter((n) => !names.has(n));
175
+ check(
176
+ `all ${REQUIRED_TOOLS.length} required tools present`,
177
+ missing.length === 0,
178
+ missing.length ? `missing: ${missing.join(", ")}` : ""
179
+ );
180
+ // Every tool must have a description
181
+ const noDesc = tools.filter((t) => !t.description);
182
+ check(
183
+ "every tool has a description",
184
+ noDesc.length === 0,
185
+ noDesc.length ? `missing on: ${noDesc.map((t) => t.name).join(", ")}` : ""
186
+ );
187
+ }
188
+
189
+ // 2. get_pricing (id=3) — should succeed in onboarding mode
190
+ const pricingResp = byId.get(3);
191
+ const pricingText = pricingResp?.result?.content?.[0]?.text || "";
192
+ check(
193
+ "get_pricing succeeds in onboarding mode",
194
+ pricingResp?.result && !pricingResp.result.isError,
195
+ pricingResp?.result?.isError ? "returned isError" : ""
196
+ );
197
+ check(
198
+ "get_pricing mentions Free Trial + Standard",
199
+ pricingText.includes("Free Trial") && pricingText.includes("Standard")
200
+ );
201
+
202
+ // 3. start_trial_link (id=4)
203
+ const trialResp = byId.get(4);
204
+ const trialText = trialResp?.result?.content?.[0]?.text || "";
205
+ check(
206
+ "start_trial_link succeeds in onboarding mode",
207
+ trialResp?.result && !trialResp.result.isError
208
+ );
209
+ check(
210
+ "start_trial_link includes UTM params",
211
+ trialText.includes("utm_source=mcp") && trialText.includes("utm_medium=ai-assistant")
212
+ );
213
+
214
+ // 4. get_signup_link (id=5)
215
+ const signupResp = byId.get(5);
216
+ const signupText = signupResp?.result?.content?.[0]?.text || "";
217
+ check(
218
+ "get_signup_link succeeds + advertises 33 tools",
219
+ !signupResp?.result?.isError && signupText.includes("33 tools")
220
+ );
221
+
222
+ // 5. Token-gated tool (id=6) returns isError with helpful message
223
+ const gatedResp = byId.get(6);
224
+ const gatedText = gatedResp?.result?.content?.[0]?.text || "";
225
+ check(
226
+ "search_expenses (token-gated) returns isError in onboarding",
227
+ gatedResp?.result?.isError === true
228
+ );
229
+ check(
230
+ "gated error message includes signup URL",
231
+ gatedText.includes("expensebot.ai") &&
232
+ gatedText.includes("AI Assistant Tokens")
233
+ );
234
+
235
+ console.log("");
236
+ if (failures.length) {
237
+ console.error(`✘ ${failures.length} check(s) failed:`);
238
+ failures.forEach((f) => console.error(" - " + f));
239
+ process.exit(1);
240
+ }
241
+ console.log("✓ All smoke tests passed.\n");
242
+ })().catch((err) => {
243
+ console.error("Test runner error:", err);
244
+ process.exit(2);
245
+ });