@fangcuntai/fangcuntai-mcp 1.6.3 → 1.6.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.en.md CHANGED
@@ -9,7 +9,7 @@ Fangcuntai Desktop Assistant MCP server. Connect it to Lobster / OpenClaw, Claud
9
9
  - Switch between families and ledger books.
10
10
  - Query summaries, entries, trends, and categories.
11
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.
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
13
  - Review and confirm AI drafts.
14
14
  - Check subscription status and AI credit balance.
15
15
  - Track writes created by the desktop assistant.
@@ -77,6 +77,18 @@ Other safeguards:
77
77
 
78
78
  `unlock_writes` -> `prepare_create_ledger_entry` -> user confirmation -> `confirm_create_ledger_entry`
79
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
+
80
92
  ### Organize notes
81
93
 
82
94
  `list_note_folders` -> `unlock_writes` -> `create_note_folder` / `rename_note_folder` / `move_note_folder`
package/README.md CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  - 切换家庭和账本,查询收支摘要、账单、趋势与分类。
10
10
  - 在确认锁保护下记账、删除、恢复回收站和清空回收站。
11
- - 查看和搜索记事,整理两层记事文件夹,创建记事草稿。
11
+ - 查看和搜索记事,整理两层记事文件夹,创建记事草稿。待办写成 `- [ ]` / `- [x]`,一篇可用 `[[标题]]` 连到另一篇。
12
12
  - 查看并批量确认 AI 草稿,查询订阅和 AI 积分。
13
13
  - 写入数据带来源标记,可在方寸台 App 中追踪。
14
14
 
@@ -75,6 +75,18 @@ MCP 只访问方寸台 API,不直连数据库。
75
75
 
76
76
  `unlock_writes` → `prepare_create_ledger_entry` → 用户确认 → `confirm_create_ledger_entry`
77
77
 
78
+ ### 记事和账单挂在一起
79
+
80
+ 流水列表只有 `has_visible_related_note`,不带篇名。看一篇用 `get_ledger_entry`(要能看见那篇记事)。看一笔相关账单用 `get_note`,没有记账读取权限时不返回金额。
81
+
82
+ 挂上或拆开已经存在的记录:`unlock_writes` → `prepare_link_ledger_note` / `prepare_unlink_ledger_note` → 向用户展示篇名、日期、分类和金额 → `confirm_link_ledger_note` / `confirm_unlink_ledger_note`。需要同时勾选写入账单和写入草稿。
83
+
84
+ 同一回合新建账单和记事时,两边传同一个 `link_group`。只有两边都保存成功才挂上;丢掉一边就不会挂。挂接本身不占每月记账条数。
85
+
86
+ ### 改一笔
87
+
88
+ `unlock_writes` → `prepare_update_ledger_entry` → 用户确认 → `confirm_update_ledger_entry`(只支持最近 1 个月内添加的流水)
89
+
78
90
  ### 整理记事
79
91
 
80
92
  `list_note_folders` → `unlock_writes` → `create_note_folder` / `rename_note_folder` / `move_note_folder`
@@ -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
@@ -1,15 +1,17 @@
1
1
  #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
2
3
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
4
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
5
  import { FangcuntaiApiClient } from "./client/api-client.js";
5
6
  import { loadConfig } from "./config.js";
6
7
  import { registerTools } from "./tools/index.js";
8
+ const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
7
9
  async function main() {
8
10
  const config = loadConfig();
9
11
  const client = new FangcuntaiApiClient(config.apiBase, config.token);
10
12
  const server = new McpServer({
11
13
  name: "fangcuntai",
12
- version: "1.6.2",
14
+ version,
13
15
  });
14
16
  registerTools(server, client);
15
17
  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.3",
3
+ "version": "1.6.5",
4
4
  "description": "方寸台桌面助手 MCP — 确认锁 + 来源标记 + 回收站 + 记事文件夹整理,安全地用自然语言管理家庭账本与记事",
5
5
  "license": "MIT",
6
6
  "type": "module",