chaimi-bookkeeping-mcp 2.3.4 → 2.3.6

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/README.md +7 -16
  2. package/package.json +1 -1
  3. package/server.js +89 -689
package/README.md CHANGED
@@ -70,22 +70,9 @@ MCP Server 会显示:
70
70
 
71
71
  ## 配置说明
72
72
 
73
- 如果使用手动安装,需要配置 `~/.mcporter/mcporter.json`:
74
-
75
- ```json
76
- {
77
- "mcpServers": {
78
- "柴米记账": {
79
- "command": "chaimi-bookkeeping-mcp",
80
- "env": {
81
- "MCP_OAUTH_URL": "https://cloud1-2gfe5jhjef06b85d-1412172089.ap-shanghai.app.tcloudbase.com/mcpOAuth",
82
- "MCP_HUB_URL": "https://cloud1-2gfe5jhjef06b85d-1412172089.ap-shanghai.app.tcloudbase.com/mcpHub-mcp",
83
- "MCP_PROMPT_URL": "https://cloud1-2gfe5jhjef06b85d-1412172089.ap-shanghai.app.tcloudbase.com/mcpPrompt"
84
- }
85
- }
86
- }
87
- }
88
- ```
73
+ npm 全局安装时会**自动配置**,无需手动操作。
74
+
75
+ 如需手动配置(如从 GitHub 下载安装),参考 `~/.mcporter/mcporter.json` 格式。
89
76
 
90
77
  ## 常见问题
91
78
 
@@ -141,6 +128,10 @@ AI 会自动调用 `save_income` 工具记录收入。
141
128
 
142
129
  ## 更新日志
143
130
 
131
+ ### v2.3.4 (2026-04-08)
132
+ - **简化** `save_expense` 工具,只保留 `name` 和 `amount` 为必填参数
133
+ - **优化** 其他参数使用默认值,简化 Agent 调用
134
+
144
135
  ### v2.3.3 (2026-04-08)
145
136
  - **修正** 版本号统一为 v2.3.3(包含 v2.3.2 的所有修复)
146
137
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chaimi-bookkeeping-mcp",
3
- "version": "2.3.4",
3
+ "version": "2.3.6",
4
4
  "description": "柴米记账 MCP Server - 支持 Claude、Cursor、OpenClaw、WorkBuddy 等 AI 工具直接记账",
5
5
  "main": "server.js",
6
6
  "bin": {
package/server.js CHANGED
@@ -1,7 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
3
  * 柴米记账 MCP Server (Node.js 版本)
4
- * 适配微信云函数 mcpHub
5
4
  * 支持 Claude Desktop、Cursor、WorkBuddy、OpenClaw
6
5
  */
7
6
 
@@ -18,60 +17,20 @@ const {
18
17
  CallToolRequestSchema,
19
18
  ListToolsRequestSchema,
20
19
  } = require('@modelcontextprotocol/sdk/types.js');
21
- const path = require('path');
22
- const os = require('os');
23
20
  const fs = require('fs');
21
+ const path = require('path');
24
22
 
25
- // 读取 package.json 获取版本
23
+ // 读取 package.json 获取版本号
26
24
  const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
27
25
  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
26
 
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
- });
67
-
68
- return oauthManager;
69
- }
27
+ // 配置
28
+ const SCF_URL = process.env.SCF_URL || 'https://1412172089-4wbwsop8pe.ap-shanghai.tencentscf.com';
70
29
 
71
30
  // 创建 MCP Server
72
31
  const server = new Server(
73
32
  {
74
- name: 'chaimi-bookkeeping-mcp',
33
+ name: 'chaihuo-mcp-server',
75
34
  version: MCP_VERSION,
76
35
  },
77
36
  {
@@ -85,49 +44,26 @@ const server = new Server(
85
44
  server.setRequestHandler(ListToolsRequestSchema, async () => {
86
45
  return {
87
46
  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 类型(如:workbuddy、claude、cursor)' },
101
- apiProvider: { type: 'string', description: 'AI 提供商' },
102
- rawInput: { type: 'string', description: '用户原始输入' },
103
- mcp_version: { type: 'string', description: 'MCP Server 版本号(自动填充)' },
104
- },
105
- required: ['name', 'amount'],
106
- },
107
- },
108
- */
109
47
  {
110
48
  name: 'save_expense',
111
- description: '保存单商品消费记录(AI文字记账)。只需提供商品名称和金额,其他参数自动填充。示例:name="午餐", amount=35',
49
+ description: '保存单商品消费记录(AI文字记账)',
112
50
  inputSchema: {
113
51
  type: 'object',
114
52
  properties: {
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: '备注(可选)' },
120
- agentType: { type: 'string', description: 'Agent 类型(可选,如:workbuddyclaudecursor)' },
121
- apiProvider: { type: 'string', description: 'AI 提供商(可选)' },
122
- rawInput: { type: 'string', description: '用户原始输入(可选)' },
123
- mcp_version: { type: 'string', description: 'MCP Server 版本号(自动填充)' },
53
+ name: { type: 'string', description: '商品名称' },
54
+ amount: { type: 'number', description: '金额' },
55
+ category: { type: 'string', description: '分类(如:餐饮、食品、交通)' },
56
+ store: { type: 'string', description: '商家名称' },
57
+ agentType: { type: 'string', description: '【推荐自动填充】Agent类型,如:claude-desktop、cursor、openclaw、workbuddy、trae' },
58
+ apiProvider: { type: 'string', description: '【推荐自动填充】AI服务提供商,如:anthropicopenaidoubao、aliyun' },
59
+ rawInput: { type: 'string', description: '【推荐自动填充】用户的原始输入内容,用于记录用户原始请求' },
124
60
  },
125
61
  required: ['name', 'amount'],
126
62
  },
127
63
  },
128
64
  {
129
65
  name: 'save_receipt',
130
- description: '保存小票(多商品记账)',
66
+ description: '【图片小票专用】保存购物小票/发票/收据(支持单商品或多商品)。当用户提供图片形式的小票、发票、收据、购物清单时,无论商品数量多少(1条或多条),都必须使用此接口。可自动识别商家名称、商品明细、金额、优惠等信息。典型场景:超市购物小票、餐厅发票、线上订单截图、手写收据照片等',
131
67
  inputSchema: {
132
68
  type: 'object',
133
69
  properties: {
@@ -139,29 +75,28 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
139
75
  actualAmount: { type: 'number', description: '实付金额' },
140
76
  paymentMethod: { type: 'string', description: '支付方式' },
141
77
  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: '【推荐自动填充】用户的原始输入内容,用于记录用户原始请求' },
142
81
  items: {
143
82
  type: 'array',
144
- description: '商品列表(必须是数组格式,如:[{"name":"苹果","amount":5.5,"price":5.5,"quantity":1}],不要传JSON字符串)',
83
+ description: '商品列表',
145
84
  items: {
146
85
  type: 'object',
147
86
  properties: {
148
87
  name: { type: 'string', description: '商品名称' },
149
88
  originalName: { type: 'string', description: '原始商品名称' },
150
89
  price: { type: 'number', description: '单价' },
151
- quantity: { type: 'number', description: '数量' },
90
+ quantity: { type: 'string', description: '数量' },
152
91
  unit: { type: 'string', description: '单位' },
153
92
  amount: { type: 'number', description: '金额' },
154
93
  weight: { type: 'string', description: '重量' },
155
94
  marketPrice: { type: 'string', description: '市场单价' },
156
95
  category: { type: 'string', description: '分类' },
157
96
  },
158
- required: ['name', 'amount', 'price', 'quantity'],
97
+ required: ['name', 'amount'],
159
98
  },
160
99
  },
161
- agentType: { type: 'string', description: 'Agent 类型(如:workbuddy、claude、cursor)' },
162
- apiProvider: { type: 'string', description: 'AI 提供商' },
163
- rawInput: { type: 'string', description: '用户原始输入' },
164
- mcp_version: { type: 'string', description: 'MCP Server 版本号(自动填充)' },
165
100
  },
166
101
  required: ['store', 'items'],
167
102
  },
@@ -174,6 +109,9 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
174
109
  properties: {
175
110
  limit: { type: 'number', description: '返回数量限制', default: 10 },
176
111
  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: '【推荐自动填充】用户的原始输入内容,用于记录用户原始请求' },
177
115
  },
178
116
  },
179
117
  },
@@ -184,6 +122,9 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
184
122
  type: 'object',
185
123
  properties: {
186
124
  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: '【推荐自动填充】用户的原始输入内容,用于记录用户原始请求' },
187
128
  },
188
129
  },
189
130
  },
@@ -195,417 +136,76 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
195
136
  properties: {
196
137
  yearMonth: { type: 'string', description: '年月(如:2026-03)' },
197
138
  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: '【推荐自动填充】用户的原始输入内容,用于记录用户原始请求' },
198
142
  },
199
143
  required: ['yearMonth'],
200
144
  },
201
145
  },
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
- },
221
146
  ],
222
147
  };
223
148
  });
224
149
 
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
-
340
150
  // 工具调用处理
341
151
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
342
152
  const { name, arguments: args } = request.params;
343
153
 
344
- // 【强制日志】测试日志是否输出 - 写入文件
345
- const fs = require('fs');
346
-
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
- }
358
-
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);
154
+ // 调试日志
155
+ console.error('收到工具调用请求:', name);
156
+ console.error('原始参数:', JSON.stringify(args, null, 2));
368
157
 
369
158
  try {
370
- // 获取 Token
371
- const token = await getToken();
159
+ // 获取 Token(这里需要实现 Token 生成逻辑)
160
+ const token = await generateToken();
372
161
 
373
- // 处理参数
162
+ // SCF 使用下划线命名,直接传递工具名
163
+ const action = name;
164
+
165
+ // 处理参数 - 将字符串格式的 items 转换为数组
374
166
  const processedArgs = { ...args };
375
167
  if (processedArgs.items && typeof processedArgs.items === 'string') {
376
168
  try {
377
169
  processedArgs.items = JSON.parse(processedArgs.items);
170
+ console.error('items 解析成功:', processedArgs.items);
378
171
  } catch (e) {
379
- // 解析失败,保持原样
172
+ // 如果解析失败,保持原样
173
+ console.error('解析 items 失败:', e);
380
174
  }
381
175
  }
382
176
 
177
+ console.error('处理后参数:', JSON.stringify(processedArgs, null, 2));
383
178
 
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
- break;
499
- }
500
-
501
- case 'save_receipt': {
502
- // 步骤1:校验数据完整性
503
- console.log('校验小票数据完整性...');
504
- const validationResult = await callMcpPrompt(
505
- 'validateResult',
506
- {
507
- data: processedArgs,
508
- type: 'parseReceipt'
509
- },
510
- token
511
- );
512
-
513
- if (validationResult.success && !validationResult.data.valid) {
514
- console.log('数据不完整,尝试补充默认值:', validationResult.data);
515
- // 调用 fillDefaults 补充缺失字段
516
- const fillResult = await callMcpPrompt(
517
- 'fillDefaults',
518
- {
519
- data: processedArgs,
520
- type: 'parseReceipt'
521
- },
522
- token
523
- );
524
-
525
- if (fillResult.success) {
526
- processedArgs = fillResult.data;
527
- console.log('补充后的数据:', processedArgs);
528
- }
529
- }
530
-
531
- // 步骤2:转换参数并调用 mcpHub 保存
532
- const mcpParams = convertParams('save_receipt', processedArgs);
533
- result = await callMcpHub('addReceipt', mcpParams, token);
534
-
535
- // 格式化输出
536
- if (result.success) {
537
- const totalAmount = processedArgs.totalAmount || processedArgs.items?.reduce((sum, item) => sum + (item.amount || 0), 0) || 0;
538
- const itemsList = processedArgs.items?.map(item => `• ${item.name || '未知商品'} - ${item.amount || 0}元`).join('\n') || '暂无商品明细';
539
- const storeName = processedArgs.store || '-';
540
- const category = processedArgs.items?.[0]?.category || '其他';
541
- userMessage = `✅ 小票记录成功\n\n| 项目 | 内容 |\n|------|------|\n| 商家 | ${storeName} |\n| 金额 | ${totalAmount}元 |\n| 分类 | ${category} |\n\n商品明细:\n${itemsList}\n\n已保存到你的柴米记账小程序数据库。`;
542
- }
543
- break;
544
- }
545
-
546
- case 'get_expenses':
547
- case 'get_receipt_list': {
548
- // 查询类工具直接调用 mcpHub
549
- const toolName = toolMapping[name];
550
- const mcpParams = convertParams(name, processedArgs);
551
- result = await callMcpHub(toolName, mcpParams, token);
552
-
553
- if (result.success) {
554
- userMessage = `📊 消费记录查询成功\n共找到 ${result.data?.length || 0} 条记录`;
555
- }
556
- break;
557
- }
558
-
559
- case 'get_statistics': {
560
- // 查询类工具直接调用 mcpHub
561
- const toolName = toolMapping[name];
562
- const mcpParams = convertParams(name, processedArgs);
563
- result = await callMcpHub(toolName, mcpParams, token);
564
-
565
- if (result.success) {
566
- userMessage = `📈 统计查询成功`;
567
- }
568
- break;
569
- }
570
-
571
- case 'save_income': {
572
- // 收入记录直接调用 mcpHub
573
- const mcpParams = convertParams('save_income', processedArgs);
574
- result = await callMcpHub('addIncome', mcpParams, token);
575
-
576
- // 格式化输出
577
- if (result.success) {
578
- const displayName = processedArgs.name || '未知来源';
579
- const displayAmount = processedArgs.amount || 0;
580
- const displayCategory = processedArgs.category || '其他';
581
- const displayStore = processedArgs.store || '-';
582
- userMessage = `✅ 收入记录成功\n\n| 来源 | 金额 | 分类 | 付款方 |\n|------|------|------|--------|\n| ${displayName} | ${displayAmount}元 | ${displayCategory} | ${displayStore} |`;
583
- }
584
- break;
585
- }
586
-
587
- default:
588
- throw new Error(`未知工具: ${name}`);
589
- }
590
-
591
- // 处理错误
592
- if (!result.success) {
593
- userMessage = `❌ 操作失败:${result.error || '未知错误'}`;
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"';
594
198
  }
595
199
 
596
- // 添加版本信息提示
597
- userMessage += `\n\n---\n📦 柴米记账 MCP v${MCP_VERSION}`;
598
-
599
200
  return {
600
201
  content: [
601
202
  {
602
203
  type: 'text',
603
- text: userMessage,
204
+ text: responseText,
604
205
  },
605
206
  ],
606
207
  };
607
208
  } catch (error) {
608
- console.error('工具调用错误:', error);
609
209
  return {
610
210
  content: [
611
211
  {
@@ -618,244 +218,44 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
618
218
  }
619
219
  });
620
220
 
621
- // 输入验证和过滤函数
622
- function sanitizeString(str, maxLength = 200) {
623
- if (!str || typeof str !== 'string') return '';
624
- // 去除 HTML 标签,防止 XSS
625
- return str.replace(/<[^>]*>/g, '').substring(0, maxLength);
626
- }
627
-
628
- function validateAmount(amount) {
629
- const num = parseFloat(amount);
630
- return isNaN(num) || num < 0 ? 0 : num;
631
- }
632
-
633
- function validateQuantity(quantity) {
634
- const num = parseFloat(quantity);
635
- return isNaN(num) || num <= 0 ? 1 : num;
636
- }
637
-
638
- // 从重量字符串中提取克数
639
- function extractWeightInGrams(weightStr) {
640
- if (!weightStr || typeof weightStr !== 'string') return 0;
641
-
642
- // 匹配数字+单位,如 "300g", "2kg", "1.5斤"
643
- const match = weightStr.match(/(\d+\.?\d*)\s*(g|kg|斤|克|千克)/i);
644
- if (!match) return 0;
645
-
646
- const value = parseFloat(match[1]);
647
- const unit = match[2].toLowerCase();
221
+ // 生成 JWT Token
222
+ async function generateToken() {
223
+ const JWT_SECRET = process.env.JWT_SECRET;
224
+ const MCP_OPENID = process.env.MCP_OPENID;
648
225
 
649
- // 转换为克
650
- switch (unit) {
651
- case 'g':
652
- case '克':
653
- return value;
654
- case 'kg':
655
- case '千克':
656
- return value * 1000;
657
- case '斤':
658
- return value * 500; // 1斤 = 500g
659
- default:
660
- return value;
226
+ if (!JWT_SECRET) {
227
+ throw new Error('JWT_SECRET 环境变量未设置');
661
228
  }
662
- }
663
-
664
- // 计算市场单价(元/500g)
665
- function calculateMarketPrice(amount, weightStr) {
666
- const amountNum = parseFloat(amount);
667
- const weightInGrams = extractWeightInGrams(weightStr);
668
229
 
669
- if (isNaN(amountNum) || amountNum <= 0 || weightInGrams <= 0) {
670
- return '';
230
+ if (!MCP_OPENID) {
231
+ throw new Error('MCP_OPENID 环境变量未设置,请从小程序获取用户Token');
671
232
  }
672
233
 
673
- // 计算每500g的价格
674
- const pricePer500g = (amountNum / weightInGrams) * 500;
675
- return `${pricePer500g.toFixed(2)}元/500g`;
676
- }
677
-
678
- // 参数转换函数
679
- function convertParams(toolName, args) {
680
- switch (toolName) {
681
- case 'save_expense': {
682
- // 必填参数校验
683
- if (!args.name || typeof args.name !== 'string' || args.name.trim() === '') {
684
- throw new Error('缺少必填参数:name(商品名称)');
685
- }
686
- if (args.amount === undefined || args.amount === null) {
687
- throw new Error('缺少必填参数:amount(金额)');
688
- }
689
-
690
- const name = sanitizeString(args.name, 100);
691
- const amount = validateAmount(args.amount);
692
-
693
- return {
694
- name: name,
695
- originalName: name,
696
- amount: amount,
697
- price: amount, // 单价默认等于金额
698
- quantity: 1, // 数量默认为1
699
- category: sanitizeString(args.category, 50) || '其他',
700
- store: sanitizeString(args.store, 100) || '',
701
- type: 'expense',
702
- unit: '',
703
- weight: '',
704
- marketPrice: '',
705
- date: args.date,
706
- note: sanitizeString(args.note, 500) || '',
707
- rawInput: sanitizeString(args.rawInput, 1000) || '',
708
- agentType: args.agentType || '',
709
- apiProvider: args.apiProvider || '',
710
- mcp_version: args.mcp_version || MCP_VERSION,
711
- source: 'mcp_txt_expense',
712
- };
713
- }
714
-
715
- case 'save_receipt': {
716
- // 处理 items 可能是 JSON 字符串的情况
717
- let items = args.items;
718
- if (typeof items === 'string') {
719
- try {
720
- items = JSON.parse(items);
721
- } catch (e) {
722
- throw new Error('items 参数格式错误:必须是数组或 JSON 数组字符串');
723
- }
724
- }
725
- if (!Array.isArray(items)) {
726
- throw new Error('items 参数必须是数组');
727
- }
728
-
729
- return {
730
- items: items.map((item, index) => {
731
- const weight = sanitizeString(item.weight, 50);
732
- const amount = validateAmount(item.amount);
733
- // 优先使用传入的 marketPrice,如果没有则自动计算
734
- const marketPrice = sanitizeString(item.marketPrice, 50) || calculateMarketPrice(amount, weight);
735
-
736
- return {
737
- itemIndex: index,
738
- name: sanitizeString(item.name, 100),
739
- originalName: sanitizeString(item.originalName, 200) || sanitizeString(item.name, 100),
740
- amount: amount,
741
- category: sanitizeString(item.category, 50) || '其他',
742
- subCategory: sanitizeString(item.subCategory, 50) || '',
743
- transactionType: item.transactionType || 'expense',
744
- price: validateAmount(item.price),
745
- quantity: item.quantity ? String(item.quantity).substring(0, 20) : '1',
746
- unit: sanitizeString(item.unit, 20),
747
- weight: weight,
748
- marketPrice: marketPrice,
749
- note: sanitizeString(item.note, 500),
750
- };
751
- }),
752
- store: sanitizeString(args.store, 100),
753
- receiptNo: sanitizeString(args.receiptNo, 50),
754
- totalAmount: validateAmount(args.totalAmount),
755
- originalAmount: validateAmount(args.originalAmount),
756
- discountAmount: validateAmount(args.discountAmount),
757
- actualAmount: validateAmount(args.actualAmount),
758
- paymentMethod: sanitizeString(args.paymentMethod, 50),
759
- memberCardNo: sanitizeString(args.memberCardNo, 50),
760
- currentPoints: parseInt(args.currentPoints) || 0,
761
- totalPoints: parseInt(args.totalPoints) || 0,
762
- date: args.date,
763
- rawInput: sanitizeString(args.rawInput, 2000),
764
- agentType: args.agentType || '',
765
- apiProvider: args.apiProvider || '',
766
- mcp_version: args.mcp_version || MCP_VERSION,
767
- source: 'mcp_receipt',
768
- };
769
- }
770
-
771
- case 'get_expenses':
772
- return {
773
- limit: Math.min(parseInt(args.limit) || 10, 100),
774
- source: args.source,
775
- };
776
-
777
- case 'get_statistics':
778
- return {
779
- startDate: args.yearMonth ? `${args.yearMonth}-01` : undefined,
780
- endDate: args.yearMonth ? getMonthEndDate(args.yearMonth) : undefined,
781
- type: args.type,
782
- };
783
-
784
- case 'save_income':
785
- return {
786
- name: sanitizeString(args.name, 100),
787
- amount: validateAmount(args.amount),
788
- category: sanitizeString(args.category, 50) || '其他',
789
- store: sanitizeString(args.store, 100),
790
- note: sanitizeString(args.note, 500),
791
- transactionType: 'income',
792
- rawInput: sanitizeString(args.rawInput, 1000),
793
- agentType: args.agentType || '',
794
- apiProvider: args.apiProvider || '',
795
- mcp_version: args.mcp_version || MCP_VERSION,
796
- source: 'mcp_txt_income',
797
- };
798
-
799
- default:
800
- return args;
801
- }
802
- }
803
-
804
- // 获取月份最后一天
805
- function getMonthEndDate(yearMonth) {
806
- const [year, month] = yearMonth.split('-').map(Number);
807
- const lastDay = new Date(year, month, 0).getDate();
808
- return `${yearMonth}-${lastDay}`;
234
+ // 使用 crypto 生成 JWT
235
+ const crypto = require('crypto');
236
+
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
+ };
243
+
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');
250
+
251
+ return `${h}.${p}.${sig}`;
809
252
  }
810
253
 
811
254
  // 启动服务器
812
255
  async function main() {
813
- console.error('========================================');
814
- console.error('柴米记账 MCP Server 启动中...');
815
- console.error('========================================\n');
816
-
817
- // 初始化 OAuth 管理器
818
- console.error('🔄 初始化 OAuth 2.0 认证...');
819
- initOAuthManager();
820
-
821
- // 尝试加载已有 Token 或启动授权流程
822
- try {
823
- const existingToken = await oauthManager.tokenStorage.load();
824
- if (existingToken) {
825
- console.error('✅ 发现已存储的 OAuth Token');
826
- // 验证 Token 是否有效
827
- const validToken = await oauthManager.getValidToken();
828
- console.error('✅ OAuth Token 验证通过');
829
- cachedToken = validToken.accessToken;
830
- tokenExpireTime = validToken.expiresAt;
831
- } else {
832
- console.error('\n⚠️ 首次使用,需要完成 OAuth 授权');
833
- console.error('请按以下步骤操作:');
834
- console.error('1. 等待授权信息出现');
835
- console.error('2. 在小程序中完成授权');
836
- console.error('3. 授权成功后即可使用\n');
837
-
838
- // 启动授权流程(这会阻塞,直到授权完成)
839
- const newToken = await oauthManager.startAuthFlow();
840
- cachedToken = newToken.accessToken;
841
- tokenExpireTime = newToken.expiresAt;
842
- }
843
- } catch (err) {
844
- console.error('\n❌ OAuth 初始化失败:', err.message);
845
- console.error('请检查 MCP_OAUTH_URL 配置是否正确\n');
846
- throw err;
847
- }
848
-
849
- console.error('\n========================================');
850
- console.error('启动 MCP Server...');
851
- console.error('========================================\n');
852
-
853
256
  const transport = new StdioServerTransport();
854
257
  await server.connect(transport);
855
- console.error('柴米记账 MCP Server 已启动');
856
- console.error(`MCP_HUB_URL: ${MCP_HUB_URL}`);
857
- console.error(`MCP_PROMPT_URL: ${MCP_PROMPT_URL}`);
858
- console.error(`MCP_OAUTH_URL: ${MCP_OAUTH_URL}`);
258
+ console.error('柴米记账 MCP Server 已启动');
859
259
  }
860
260
 
861
261
  main().catch(console.error);