@fangcuntai/fangcuntai-mcp 1.6.2 → 1.6.4

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.en.md ADDED
@@ -0,0 +1,137 @@
1
+ # @fangcuntai/fangcuntai-mcp
2
+
3
+ Fangcuntai Desktop Assistant MCP server. Connect it to Lobster / OpenClaw, Claude Desktop, Cursor, or another MCP-compatible client to query family ledgers and notes, organize notes, and safely write data after user confirmation.
4
+
5
+ [简体中文](https://unpkg.com/@fangcuntai/fangcuntai-mcp/README.md)
6
+
7
+ ## Features
8
+
9
+ - Switch between families and ledger books.
10
+ - Query summaries, entries, trends, and categories.
11
+ - Create, delete, and restore ledger entries behind a write confirmation lock.
12
+ - Browse and search notes, organize two-level note folders, and create note drafts. Write to-dos as `- [ ]` / `- [x]`; link another note with `[[title]]`.
13
+ - Review and confirm AI drafts.
14
+ - Check subscription status and AI credit balance.
15
+ - Track writes created by the desktop assistant.
16
+
17
+ The MCP server accesses the Fangcuntai API only. It does not connect directly to the database.
18
+
19
+ ## Requirements
20
+
21
+ - Node.js 18 or later.
22
+ - A Fangcuntai account.
23
+ - A desktop assistant token created in the Fangcuntai app:
24
+ **Me > Settings > Connect Desktop Assistant**.
25
+
26
+ You can choose the default family and permissions when creating the token. The token is shown only once and can be revoked in the app at any time.
27
+
28
+ ## Configuration
29
+
30
+ Add this server to your MCP-compatible desktop client:
31
+
32
+ ```json
33
+ {
34
+ "command": "npx",
35
+ "args": ["-y", "@fangcuntai/fangcuntai-mcp"],
36
+ "env": {
37
+ "FANGCUNTAI_API": "https://api-service.fangcuntai.com",
38
+ "FANGCUNTAI_TOKEN": "hm_at_your_token"
39
+ }
40
+ }
41
+ ```
42
+
43
+ You can also copy the complete configuration from the **Connect Desktop Assistant** page in the Fangcuntai app.
44
+
45
+ ### Environment variables
46
+
47
+ | Variable | Required | Description |
48
+ |----------|----------|-------------|
49
+ | `FANGCUNTAI_TOKEN` | Yes | Assistant token created in the app, starting with `hm_at_` |
50
+ | `FANGCUNTAI_API` | No | API base URL. Defaults to `http://127.0.0.1:9080` |
51
+
52
+ Production API: `https://api-service.fangcuntai.com`
53
+
54
+ ## Security model
55
+
56
+ Write access is locked by default.
57
+
58
+ 1. After the user explicitly agrees, call `unlock_writes`.
59
+ 2. Prepare the write and show its summary to the user.
60
+ 3. Complete the write with a one-time confirmation token only after the user confirms.
61
+
62
+ Other safeguards:
63
+
64
+ - The server validates the token permissions selected in the app.
65
+ - A token is bound to a default family and can only switch to families the user has joined.
66
+ - Deleted ledger entries and notes are moved to the recycle bin.
67
+ - Ledger writes are marked with the `desktop_mcp` source.
68
+ - Requests include `X-App-ID: 60000` and `X-MCP-Tool` for auditing.
69
+
70
+ ## Common flows
71
+
72
+ ### Query the ledger
73
+
74
+ `list_my_families` -> `select_family` -> `list_ledger_books` -> `select_ledger_book` -> `get_ledger_summary`
75
+
76
+ ### Create a ledger entry
77
+
78
+ `unlock_writes` -> `prepare_create_ledger_entry` -> user confirmation -> `confirm_create_ledger_entry`
79
+
80
+ ### Link a note to a bill
81
+
82
+ Entry lists only include `has_visible_related_note`, never note titles. `get_ledger_entry` returns titles the member can see. `get_note` returns related amounts only when the token can read the ledger.
83
+
84
+ Link or unlink existing records: `unlock_writes` -> `prepare_link_ledger_note` / `prepare_unlink_ledger_note` -> show the title, date, category, and amount -> `confirm_link_ledger_note` / `confirm_unlink_ledger_note`. Both write scopes are required.
85
+
86
+ When a new bill and a new note are created in the same turn, pass the same `link_group`. The link is written only after both saves succeed.
87
+
88
+ ### Update a ledger entry
89
+
90
+ `unlock_writes` -> `prepare_update_ledger_entry` -> user confirmation -> `confirm_update_ledger_entry` (only entries added in the last month)
91
+
92
+ ### Organize notes
93
+
94
+ `list_note_folders` -> `unlock_writes` -> `create_note_folder` / `rename_note_folder` / `move_note_folder`
95
+
96
+ ### Restore deleted items
97
+
98
+ Ledger entries: `list_ledger_trash` -> `restore_ledger_entry`
99
+
100
+ Notes: `list_notes_trash` -> `restore_note`
101
+
102
+ ## Local development
103
+
104
+ ```bash
105
+ cd fangcuntai-mcp
106
+ npm install
107
+ npm test
108
+ npm run build
109
+
110
+ FANGCUNTAI_TOKEN=hm_at_xxx \
111
+ FANGCUNTAI_API=http://127.0.0.1:9080 \
112
+ node dist/index.js
113
+ ```
114
+
115
+ Local test data:
116
+
117
+ ```bash
118
+ cd ../home-admin
119
+ go run cmd/seed-mcp-test-data/main.go -config config/config.yaml
120
+ ```
121
+
122
+ The command only writes to the local development database and can be run repeatedly.
123
+
124
+ ## Publishing
125
+
126
+ ```bash
127
+ npm publish --access public
128
+ ```
129
+
130
+ ## Links
131
+
132
+ - Website: https://www.fangcuntai.com
133
+ - npm: https://www.npmjs.com/package/@fangcuntai/fangcuntai-mcp
134
+
135
+ ## License
136
+
137
+ MIT
package/README.md CHANGED
@@ -1,44 +1,31 @@
1
1
  # @fangcuntai/fangcuntai-mcp
2
2
 
3
- 方寸台桌面助手 MCP 服务,供有道龙虾 / OpenClaw / Claude Desktop / Cursor 等客户端连接。
3
+ 方寸台桌面助手 MCP 服务。连接后可在有道龙虾 / OpenClaw、Claude Desktop、Cursor 等支持 MCP 的桌面客户端中,用自然语言查询家庭账本、整理记事,并在确认后安全地写入数据。
4
4
 
5
- 用自然语言完成:**切换家庭/账本 → 查账 →(解锁并确认后)记一笔/删一笔**;删除进回收站可恢复;**整理记事两层文件夹**(浏览本层、建文件夹、移动记事)。
5
+ [English](https://unpkg.com/@fangcuntai/fangcuntai-mcp/README.en.md)
6
6
 
7
- > **事情提醒已下线**:不再提供 `list_reminders` / `create_reminder_draft` / `mark_reminder_done`。
7
+ ## 功能
8
8
 
9
- ## 前置条件
10
-
11
- 1. 在方寸台 App:**我的 → 设置 → 连接桌面助手**
12
- 2. 选择**默认家庭**,勾选权限后生成令牌(查询账单 / 查看统计 / 创建草稿 / 记一笔·删除;已有令牌不能改权限);可一键复制完整 MCP 配置
13
- 3. 按页面内「如何安装到桌面 AI」把配置粘贴到龙虾 / Claude Desktop / Cursor
14
- 4. 确保主 API 可访问(App 生产:`https://api-service.fangcuntai.com`;本地默认 `http://127.0.0.1:9080`)
15
-
16
- ## 环境变量
17
-
18
- | 变量 | 必填 | 说明 |
19
- |------|------|------|
20
- | `FANGCUNTAI_TOKEN` | 是 | App 生成的助手令牌(`hm_at_...`) |
21
- | `FANGCUNTAI_API` | 否 | API 根地址,默认 `http://127.0.0.1:9080` |
9
+ - 切换家庭和账本,查询收支摘要、账单、趋势与分类。
10
+ - 在确认锁保护下记账、删除、恢复回收站和清空回收站。
11
+ - 查看和搜索记事,整理两层记事文件夹,创建记事草稿。待办写成 `- [ ]` / `- [x]`,一篇可用 `[[标题]]` 连到另一篇。
12
+ - 查看并批量确认 AI 草稿,查询订阅和 AI 积分。
13
+ - 写入数据带来源标记,可在方寸台 App 中追踪。
22
14
 
23
- > 兼容旧变量名:`HOME_MAN_TOKEN` / `HOME_MAN_API`(仍可使用,优先读 `FANGCUNTAI_*`)。
15
+ MCP 只访问方寸台 API,不直连数据库。
24
16
 
25
- ## 安全模型(v1.5)
26
-
27
- 防的是:**AI 误调写接口改正式数据**(MCP 不直连数据库)。
17
+ ## 前置条件
28
18
 
29
- | 层 | 机制 |
30
- |----|------|
31
- | **确认锁(前门)** | 默认上锁。入账/删除记账或记事/清空回收站/确认草稿(含批量)/删除文件夹/移动记事所属:`unlock_writes` → `prepare_*` → 展示摘要 → `confirm_*` |
32
- | **结构写(轻门)** | 新建/改名/移动文件夹:须 `unlock_writes` 后直接调用(非空文件夹不可删,服务端兜底) |
33
- | **令牌权限** | App 生成时勾选查询/统计/草稿/记一笔;缺权限时工具拒绝并提示重新生成。已有令牌不能改权限 |
34
- | **来源标记(追溯)** | 入账 `source=desktop_mcp`,App 可区分桌面助手写入 |
35
- | **回收站(后门)** | 删除软删;`list_ledger_trash` / `restore_ledger_entry`、`list_notes_trash` / `restore_note` 可恢复。清空回收站为永久删除,须确认锁 |
19
+ - Node.js 18 或更高版本。
20
+ - 一个方寸台账号。
21
+ - 在方寸台 App 中生成桌面助手令牌:
22
+ **我的 → 设置 → 连接桌面助手**。
36
23
 
37
- 查账、列账本、列文件夹、建草稿、丢弃草稿、恢复回收站:**不需解锁**。
24
+ 生成令牌时可选择默认家庭和权限。令牌明文只显示一次,可在 App 中随时撤销。
38
25
 
39
- > 亦可先 `create_ledger_draft` / `create_note_draft`,再确认草稿入账。当前账号开启个人 `auto_confirm_ai_drafts`(App「设置 → 草稿自动保存」)后,创建草稿会自动确认;失败则仍为 `pending`,可在 App「我的 → AI 草稿箱」批量保存。家长打开开关不会替家人自动保存。
26
+ ## 配置
40
27
 
41
- ## 有道龙虾 / OpenClaw 配置示例
28
+ 把以下配置添加到支持 MCP 的桌面客户端:
42
29
 
43
30
  ```json
44
31
  {
@@ -51,106 +38,64 @@
51
38
  }
52
39
  ```
53
40
 
54
- ## 推荐用法
41
+ 也可以从方寸台 App 的「连接桌面助手」页面复制完整配置。
55
42
 
56
- ### 查账(无需解锁)
43
+ ### 环境变量
57
44
 
58
- `list_my_families` → `select_family` → `list_ledger_books` → `select_ledger_book` → `get_ledger_summary` / `list_ledger_entries`
45
+ | 变量 | 必填 | 说明 |
46
+ |------|------|------|
47
+ | `FANGCUNTAI_TOKEN` | 是 | App 生成的助手令牌,以 `hm_at_` 开头 |
48
+ | `FANGCUNTAI_API` | 否 | API 地址,默认 `http://127.0.0.1:9080` |
59
49
 
60
- ### 记一笔(须确认)
50
+ 生产 API:`https://api-service.fangcuntai.com`
61
51
 
62
- 1. 征得用户同意 → `unlock_writes`(`user_acknowledged=true`)
63
- 2. `prepare_create_ledger_entry` → 向用户展示 summary
64
- 3. 用户说确认 → `confirm_create_ledger_entry(confirm_token)`
52
+ ## 安全模型
65
53
 
66
- ### 删一笔(进回收站)
54
+ 桌面助手默认处于写锁状态。
67
55
 
68
- `unlock_writes` → `prepare_delete_ledger_entry` → 确认 → `confirm_delete_ledger_entry`
69
- 误删:`list_ledger_trash` → `restore_ledger_entry`
70
- 清空:`prepare_empty_ledger_trash` → 确认 → `confirm_empty_ledger_trash`(永久删除)
56
+ 1. 用户明确同意后,调用 `unlock_writes` 解锁。
57
+ 2. 写操作先生成待确认内容并展示摘要。
58
+ 3. 用户确认后,才使用一次性确认令牌完成写入。
71
59
 
72
- ### 删一篇记事(进回收站)
60
+ 此外:
73
61
 
74
- `unlock_writes` → `prepare_delete_note` → 确认 → `confirm_delete_note`
75
- 误删:`list_notes_trash` → `restore_note`
76
- 清空:`prepare_empty_notes_trash` → 确认 → `confirm_empty_notes_trash`(永久删除)
62
+ - 令牌权限由 App 生成时决定,服务端会再次校验。
63
+ - 令牌绑定默认家庭,会话中只能切换到用户已加入的其他家庭。
64
+ - 删除的账单和记事进入回收站,可以恢复。
65
+ - 写入账单的来源标记为 `desktop_mcp`。
66
+ - 请求使用 `X-App-ID: 60000` 和 `X-MCP-Tool` 便于审计。
77
67
 
78
- ## 工具列表(v1.5)
68
+ ## 常用流程
79
69
 
80
- ### 安全锁
70
+ ### 查账
81
71
 
82
- | Tool | 说明 |
83
- |------|------|
84
- | `get_write_lock_status` | 是否解锁、剩余秒数 |
85
- | `unlock_writes` | 解锁(须 `user_acknowledged=true`) |
86
- | `lock_writes` | 立即上锁 |
72
+ `list_my_families` → `select_family` → `list_ledger_books` → `select_ledger_book` → `get_ledger_summary`
87
73
 
88
- ### 上下文 / 工作区
74
+ ### 记一笔
89
75
 
90
- | Tool | 说明 |
91
- |------|------|
92
- | `get_assistant_context` | 令牌默认家庭 / 公开 scopes + workspace |
93
- | `get_active_workspace` | 当前会话家庭与账本 |
94
- | `list_my_families` / `select_family` | 家庭列表与切换 |
95
- | `get_bound_family` / `get_family_entitlements` / `list_family_members` | 家庭信息与权限 |
76
+ `unlock_writes` → `prepare_create_ledger_entry` → 用户确认 → `confirm_create_ledger_entry`
96
77
 
97
- ### 记账
78
+ ### 记事和账单挂在一起
98
79
 
99
- | Tool | 说明 |
100
- |------|------|
101
- | `list_ledger_books` / `select_ledger_book` | 账本;列表含用法、状态、说明(最多 50 字) |
102
- | `get_ledger_summary` / `list_ledger_entries` / `get_ledger_trends` | 查账;时期账本不传 `month` 时 `get_ledger_summary` 返回整件事;`list_ledger_entries` 可按 `external_order_id` 精确查找 |
103
- | `list_ledger_categories` | 分类 |
104
- | `prepare_create_ledger_entry` / `confirm_create_ledger_entry` | 确认后入账;可传 `external_order_id`,已存在则 `already_exists` |
105
- | `prepare_delete_ledger_entry` / `confirm_delete_ledger_entry` | 确认后进回收站 |
106
- | `list_ledger_trash` / `restore_ledger_entry` | 回收站 |
107
- | `prepare_empty_ledger_trash` / `confirm_empty_ledger_trash` | 清空回收站(永久删除) |
108
- | `create_ledger_draft` | 仅草稿 |
80
+ 流水列表只有 `has_visible_related_note`,不带篇名。看一篇用 `get_ledger_entry`(要能看见那篇记事)。看一笔相关账单用 `get_note`,没有记账读取权限时不返回金额。
109
81
 
110
- ### 记事 / 文件夹 / 草稿
82
+ 挂上或拆开已经存在的记录:`unlock_writes` → `prepare_link_ledger_note` / `prepare_unlink_ledger_note` → 向用户展示篇名、日期、分类和金额 → `confirm_link_ledger_note` / `confirm_unlink_ledger_note`。需要同时勾选写入账单和写入草稿。
111
83
 
112
- | Tool | 说明 |
113
- |------|------|
114
- | `list_note_folders` | 文件夹扁平列表(最多两层;按 `parent_id` 组树) |
115
- | `create_note_folder` / `rename_note_folder` / `move_note_folder` | 建/改名/移动文件夹(须 `unlock_writes`) |
116
- | `prepare_delete_note_folder` / `confirm_delete_note_folder` | 删空文件夹(须解锁 + confirm_token;非空拒绝) |
117
- | `list_notes` / `search_notes` | 记事;`list_notes` 可传 `folder_id`(`0`=未分类;有关键词时忽略) |
118
- | `create_note_draft` | 记事草稿;可传 `folder_id` |
119
- | `prepare_move_note` / `confirm_move_note` | 已有记事改所属文件夹(须解锁 + confirm_token) |
120
- | `prepare_delete_note` / `confirm_delete_note` | 确认后进回收站 |
121
- | `list_notes_trash` / `restore_note` | 记事回收站 |
122
- | `prepare_empty_notes_trash` / `confirm_empty_notes_trash` | 清空记事回收站(永久删除) |
123
- | `list_ai_drafts` | 待确认列表(**仅当前账号自己创建的**;家长也不能看全家);可传 `session_id=mcp` |
124
- | `get_ai_draft` | 单条详情(仅创建者;他人 404) |
125
- | `prepare_confirm_ai_draft` / `confirm_ai_draft` | 单条确认(须解锁 + confirm_token;仅创建者) |
126
- | `discard_ai_draft` | 单条丢弃(仅创建者) |
127
- | `prepare_batch_confirm_ai_drafts` / `batch_confirm_ai_drafts` | 批量确认自己的草稿(须解锁 + confirm_token) |
128
- | `batch_discard_ai_drafts` | 批量丢弃自己的草稿(不改正式数据,无需解锁) |
84
+ 同一回合新建账单和记事时,两边传同一个 `link_group`。只有两边都保存成功才挂上;丢掉一边就不会挂。挂接本身不占每月记账条数。
129
85
 
130
- > App 侧也可在 **我的 → AI 草稿箱** 勾选后批量保存。文件夹规则与 App 一致:全家共用、最多两层、非空不可删。
86
+ ### 改一笔
131
87
 
132
- ### 推荐:整理记事文件夹
88
+ `unlock_writes` → `prepare_update_ledger_entry` → 用户确认 → `confirm_update_ledger_entry`(只支持最近 1 个月内添加的流水)
133
89
 
134
- 1. `list_note_folders` → 了解树
135
- 2. 征得同意 → `unlock_writes`
136
- 3. `create_note_folder` / `rename_note_folder` / `move_note_folder`
137
- 4. `list_notes(folder_id=…)` 浏览本层;`create_note_draft(folder_id=…)` 写入
138
- 5. 移动已有记事:`prepare_move_note` → 确认 → `confirm_move_note`
139
- 6. 删空文件夹:`prepare_delete_note_folder` → 确认 → `confirm_delete_note_folder`
90
+ ### 整理记事
140
91
 
141
- ### 账号只读
92
+ `list_note_folders` → `unlock_writes` → `create_note_folder` / `rename_note_folder` / `move_note_folder`
142
93
 
143
- | Tool | 说明 |
144
- |------|------|
145
- | `get_subscription_info` | 订阅状态 |
146
- | `get_credit_balance` | AI 积分余额 |
94
+ ### 恢复误删
147
95
 
148
- ## 安全说明
96
+ 账单:`list_ledger_trash` → `restore_ledger_entry`
149
97
 
150
- - 令牌生成时**绑定默认家庭**;MCP 会话可切换到**你已加入**的其他家庭,不能访问无关家庭
151
- - 助手令牌仅开放白名单 API;写操作前检查家庭 `entitlements`
152
- - App 内可随时撤销令牌
153
- - 请求带 `X-App-ID: 60000` 与 `X-MCP-Tool`
98
+ 记事:`list_notes_trash` → `restore_note`
154
99
 
155
100
  ## 本地开发
156
101
 
@@ -159,24 +104,32 @@ cd fangcuntai-mcp
159
104
  npm install
160
105
  npm test
161
106
  npm run build
162
- FANGCUNTAI_TOKEN=hm_at_xxx FANGCUNTAI_API=http://127.0.0.1:9080 node dist/index.js
163
- ```
164
107
 
165
- ### 本地功能测试数据
108
+ FANGCUNTAI_TOKEN=hm_at_xxx \
109
+ FANGCUNTAI_API=http://127.0.0.1:9080 \
110
+ node dist/index.js
111
+ ```
166
112
 
167
- 先确保本地 PostgreSQL(`127.0.0.1:5433`)和 Redis(`127.0.0.1:6379`)可用,再执行:
113
+ 本地功能测试数据:
168
114
 
169
115
  ```bash
170
116
  cd ../home-admin
171
117
  go run cmd/seed-mcp-test-data/main.go -config config/config.yaml
172
118
  ```
173
119
 
174
- 命令仅允许写本机开发库,可重复执行且不会重复插入。它会创建 2 个家庭、2 个账本、
175
- 近 3 个月账单、回收站条目、两层记事文件夹、不同可见范围的记事、MCP / 小家师草稿、
176
- 积分和固定测试令牌。输出中的 `FANGCUNTAI_TOKEN` 可直接用于本地 MCP 配置。
120
+ 命令只允许写入本机开发库,可重复执行。
177
121
 
178
122
  ## 发布
179
123
 
180
124
  ```bash
181
125
  npm publish --access public
182
126
  ```
127
+
128
+ ## 链接
129
+
130
+ - 官网:https://www.fangcuntai.com
131
+ - npm:https://www.npmjs.com/package/@fangcuntai/fangcuntai-mcp
132
+
133
+ ## License
134
+
135
+ MIT
@@ -51,5 +51,7 @@ export declare function fetchEntitlements(client: FangcuntaiApiClient, familyId:
51
51
  /** 写操作前检查能力位;失败时抛出中文错误。 */
52
52
  export declare function requireEntitlement(client: FangcuntaiApiClient, familyId: number, key: keyof FamilyEntitlements, denyMessage: string): Promise<void>;
53
53
  export declare function parseAssistantScopes(raw: unknown): string[];
54
+ /** 令牌是否包含任一 scope。还没拉到 scopes 时返回 false,调用方应交给后端判断。 */
55
+ export declare function tokenHasAnyScope(client: FangcuntaiApiClient, anyOf: string[]): Promise<boolean>;
54
56
  /** 令牌未勾选对应权限时拒绝;尚未拉到 scopes 时交给后端 40305。 */
55
57
  export declare function requireTokenScope(client: FangcuntaiApiClient, anyOf: string[], denyMessage?: string): Promise<void>;
@@ -172,6 +172,13 @@ async function ensureTokenScopes(client) {
172
172
  }
173
173
  return cachedTokenScopes ?? [];
174
174
  }
175
+ /** 令牌是否包含任一 scope。还没拉到 scopes 时返回 false,调用方应交给后端判断。 */
176
+ export async function tokenHasAnyScope(client, anyOf) {
177
+ const scopes = await ensureTokenScopes(client);
178
+ if (scopes.length === 0)
179
+ return false;
180
+ return anyOf.some((scope) => scopes.includes(scope));
181
+ }
175
182
  /** 令牌未勾选对应权限时拒绝;尚未拉到 scopes 时交给后端 40305。 */
176
183
  export async function requireTokenScope(client, anyOf, denyMessage = TOKEN_SCOPE_DENIED) {
177
184
  const scopes = await ensureTokenScopes(client);
@@ -1,4 +1,4 @@
1
- export type PendingKind = "create_ledger" | "delete_ledger" | "empty_ledger_trash" | "confirm_draft" | "batch_confirm_draft" | "delete_note" | "empty_notes_trash" | "delete_note_folder" | "move_note";
1
+ export type PendingKind = "create_ledger" | "update_ledger" | "delete_ledger" | "empty_ledger_trash" | "confirm_draft" | "batch_confirm_draft" | "delete_note" | "empty_notes_trash" | "delete_note_folder" | "move_note" | "link_ledger_note" | "unlink_ledger_note";
2
2
  export type PendingWrite = {
3
3
  kind: PendingKind;
4
4
  token: string;
@@ -17,7 +17,7 @@ export function unlockWrites(ttlMs = UNLOCK_TTL_MS) {
17
17
  return {
18
18
  unlocked: true,
19
19
  expires_in_seconds: Math.floor(ttlMs / 1000),
20
- hint: "已解锁写操作。入账/删除/清空回收站/确认草稿仍须 prepare → 向用户展示摘要 → confirm。",
20
+ hint: "已解锁写操作。入账/改账/删除/清空回收站/确认草稿仍须 prepare → 向用户展示摘要 → confirm。",
21
21
  };
22
22
  }
23
23
  export function lockWrites() {
@@ -16,6 +16,8 @@ export function mapApiError(code, message) {
16
16
  return "游客无法使用桌面助手写入能力,请先在 App 绑定邮箱";
17
17
  case 40305:
18
18
  return "当前令牌未勾选此项权限。请在方寸台 App 生成新令牌并勾选对应权限;已有令牌不能改权限";
19
+ case 40306:
20
+ return "桌面助手只能改最近 1 个月内添加的记账";
19
21
  case 40401:
20
22
  return "未找到相关数据";
21
23
  case 40907:
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ async function main() {
9
9
  const client = new FangcuntaiApiClient(config.apiBase, config.token);
10
10
  const server = new McpServer({
11
11
  name: "fangcuntai",
12
- version: "1.6.1",
12
+ version: "1.6.2",
13
13
  });
14
14
  registerTools(server, client);
15
15
  const transport = new StdioServerTransport();
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { ensureFamilyId, familyPath, requireTokenScope, TOKEN_SCOPE_WRITE_DRAFT, TOKEN_SCOPE_WRITE_LEDGER, } from "../context/family-context.js";
3
3
  import { createPending, pendingPublicView, takePending, } from "../context/write-lock.js";
4
+ import { linkRememberedPair } from "./ledger-note-link.js";
4
5
  import { fenToYuan } from "../utils/money.js";
5
6
  import { okJson, runTool } from "../utils/response.js";
6
7
  export function registerDraftTools(server, client) {
@@ -45,7 +46,11 @@ export function registerDraftTools(server, client) {
45
46
  if (draft.draft_type === "ledger" && amount > 0) {
46
47
  summary.amount_yuan = fenToYuan(amount);
47
48
  }
48
- const pending = createPending("confirm_draft", familyId, summary, { draft_id });
49
+ const pending = createPending("confirm_draft", familyId, summary, {
50
+ draft_id,
51
+ draft_type: draft.draft_type,
52
+ link_group: typeof payload.link_group === "string" ? payload.link_group : "",
53
+ });
49
54
  return okJson(pendingPublicView(pending));
50
55
  }));
51
56
  server.tool("confirm_ai_draft", "确认 AI 草稿并写入正式数据。必须传入 prepare_confirm_ai_draft 返回的 confirm_token(不再接受仅 draft_id)。", {
@@ -58,7 +63,18 @@ export function registerDraftTools(server, client) {
58
63
  if (!draftId)
59
64
  throw new Error("确认码缺少 draft_id");
60
65
  const data = await client.post(familyPath(pending.familyId, `/ai-drafts/${draftId}/confirm`));
61
- return okJson({ ...data, hint: "草稿已确认并写入正式数据。" });
66
+ const result = data.result && typeof data.result === "object" ? data.result : {};
67
+ const createdId = Number(result.id ?? 0);
68
+ const draftType = String(pending.exec.draft_type ?? "");
69
+ const side = draftType === "ledger" ? "entry" : draftType === "note" ? "note" : "";
70
+ const link = side
71
+ ? await linkRememberedPair(client, pending.familyId, String(pending.exec.link_group ?? ""), side, createdId)
72
+ : null;
73
+ return okJson({
74
+ ...data,
75
+ link,
76
+ hint: link?.linked ? "草稿已确认,并和另一边挂在一起。" : "草稿已确认并写入正式数据。",
77
+ });
62
78
  }));
63
79
  server.tool("discard_ai_draft", "丢弃 AI 草稿(不可恢复)。丢弃草稿不改正式账本,无需解锁。", { draft_id: z.string().min(1) }, async ({ draft_id }) => runTool(async () => {
64
80
  client.setToolName("discard_ai_draft");
@@ -2,12 +2,14 @@ import { registerAccountTools } from "./account.js";
2
2
  import { registerContextTools } from "./context.js";
3
3
  import { registerDraftTools } from "./drafts.js";
4
4
  import { registerLedgerTools } from "./ledger.js";
5
+ import { registerLedgerNoteLinkTools } from "./ledger-note-link.js";
5
6
  import { registerNoteTools } from "./notes.js";
6
7
  import { registerSafetyTools } from "./safety.js";
7
8
  export function registerTools(server, client) {
8
9
  registerSafetyTools(server);
9
10
  registerContextTools(server, client);
10
11
  registerLedgerTools(server, client);
12
+ registerLedgerNoteLinkTools(server, client);
11
13
  registerNoteTools(server, client);
12
14
  registerDraftTools(server, client);
13
15
  registerAccountTools(server, client);
@@ -0,0 +1,11 @@
1
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import type { FangcuntaiApiClient } from "../client/api-client.js";
3
+ export declare function clearLinkGroups(): void;
4
+ /** 两边都成功后才返回要挂的一对;只到一边就先记住。 */
5
+ export declare function rememberLinkSide(familyId: number, group: string, side: "entry" | "note", id: number): {
6
+ entryId: number;
7
+ noteId: number;
8
+ } | null;
9
+ export declare function linkRememberedPair(client: FangcuntaiApiClient, familyId: number, group: string | undefined, side: "entry" | "note", id: number): Promise<Record<string, unknown> | null>;
10
+ export declare function registerLedgerNoteLinkTools(server: McpServer, client: FangcuntaiApiClient): void;
11
+ export declare function tokenCanSeeLedgerAmounts(client: FangcuntaiApiClient): Promise<boolean>;
@@ -0,0 +1,174 @@
1
+ import { z } from "zod";
2
+ import { ensureFamilyId, familyPath, requireEntitlement, requireTokenScope, tokenHasAnyScope, TOKEN_SCOPE_READ_LEDGER, TOKEN_SCOPE_WRITE_DRAFT, TOKEN_SCOPE_WRITE_LEDGER, } from "../context/family-context.js";
3
+ import { createPending, pendingPublicView, takePending, } from "../context/write-lock.js";
4
+ import { fenToYuan } from "../utils/money.js";
5
+ import { okJson, runTool } from "../utils/response.js";
6
+ const linkGroups = new Map();
7
+ export function clearLinkGroups() {
8
+ linkGroups.clear();
9
+ }
10
+ function groupKey(familyId, group) {
11
+ return `${familyId}:${group.trim()}`;
12
+ }
13
+ /** 两边都成功后才返回要挂的一对;只到一边就先记住。 */
14
+ export function rememberLinkSide(familyId, group, side, id) {
15
+ const name = group.trim();
16
+ if (!name || id <= 0)
17
+ return null;
18
+ const key = groupKey(familyId, name);
19
+ const current = linkGroups.get(key) ?? {};
20
+ if (side === "entry")
21
+ current.entryId = id;
22
+ else
23
+ current.noteId = id;
24
+ if (current.entryId && current.noteId) {
25
+ linkGroups.delete(key);
26
+ return { entryId: current.entryId, noteId: current.noteId };
27
+ }
28
+ linkGroups.set(key, current);
29
+ return null;
30
+ }
31
+ export async function linkRememberedPair(client, familyId, group, side, id) {
32
+ if (!group?.trim())
33
+ return null;
34
+ const pair = rememberLinkSide(familyId, group, side, id);
35
+ if (!pair)
36
+ return { linked: false, waiting: true, link_group: group.trim() };
37
+ try {
38
+ await client.post(familyPath(familyId, "/ledger-note-links"), {
39
+ entry_id: pair.entryId,
40
+ note_id: pair.noteId,
41
+ });
42
+ return { linked: true, link_group: group.trim(), ...pair };
43
+ }
44
+ catch (err) {
45
+ return {
46
+ linked: false,
47
+ link_group: group.trim(),
48
+ link_error: err instanceof Error ? err.message : String(err),
49
+ ...pair,
50
+ };
51
+ }
52
+ }
53
+ async function requireLinkWriteScopes(client) {
54
+ await requireTokenScope(client, [TOKEN_SCOPE_WRITE_LEDGER]);
55
+ await requireTokenScope(client, [TOKEN_SCOPE_WRITE_DRAFT]);
56
+ }
57
+ function entrySummary(entry, bookName) {
58
+ const amount = Number(entry.amount ?? 0);
59
+ return {
60
+ entry_id: entry.id,
61
+ record_date: entry.record_date,
62
+ category: entry.category,
63
+ category_name: entry.category_name,
64
+ description: entry.description ?? "",
65
+ amount,
66
+ amount_yuan: fenToYuan(amount),
67
+ currency: entry.currency,
68
+ ledger_book_name: bookName,
69
+ };
70
+ }
71
+ export function registerLedgerNoteLinkTools(server, client) {
72
+ server.tool("get_ledger_entry", "读取一笔账单。列表里的记事只是有没有,篇名只在这一笔里返回,而且要能看见那篇记事。不含银行卡号和凭证。", {
73
+ entry_id: z.number().int().positive(),
74
+ ledger_book_id: z.number().int().positive().optional(),
75
+ }, async ({ entry_id, ledger_book_id }) => runTool(async () => {
76
+ client.setToolName("get_ledger_entry");
77
+ await requireTokenScope(client, [TOKEN_SCOPE_READ_LEDGER]);
78
+ const familyId = await ensureFamilyId(client);
79
+ await requireEntitlement(client, familyId, "can_use_ledger", "当前角色没有记账权限");
80
+ const query = ledger_book_id ? { ledger_book_id } : undefined;
81
+ const entry = await client.get(familyPath(familyId, `/ledger/${entry_id}`), query);
82
+ const amount = Number(entry.amount ?? 0);
83
+ const notes = Array.isArray(entry.related_notes)
84
+ ? entry.related_notes.map((item) => {
85
+ const row = item;
86
+ return {
87
+ id: row.id,
88
+ title: row.title,
89
+ folder_id: row.folder_id,
90
+ folder_name: row.folder_name,
91
+ };
92
+ })
93
+ : [];
94
+ return okJson({
95
+ ...entry,
96
+ amount_yuan: fenToYuan(amount),
97
+ related_notes: notes,
98
+ });
99
+ }));
100
+ server.tool("prepare_link_ledger_note", "准备把一篇记事挂到一笔账上(先不挂)。须先 unlock_writes。向用户展示篇名、日期、分类和金额后再 confirm_link_ledger_note。", {
101
+ entry_id: z.number().int().positive(),
102
+ note_id: z.number().int().positive(),
103
+ ledger_book_id: z.number().int().positive().optional(),
104
+ }, async ({ entry_id, note_id, ledger_book_id }) => runTool(async () => {
105
+ client.setToolName("prepare_link_ledger_note");
106
+ const familyId = await ensureFamilyId(client);
107
+ await requireLinkWriteScopes(client);
108
+ await requireEntitlement(client, familyId, "can_use_ledger", "当前角色没有记账权限");
109
+ await requireEntitlement(client, familyId, "can_view_notes", "当前角色没有记事权限");
110
+ const query = ledger_book_id ? { ledger_book_id } : undefined;
111
+ const entry = await client.get(familyPath(familyId, `/ledger/${entry_id}`), query);
112
+ const note = await client.get(familyPath(familyId, `/notes/${note_id}`));
113
+ const summary = {
114
+ action: "link",
115
+ ...entrySummary(entry, String(entry.ledger_book_name ?? "")),
116
+ note_id: note.id,
117
+ note_title: note.title,
118
+ folder_name: note.folder_name ?? "",
119
+ };
120
+ const pending = createPending("link_ledger_note", familyId, summary, {
121
+ entry_id,
122
+ note_id,
123
+ });
124
+ return okJson(pendingPublicView(pending));
125
+ }));
126
+ server.tool("confirm_link_ledger_note", "确认挂接。必须传入 prepare_link_ledger_note 的 confirm_token。", { confirm_token: z.string().min(1) }, async ({ confirm_token }) => runTool(async () => {
127
+ client.setToolName("confirm_link_ledger_note");
128
+ await requireLinkWriteScopes(client);
129
+ const pending = takePending(confirm_token, "link_ledger_note");
130
+ await client.post(familyPath(pending.familyId, "/ledger-note-links"), {
131
+ entry_id: pending.exec.entry_id,
132
+ note_id: pending.exec.note_id,
133
+ });
134
+ return okJson({ ok: true, ...pending.summary, hint: "已挂上。拆开用 prepare_unlink_ledger_note。" });
135
+ }));
136
+ server.tool("prepare_unlink_ledger_note", "准备拆开一篇记事和一笔账(先不拆)。须先 unlock_writes。向用户展示摘要后再 confirm_unlink_ledger_note。", {
137
+ entry_id: z.number().int().positive(),
138
+ note_id: z.number().int().positive(),
139
+ ledger_book_id: z.number().int().positive().optional(),
140
+ }, async ({ entry_id, note_id, ledger_book_id }) => runTool(async () => {
141
+ client.setToolName("prepare_unlink_ledger_note");
142
+ const familyId = await ensureFamilyId(client);
143
+ await requireLinkWriteScopes(client);
144
+ await requireEntitlement(client, familyId, "can_use_ledger", "当前角色没有记账权限");
145
+ await requireEntitlement(client, familyId, "can_view_notes", "当前角色没有记事权限");
146
+ const query = ledger_book_id ? { ledger_book_id } : undefined;
147
+ const entry = await client.get(familyPath(familyId, `/ledger/${entry_id}`), query);
148
+ const note = await client.get(familyPath(familyId, `/notes/${note_id}`));
149
+ const summary = {
150
+ action: "unlink",
151
+ ...entrySummary(entry, String(entry.ledger_book_name ?? "")),
152
+ note_id: note.id,
153
+ note_title: note.title,
154
+ };
155
+ const pending = createPending("unlink_ledger_note", familyId, summary, {
156
+ entry_id,
157
+ note_id,
158
+ });
159
+ return okJson(pendingPublicView(pending));
160
+ }));
161
+ server.tool("confirm_unlink_ledger_note", "确认拆开。必须传入 prepare_unlink_ledger_note 的 confirm_token。只拆挂接,不删账也不删记事。", { confirm_token: z.string().min(1) }, async ({ confirm_token }) => runTool(async () => {
162
+ client.setToolName("confirm_unlink_ledger_note");
163
+ await requireLinkWriteScopes(client);
164
+ const pending = takePending(confirm_token, "unlink_ledger_note");
165
+ await client.delete(familyPath(pending.familyId, "/ledger-note-links"), {
166
+ entry_id: Number(pending.exec.entry_id),
167
+ note_id: Number(pending.exec.note_id),
168
+ });
169
+ return okJson({ ok: true, ...pending.summary, hint: "已拆开。账和记事都还在。" });
170
+ }));
171
+ }
172
+ export async function tokenCanSeeLedgerAmounts(client) {
173
+ return tokenHasAnyScope(client, [TOKEN_SCOPE_READ_LEDGER, TOKEN_SCOPE_WRITE_LEDGER]);
174
+ }
@@ -10,9 +10,37 @@ export type PrepareCreateLedgerInput = {
10
10
  ledger_book_id?: number;
11
11
  tags?: string[];
12
12
  external_order_id?: string;
13
+ link_group?: string;
13
14
  };
14
15
  /** 准备记一笔:须先 unlock_writes。不打入账 API。 */
15
16
  export declare function prepareCreateLedgerEntry(client: FangcuntaiApiClient, input: PrepareCreateLedgerInput): Promise<Record<string, unknown>>;
17
+ export type PrepareUpdateLedgerInput = {
18
+ entry_id: number;
19
+ ledger_book_id?: number;
20
+ type?: "expense" | "income";
21
+ amount_yuan?: number;
22
+ category?: string;
23
+ description?: string;
24
+ date?: string;
25
+ record_time_enabled?: boolean;
26
+ currency?: string;
27
+ fund_account_type?: string;
28
+ fund_account_detail?: string;
29
+ payer?: string;
30
+ billing_month?: string;
31
+ tags?: string[];
32
+ add_tags?: string[];
33
+ voucher_flags?: string[];
34
+ external_order_id?: string;
35
+ recorder_user_id?: number;
36
+ pocket_user_id?: number;
37
+ linked_ledger_book_id?: number;
38
+ };
39
+ export declare function ledgerCreatedWithinLastMonth(createdAtSec: number, nowMs?: number): boolean;
40
+ /** 准备改一笔:须先 unlock_writes。只允许改最近 1 个月内添加的流水。 */
41
+ export declare function prepareUpdateLedgerEntry(client: FangcuntaiApiClient, input: PrepareUpdateLedgerInput): Promise<Record<string, unknown>>;
42
+ /** 确认改一笔:一次性 token,PUT 原条目。 */
43
+ export declare function confirmUpdateLedgerEntry(client: FangcuntaiApiClient, confirmToken: string): Promise<Record<string, unknown>>;
16
44
  /** 确认记一笔:一次性 token,POST 金额为分,并标记 source=desktop_mcp。 */
17
45
  export declare function confirmCreateLedgerEntry(client: FangcuntaiApiClient, confirmToken: string): Promise<Record<string, unknown>>;
18
46
  export declare function registerLedgerTools(server: McpServer, client: FangcuntaiApiClient): void;
@@ -1,7 +1,8 @@
1
1
  import { z } from "zod";
2
2
  import { currentLedgerBookId, ensureFamilyId, familyPath, getWorkspaceContext, ledgerBookQuery, requireEntitlement, requireTokenScope, selectLedgerBook, TOKEN_SCOPE_READ_LEDGER, TOKEN_SCOPE_READ_STATS, TOKEN_SCOPE_WRITE_DRAFT, TOKEN_SCOPE_WRITE_LEDGER, } from "../context/family-context.js";
3
3
  import { createPending, pendingPublicView, takePending, } from "../context/write-lock.js";
4
- import { fenToYuan, mapItemsWithYuan, yuanToFen } from "../utils/money.js";
4
+ import { linkRememberedPair } from "./ledger-note-link.js";
5
+ import { fenToYuan, mapItemsWithYuan, stripLedgerListNoteDetails, yuanToFen } from "../utils/money.js";
5
6
  import { okJson, runTool } from "../utils/response.js";
6
7
  const optionalBookId = z
7
8
  .number()
@@ -60,6 +61,7 @@ export async function prepareCreateLedgerEntry(client, input) {
60
61
  ledger_book_id: bookId || null,
61
62
  tags: input.tags ?? [],
62
63
  external_order_id: externalOrderId || null,
64
+ link_group: input.link_group?.trim() || null,
63
65
  source: "desktop_mcp",
64
66
  family_id: familyId,
65
67
  }, {
@@ -72,9 +74,135 @@ export async function prepareCreateLedgerEntry(client, input) {
72
74
  ledger_book_id: bookId,
73
75
  tags: input.tags,
74
76
  external_order_id: externalOrderId || undefined,
77
+ link_group: input.link_group?.trim() || undefined,
75
78
  });
76
79
  return { ...pendingPublicView(pending), workspace };
77
80
  }
81
+ export function ledgerCreatedWithinLastMonth(createdAtSec, nowMs = Date.now()) {
82
+ if (!Number.isFinite(createdAtSec) || createdAtSec <= 0)
83
+ return false;
84
+ const cutoff = new Date(nowMs);
85
+ cutoff.setMonth(cutoff.getMonth() - 1);
86
+ return createdAtSec * 1000 >= cutoff.getTime();
87
+ }
88
+ function buildLedgerUpdatePatch(input) {
89
+ const patch = {};
90
+ if (input.type)
91
+ patch.type = input.type;
92
+ if (input.amount_yuan !== undefined)
93
+ patch.amount = yuanToFen(input.amount_yuan);
94
+ if (input.category !== undefined)
95
+ patch.category = input.category;
96
+ if (input.description !== undefined)
97
+ patch.description = input.description;
98
+ if (input.date !== undefined)
99
+ patch.record_date = parseRecordDate(input.date);
100
+ if (input.record_time_enabled !== undefined)
101
+ patch.record_time_enabled = input.record_time_enabled;
102
+ if (input.currency !== undefined)
103
+ patch.currency = input.currency;
104
+ if (input.fund_account_type !== undefined)
105
+ patch.fund_account_type = input.fund_account_type;
106
+ if (input.fund_account_detail !== undefined)
107
+ patch.fund_account_detail = input.fund_account_detail;
108
+ if (input.payer !== undefined)
109
+ patch.payer = input.payer;
110
+ if (input.billing_month !== undefined)
111
+ patch.billing_month = input.billing_month;
112
+ if (input.voucher_flags !== undefined)
113
+ patch.voucher_flags = input.voucher_flags;
114
+ if (input.external_order_id !== undefined)
115
+ patch.external_order_id = input.external_order_id.trim();
116
+ if (input.recorder_user_id !== undefined)
117
+ patch.recorder_user_id = input.recorder_user_id;
118
+ if (input.pocket_user_id !== undefined)
119
+ patch.pocket_user_id = input.pocket_user_id;
120
+ if (input.linked_ledger_book_id !== undefined)
121
+ patch.linked_ledger_book_id = input.linked_ledger_book_id;
122
+ if (input.tags !== undefined)
123
+ patch.tags = input.tags;
124
+ return patch;
125
+ }
126
+ /** 准备改一笔:须先 unlock_writes。只允许改最近 1 个月内添加的流水。 */
127
+ export async function prepareUpdateLedgerEntry(client, input) {
128
+ const familyId = await ensureFamilyId(client);
129
+ await requireTokenScope(client, [TOKEN_SCOPE_WRITE_LEDGER]);
130
+ await requireEntitlement(client, familyId, "can_use_ledger", "当前角色没有记账权限,无法修改记账");
131
+ const bookQuery = ledgerBookQuery(input.ledger_book_id);
132
+ const entry = await client.get(familyPath(familyId, `/ledger/${input.entry_id}`), bookQuery);
133
+ const createdAt = Number(entry.created_at ?? 0);
134
+ if (!ledgerCreatedWithinLastMonth(createdAt)) {
135
+ throw new Error("桌面助手只能改最近 1 个月内添加的记账。更早的请在 App 里改,或让小家师出更新草稿。");
136
+ }
137
+ const patch = buildLedgerUpdatePatch(input);
138
+ if (input.add_tags?.length) {
139
+ const existingTags = Array.isArray(entry.tags)
140
+ ? entry.tags
141
+ .map((tag) => {
142
+ if (typeof tag === "string")
143
+ return tag.trim();
144
+ if (tag && typeof tag === "object" && "name" in tag) {
145
+ return String(tag.name ?? "").trim();
146
+ }
147
+ return "";
148
+ })
149
+ .filter(Boolean)
150
+ : [];
151
+ const merged = [...existingTags];
152
+ for (const raw of input.add_tags) {
153
+ const name = String(raw ?? "").trim();
154
+ if (!name)
155
+ continue;
156
+ if (!merged.some((item) => item.toLowerCase() === name.toLowerCase())) {
157
+ merged.push(name);
158
+ }
159
+ }
160
+ patch.tags = merged.slice(0, 5);
161
+ }
162
+ if (Object.keys(patch).length === 0) {
163
+ throw new Error("请至少提供一个要修改的字段");
164
+ }
165
+ const pending = createPending("update_ledger", familyId, {
166
+ action: "update_ledger_entry",
167
+ entry_id: input.entry_id,
168
+ current: {
169
+ type: entry.type,
170
+ amount_yuan: fenToYuan(Number(entry.amount ?? 0)),
171
+ category: entry.category,
172
+ description: entry.description,
173
+ record_date: entry.record_date,
174
+ tags: entry.tags ?? [],
175
+ created_at: createdAt,
176
+ },
177
+ patch: {
178
+ ...patch,
179
+ amount_yuan: input.amount_yuan,
180
+ },
181
+ note: "只改原来这一笔,不会另记一笔新账。只能改最近 1 个月内添加的流水。",
182
+ }, {
183
+ entry_id: input.entry_id,
184
+ ledger_book_id: bookQuery.ledger_book_id,
185
+ patch,
186
+ });
187
+ return { ...pendingPublicView(pending), workspace: await getWorkspaceContext(client) };
188
+ }
189
+ /** 确认改一笔:一次性 token,PUT 原条目。 */
190
+ export async function confirmUpdateLedgerEntry(client, confirmToken) {
191
+ await requireTokenScope(client, [TOKEN_SCOPE_WRITE_LEDGER]);
192
+ const pending = takePending(confirmToken, "update_ledger");
193
+ const entryId = Number(pending.exec.entry_id);
194
+ const bookId = pending.exec.ledger_book_id;
195
+ const patch = (pending.exec.patch ?? {});
196
+ const path = bookId && bookId > 0
197
+ ? `${familyPath(pending.familyId, `/ledger/${entryId}`)}?ledger_book_id=${bookId}`
198
+ : familyPath(pending.familyId, `/ledger/${entryId}`);
199
+ const data = await client.put(path, patch);
200
+ return {
201
+ ...data,
202
+ hint: "已改原来那一笔(来源:桌面助手 MCP)。",
203
+ workspace: await getWorkspaceContext(client),
204
+ };
205
+ }
78
206
  /** 确认记一笔:一次性 token,POST 金额为分,并标记 source=desktop_mcp。 */
79
207
  export async function confirmCreateLedgerEntry(client, confirmToken) {
80
208
  await requireTokenScope(client, [TOKEN_SCOPE_WRITE_LEDGER]);
@@ -103,11 +231,16 @@ export async function confirmCreateLedgerEntry(client, confirmToken) {
103
231
  ? `${familyPath(familyId, "/ledger")}?ledger_book_id=${bookId}`
104
232
  : familyPath(familyId, "/ledger");
105
233
  const data = await client.post(path, payload);
234
+ const entryId = Number(data.id ?? 0);
235
+ const link = await linkRememberedPair(client, familyId, typeof exec.link_group === "string" ? exec.link_group : undefined, "entry", entryId);
106
236
  return {
107
237
  ...data,
108
238
  amount_yuan: exec.amount_yuan,
109
239
  source: "desktop_mcp",
110
- hint: "已入账(来源:桌面助手 MCP)。",
240
+ link,
241
+ hint: link?.linked
242
+ ? "已入账,并和对应记事挂在一起。"
243
+ : "已入账(来源:桌面助手 MCP)。",
111
244
  workspace: await getWorkspaceContext(client),
112
245
  };
113
246
  }
@@ -185,7 +318,7 @@ export function registerLedgerTools(server, client) {
185
318
  ...ledgerBookQuery(ledger_book_id),
186
319
  });
187
320
  return okJson({
188
- ...mapItemsWithYuan(data),
321
+ ...stripLedgerListNoteDetails(mapItemsWithYuan(data)),
189
322
  workspace: await getWorkspaceContext(client),
190
323
  });
191
324
  }));
@@ -229,6 +362,10 @@ export function registerLedgerTools(server, client) {
229
362
  .string()
230
363
  .optional()
231
364
  .describe("外部订单号,非必填。同一账本内已存在则不会重复入账"),
365
+ link_group: z
366
+ .string()
367
+ .optional()
368
+ .describe("和同一回合新建的记事使用同一个名字,两边都成功后才挂上。用户没明确要求就不要传"),
232
369
  }, async (input) => runTool(async () => {
233
370
  client.setToolName("prepare_create_ledger_entry");
234
371
  return okJson(await prepareCreateLedgerEntry(client, input));
@@ -239,6 +376,37 @@ export function registerLedgerTools(server, client) {
239
376
  client.setToolName("confirm_create_ledger_entry");
240
377
  return okJson(await confirmCreateLedgerEntry(client, confirm_token));
241
378
  }));
379
+ server.tool("prepare_update_ledger_entry", "准备修改已入账的一笔流水(不直接写入)。须先 unlock_writes。只支持修改最近 1 个月内添加的内容。返回 summary + confirm_token,向用户确认后再 confirm_update_ledger_entry。不会另记一笔新账。", {
380
+ entry_id: z.number().int().positive().describe("记账条目 ID"),
381
+ ledger_book_id: optionalBookId,
382
+ type: z.enum(["expense", "income"]).optional(),
383
+ amount_yuan: z.number().positive().optional().describe("金额(元)"),
384
+ category: z.string().optional(),
385
+ description: z.string().optional(),
386
+ date: z.string().optional().describe("YYYY-MM-DD"),
387
+ record_time_enabled: z.boolean().optional(),
388
+ currency: z.string().optional(),
389
+ fund_account_type: z.string().optional().describe("cash / wechat / alipay / bank_card 等"),
390
+ fund_account_detail: z.string().optional(),
391
+ payer: z.string().optional().describe("对方"),
392
+ billing_month: z.string().optional().describe("YYYY-MM"),
393
+ tags: z.array(z.string()).optional().describe("整笔替换标签"),
394
+ add_tags: z.array(z.string()).optional().describe("追加标签,不覆盖已有"),
395
+ voucher_flags: z.array(z.string()).optional(),
396
+ external_order_id: z.string().optional(),
397
+ recorder_user_id: z.number().int().min(0).optional(),
398
+ pocket_user_id: z.number().int().min(0).optional(),
399
+ linked_ledger_book_id: z.number().int().min(0).optional(),
400
+ }, async (input) => runTool(async () => {
401
+ client.setToolName("prepare_update_ledger_entry");
402
+ return okJson(await prepareUpdateLedgerEntry(client, input));
403
+ }));
404
+ server.tool("confirm_update_ledger_entry", "确认修改原来那一笔记账。必须传入 prepare_update_ledger_entry 返回的 confirm_token。只能改最近 1 个月内添加的流水。", {
405
+ confirm_token: z.string().min(1),
406
+ }, async ({ confirm_token }) => runTool(async () => {
407
+ client.setToolName("confirm_update_ledger_entry");
408
+ return okJson(await confirmUpdateLedgerEntry(client, confirm_token));
409
+ }));
242
410
  server.tool("prepare_delete_ledger_entry", "准备删除记账(移入回收站,可恢复)。须先 unlock_writes。会拉取条目摘要供用户确认。", {
243
411
  entry_id: z.number().int().positive().describe("记账条目 ID"),
244
412
  ledger_book_id: optionalBookId,
@@ -296,7 +464,7 @@ export function registerLedgerTools(server, client) {
296
464
  const familyId = await ensureFamilyId(client);
297
465
  const data = await client.get(familyPath(familyId, "/ledger/trash"), { page, page_size, ...ledgerBookQuery(ledger_book_id) });
298
466
  return okJson({
299
- ...mapItemsWithYuan(data),
467
+ ...stripLedgerListNoteDetails(mapItemsWithYuan(data)),
300
468
  workspace: await getWorkspaceContext(client),
301
469
  });
302
470
  }));
@@ -1,5 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { ensureFamilyId, familyPath, requireEntitlement, requireTokenScope, TOKEN_SCOPE_WRITE_DRAFT } from "../context/family-context.js";
3
+ import { tokenCanSeeLedgerAmounts } from "./ledger-note-link.js";
4
+ import { fenToYuan, stripNoteListLedgerDetails } from "../utils/money.js";
3
5
  import { createPending, pendingPublicView, requireWritesUnlocked, takePending, } from "../context/write-lock.js";
4
6
  import { okJson, runTool } from "../utils/response.js";
5
7
  /** folder_id:省略=不过滤/不改;0=未分类;正整数=指定文件夹。 */
@@ -134,7 +136,37 @@ export function registerNoteTools(server, client) {
134
136
  query.folder_id = folder_id;
135
137
  }
136
138
  const data = await client.get(familyPath(familyId, "/notes"), query);
137
- return okJson(data);
139
+ const seeLedger = await tokenCanSeeLedgerAmounts(client);
140
+ return okJson(stripNoteListLedgerDetails(data, seeLedger));
141
+ }));
142
+ server.tool("get_note", "读取一篇看得见的记事。有记账读取权限时附带相关账单的日期、分类、金额和备注,不含银行卡号和凭证。", { note_id: z.number().int().positive() }, async ({ note_id }) => runTool(async () => {
143
+ client.setToolName("get_note");
144
+ const familyId = await ensureFamilyId(client);
145
+ await requireEntitlement(client, familyId, "can_view_notes", "当前角色没有记事权限");
146
+ const note = await client.get(familyPath(familyId, `/notes/${note_id}`));
147
+ const seeLedger = await tokenCanSeeLedgerAmounts(client);
148
+ if (!seeLedger) {
149
+ delete note.related_entries;
150
+ delete note.has_visible_related_entry;
151
+ return okJson(note);
152
+ }
153
+ const entries = Array.isArray(note.related_entries) ? note.related_entries : [];
154
+ note.related_entries = entries.map((item) => {
155
+ const row = item;
156
+ const amount = Number(row.amount ?? 0);
157
+ return {
158
+ id: row.id,
159
+ record_date: row.record_date,
160
+ category: row.category,
161
+ category_name: row.category_name,
162
+ amount,
163
+ amount_yuan: fenToYuan(amount),
164
+ currency: row.currency,
165
+ ledger_book_name: row.ledger_book_name,
166
+ description: row.description ?? "",
167
+ };
168
+ });
169
+ return okJson(note);
138
170
  }));
139
171
  server.tool("search_notes", "按关键词搜索家庭记事(全部可见笔记,不受当前文件夹限制)。", { keyword: z.string().min(1) }, async ({ keyword }) => runTool(async () => {
140
172
  client.setToolName("search_notes");
@@ -144,13 +176,16 @@ export function registerNoteTools(server, client) {
144
176
  page: 1,
145
177
  page_size: 20,
146
178
  });
147
- return okJson(data);
179
+ const seeLedger = await tokenCanSeeLedgerAmounts(client);
180
+ return okJson(stripNoteListLedgerDetails(data, seeLedger));
148
181
  }));
149
- server.tool("create_note_draft", "创建记事草稿(不会直接保存)。visibility 可选 family / personal / selected / owner_only。folder_id 可选:0/省略=未分类,正整数=指定文件夹。", {
182
+ server.tool("create_note_draft", "创建记事草稿(不会直接保存)。visibility 可选 family / personal / selected / owner_only。folder_id 可选:0/省略=未分类,正整数=指定文件夹。待办写成 - [ ] / - [x];引用其他记事用 [[标题]] 或 [说明](note:id)。", {
150
183
  title: z.string().min(1),
151
184
  content: z.string().optional(),
152
185
  visibility: z.enum(["family", "personal", "selected", "owner_only"]).optional(),
153
186
  folder_id: folderIdParam.describe("所属文件夹;0/省略=未分类"),
187
+ link_group: z.string().optional().describe("和同一回合新建的账单使用同一个名字,两边都成功后才挂上"),
188
+ related_entry_ids: z.array(z.number().int().positive()).optional().describe("挂到已经存在的账单;用户没明确要求就不要传"),
154
189
  }, async (input) => runTool(async () => {
155
190
  client.setToolName("create_note_draft");
156
191
  const familyId = await ensureFamilyId(client);
@@ -164,6 +199,14 @@ export function registerNoteTools(server, client) {
164
199
  if (input.folder_id !== undefined) {
165
200
  payload.folder_id = input.folder_id;
166
201
  }
202
+ if (input.link_group?.trim()) {
203
+ payload.link_group = input.link_group.trim();
204
+ payload.link_after_save = true;
205
+ }
206
+ if (input.related_entry_ids?.length) {
207
+ payload.related_entry_ids = input.related_entry_ids;
208
+ payload.link_after_save = true;
209
+ }
167
210
  const data = await client.post(familyPath(familyId, "/ai-drafts"), {
168
211
  draft_type: "note",
169
212
  session_id: "mcp",
@@ -5,10 +5,10 @@ export function registerSafetyTools(server) {
5
5
  server.tool("get_write_lock_status", "查看 MCP 写操作安全锁状态(是否已解锁、剩余秒数、待确认数)。", {}, async () => runTool(async () => {
6
6
  return okJson({
7
7
  ...getWriteLockStatus(),
8
- policy: "默认上锁。查账/列文件夹/建草稿可用;入账、删除记账/记事、清空回收站、确认草稿、删除文件夹、移动记事所属文件夹须 unlock_writes → prepare_* → 用户确认 → confirm_*。新建/改名/移动文件夹须先 unlock_writes。删除进入回收站,可恢复;清空回收站不可恢复。",
8
+ policy: "默认上锁。查账/列文件夹/建草稿可用;入账、改账、删除记账/记事、清空回收站、确认草稿、删除文件夹、移动记事所属文件夹须 unlock_writes → prepare_* → 用户确认 → confirm_*。新建/改名/移动文件夹须先 unlock_writes。删除进入回收站,可恢复;清空回收站不可恢复。改账只支持最近 1 个月内添加的流水。",
9
9
  });
10
10
  }));
11
- server.tool("unlock_writes", "解锁写操作(须先征得用户同意)。解锁后仍须对入账/删除/确认草稿(含批量)走 prepare→confirm,不能一步写库。约 15 分钟无操作会过期。", {
11
+ server.tool("unlock_writes", "解锁写操作(须先征得用户同意)。解锁后仍须对入账/改账/删除/确认草稿(含批量)走 prepare→confirm,不能一步写库。约 15 分钟无操作会过期。", {
12
12
  user_acknowledged: z
13
13
  .boolean()
14
14
  .describe("必须为 true,表示已向用户说明风险并获得同意"),
@@ -8,3 +8,7 @@ export declare function withYuanAmount<T extends Record<string, unknown>>(entry:
8
8
  };
9
9
  /** 列表结果中的 items 批量补元。 */
10
10
  export declare function mapItemsWithYuan(data: Record<string, unknown>): Record<string, unknown>;
11
+ /** 流水列表只留「有没有看得见的记事」,不带篇名。 */
12
+ export declare function stripLedgerListNoteDetails(data: Record<string, unknown>): Record<string, unknown>;
13
+ /** 记事列表只留布尔值;没有记账读取权限时连布尔值也不给。 */
14
+ export declare function stripNoteListLedgerDetails(data: Record<string, unknown>, includeLedgerFlag: boolean): Record<string, unknown>;
@@ -26,3 +26,37 @@ export function mapItemsWithYuan(data) {
26
26
  items: items.map((item) => item && typeof item === "object" ? withYuanAmount(item) : item),
27
27
  };
28
28
  }
29
+ /** 流水列表只留「有没有看得见的记事」,不带篇名。 */
30
+ export function stripLedgerListNoteDetails(data) {
31
+ const items = data.items;
32
+ if (!Array.isArray(items))
33
+ return data;
34
+ return {
35
+ ...data,
36
+ items: items.map((item) => {
37
+ if (!item || typeof item !== "object")
38
+ return item;
39
+ const row = { ...item };
40
+ delete row.related_notes;
41
+ return row;
42
+ }),
43
+ };
44
+ }
45
+ /** 记事列表只留布尔值;没有记账读取权限时连布尔值也不给。 */
46
+ export function stripNoteListLedgerDetails(data, includeLedgerFlag) {
47
+ const items = data.items;
48
+ if (!Array.isArray(items))
49
+ return data;
50
+ return {
51
+ ...data,
52
+ items: items.map((item) => {
53
+ if (!item || typeof item !== "object")
54
+ return item;
55
+ const row = { ...item };
56
+ delete row.related_entries;
57
+ if (!includeLedgerFlag)
58
+ delete row.has_visible_related_entry;
59
+ return row;
60
+ }),
61
+ };
62
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fangcuntai/fangcuntai-mcp",
3
- "version": "1.6.2",
3
+ "version": "1.6.4",
4
4
  "description": "方寸台桌面助手 MCP — 确认锁 + 来源标记 + 回收站 + 记事文件夹整理,安全地用自然语言管理家庭账本与记事",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -9,7 +9,8 @@
9
9
  },
10
10
  "files": [
11
11
  "dist",
12
- "README.md"
12
+ "README.md",
13
+ "README.en.md"
13
14
  ],
14
15
  "scripts": {
15
16
  "build": "tsc",