chaimi-bookkeeping-mcp 2.3.4 → 2.3.5
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 +7 -16
- package/package.json +1 -1
- package/server.js +89 -696
package/README.md
CHANGED
|
@@ -70,22 +70,9 @@ MCP Server 会显示:
|
|
|
70
70
|
|
|
71
71
|
## 配置说明
|
|
72
72
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
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
package/server.js
CHANGED
|
@@ -1,77 +1,29 @@
|
|
|
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
|
|
|
8
|
-
// 加载 .env 文件
|
|
9
|
-
try {
|
|
10
|
-
require('dotenv').config();
|
|
11
|
-
} catch (e) {
|
|
12
|
-
// dotenv 未安装,忽略
|
|
13
|
-
}
|
|
14
|
-
|
|
15
7
|
const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
|
|
16
8
|
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
|
|
17
9
|
const {
|
|
18
10
|
CallToolRequestSchema,
|
|
19
11
|
ListToolsRequestSchema,
|
|
20
12
|
} = require('@modelcontextprotocol/sdk/types.js');
|
|
21
|
-
const path = require('path');
|
|
22
|
-
const os = require('os');
|
|
23
13
|
const fs = require('fs');
|
|
14
|
+
const path = require('path');
|
|
24
15
|
|
|
25
|
-
// 读取 package.json
|
|
16
|
+
// 读取 package.json 获取版本号
|
|
26
17
|
const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
|
|
27
18
|
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
19
|
|
|
45
|
-
//
|
|
46
|
-
|
|
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
|
-
}
|
|
20
|
+
// 配置
|
|
21
|
+
const SCF_URL = process.env.SCF_URL || 'https://1412172089-4wbwsop8pe.ap-shanghai.tencentscf.com';
|
|
70
22
|
|
|
71
23
|
// 创建 MCP Server
|
|
72
24
|
const server = new Server(
|
|
73
25
|
{
|
|
74
|
-
name: '
|
|
26
|
+
name: 'chaihuo-mcp-server',
|
|
75
27
|
version: MCP_VERSION,
|
|
76
28
|
},
|
|
77
29
|
{
|
|
@@ -85,49 +37,26 @@ const server = new Server(
|
|
|
85
37
|
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
86
38
|
return {
|
|
87
39
|
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
40
|
{
|
|
110
41
|
name: 'save_expense',
|
|
111
|
-
description: '保存单商品消费记录(AI
|
|
42
|
+
description: '保存单商品消费记录(AI文字记账)',
|
|
112
43
|
inputSchema: {
|
|
113
44
|
type: 'object',
|
|
114
45
|
properties: {
|
|
115
|
-
name: { type: 'string', description: '
|
|
116
|
-
amount: { type: 'number', description: '
|
|
117
|
-
category: { type: 'string', description: '
|
|
118
|
-
store: { type: 'string', description: '
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
rawInput: { type: 'string', description: '用户原始输入(可选)' },
|
|
123
|
-
mcp_version: { type: 'string', description: 'MCP Server 版本号(自动填充)' },
|
|
46
|
+
name: { type: 'string', description: '商品名称' },
|
|
47
|
+
amount: { type: 'number', description: '金额' },
|
|
48
|
+
category: { type: 'string', description: '分类(如:餐饮、食品、交通)' },
|
|
49
|
+
store: { type: 'string', description: '商家名称' },
|
|
50
|
+
agentType: { type: 'string', description: '【推荐自动填充】Agent类型,如:claude-desktop、cursor、openclaw、workbuddy、trae' },
|
|
51
|
+
apiProvider: { type: 'string', description: '【推荐自动填充】AI服务提供商,如:anthropic、openai、doubao、aliyun' },
|
|
52
|
+
rawInput: { type: 'string', description: '【推荐自动填充】用户的原始输入内容,用于记录用户原始请求' },
|
|
124
53
|
},
|
|
125
54
|
required: ['name', 'amount'],
|
|
126
55
|
},
|
|
127
56
|
},
|
|
128
57
|
{
|
|
129
58
|
name: 'save_receipt',
|
|
130
|
-
description: '
|
|
59
|
+
description: '【图片小票专用】保存购物小票/发票/收据(支持单商品或多商品)。当用户提供图片形式的小票、发票、收据、购物清单时,无论商品数量多少(1条或多条),都必须使用此接口。可自动识别商家名称、商品明细、金额、优惠等信息。典型场景:超市购物小票、餐厅发票、线上订单截图、手写收据照片等',
|
|
131
60
|
inputSchema: {
|
|
132
61
|
type: 'object',
|
|
133
62
|
properties: {
|
|
@@ -139,29 +68,28 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
|
139
68
|
actualAmount: { type: 'number', description: '实付金额' },
|
|
140
69
|
paymentMethod: { type: 'string', description: '支付方式' },
|
|
141
70
|
receiptNo: { type: 'string', description: '小票编号' },
|
|
71
|
+
agentType: { type: 'string', description: '【推荐自动填充】Agent类型,如:claude-desktop、cursor、openclaw、workbuddy、trae' },
|
|
72
|
+
apiProvider: { type: 'string', description: '【推荐自动填充】AI服务提供商,如:anthropic、openai、doubao、aliyun' },
|
|
73
|
+
rawInput: { type: 'string', description: '【推荐自动填充】用户的原始输入内容,用于记录用户原始请求' },
|
|
142
74
|
items: {
|
|
143
75
|
type: 'array',
|
|
144
|
-
description: '
|
|
76
|
+
description: '商品列表',
|
|
145
77
|
items: {
|
|
146
78
|
type: 'object',
|
|
147
79
|
properties: {
|
|
148
80
|
name: { type: 'string', description: '商品名称' },
|
|
149
81
|
originalName: { type: 'string', description: '原始商品名称' },
|
|
150
82
|
price: { type: 'number', description: '单价' },
|
|
151
|
-
quantity: { type: '
|
|
83
|
+
quantity: { type: 'string', description: '数量' },
|
|
152
84
|
unit: { type: 'string', description: '单位' },
|
|
153
85
|
amount: { type: 'number', description: '金额' },
|
|
154
86
|
weight: { type: 'string', description: '重量' },
|
|
155
87
|
marketPrice: { type: 'string', description: '市场单价' },
|
|
156
88
|
category: { type: 'string', description: '分类' },
|
|
157
89
|
},
|
|
158
|
-
required: ['name', 'amount'
|
|
90
|
+
required: ['name', 'amount'],
|
|
159
91
|
},
|
|
160
92
|
},
|
|
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
93
|
},
|
|
166
94
|
required: ['store', 'items'],
|
|
167
95
|
},
|
|
@@ -174,6 +102,9 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
|
174
102
|
properties: {
|
|
175
103
|
limit: { type: 'number', description: '返回数量限制', default: 10 },
|
|
176
104
|
source: { type: 'string', description: '来源筛选' },
|
|
105
|
+
agentType: { type: 'string', description: '【推荐自动填充】Agent类型,如:claude-desktop、cursor、openclaw、workbuddy、trae' },
|
|
106
|
+
apiProvider: { type: 'string', description: '【推荐自动填充】AI服务提供商,如:anthropic、openai、doubao、aliyun' },
|
|
107
|
+
rawInput: { type: 'string', description: '【推荐自动填充】用户的原始输入内容,用于记录用户原始请求' },
|
|
177
108
|
},
|
|
178
109
|
},
|
|
179
110
|
},
|
|
@@ -184,6 +115,9 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
|
184
115
|
type: 'object',
|
|
185
116
|
properties: {
|
|
186
117
|
limit: { type: 'number', description: '返回数量限制', default: 5 },
|
|
118
|
+
agentType: { type: 'string', description: '【推荐自动填充】Agent类型,如:claude-desktop、cursor、openclaw、workbuddy、trae' },
|
|
119
|
+
apiProvider: { type: 'string', description: '【推荐自动填充】AI服务提供商,如:anthropic、openai、doubao、aliyun' },
|
|
120
|
+
rawInput: { type: 'string', description: '【推荐自动填充】用户的原始输入内容,用于记录用户原始请求' },
|
|
187
121
|
},
|
|
188
122
|
},
|
|
189
123
|
},
|
|
@@ -195,417 +129,76 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
|
195
129
|
properties: {
|
|
196
130
|
yearMonth: { type: 'string', description: '年月(如:2026-03)' },
|
|
197
131
|
type: { type: 'string', description: '统计类型:item/receipt/category' },
|
|
132
|
+
agentType: { type: 'string', description: '【推荐自动填充】Agent类型,如:claude-desktop、cursor、openclaw、workbuddy、trae' },
|
|
133
|
+
apiProvider: { type: 'string', description: '【推荐自动填充】AI服务提供商,如:anthropic、openai、doubao、aliyun' },
|
|
134
|
+
rawInput: { type: 'string', description: '【推荐自动填充】用户的原始输入内容,用于记录用户原始请求' },
|
|
198
135
|
},
|
|
199
136
|
required: ['yearMonth'],
|
|
200
137
|
},
|
|
201
138
|
},
|
|
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
139
|
],
|
|
222
140
|
};
|
|
223
141
|
});
|
|
224
142
|
|
|
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
143
|
// 工具调用处理
|
|
341
144
|
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
342
145
|
const { name, arguments: args } = request.params;
|
|
343
146
|
|
|
344
|
-
//
|
|
345
|
-
|
|
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);
|
|
147
|
+
// 调试日志
|
|
148
|
+
console.error('收到工具调用请求:', name);
|
|
149
|
+
console.error('原始参数:', JSON.stringify(args, null, 2));
|
|
368
150
|
|
|
369
151
|
try {
|
|
370
|
-
// 获取 Token
|
|
371
|
-
const token = await
|
|
152
|
+
// 获取 Token(这里需要实现 Token 生成逻辑)
|
|
153
|
+
const token = await generateToken();
|
|
154
|
+
|
|
155
|
+
// SCF 使用下划线命名,直接传递工具名
|
|
156
|
+
const action = name;
|
|
372
157
|
|
|
373
|
-
// 处理参数
|
|
158
|
+
// 处理参数 - 将字符串格式的 items 转换为数组
|
|
374
159
|
const processedArgs = { ...args };
|
|
375
160
|
if (processedArgs.items && typeof processedArgs.items === 'string') {
|
|
376
161
|
try {
|
|
377
162
|
processedArgs.items = JSON.parse(processedArgs.items);
|
|
163
|
+
console.error('items 解析成功:', processedArgs.items);
|
|
378
164
|
} catch (e) {
|
|
379
|
-
//
|
|
165
|
+
// 如果解析失败,保持原样
|
|
166
|
+
console.error('解析 items 失败:', e);
|
|
380
167
|
}
|
|
381
168
|
}
|
|
382
169
|
|
|
170
|
+
console.error('处理后参数:', JSON.stringify(processedArgs, null, 2));
|
|
383
171
|
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
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 || '未知错误'}`;
|
|
172
|
+
// 调用 SCF
|
|
173
|
+
const response = await fetch(SCF_URL, {
|
|
174
|
+
method: 'POST',
|
|
175
|
+
headers: {
|
|
176
|
+
'Content-Type': 'application/json',
|
|
177
|
+
'Authorization': `Bearer ${token}`,
|
|
178
|
+
},
|
|
179
|
+
body: JSON.stringify({
|
|
180
|
+
action: action,
|
|
181
|
+
data: processedArgs,
|
|
182
|
+
}),
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
const result = await response.json();
|
|
186
|
+
|
|
187
|
+
// 检查是否传递了agentType和apiProvider参数,如果没有则添加提示
|
|
188
|
+
let responseText = JSON.stringify(result, null, 2);
|
|
189
|
+
if (!processedArgs.agentType || !processedArgs.apiProvider) {
|
|
190
|
+
responseText += '\n\n💡 提示:传递agentType和apiProvider参数可解锁小程序记录来源统计功能,示例:agentType="openclaw", apiProvider="doubao"';
|
|
594
191
|
}
|
|
595
192
|
|
|
596
|
-
// 添加版本信息提示
|
|
597
|
-
userMessage += `\n\n---\n📦 柴米记账 MCP v${MCP_VERSION}`;
|
|
598
|
-
|
|
599
193
|
return {
|
|
600
194
|
content: [
|
|
601
195
|
{
|
|
602
196
|
type: 'text',
|
|
603
|
-
text:
|
|
197
|
+
text: responseText,
|
|
604
198
|
},
|
|
605
199
|
],
|
|
606
200
|
};
|
|
607
201
|
} catch (error) {
|
|
608
|
-
console.error('工具调用错误:', error);
|
|
609
202
|
return {
|
|
610
203
|
content: [
|
|
611
204
|
{
|
|
@@ -618,244 +211,44 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
618
211
|
}
|
|
619
212
|
});
|
|
620
213
|
|
|
621
|
-
//
|
|
622
|
-
function
|
|
623
|
-
|
|
624
|
-
|
|
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();
|
|
214
|
+
// 生成 JWT Token
|
|
215
|
+
async function generateToken() {
|
|
216
|
+
const JWT_SECRET = process.env.JWT_SECRET;
|
|
217
|
+
const MCP_OPENID = process.env.MCP_OPENID;
|
|
648
218
|
|
|
649
|
-
|
|
650
|
-
|
|
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;
|
|
219
|
+
if (!JWT_SECRET) {
|
|
220
|
+
throw new Error('JWT_SECRET 环境变量未设置');
|
|
661
221
|
}
|
|
662
|
-
}
|
|
663
|
-
|
|
664
|
-
// 计算市场单价(元/500g)
|
|
665
|
-
function calculateMarketPrice(amount, weightStr) {
|
|
666
|
-
const amountNum = parseFloat(amount);
|
|
667
|
-
const weightInGrams = extractWeightInGrams(weightStr);
|
|
668
222
|
|
|
669
|
-
if (
|
|
670
|
-
|
|
223
|
+
if (!MCP_OPENID) {
|
|
224
|
+
throw new Error('MCP_OPENID 环境变量未设置,请从小程序获取用户Token');
|
|
671
225
|
}
|
|
672
226
|
|
|
673
|
-
//
|
|
674
|
-
const
|
|
675
|
-
|
|
676
|
-
}
|
|
677
|
-
|
|
678
|
-
//
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
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}`;
|
|
227
|
+
// 使用 crypto 生成 JWT
|
|
228
|
+
const crypto = require('crypto');
|
|
229
|
+
|
|
230
|
+
const header = { alg: 'HS256', typ: 'JWT' };
|
|
231
|
+
const payload = {
|
|
232
|
+
openid: MCP_OPENID, // 使用固定的用户 openid
|
|
233
|
+
iat: Math.floor(Date.now() / 1000),
|
|
234
|
+
exp: Math.floor(Date.now() / 1000) + 86400
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
const h = Buffer.from(JSON.stringify(header)).toString('base64url');
|
|
238
|
+
const p = Buffer.from(JSON.stringify(payload)).toString('base64url');
|
|
239
|
+
const sig = crypto
|
|
240
|
+
.createHmac('sha256', JWT_SECRET)
|
|
241
|
+
.update(h + '.' + p)
|
|
242
|
+
.digest('base64url');
|
|
243
|
+
|
|
244
|
+
return `${h}.${p}.${sig}`;
|
|
809
245
|
}
|
|
810
246
|
|
|
811
247
|
// 启动服务器
|
|
812
248
|
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
249
|
const transport = new StdioServerTransport();
|
|
854
250
|
await server.connect(transport);
|
|
855
|
-
console.error('
|
|
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}`);
|
|
251
|
+
console.error('柴米记账 MCP Server 已启动');
|
|
859
252
|
}
|
|
860
253
|
|
|
861
254
|
main().catch(console.error);
|