@expensebot/mcp-server-auth 0.1.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.
Files changed (3) hide show
  1. package/package.json +36 -0
  2. package/src/client.js +94 -0
  3. package/src/index.js +420 -0
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@expensebot/mcp-server-auth",
3
+ "version": "0.1.0",
4
+ "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.",
5
+ "bin": {
6
+ "expensebot-mcp-auth": "./src/index.js"
7
+ },
8
+ "type": "module",
9
+ "main": "./src/index.js",
10
+ "files": [
11
+ "src",
12
+ "README.md"
13
+ ],
14
+ "keywords": [
15
+ "mcp",
16
+ "model-context-protocol",
17
+ "expensebot",
18
+ "expenses",
19
+ "receipts",
20
+ "ai",
21
+ "claude",
22
+ "accounting"
23
+ ],
24
+ "engines": {
25
+ "node": ">=18"
26
+ },
27
+ "dependencies": {
28
+ "@modelcontextprotocol/sdk": "^1.0.0"
29
+ },
30
+ "scripts": {
31
+ "start": "node src/index.js",
32
+ "test": "node src/test.js"
33
+ },
34
+ "author": "ExpenseBot",
35
+ "license": "MIT"
36
+ }
package/src/client.js ADDED
@@ -0,0 +1,94 @@
1
+ /**
2
+ * HTTP client for the ExpenseBot MCP API.
3
+ * Handles authentication, request formatting, and analytics polling.
4
+ */
5
+
6
+ const DEFAULT_BASE = "https://www.expensebot.ai";
7
+ const POLL_INTERVAL_MS = 3000;
8
+ const POLL_TIMEOUT_MS = 60000;
9
+
10
+ export class ExpenseBotClient {
11
+ constructor(token, baseUrl) {
12
+ this.token = token;
13
+ this.baseUrl = baseUrl || process.env.EXPENSEBOT_API_BASE || DEFAULT_BASE;
14
+ }
15
+
16
+ async request(path, options = {}) {
17
+ const url = `${this.baseUrl}${path}`;
18
+ const res = await fetch(url, {
19
+ method: options.method || "GET",
20
+ headers: {
21
+ Authorization: `Bearer ${this.token}`,
22
+ "Content-Type": "application/json",
23
+ "User-Agent": "expensebot-mcp-auth/0.1.0",
24
+ ...options.headers,
25
+ },
26
+ body: options.body ? JSON.stringify(options.body) : undefined,
27
+ });
28
+
29
+ if (res.status === 401) {
30
+ throw new Error(
31
+ "Authentication failed — token may be expired or revoked. " +
32
+ "Generate a new token at https://www.expensebot.ai (Settings → API Tokens)."
33
+ );
34
+ }
35
+ if (!res.ok) {
36
+ const text = await res.text().catch(() => "");
37
+ throw new Error(`API error ${res.status}: ${text.substring(0, 200)}`);
38
+ }
39
+ return res.json();
40
+ }
41
+
42
+ /**
43
+ * Execute an action via /api/mcp/execute.
44
+ * For async actions (analytics), automatically polls until complete.
45
+ */
46
+ async execute(actionId, params = {}) {
47
+ const result = await this.request("/api/mcp/execute", {
48
+ method: "POST",
49
+ body: { actionId, params },
50
+ });
51
+
52
+ // If the action returned an async job, poll for completion
53
+ if (
54
+ result.type === "analytics_pending" ||
55
+ result.jobId ||
56
+ result.data?.jobId
57
+ ) {
58
+ const jobId = result.jobId || result.data?.jobId;
59
+ if (jobId) {
60
+ return this.pollAnalytics(jobId);
61
+ }
62
+ }
63
+
64
+ return result;
65
+ }
66
+
67
+ /**
68
+ * Poll an async analytics job until it completes or times out.
69
+ */
70
+ async pollAnalytics(jobId) {
71
+ const start = Date.now();
72
+ while (Date.now() - start < POLL_TIMEOUT_MS) {
73
+ const progress = await this.request(`/api/mcp/poll/${jobId}`);
74
+ if (progress.status === "complete") {
75
+ return progress;
76
+ }
77
+ if (progress.status === "failed") {
78
+ throw new Error(
79
+ `Analytics job failed: ${progress.error || "unknown error"}`
80
+ );
81
+ }
82
+ // Wait before next poll
83
+ await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
84
+ }
85
+ return {
86
+ success: true,
87
+ status: "timeout",
88
+ message:
89
+ "Analytics job is still processing. Try again in a minute — " +
90
+ "complex queries over large datasets can take up to 2 minutes.",
91
+ jobId,
92
+ };
93
+ }
94
+ }
package/src/index.js ADDED
@@ -0,0 +1,420 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Authenticated MCP server for ExpenseBot.
4
+ *
5
+ * Lets Claude Desktop, Cursor, and other MCP clients search expenses,
6
+ * create reports, get analytics, and more — using the user's actual
7
+ * ExpenseBot data.
8
+ *
9
+ * Usage:
10
+ * npx @expensebot/mcp-server-auth --token=<your-pat>
11
+ *
12
+ * Claude Desktop config:
13
+ * {
14
+ * "mcpServers": {
15
+ * "expensebot": {
16
+ * "command": "npx",
17
+ * "args": ["-y", "@expensebot/mcp-server-auth", "--token=<your-pat>"]
18
+ * }
19
+ * }
20
+ * }
21
+ */
22
+
23
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
24
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
25
+ import {
26
+ CallToolRequestSchema,
27
+ ListToolsRequestSchema,
28
+ } from "@modelcontextprotocol/sdk/types.js";
29
+ import { ExpenseBotClient } from "./client.js";
30
+
31
+ // Parse --token from args
32
+ const args = process.argv.slice(2);
33
+ let token = process.env.EXPENSEBOT_TOKEN;
34
+ for (const arg of args) {
35
+ if (arg.startsWith("--token=")) token = arg.split("=").slice(1).join("=");
36
+ }
37
+
38
+ if (!token) {
39
+ console.error(
40
+ "Error: --token=<your-pat> is required.\n\n" +
41
+ "Generate a token:\n" +
42
+ " 1. Go to https://www.expensebot.ai → Settings → API Tokens\n" +
43
+ " 2. Click 'Generate Token'\n" +
44
+ " 3. Run: npx @expensebot/mcp-server-auth --token=<paste-token>\n"
45
+ );
46
+ process.exit(1);
47
+ }
48
+
49
+ const client = new ExpenseBotClient(token);
50
+
51
+ // ── Tool Definitions ───────────────────────────────────────────────────
52
+
53
+ const TOOLS = [
54
+ {
55
+ name: "search_expenses",
56
+ description:
57
+ "Search and filter the user's expenses. Returns matching expense rows " +
58
+ "from their spreadsheet. Filter by category, merchant, date range, " +
59
+ "amount, or tags.",
60
+ inputSchema: {
61
+ type: "object",
62
+ properties: {
63
+ categories: {
64
+ type: "array",
65
+ items: { type: "string" },
66
+ description: "Filter by expense categories (e.g., ['Travel', 'Meals'])",
67
+ },
68
+ merchants: {
69
+ type: "array",
70
+ items: { type: "string" },
71
+ description: "Filter by merchant names (e.g., ['Uber', 'Starbucks'])",
72
+ },
73
+ dateRange: {
74
+ type: "object",
75
+ description: "Time period filter",
76
+ properties: {
77
+ type: { type: "string", enum: ["month", "quarter", "year", "specific", "relative"] },
78
+ month: { type: "string" },
79
+ year: { type: "integer" },
80
+ quarter: { type: "integer", minimum: 1, maximum: 4 },
81
+ value: { type: "string", description: "Relative date like 'last month', 'this week'" },
82
+ start: { type: "string", format: "date" },
83
+ end: { type: "string", format: "date" },
84
+ },
85
+ },
86
+ minAmount: { type: "number", description: "Minimum expense amount" },
87
+ maxAmount: { type: "number", description: "Maximum expense amount" },
88
+ tags: { type: "array", items: { type: "string" }, description: "Filter by tags" },
89
+ limit: { type: "integer", description: "Max results (default 20)", default: 20 },
90
+ },
91
+ },
92
+ },
93
+ {
94
+ name: "get_spending_summary",
95
+ description:
96
+ "Get spending totals, breakdowns by category or merchant, and basic " +
97
+ "expense analytics. For simple questions like 'how much did I spend " +
98
+ "last month' or 'top merchants'.",
99
+ inputSchema: {
100
+ type: "object",
101
+ properties: {
102
+ query: {
103
+ type: "string",
104
+ description: "Natural language analytics question (e.g., 'how much did I spend in March')",
105
+ },
106
+ categories: { type: "array", items: { type: "string" } },
107
+ dateRange: {
108
+ type: "object",
109
+ properties: {
110
+ type: { type: "string" },
111
+ month: { type: "string" },
112
+ year: { type: "integer" },
113
+ quarter: { type: "integer" },
114
+ value: { type: "string" },
115
+ },
116
+ },
117
+ groupBy: { type: "string", enum: ["category", "merchant", "month"] },
118
+ metric: { type: "string", enum: ["total", "count", "average"] },
119
+ },
120
+ },
121
+ },
122
+ {
123
+ name: "get_deep_analytics",
124
+ description:
125
+ "Run deep analytics on the user's expenses. Use for complex questions " +
126
+ "like 'why did my spending increase', 'compare Q1 vs Q2', or 'find " +
127
+ "unusual patterns'. Takes 10-30 seconds (runs in background).",
128
+ inputSchema: {
129
+ type: "object",
130
+ properties: {
131
+ query: {
132
+ type: "string",
133
+ description: "The analytics question to answer",
134
+ },
135
+ dateRange: {
136
+ type: "object",
137
+ properties: {
138
+ type: { type: "string" },
139
+ month: { type: "string" },
140
+ year: { type: "integer" },
141
+ quarter: { type: "integer" },
142
+ },
143
+ },
144
+ },
145
+ required: ["query"],
146
+ },
147
+ },
148
+ {
149
+ name: "create_report",
150
+ description:
151
+ "Create an expense report from filtered expenses. Returns the report " +
152
+ "ID and summary. Can optionally share with recipients.",
153
+ inputSchema: {
154
+ type: "object",
155
+ properties: {
156
+ dateRange: {
157
+ type: "object",
158
+ description: "Time period for the report (required)",
159
+ properties: {
160
+ type: { type: "string", enum: ["month", "quarter", "year", "specific"] },
161
+ month: { type: "string" },
162
+ year: { type: "integer" },
163
+ quarter: { type: "integer" },
164
+ start: { type: "string", format: "date" },
165
+ end: { type: "string", format: "date" },
166
+ },
167
+ },
168
+ title: { type: "string", description: "Custom report title" },
169
+ categories: { type: "array", items: { type: "string" } },
170
+ tags: { type: "array", items: { type: "string" } },
171
+ shareWith: {
172
+ type: "array",
173
+ items: { type: "string", format: "email" },
174
+ description: "Email addresses to share the report with",
175
+ },
176
+ },
177
+ required: ["dateRange"],
178
+ },
179
+ },
180
+ {
181
+ name: "list_reports",
182
+ description:
183
+ "List the user's expense reports with pagination. Filter by status " +
184
+ "(All, Draft, Submitted, Shared).",
185
+ inputSchema: {
186
+ type: "object",
187
+ properties: {
188
+ page: { type: "integer", default: 1 },
189
+ limit: { type: "integer", default: 20 },
190
+ filter: { type: "string", enum: ["All", "Draft", "Submitted", "Shared"], default: "All" },
191
+ },
192
+ },
193
+ },
194
+ {
195
+ name: "get_report_details",
196
+ description:
197
+ "Get full details of a specific expense report including all expenses, " +
198
+ "totals, and compliance status.",
199
+ inputSchema: {
200
+ type: "object",
201
+ properties: {
202
+ reportId: { type: "string", description: "The report/spreadsheet ID" },
203
+ },
204
+ required: ["reportId"],
205
+ },
206
+ },
207
+ {
208
+ name: "share_report",
209
+ description:
210
+ "Share an expense report with one or more email addresses for review " +
211
+ "or approval.",
212
+ inputSchema: {
213
+ type: "object",
214
+ properties: {
215
+ reportId: { type: "string" },
216
+ recipients: {
217
+ type: "array",
218
+ items: { type: "string", format: "email" },
219
+ },
220
+ },
221
+ required: ["reportId", "recipients"],
222
+ },
223
+ },
224
+ {
225
+ name: "check_compliance",
226
+ description:
227
+ "Check an expense report for compliance issues (missing business " +
228
+ "purpose, policy violations, etc.).",
229
+ inputSchema: {
230
+ type: "object",
231
+ properties: {
232
+ reportId: { type: "string", description: "Report ID to check" },
233
+ },
234
+ required: ["reportId"],
235
+ },
236
+ },
237
+ {
238
+ name: "fix_compliance",
239
+ description:
240
+ "Bulk-fix compliance issues in a report (e.g., apply the same " +
241
+ "business purpose to all flagged expenses).",
242
+ inputSchema: {
243
+ type: "object",
244
+ properties: {
245
+ reportId: { type: "string" },
246
+ action: {
247
+ type: "string",
248
+ enum: ["add_purpose", "set_category", "add_tag"],
249
+ },
250
+ value: { type: "string", description: "The value to apply" },
251
+ },
252
+ required: ["reportId", "action", "value"],
253
+ },
254
+ },
255
+ {
256
+ name: "check_tax_deductibility",
257
+ description:
258
+ "Check if a specific expense type or purchase is tax deductible. " +
259
+ "Provides guidance based on the user's country/tax jurisdiction.",
260
+ inputSchema: {
261
+ type: "object",
262
+ properties: {
263
+ query: {
264
+ type: "string",
265
+ description: "The tax question (e.g., 'is Uber tax deductible?')",
266
+ },
267
+ category: { type: "string" },
268
+ merchant: { type: "string" },
269
+ },
270
+ required: ["query"],
271
+ },
272
+ },
273
+ {
274
+ name: "search_knowledge",
275
+ description:
276
+ "Search the ExpenseBot knowledge base for help articles and " +
277
+ "how-to guides. Use when the user asks about ExpenseBot features.",
278
+ inputSchema: {
279
+ type: "object",
280
+ properties: {
281
+ query: { type: "string", description: "Search terms" },
282
+ limit: { type: "integer", default: 5 },
283
+ },
284
+ required: ["query"],
285
+ },
286
+ },
287
+ ];
288
+
289
+ // ── Tool Handlers ──────────────────────────────────────────────────────
290
+
291
+ async function handleTool(name, args) {
292
+ switch (name) {
293
+ case "search_expenses":
294
+ return formatResult(
295
+ await client.execute("query_expenses", args)
296
+ );
297
+
298
+ case "get_spending_summary":
299
+ return formatResult(
300
+ await client.execute("query_analytics", {
301
+ ...args,
302
+ message: args.query || JSON.stringify(args),
303
+ })
304
+ );
305
+
306
+ case "get_deep_analytics":
307
+ return formatResult(
308
+ await client.execute("query_analytics", {
309
+ ...args,
310
+ message: args.query,
311
+ forceIntelligent: true,
312
+ })
313
+ );
314
+
315
+ case "create_report":
316
+ return formatResult(await client.execute("create_report", args));
317
+
318
+ case "list_reports":
319
+ return formatResult(await client.execute("list_reports", args));
320
+
321
+ case "get_report_details":
322
+ return formatResult(await client.execute("get_report_details", args));
323
+
324
+ case "share_report":
325
+ return formatResult(await client.execute("share_report", args));
326
+
327
+ case "check_compliance":
328
+ return formatResult(
329
+ await client.execute("help_compliance", {
330
+ reportId: args.reportId,
331
+ })
332
+ );
333
+
334
+ case "fix_compliance":
335
+ return formatResult(await client.execute("batch_fix", args));
336
+
337
+ case "check_tax_deductibility":
338
+ return formatResult(
339
+ await client.execute("tax_query", {
340
+ message: args.query,
341
+ category: args.category,
342
+ merchant: args.merchant,
343
+ })
344
+ );
345
+
346
+ case "search_knowledge":
347
+ return formatResult(
348
+ await client.execute("search_knowledge", args)
349
+ );
350
+
351
+ default:
352
+ return {
353
+ content: [{ type: "text", text: `Unknown tool: ${name}` }],
354
+ isError: true,
355
+ };
356
+ }
357
+ }
358
+
359
+ function formatResult(result) {
360
+ // Extract the meaningful content
361
+ let text;
362
+ if (result.message && typeof result.message === "string") {
363
+ text = result.message;
364
+ } else if (result.data) {
365
+ text = JSON.stringify(result.data, null, 2);
366
+ } else {
367
+ text = JSON.stringify(result, null, 2);
368
+ }
369
+
370
+ // Append structured data if present
371
+ if (result.data && result.message) {
372
+ text += "\n\n---\nRaw data:\n" + JSON.stringify(result.data, null, 2);
373
+ }
374
+
375
+ return {
376
+ content: [{ type: "text", text }],
377
+ isError: result.success === false,
378
+ };
379
+ }
380
+
381
+ // ── MCP Server Setup ───────────────────────────────────────────────────
382
+
383
+ async function main() {
384
+ const server = new Server(
385
+ { name: "expensebot-auth", version: "0.1.0" },
386
+ { capabilities: { tools: {} } }
387
+ );
388
+
389
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
390
+ tools: TOOLS,
391
+ }));
392
+
393
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
394
+ const { name, arguments: args } = request.params;
395
+ try {
396
+ return await handleTool(name, args || {});
397
+ } catch (err) {
398
+ return {
399
+ content: [
400
+ {
401
+ type: "text",
402
+ text: `Error: ${err.message}`,
403
+ },
404
+ ],
405
+ isError: true,
406
+ };
407
+ }
408
+ });
409
+
410
+ const transport = new StdioServerTransport();
411
+ await server.connect(transport);
412
+ console.error(
413
+ `[expensebot-auth] MCP server ready. tools=${TOOLS.length}, base=${client.baseUrl}`
414
+ );
415
+ }
416
+
417
+ main().catch((err) => {
418
+ console.error("[expensebot-auth] fatal:", err);
419
+ process.exit(1);
420
+ });