chaimi-bookkeeping-mcp 2.3.6 → 2.3.7

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 (2) hide show
  1. package/package.json +1 -1
  2. package/server.js +695 -85
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chaimi-bookkeeping-mcp",
3
- "version": "2.3.6",
3
+ "version": "2.3.7",
4
4
  "description": "柴米记账 MCP Server - 支持 Claude、Cursor、OpenClaw、WorkBuddy 等 AI 工具直接记账",
5
5
  "main": "server.js",
6
6
  "bin": {
package/server.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
3
  * 柴米记账 MCP Server (Node.js 版本)
4
+ * 适配微信云函数 mcpHub
4
5
  * 支持 Claude Desktop、Cursor、WorkBuddy、OpenClaw
5
6
  */
6
7
 
@@ -17,20 +18,60 @@ const {
17
18
  CallToolRequestSchema,
18
19
  ListToolsRequestSchema,
19
20
  } = require('@modelcontextprotocol/sdk/types.js');
20
- const fs = require('fs');
21
21
  const path = require('path');
22
+ const os = require('os');
23
+ const fs = require('fs');
22
24
 
23
- // 读取 package.json 获取版本号
25
+ // 读取 package.json 获取版本
24
26
  const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
25
27
  const MCP_VERSION = packageJson.version;
28
+ console.log('柴米记账 MCP Server 版本:', MCP_VERSION);
29
+
30
+ // 导入 OAuth 模块
31
+ const { OAuthManager, FileTokenStorage } = require('./oauth.js');
32
+
33
+ // 配置 - 微信云函数
34
+ const MCP_HUB_URL = process.env.MCP_HUB_URL || 'https://cloud1-2gfe5jhjef06b85d-1412172089.ap-shanghai.app.tcloudbase.com/mcpHub-mcp';
35
+ const MCP_PROMPT_URL = process.env.MCP_PROMPT_URL || 'https://cloud1-2gfe5jhjef06b85d-1412172089.ap-shanghai.app.tcloudbase.com/mcpPrompt';
36
+ const MCP_OAUTH_URL = process.env.MCP_OAUTH_URL || 'https://cloud1-2gfe5jhjef06b85d-1412172089.ap-shanghai.app.tcloudbase.com/mcpOAuth';
37
+
38
+ // Token 缓存
39
+ let cachedToken = null;
40
+ let tokenExpireTime = 0;
41
+
42
+ // OAuth 管理器实例
43
+ let oauthManager = null;
44
+
45
+ // 初始化 OAuth 管理器
46
+ function initOAuthManager() {
47
+ const tokenStorage = new FileTokenStorage(
48
+ path.join(os.homedir(), '.mcporter', 'oauth-token.json')
49
+ );
50
+
51
+ oauthManager = new OAuthManager({
52
+ mcpOAuthUrl: MCP_OAUTH_URL,
53
+ tokenStorage: tokenStorage,
54
+ onQrCode: (qrData) => {
55
+ // 显示授权信息
56
+ console.log('\n========================================');
57
+ console.log('🔐 请完成授权');
58
+ console.log('========================================');
59
+ console.log(`验证码: ${qrData.userCode}`);
60
+ console.log(`验证地址: ${qrData.verificationUri}`);
61
+ console.log('========================================\n');
62
+ },
63
+ onTokenReady: (token) => {
64
+ console.log('✅ Token 已就绪,可以开始使用');
65
+ }
66
+ });
26
67
 
27
- // 配置
28
- const SCF_URL = process.env.SCF_URL || 'https://1412172089-4wbwsop8pe.ap-shanghai.tencentscf.com';
68
+ return oauthManager;
69
+ }
29
70
 
30
71
  // 创建 MCP Server
31
72
  const server = new Server(
32
73
  {
33
- name: 'chaihuo-mcp-server',
74
+ name: 'chaimi-bookkeeping-mcp',
34
75
  version: MCP_VERSION,
35
76
  },
36
77
  {
@@ -44,19 +85,42 @@ const server = new Server(
44
85
  server.setRequestHandler(ListToolsRequestSchema, async () => {
45
86
  return {
46
87
  tools: [
88
+ /*
89
+ {
90
+ name: 'quick_book',
91
+ description: '【推荐首选】极简快捷记账 - 自动识别支出/收入,智能匹配分类。仅需 name 和 amount 两个参数,其他自动补全。输入如:"午餐 30 元"、"工资 8000 元"、"木屋烧烤 35 元"',
92
+ inputSchema: {
93
+ type: 'object',
94
+ properties: {
95
+ name: { type: 'string', description: '商品/服务名称或自然语言描述(必填)' },
96
+ amount: { type: 'number', description: '金额(必填)' },
97
+ category: { type: 'string', description: '分类(可选,系统自动推荐)' },
98
+ store: { type: 'string', description: '商家名称(可选)' },
99
+ note: { type: 'string', description: '备注(可选)' },
100
+ agentType: { type: 'string', description: '【推荐自动填充】Agent类型,如:claude-desktop、cursor、openclaw、workbuddy、trae' },
101
+ apiProvider: { type: 'string', description: '【推荐自动填充】AI服务提供商,如:anthropic、openai、doubao、aliyun' },
102
+ rawInput: { type: 'string', description: '【推荐自动填充】用户的原始输入内容,用于记录用户原始请求' },
103
+ mcp_version: { type: 'string', description: 'MCP Server 版本号(自动填充)' },
104
+ },
105
+ required: ['name', 'amount'],
106
+ },
107
+ },
108
+ */
47
109
  {
48
110
  name: 'save_expense',
49
- description: '保存单商品消费记录(AI文字记账)',
111
+ description: '保存单商品消费记录(AI文字记账)。只需提供商品名称和金额,其他参数自动填充。示例:name="午餐", amount=35',
50
112
  inputSchema: {
51
113
  type: 'object',
52
114
  properties: {
53
- name: { type: 'string', description: '商品名称' },
54
- amount: { type: 'number', description: '金额' },
55
- category: { type: 'string', description: '分类(如:餐饮、食品、交通)' },
56
- store: { type: 'string', description: '商家名称' },
115
+ name: { type: 'string', description: '商品名称(必填)' },
116
+ amount: { type: 'number', description: '金额(必填)' },
117
+ category: { type: 'string', description: '分类(可选,如:餐饮、食品、交通)' },
118
+ store: { type: 'string', description: '商家名称(可选)' },
119
+ note: { type: 'string', description: '备注(可选)' },
57
120
  agentType: { type: 'string', description: '【推荐自动填充】Agent类型,如:claude-desktop、cursor、openclaw、workbuddy、trae' },
58
121
  apiProvider: { type: 'string', description: '【推荐自动填充】AI服务提供商,如:anthropic、openai、doubao、aliyun' },
59
122
  rawInput: { type: 'string', description: '【推荐自动填充】用户的原始输入内容,用于记录用户原始请求' },
123
+ mcp_version: { type: 'string', description: 'MCP Server 版本号(自动填充)' },
60
124
  },
61
125
  required: ['name', 'amount'],
62
126
  },
@@ -75,28 +139,29 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
75
139
  actualAmount: { type: 'number', description: '实付金额' },
76
140
  paymentMethod: { type: 'string', description: '支付方式' },
77
141
  receiptNo: { type: 'string', description: '小票编号' },
78
- agentType: { type: 'string', description: '【推荐自动填充】Agent类型,如:claude-desktop、cursor、openclaw、workbuddy、trae' },
79
- apiProvider: { type: 'string', description: '【推荐自动填充】AI服务提供商,如:anthropic、openai、doubao、aliyun' },
80
- rawInput: { type: 'string', description: '【推荐自动填充】用户的原始输入内容,用于记录用户原始请求' },
81
142
  items: {
82
143
  type: 'array',
83
- description: '商品列表',
144
+ description: '商品列表(必须是数组格式,如:[{"name":"苹果","amount":5.5,"price":5.5,"quantity":1}],不要传JSON字符串)',
84
145
  items: {
85
146
  type: 'object',
86
147
  properties: {
87
148
  name: { type: 'string', description: '商品名称' },
88
149
  originalName: { type: 'string', description: '原始商品名称' },
89
150
  price: { type: 'number', description: '单价' },
90
- quantity: { type: 'string', description: '数量' },
151
+ quantity: { type: 'number', description: '数量' },
91
152
  unit: { type: 'string', description: '单位' },
92
153
  amount: { type: 'number', description: '金额' },
93
154
  weight: { type: 'string', description: '重量' },
94
155
  marketPrice: { type: 'string', description: '市场单价' },
95
156
  category: { type: 'string', description: '分类' },
96
157
  },
97
- required: ['name', 'amount'],
158
+ required: ['name', 'amount', 'price', 'quantity'],
98
159
  },
99
160
  },
161
+ agentType: { type: 'string', description: '【推荐自动填充】Agent类型,如:claude-desktop、cursor、openclaw、workbuddy、trae' },
162
+ apiProvider: { type: 'string', description: '【推荐自动填充】AI服务提供商,如:anthropic、openai、doubao、aliyun' },
163
+ rawInput: { type: 'string', description: '【推荐自动填充】用户的原始输入内容,用于记录用户原始请求' },
164
+ mcp_version: { type: 'string', description: 'MCP Server 版本号(自动填充)' },
100
165
  },
101
166
  required: ['store', 'items'],
102
167
  },
@@ -109,9 +174,6 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
109
174
  properties: {
110
175
  limit: { type: 'number', description: '返回数量限制', default: 10 },
111
176
  source: { type: 'string', description: '来源筛选' },
112
- agentType: { type: 'string', description: '【推荐自动填充】Agent类型,如:claude-desktop、cursor、openclaw、workbuddy、trae' },
113
- apiProvider: { type: 'string', description: '【推荐自动填充】AI服务提供商,如:anthropic、openai、doubao、aliyun' },
114
- rawInput: { type: 'string', description: '【推荐自动填充】用户的原始输入内容,用于记录用户原始请求' },
115
177
  },
116
178
  },
117
179
  },
@@ -122,9 +184,6 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
122
184
  type: 'object',
123
185
  properties: {
124
186
  limit: { type: 'number', description: '返回数量限制', default: 5 },
125
- agentType: { type: 'string', description: '【推荐自动填充】Agent类型,如:claude-desktop、cursor、openclaw、workbuddy、trae' },
126
- apiProvider: { type: 'string', description: '【推荐自动填充】AI服务提供商,如:anthropic、openai、doubao、aliyun' },
127
- rawInput: { type: 'string', description: '【推荐自动填充】用户的原始输入内容,用于记录用户原始请求' },
128
187
  },
129
188
  },
130
189
  },
@@ -136,76 +195,427 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
136
195
  properties: {
137
196
  yearMonth: { type: 'string', description: '年月(如:2026-03)' },
138
197
  type: { type: 'string', description: '统计类型:item/receipt/category' },
139
- agentType: { type: 'string', description: '【推荐自动填充】Agent类型,如:claude-desktop、cursor、openclaw、workbuddy、trae' },
140
- apiProvider: { type: 'string', description: '【推荐自动填充】AI服务提供商,如:anthropic、openai、doubao、aliyun' },
141
- rawInput: { type: 'string', description: '【推荐自动填充】用户的原始输入内容,用于记录用户原始请求' },
142
198
  },
143
199
  required: ['yearMonth'],
144
200
  },
145
201
  },
202
+ {
203
+ name: 'save_income',
204
+ description: '保存收入记录(工资、奖金、红包等)',
205
+ inputSchema: {
206
+ type: 'object',
207
+ properties: {
208
+ name: { type: 'string', description: '收入来源(如:工资、奖金、红包)' },
209
+ amount: { type: 'number', description: '收入金额' },
210
+ category: { type: 'string', description: '收入分类(如:工资、奖金、投资)' },
211
+ store: { type: 'string', description: '付款方(如:公司名称)' },
212
+ note: { type: 'string', description: '备注' },
213
+ agentType: { type: 'string', description: 'Agent 类型(如:workbuddy、claude、cursor)' },
214
+ apiProvider: { type: 'string', description: 'AI 提供商' },
215
+ rawInput: { type: 'string', description: '用户原始输入' },
216
+ mcp_version: { type: 'string', description: 'MCP Server 版本号(自动填充)' },
217
+ },
218
+ required: ['name', 'amount'],
219
+ },
220
+ },
146
221
  ],
147
222
  };
148
223
  });
149
224
 
225
+ // 工具名称映射:SCF action -> mcpHub tool
226
+ const toolMapping = {
227
+ 'quick_book': 'addExpense', // quick_book 内部会判断支出/收入
228
+ 'save_expense': 'addExpense',
229
+ 'save_receipt': 'addReceipt',
230
+ 'save_income': 'addIncome',
231
+ 'get_expenses': 'getExpenses',
232
+ 'get_receipt_list': 'getExpenses',
233
+ 'get_statistics': 'getStatistics',
234
+ };
235
+
236
+ // 获取或刷新 Token(OAuth 2.0 Device Flow)
237
+ // 自动刷新周期:2小时(测试用,生产环境建议24小时)
238
+ const TOKEN_REFRESH_INTERVAL = 2 * 60 * 60 * 1000; // 2小时
239
+ let lastRefreshTime = 0;
240
+
241
+ async function getToken() {
242
+ // 检查缓存的 Token 是否有效(提前5分钟过期)
243
+ if (cachedToken && tokenExpireTime > Date.now() + 5 * 60 * 1000) {
244
+ // 检查是否需要主动刷新(超过24小时)
245
+ if (Date.now() - lastRefreshTime < TOKEN_REFRESH_INTERVAL) {
246
+ return cachedToken;
247
+ }
248
+ // 超过2小时,尝试刷新
249
+ console.log('Token 超过2小时,尝试自动刷新...');
250
+ } else if (cachedToken && tokenExpireTime <= Date.now() + 5 * 60 * 1000) {
251
+ // Token 已过期,添加友好提示
252
+ console.log('🔐 Token 已过期,需要重新授权');
253
+ console.log('请使用 mcporter 调用 柴米记账.save_expense() 开始授权');
254
+ }
255
+
256
+ // 使用 OAuth 获取有效 Token
257
+ if (!oauthManager) {
258
+ throw new Error('OAuth 管理器未初始化,请检查 MCP_OAUTH_URL 配置');
259
+ }
260
+
261
+ try {
262
+ const oauthToken = await oauthManager.getValidToken();
263
+ cachedToken = oauthToken.accessToken;
264
+ tokenExpireTime = oauthToken.expiresAt;
265
+ lastRefreshTime = Date.now();
266
+ // 授权成功,清除授权状态
267
+ await oauthManager.clearAuthState();
268
+ return cachedToken;
269
+ } catch (err) {
270
+ // OAuth Token 无效,检查是否有未完成的授权
271
+ console.log('🔐 Token 已过期,需要重新授权');
272
+ console.log('请使用 mcporter 调用 柴米记账.save_expense() 开始授权');
273
+ console.log('OAuth Token 无效,检查授权状态...');
274
+
275
+ // 检查是否有未完成的授权
276
+ const authState = await oauthManager.loadAuthState();
277
+ if (authState && !oauthManager.isAuthStateExpired(authState)) {
278
+ console.log(`检测到未完成的授权,验证码: ${authState.userCode}`);
279
+ console.log('请在微信柴米记账小程序中输入此验证码完成授权');
280
+ console.log('授权完成后,请重新调用工具');
281
+ throw new Error(`授权进行中,请使用验证码 ${authState.userCode} 完成授权`);
282
+ }
283
+
284
+ // 没有未完成的授权,启动新的授权流程
285
+ console.log('启动新的授权流程...');
286
+ const newToken = await oauthManager.startAuthFlow();
287
+ cachedToken = newToken.accessToken;
288
+ tokenExpireTime = newToken.expiresAt;
289
+ lastRefreshTime = Date.now();
290
+ // 授权成功,清除授权状态
291
+ await oauthManager.clearAuthState();
292
+ return cachedToken;
293
+ }
294
+ }
295
+
296
+ // 调用 mcpPrompt 云函数(获取 Prompt 或校验数据)
297
+ async function callMcpPrompt(tool, params, token) {
298
+ const response = await fetch(MCP_PROMPT_URL, {
299
+ method: 'POST',
300
+ headers: {
301
+ 'Content-Type': 'application/json',
302
+ 'Authorization': `Bearer ${token}`,
303
+ },
304
+ body: JSON.stringify({
305
+ tool: tool,
306
+ params: params,
307
+ }),
308
+ });
309
+
310
+ if (!response.ok) {
311
+ const errorText = await response.text();
312
+ throw new Error(`mcpPrompt 调用失败: ${errorText}`);
313
+ }
314
+
315
+ return await response.json();
316
+ }
317
+
318
+ // 调用 mcpHub 云函数
319
+ async function callMcpHub(tool, params, token) {
320
+ const response = await fetch(MCP_HUB_URL, {
321
+ method: 'POST',
322
+ headers: {
323
+ 'Content-Type': 'application/json',
324
+ 'Authorization': `Bearer ${token}`,
325
+ },
326
+ body: JSON.stringify({
327
+ tool: tool,
328
+ params: params,
329
+ }),
330
+ });
331
+
332
+ if (!response.ok) {
333
+ const errorText = await response.text();
334
+ throw new Error(`mcpHub 调用失败: ${errorText}`);
335
+ }
336
+
337
+ return await response.json();
338
+ }
339
+
150
340
  // 工具调用处理
151
341
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
152
342
  const { name, arguments: args } = request.params;
153
343
 
154
- // 调试日志
155
- console.error('收到工具调用请求:', name);
156
- console.error('原始参数:', JSON.stringify(args, null, 2));
344
+ // 【强制日志】测试日志是否输出 - 写入文件
345
+ const fs = require('fs');
157
346
 
158
- try {
159
- // 获取 Token(这里需要实现 Token 生成逻辑)
160
- const token = await generateToken();
347
+ // 从环境变量获取 agentType 和 apiProvider
348
+ const agentTypeFromEnv = process.env.AGENT_TYPE || process.env.MCP_AGENT_TYPE || '';
349
+ const apiProviderFromEnv = process.env.API_PROVIDER || process.env.MCP_API_PROVIDER || '';
350
+
351
+ // 如果参数中没有,使用环境变量的值
352
+ if (!args.agentType && agentTypeFromEnv) {
353
+ args.agentType = agentTypeFromEnv;
354
+ }
355
+ if (!args.apiProvider && apiProviderFromEnv) {
356
+ args.apiProvider = apiProviderFromEnv;
357
+ }
161
358
 
162
- // SCF 使用下划线命名,直接传递工具名
163
- const action = name;
359
+ const logMsg = `
360
+ [${new Date().toISOString()}] MCP 工具被调用
361
+ 工具名称: ${name}
362
+ 参数: ${JSON.stringify(args, null, 2)}
363
+ 环境变量 AGENT_TYPE: ${agentTypeFromEnv || '(未设置)'}
364
+ 环境变量 API_PROVIDER: ${apiProviderFromEnv || '(未设置)'}
365
+ `;
366
+ fs.appendFileSync('/tmp/mcp-debug.log', logMsg);
367
+ console.error(logMsg);
164
368
 
165
- // 处理参数 - 将字符串格式的 items 转换为数组
369
+ try {
370
+ // 获取 Token
371
+ const token = await getToken();
372
+
373
+ // 处理参数
166
374
  const processedArgs = { ...args };
167
375
  if (processedArgs.items && typeof processedArgs.items === 'string') {
168
376
  try {
169
377
  processedArgs.items = JSON.parse(processedArgs.items);
170
- console.error('items 解析成功:', processedArgs.items);
171
378
  } catch (e) {
172
- // 如果解析失败,保持原样
173
- console.error('解析 items 失败:', e);
379
+ // 解析失败,保持原样
174
380
  }
175
381
  }
176
382
 
177
- console.error('处理后参数:', JSON.stringify(processedArgs, null, 2));
178
383
 
179
- // 调用 SCF
180
- const response = await fetch(SCF_URL, {
181
- method: 'POST',
182
- headers: {
183
- 'Content-Type': 'application/json',
184
- 'Authorization': `Bearer ${token}`,
185
- },
186
- body: JSON.stringify({
187
- action: action,
188
- data: processedArgs,
189
- }),
190
- });
191
-
192
- const result = await response.json();
193
-
194
- // 检查是否传递了agentType和apiProvider参数,如果没有则添加提示
195
- let responseText = JSON.stringify(result, null, 2);
196
- if (!processedArgs.agentType || !processedArgs.apiProvider) {
197
- responseText += '\n\n💡 提示:传递agentType和apiProvider参数可解锁小程序记录来源统计功能,示例:agentType="openclaw", apiProvider="doubao"';
384
+
385
+ let result;
386
+ let userMessage;
387
+
388
+ // 【调试日志】打印原始传入参数
389
+ console.error('\n========== MCP 参数调试日志 ==========');
390
+ console.error('工具名称:', name);
391
+ console.error('原始参数 agentType:', args.agentType || '(未传入)');
392
+ console.error('原始参数 apiProvider:', args.apiProvider || '(未传入)');
393
+ console.error('原始参数 rawInput:', args.rawInput ? args.rawInput.substring(0, 50) + '...' : '(未传入)');
394
+ console.error('原始参数 llm_provider:', args.llm_provider || '(未传入)');
395
+ console.error('原始参数 store:', args.store || '(未传入)');
396
+ console.error('======================================\n');
397
+
398
+ // 根据工具类型选择处理流程
399
+ switch (name) {
400
+ /*
401
+ case 'quick_book': {
402
+ // 极简快捷记账:自动识别支出/收入,智能匹配分类
403
+ console.log('处理极简快捷记账...');
404
+
405
+ // 1. 从环境变量补充参数(确保上报)
406
+ const agentType = process.env.AGENT_TYPE || process.env.MCP_AGENT_TYPE || args.agentType || '';
407
+ const apiProvider = process.env.API_PROVIDER || process.env.MCP_API_PROVIDER || args.apiProvider || '';
408
+ const rawInput = args.rawInput || args.name;
409
+
410
+ // 2. 判断是支出还是收入
411
+ const isIncome = isIncomeName(args.name);
412
+
413
+ // 3. 智能匹配分类
414
+ const category = args.category || getCategory(args.name);
415
+
416
+ // 4. 自动补全参数
417
+ const completedArgs = {
418
+ name: sanitizeString(args.name, 100),
419
+ amount: validateAmount(args.amount),
420
+ price: args.price || validateAmount(args.amount),
421
+ quantity: args.quantity || 1,
422
+ unit: args.unit || '个',
423
+ category: category,
424
+ store: sanitizeString(args.store, 100) || '未知商家',
425
+ note: sanitizeString(args.note, 500),
426
+ agentType: agentType,
427
+ apiProvider: apiProvider,
428
+ rawInput: rawInput,
429
+ mcp_version: MCP_VERSION,
430
+ };
431
+
432
+ // 5. 根据类型选择接口
433
+ if (isIncome) {
434
+ // 收入记账
435
+ console.log('识别为收入,调用 save_income...');
436
+ const mcpParams = convertParams('save_income', completedArgs);
437
+ result = await callMcpHub('addIncome', mcpParams, token);
438
+
439
+ if (result.success) {
440
+ userMessage = `✅ 记账成功\n\n| 收入来源 | 金额 | 分类 |\n|------|------|------|\n| ${completedArgs.name} | ${completedArgs.amount}元 | ${completedArgs.category || '其他收入'} |\n\n已保存到你的柴米记账小程序数据库。`;
441
+ }
442
+ } else {
443
+ // 支出记账
444
+ console.log('识别为支出,调用 save_expense...');
445
+ const mcpParams = convertParams('save_expense', completedArgs);
446
+ result = await callMcpHub('addExpense', mcpParams, token);
447
+
448
+ if (result.success) {
449
+ userMessage = `✅ 记账成功\n\n| 商品 | 金额 | 分类 | 商家 |\n|------|------|------|------|\n| ${completedArgs.name} | ${completedArgs.amount}元 | ${completedArgs.category || '其他'} | ${completedArgs.store} |\n\n已保存到你的柴米记账小程序数据库。`;
450
+ }
451
+ }
452
+ break;
453
+ }
454
+ */
455
+
456
+ case 'save_expense': {
457
+ // 步骤1:校验数据完整性
458
+ console.log('校验消费数据完整性...');
459
+ const validationResult = await callMcpPrompt(
460
+ 'validateResult',
461
+ {
462
+ data: processedArgs,
463
+ type: 'parseText'
464
+ },
465
+ token
466
+ );
467
+
468
+ if (validationResult.success && !validationResult.data.valid) {
469
+ console.log('数据不完整,尝试补充默认值:', validationResult.data);
470
+ // 调用 fillDefaults 补充缺失字段
471
+ const fillResult = await callMcpPrompt(
472
+ 'fillDefaults',
473
+ {
474
+ data: processedArgs,
475
+ type: 'parseText'
476
+ },
477
+ token
478
+ );
479
+
480
+ if (fillResult.success) {
481
+ processedArgs = fillResult.data;
482
+ console.log('补充后的数据:', processedArgs);
483
+ }
484
+ }
485
+
486
+ // 步骤2:转换参数并调用 mcpHub 保存
487
+ const mcpParams = convertParams('save_expense', processedArgs);
488
+ result = await callMcpHub('addExpense', mcpParams, token);
489
+
490
+ // 格式化输出
491
+ if (result.success) {
492
+ const displayName = processedArgs.name || '未知商品';
493
+ const displayAmount = processedArgs.amount || 0;
494
+ const displayCategory = processedArgs.category || '其他';
495
+ const displayStore = processedArgs.store || '-';
496
+ userMessage = `✅ 记账成功\n\n| 商品 | 金额 | 分类 | 商家 |\n|------|------|------|------|\n| ${displayName} | ${displayAmount}元 | ${displayCategory} | ${displayStore} |\n\n已保存到你的柴米记账小程序数据库。`;
497
+
498
+ // 提示Agent可以传递agentType和apiProvider参数
499
+ if (!processedArgs.agentType || !processedArgs.apiProvider) {
500
+ userMessage += '\n\n💡 提示:传递agentType和apiProvider参数可解锁小程序记录来源统计功能,示例:agentType="openclaw", apiProvider="doubao"';
501
+ }
502
+ }
503
+ break;
504
+ }
505
+
506
+ case 'save_receipt': {
507
+ // 步骤1:校验数据完整性
508
+ console.log('校验小票数据完整性...');
509
+ const validationResult = await callMcpPrompt(
510
+ 'validateResult',
511
+ {
512
+ data: processedArgs,
513
+ type: 'parseReceipt'
514
+ },
515
+ token
516
+ );
517
+
518
+ if (validationResult.success && !validationResult.data.valid) {
519
+ console.log('数据不完整,尝试补充默认值:', validationResult.data);
520
+ // 调用 fillDefaults 补充缺失字段
521
+ const fillResult = await callMcpPrompt(
522
+ 'fillDefaults',
523
+ {
524
+ data: processedArgs,
525
+ type: 'parseReceipt'
526
+ },
527
+ token
528
+ );
529
+
530
+ if (fillResult.success) {
531
+ processedArgs = fillResult.data;
532
+ console.log('补充后的数据:', processedArgs);
533
+ }
534
+ }
535
+
536
+ // 步骤2:转换参数并调用 mcpHub 保存
537
+ const mcpParams = convertParams('save_receipt', processedArgs);
538
+ result = await callMcpHub('addReceipt', mcpParams, token);
539
+
540
+ // 格式化输出
541
+ if (result.success) {
542
+ const totalAmount = processedArgs.totalAmount || processedArgs.items?.reduce((sum, item) => sum + (item.amount || 0), 0) || 0;
543
+ const itemsList = processedArgs.items?.map(item => `• ${item.name || '未知商品'} - ${item.amount || 0}元`).join('\n') || '暂无商品明细';
544
+ const storeName = processedArgs.store || '-';
545
+ const category = processedArgs.items?.[0]?.category || '其他';
546
+ userMessage = `✅ 小票记录成功\n\n| 项目 | 内容 |\n|------|------|\n| 商家 | ${storeName} |\n| 金额 | ${totalAmount}元 |\n| 分类 | ${category} |\n\n商品明细:\n${itemsList}\n\n已保存到你的柴米记账小程序数据库。`;
547
+
548
+ // 提示Agent可以传递agentType和apiProvider参数
549
+ if (!processedArgs.agentType || !processedArgs.apiProvider) {
550
+ userMessage += '\n\n💡 提示:传递agentType和apiProvider参数可解锁小程序记录来源统计功能,示例:agentType="openclaw", apiProvider="doubao"';
551
+ }
552
+ }
553
+ break;
554
+ }
555
+
556
+ case 'get_expenses':
557
+ case 'get_receipt_list': {
558
+ // 查询类工具直接调用 mcpHub
559
+ const toolName = toolMapping[name];
560
+ const mcpParams = convertParams(name, processedArgs);
561
+ result = await callMcpHub(toolName, mcpParams, token);
562
+
563
+ if (result.success) {
564
+ userMessage = `📊 消费记录查询成功\n共找到 ${result.data?.length || 0} 条记录`;
565
+ }
566
+ break;
567
+ }
568
+
569
+ case 'get_statistics': {
570
+ // 查询类工具直接调用 mcpHub
571
+ const toolName = toolMapping[name];
572
+ const mcpParams = convertParams(name, processedArgs);
573
+ result = await callMcpHub(toolName, mcpParams, token);
574
+
575
+ if (result.success) {
576
+ userMessage = `📈 统计查询成功`;
577
+ }
578
+ break;
579
+ }
580
+
581
+ case 'save_income': {
582
+ // 收入记录直接调用 mcpHub
583
+ const mcpParams = convertParams('save_income', processedArgs);
584
+ result = await callMcpHub('addIncome', mcpParams, token);
585
+
586
+ // 格式化输出
587
+ if (result.success) {
588
+ const displayName = processedArgs.name || '未知来源';
589
+ const displayAmount = processedArgs.amount || 0;
590
+ const displayCategory = processedArgs.category || '其他';
591
+ const displayStore = processedArgs.store || '-';
592
+ userMessage = `✅ 收入记录成功\n\n| 来源 | 金额 | 分类 | 付款方 |\n|------|------|------|--------|\n| ${displayName} | ${displayAmount}元 | ${displayCategory} | ${displayStore} |`;
593
+ }
594
+ break;
595
+ }
596
+
597
+ default:
598
+ throw new Error(`未知工具: ${name}`);
599
+ }
600
+
601
+ // 处理错误
602
+ if (!result.success) {
603
+ userMessage = `❌ 操作失败:${result.error || '未知错误'}`;
198
604
  }
199
605
 
606
+ // 添加版本信息提示
607
+ userMessage += `\n\n---\n📦 柴米记账 MCP v${MCP_VERSION}`;
608
+
200
609
  return {
201
610
  content: [
202
611
  {
203
612
  type: 'text',
204
- text: responseText,
613
+ text: userMessage,
205
614
  },
206
615
  ],
207
616
  };
208
617
  } catch (error) {
618
+ console.error('工具调用错误:', error);
209
619
  return {
210
620
  content: [
211
621
  {
@@ -218,44 +628,244 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
218
628
  }
219
629
  });
220
630
 
221
- // 生成 JWT Token
222
- async function generateToken() {
223
- const JWT_SECRET = process.env.JWT_SECRET;
224
- const MCP_OPENID = process.env.MCP_OPENID;
225
-
226
- if (!JWT_SECRET) {
227
- throw new Error('JWT_SECRET 环境变量未设置');
228
- }
631
+ // 输入验证和过滤函数
632
+ function sanitizeString(str, maxLength = 200) {
633
+ if (!str || typeof str !== 'string') return '';
634
+ // 去除 HTML 标签,防止 XSS
635
+ return str.replace(/<[^>]*>/g, '').substring(0, maxLength);
636
+ }
637
+
638
+ function validateAmount(amount) {
639
+ const num = parseFloat(amount);
640
+ return isNaN(num) || num < 0 ? 0 : num;
641
+ }
642
+
643
+ function validateQuantity(quantity) {
644
+ const num = parseFloat(quantity);
645
+ return isNaN(num) || num <= 0 ? 1 : num;
646
+ }
647
+
648
+ // 从重量字符串中提取克数
649
+ function extractWeightInGrams(weightStr) {
650
+ if (!weightStr || typeof weightStr !== 'string') return 0;
229
651
 
230
- if (!MCP_OPENID) {
231
- throw new Error('MCP_OPENID 环境变量未设置,请从小程序获取用户Token');
232
- }
652
+ // 匹配数字+单位,如 "300g", "2kg", "1.5斤"
653
+ const match = weightStr.match(/(\d+\.?\d*)\s*(g|kg|斤|克|千克)/i);
654
+ if (!match) return 0;
233
655
 
234
- // 使用 crypto 生成 JWT
235
- const crypto = require('crypto');
656
+ const value = parseFloat(match[1]);
657
+ const unit = match[2].toLowerCase();
236
658
 
237
- const header = { alg: 'HS256', typ: 'JWT' };
238
- const payload = {
239
- openid: MCP_OPENID, // 使用固定的用户 openid
240
- iat: Math.floor(Date.now() / 1000),
241
- exp: Math.floor(Date.now() / 1000) + 86400
242
- };
659
+ // 转换为克
660
+ switch (unit) {
661
+ case 'g':
662
+ case '克':
663
+ return value;
664
+ case 'kg':
665
+ case '千克':
666
+ return value * 1000;
667
+ case '斤':
668
+ return value * 500; // 1斤 = 500g
669
+ default:
670
+ return value;
671
+ }
672
+ }
673
+
674
+ // 计算市场单价(元/500g)
675
+ function calculateMarketPrice(amount, weightStr) {
676
+ const amountNum = parseFloat(amount);
677
+ const weightInGrams = extractWeightInGrams(weightStr);
243
678
 
244
- const h = Buffer.from(JSON.stringify(header)).toString('base64url');
245
- const p = Buffer.from(JSON.stringify(payload)).toString('base64url');
246
- const sig = crypto
247
- .createHmac('sha256', JWT_SECRET)
248
- .update(h + '.' + p)
249
- .digest('base64url');
679
+ if (isNaN(amountNum) || amountNum <= 0 || weightInGrams <= 0) {
680
+ return '';
681
+ }
250
682
 
251
- return `${h}.${p}.${sig}`;
683
+ // 计算每500g的价格
684
+ const pricePer500g = (amountNum / weightInGrams) * 500;
685
+ return `${pricePer500g.toFixed(2)}元/500g`;
686
+ }
687
+
688
+ // 参数转换函数
689
+ function convertParams(toolName, args) {
690
+ switch (toolName) {
691
+ case 'save_expense': {
692
+ // 必填参数校验
693
+ if (!args.name || typeof args.name !== 'string' || args.name.trim() === '') {
694
+ throw new Error('缺少必填参数:name(商品名称)');
695
+ }
696
+ if (args.amount === undefined || args.amount === null) {
697
+ throw new Error('缺少必填参数:amount(金额)');
698
+ }
699
+
700
+ const name = sanitizeString(args.name, 100);
701
+ const amount = validateAmount(args.amount);
702
+
703
+ return {
704
+ name: name,
705
+ originalName: name,
706
+ amount: amount,
707
+ price: amount, // 单价默认等于金额
708
+ quantity: 1, // 数量默认为1
709
+ category: sanitizeString(args.category, 50) || '其他',
710
+ store: sanitizeString(args.store, 100) || '',
711
+ type: 'expense',
712
+ unit: '',
713
+ weight: '',
714
+ marketPrice: '',
715
+ date: args.date,
716
+ note: sanitizeString(args.note, 500) || '',
717
+ rawInput: sanitizeString(args.rawInput, 1000) || '',
718
+ agentType: args.agentType || '',
719
+ apiProvider: args.apiProvider || '',
720
+ mcp_version: args.mcp_version || MCP_VERSION,
721
+ source: 'mcp_txt_expense',
722
+ };
723
+ }
724
+
725
+ case 'save_receipt': {
726
+ // 处理 items 可能是 JSON 字符串的情况
727
+ let items = args.items;
728
+ if (typeof items === 'string') {
729
+ try {
730
+ items = JSON.parse(items);
731
+ } catch (e) {
732
+ throw new Error('items 参数格式错误:必须是数组或 JSON 数组字符串');
733
+ }
734
+ }
735
+ if (!Array.isArray(items)) {
736
+ throw new Error('items 参数必须是数组');
737
+ }
738
+
739
+ return {
740
+ items: items.map((item, index) => {
741
+ const weight = sanitizeString(item.weight, 50);
742
+ const amount = validateAmount(item.amount);
743
+ // 优先使用传入的 marketPrice,如果没有则自动计算
744
+ const marketPrice = sanitizeString(item.marketPrice, 50) || calculateMarketPrice(amount, weight);
745
+
746
+ return {
747
+ itemIndex: index,
748
+ name: sanitizeString(item.name, 100),
749
+ originalName: sanitizeString(item.originalName, 200) || sanitizeString(item.name, 100),
750
+ amount: amount,
751
+ category: sanitizeString(item.category, 50) || '其他',
752
+ subCategory: sanitizeString(item.subCategory, 50) || '',
753
+ transactionType: item.transactionType || 'expense',
754
+ price: validateAmount(item.price),
755
+ quantity: item.quantity ? String(item.quantity).substring(0, 20) : '1',
756
+ unit: sanitizeString(item.unit, 20),
757
+ weight: weight,
758
+ marketPrice: marketPrice,
759
+ note: sanitizeString(item.note, 500),
760
+ };
761
+ }),
762
+ store: sanitizeString(args.store, 100),
763
+ receiptNo: sanitizeString(args.receiptNo, 50),
764
+ totalAmount: validateAmount(args.totalAmount),
765
+ originalAmount: validateAmount(args.originalAmount),
766
+ discountAmount: validateAmount(args.discountAmount),
767
+ actualAmount: validateAmount(args.actualAmount),
768
+ paymentMethod: sanitizeString(args.paymentMethod, 50),
769
+ memberCardNo: sanitizeString(args.memberCardNo, 50),
770
+ currentPoints: parseInt(args.currentPoints) || 0,
771
+ totalPoints: parseInt(args.totalPoints) || 0,
772
+ date: args.date,
773
+ rawInput: sanitizeString(args.rawInput, 2000),
774
+ agentType: args.agentType || '',
775
+ apiProvider: args.apiProvider || '',
776
+ mcp_version: args.mcp_version || MCP_VERSION,
777
+ source: 'mcp_receipt',
778
+ };
779
+ }
780
+
781
+ case 'get_expenses':
782
+ return {
783
+ limit: Math.min(parseInt(args.limit) || 10, 100),
784
+ source: args.source,
785
+ };
786
+
787
+ case 'get_statistics':
788
+ return {
789
+ startDate: args.yearMonth ? `${args.yearMonth}-01` : undefined,
790
+ endDate: args.yearMonth ? getMonthEndDate(args.yearMonth) : undefined,
791
+ type: args.type,
792
+ };
793
+
794
+ case 'save_income':
795
+ return {
796
+ name: sanitizeString(args.name, 100),
797
+ amount: validateAmount(args.amount),
798
+ category: sanitizeString(args.category, 50) || '其他',
799
+ store: sanitizeString(args.store, 100),
800
+ note: sanitizeString(args.note, 500),
801
+ transactionType: 'income',
802
+ rawInput: sanitizeString(args.rawInput, 1000),
803
+ agentType: args.agentType || '',
804
+ apiProvider: args.apiProvider || '',
805
+ mcp_version: args.mcp_version || MCP_VERSION,
806
+ source: 'mcp_txt_income',
807
+ };
808
+
809
+ default:
810
+ return args;
811
+ }
812
+ }
813
+
814
+ // 获取月份最后一天
815
+ function getMonthEndDate(yearMonth) {
816
+ const [year, month] = yearMonth.split('-').map(Number);
817
+ const lastDay = new Date(year, month, 0).getDate();
818
+ return `${yearMonth}-${lastDay}`;
252
819
  }
253
820
 
254
821
  // 启动服务器
255
822
  async function main() {
823
+ console.error('========================================');
824
+ console.error('柴米记账 MCP Server 启动中...');
825
+ console.error('========================================\n');
826
+
827
+ // 初始化 OAuth 管理器
828
+ console.error('🔄 初始化 OAuth 2.0 认证...');
829
+ initOAuthManager();
830
+
831
+ // 尝试加载已有 Token 或启动授权流程
832
+ try {
833
+ const existingToken = await oauthManager.tokenStorage.load();
834
+ if (existingToken) {
835
+ console.error('✅ 发现已存储的 OAuth Token');
836
+ // 验证 Token 是否有效
837
+ const validToken = await oauthManager.getValidToken();
838
+ console.error('✅ OAuth Token 验证通过');
839
+ cachedToken = validToken.accessToken;
840
+ tokenExpireTime = validToken.expiresAt;
841
+ } else {
842
+ console.error('\n⚠️ 首次使用,需要完成 OAuth 授权');
843
+ console.error('请按以下步骤操作:');
844
+ console.error('1. 等待授权信息出现');
845
+ console.error('2. 在小程序中完成授权');
846
+ console.error('3. 授权成功后即可使用\n');
847
+
848
+ // 启动授权流程(这会阻塞,直到授权完成)
849
+ const newToken = await oauthManager.startAuthFlow();
850
+ cachedToken = newToken.accessToken;
851
+ tokenExpireTime = newToken.expiresAt;
852
+ }
853
+ } catch (err) {
854
+ console.error('\n❌ OAuth 初始化失败:', err.message);
855
+ console.error('请检查 MCP_OAUTH_URL 配置是否正确\n');
856
+ throw err;
857
+ }
858
+
859
+ console.error('\n========================================');
860
+ console.error('启动 MCP Server...');
861
+ console.error('========================================\n');
862
+
256
863
  const transport = new StdioServerTransport();
257
864
  await server.connect(transport);
258
- console.error('柴米记账 MCP Server 已启动');
865
+ console.error('柴米记账 MCP Server 已启动');
866
+ console.error(`MCP_HUB_URL: ${MCP_HUB_URL}`);
867
+ console.error(`MCP_PROMPT_URL: ${MCP_PROMPT_URL}`);
868
+ console.error(`MCP_OAUTH_URL: ${MCP_OAUTH_URL}`);
259
869
  }
260
870
 
261
871
  main().catch(console.error);