@getnote/mcp 1.7.2 → 1.9.0

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.
@@ -0,0 +1,89 @@
1
+ import { z } from "zod";
2
+
3
+ const text = z.string().trim().min(1);
4
+ const integer = z.number().int().positive();
5
+ const times = ["created_from", "created_to", "edited_from", "edited_to", "record_updated_from", "record_updated_to"] as const;
6
+ export const noteSelectors = {
7
+ source: text.optional(), note_type: text.optional(),
8
+ reference_resource_type: text.optional(), reference_resource_id: text.optional(),
9
+ reference_article_url: z.string().url().refine(v => /^https?:\/\//.test(v)).optional(),
10
+ topic_id: text.optional(), page_size: integer.max(100).optional(),
11
+ created_from: text.optional(), created_to: text.optional(), edited_from: text.optional(), edited_to: text.optional(),
12
+ record_updated_from: text.optional(), record_updated_to: text.optional(),
13
+ };
14
+ export type NoteDiscoveryOptions = z.infer<ReturnType<typeof noteSchema>>;
15
+ function noteSchema() { return z.object({ ...noteSelectors, page: integer.optional(), cursor: z.string().min(1).optional() }).strict(); }
16
+ const lookupSchema = z.object({ page: integer.optional(), scope: z.enum(["DEFAULT", "CUSTOMER", "BOOKSPACE", "TEAMSPACE"]).optional(), query: text.optional(), author: text.optional(), book_id: text.optional(), page_size: integer.max(100).optional() }).strict();
17
+ export type LookupOptions = z.infer<typeof lookupSchema>;
18
+ export type DiscoveryKind = "notes" | "topicNotes" | "topics" | "detail";
19
+ export type DiscoveryContract = { params: Record<string, unknown>; filters: Record<string, string>; capabilities: string[]; kind: DiscoveryKind };
20
+
21
+ export function normalizeLookup(value: string): string {
22
+ value = value.normalize("NFKC").trim();
23
+ for (const [left, right] of [["《", "》"], ["“", "”"], ['"', '"'], ["'", "'"]]) {
24
+ if (value.startsWith(left) && value.endsWith(right) && value.length >= left.length + right.length) { value = value.slice(left.length, -right.length).trim(); break; }
25
+ }
26
+ return value.toLowerCase();
27
+ }
28
+
29
+ // Keep nanoseconds: Date alone would round distinct reference/time boundaries.
30
+ function timestamp(value: string): { text: string; epoch: bigint } {
31
+ z.string().datetime({ offset: true }).parse(value);
32
+ const m = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/.exec(value);
33
+ if (!m) throw new Error("time filters require RFC3339 with timezone");
34
+ const ms = Date.parse(m[1] + m[3]);
35
+ if (!Number.isFinite(ms)) throw new Error("invalid time filter");
36
+ const fraction = (m[2] || "").replace(/0+$/, "");
37
+ return { text: new Date(ms).toISOString().slice(0, 19) + (fraction ? "." + fraction : "") + "Z", epoch: BigInt(ms) * 1000000n + BigInt((m[2] || "").padEnd(9, "0")) };
38
+ }
39
+
40
+ export function discoveryContract(kind: DiscoveryKind, input: Record<string, unknown>): DiscoveryContract | undefined {
41
+ const values = Object.fromEntries(Object.entries(input).filter(([, v]) => v !== undefined));
42
+ const legacy = kind === "topics" ? ["page", "scope"] : kind === "detail" ? ["id", "image_quality"] : kind === "topicNotes" ? ["topic_id", "page"] : ["cursor"];
43
+ if (!Object.keys(values).some(k => !legacy.includes(k))) return undefined;
44
+ let params: Record<string, unknown>;
45
+ const filters: Record<string, string> = {};
46
+ if (kind === "detail") {
47
+ params = z.object({ id: z.union([text, z.number().int().safe()]), image_quality: z.enum(["original"]).optional() }).strict().parse(values);
48
+ return { params, filters, capabilities: ["note.reference.v1"], kind };
49
+ }
50
+ if (kind === "topics") {
51
+ params = { scope: "DEFAULT", page: 1, page_size: 20, ...lookupSchema.parse(values) };
52
+ if (params.scope !== "BOOKSPACE" && (params.author || params.book_id)) throw new Error("author and book_id require BOOKSPACE");
53
+ for (const key of ["query", "author"]) if (typeof params[key] === "string") params[key] = normalizeLookup(params[key] as string);
54
+ } else {
55
+ params = { page_size: 20, ...(kind === "topicNotes" ? { page: 1 } : {}), ...noteSchema().parse(values) };
56
+ if (kind === "topicNotes" && !params.topic_id) throw new Error("topic_id is required");
57
+ if (params.page && (!params.topic_id || params.cursor)) throw new Error("page requires topic_id and cannot be combined with cursor");
58
+ if (params.reference_resource_id) {
59
+ if (!params.source || !params.reference_resource_type) throw new Error("reference ID requires source and resource type");
60
+ const id = String(params.reference_resource_id);
61
+ if (!/^\d+$/.test(id) || BigInt(id) <= 0n || BigInt(id) > 9223372036854775807n) throw new Error("invalid reference ID");
62
+ }
63
+ const epochs: Record<string, bigint> = {};
64
+ for (const key of times) if (typeof params[key] === "string") { const t = timestamp(params[key] as string); params[key] = t.text; epochs[key] = t.epoch; }
65
+ for (const prefix of ["created", "edited", "record_updated"]) if (epochs[prefix + "_from"] !== undefined && epochs[prefix + "_to"] !== undefined && epochs[prefix + "_from"] >= epochs[prefix + "_to"]) throw new Error("time interval must have from < to");
66
+ }
67
+ for (const [key, value] of Object.entries(params)) if (!["cursor", "page", "page_size"].includes(key)) filters[key] = String(value);
68
+ const capabilities = ["pagination.v1"];
69
+ if (kind === "topics") capabilities.push("knowledge.lookup.v1");
70
+ else if (Object.keys(filters).length) capabilities.push("note.filters.v1");
71
+ if (kind !== "topics") capabilities.push("note.reference.v1");
72
+ return { params, filters, capabilities, kind };
73
+ }
74
+
75
+ export function verifyDiscovery(body: unknown, contract: DiscoveryContract): void {
76
+ const envelope = z.object({ meta: z.object({ capabilities: z.array(z.string()) }), data: z.record(z.unknown()) }).safeParse(body);
77
+ if (!envelope.success) throw new Error("server does not declare discovery capabilities; upgrade the server (unfiltered results not accepted)");
78
+ for (const cap of contract.capabilities) if (!envelope.data.meta.capabilities.includes(cap)) throw new Error(`server does not support ${cap}; unfiltered results not accepted`);
79
+ if (contract.kind === "detail") return;
80
+ const data = envelope.data.data;
81
+ const applied = z.record(z.string()).safeParse(data.applied_filters);
82
+ if (!applied.success) throw new Error("server did not return applied_filters");
83
+ for (const [key, value] of Object.entries(contract.filters)) if (applied.data[key] !== value) throw new Error(`server did not apply ${key}`);
84
+ const p = z.object({ mode: z.enum(["page", "cursor"]), page: integer.nullable(), page_size: integer.max(100), returned_count: z.number().int().nonnegative(), total_count: z.number().int().nonnegative().nullable(), has_more: z.boolean(), next_page: integer.nullable(), next_cursor: z.string().min(1).nullable() }).parse(data.pagination);
85
+ const items = data[contract.kind === "topics" ? "topics" : "notes"];
86
+ const page = contract.params.page;
87
+ if (!Array.isArray(items) || p.mode !== (page ? "page" : "cursor") || p.page_size !== contract.params.page_size || p.returned_count !== items.length || items.length > p.page_size || (p.total_count !== null && p.total_count < items.length) || (page && p.page !== page)) throw new Error("invalid discovery pagination response");
88
+ if (p.has_more ? (page ? p.next_page !== Number(page) + 1 || p.next_cursor !== null : !p.next_cursor || p.next_page !== null) : p.next_page !== null || p.next_cursor !== null) throw new Error("invalid discovery continuation");
89
+ }
package/src/index.ts CHANGED
@@ -121,15 +121,34 @@ function snowflakeID(value: unknown, field: string): string | number {
121
121
 
122
122
  // ─── Tool Definitions ────────────────────────────────────────────────────────
123
123
 
124
+ const noteDiscoveryProperties = {
125
+ page: { type: "integer", minimum: 1, description: "知识库内可用页码;与 cursor 互斥" },
126
+ source: { type: "string", description: "来源平台精确筛选,如 dedao" },
127
+ note_type: { type: "string", description: "笔记真实类型精确筛选,如 ref" },
128
+ reference_resource_type: { type: "string", description: "引用资源类型,如 ebook、course_article、audio_book" },
129
+ reference_resource_id: { type: "string", description: "引用资源 ID,必须字符串;同时传 source 和 reference_resource_type" },
130
+ reference_article_url: { type: "string", description: "文章 URL 精确筛选,保留 query 和 fragment" },
131
+ topic_id: { type: "string", description: "知识库 ID,限定授权范围" },
132
+ page_size: { type: "integer", minimum: 1, maximum: 100, description: "每页 1–100 条,默认 20" },
133
+ ...Object.fromEntries(["created_from", "created_to", "edited_from", "edited_to", "record_updated_from", "record_updated_to"].map(key => [key, { type: "string", description: "RFC3339 带时区,from 包含、to 不包含;三种时间轴独立" }])),
134
+ };
135
+ const knowledgeLookupProperties = {
136
+ query: { type: "string", description: "按知识库名/书名定位;多候选须核对书名、作者和 book_id" },
137
+ author: { type: "string", description: "书籍作者,限 BOOKSPACE" },
138
+ book_id: { type: "string", description: "书籍 ID 字符串,限 BOOKSPACE" },
139
+ page_size: noteDiscoveryProperties.page_size,
140
+ };
141
+
124
142
  const TOOLS: Tool[] = [
125
143
  // ── Notes ──
126
144
  {
127
145
  name: "list_notes",
128
146
  description:
129
- "获取笔记列表(每次固定返回 20 条,服务端不支持 limit 参数)。用游标翻页:首次请求不传 cursor;后续把上一次响应返回的 cursor 字段原样传入,直到 has_more 为 false。响应里的 total 是全库笔记总数,不是本页条数。",
147
+ "按来源、引用资源或知识库查找笔记。列表只返回定位信息;需要正文和完整元数据时调用 get_note。新查询须核对 meta.capabilities、applied_filters,按 pagination.next_cursor 翻页到 has_more=false 才能说全量完成。total_count=null 表示未知,不能用本页条数代替全库总数。",
130
148
  inputSchema: {
131
149
  type: "object" as const,
132
150
  properties: {
151
+ ...noteDiscoveryProperties,
133
152
  cursor: {
134
153
  type: "string",
135
154
  description: "翻页游标。首次不传;后续将上一次响应的 cursor 字段原样传入即可,无需任何转换。",
@@ -140,7 +159,7 @@ const TOOLS: Tool[] = [
140
159
  },
141
160
  {
142
161
  name: "get_note",
143
- description: "获取指定笔记的详细内容,包括正文、标签、附件、音频转录、网页链接等。\n\n**字段语义说明(AI Agent 重要参考)**:\n`content` 通常是 AI 总结,不一定是原文。不同类型笔记的原文字段如下:\n- 普通文字笔记(plain_text):原文 = `note.content`\n- 链接/网页笔记(link):原文 = `note.web_page.content`,AI 总结 = `note.content`\n- 录音笔记(audio/local_audio 等):转写原文 = `note.audio.original`,AI 总结 = `note.content`\n\n用户要求'读原文'时,先看 `note.note_type`,再按上述对应关系取字段。",
162
+ description: "获取指定笔记的详细内容,包括正文、标签、附件、音频转录、网页链接等。\n\n**字段语义说明(AI Agent 重要参考)**:\n`content` 通常是 AI 总结,不一定是原文。不同类型笔记的原文字段如下:\n- 引用笔记(ref):原文 = `note.ref_content`,`note.content` 是个人评论\n- 普通文字笔记(plain_text):原文 = `note.content`\n- 链接/网页笔记(link):原文 = `note.web_page.content`,AI 总结 = `note.content`\n- 录音笔记(audio/local_audio):转写原文 = `note.audio.original`,AI 总结 = `note.content`\n\n用户要求'读原文'时,先看 `note.note_type`,再按上述对应关系取字段。",
144
163
  inputSchema: {
145
164
  type: "object" as const,
146
165
  properties: {
@@ -159,7 +178,7 @@ const TOOLS: Tool[] = [
159
178
  },
160
179
  {
161
180
  name: "get_note_original",
162
- description: "直接读取笔记原文。链接笔记返回网页原文,录音笔记返回转写原文,文字笔记返回正文;不要把 AI 摘要冒充原文。",
181
+ description: "直接读取笔记原文。引用笔记返回 ref_content,链接笔记返回网页原文,录音笔记返回转写原文,文字笔记返回正文;无原文或不支持的类型会报错。",
163
182
  inputSchema: { type: "object" as const, properties: { id: { type: ["string", "number"], description: "笔记 ID,推荐十进制字符串" } }, required: ["id"] },
164
183
  },
165
184
  {
@@ -177,6 +196,11 @@ const TOOLS: Tool[] = [
177
196
  description: "直接读取录音或会议笔记的结构化时间线和原文资源;没有时间线时明确返回不可用。",
178
197
  inputSchema: { type: "object" as const, properties: { id: { type: ["string", "number"], description: "笔记 ID,推荐十进制字符串" } }, required: ["id"] },
179
198
  },
199
+ {
200
+ name: "get_note_chapters",
201
+ description: "读取总结中的独立章节时间线 chapter_timeline;start_ms 为毫秒,保留 source。与录音 moments 和标记分别读取,不能相互替代。",
202
+ inputSchema: { type: "object" as const, properties: { id: { type: "string", description: "笔记 ID" } }, required: ["id"] },
203
+ },
180
204
  {
181
205
  name: "get_note_quick_note",
182
206
  description: "直接读取录音笔记的快捷笔记;没有快捷笔记时明确返回不可用。",
@@ -342,6 +366,7 @@ const TOOLS: Tool[] = [
342
366
  inputSchema: {
343
367
  type: "object" as const,
344
368
  properties: {
369
+ ...knowledgeLookupProperties,
345
370
  page: {
346
371
  type: "number",
347
372
  description: "页码,从 1 开始(默认 1)",
@@ -381,10 +406,11 @@ const TOOLS: Tool[] = [
381
406
  },
382
407
  {
383
408
  name: "list_topic_notes",
384
- description: "获取指定知识库内的笔记列表(每页 20 条)。\n\n**AI Agent 提示**:列表返回的 `content` 字段可能较长且通常为 AI 总结。如需先获取标题和类型再按需读详情,可用此接口获取 `note_id` 列表,再对感兴趣的条目逐一调用 `get_note`。",
409
+ description: "列出知识库内可访问的笔记,支持来源、引用资源、时间筛选。列表只返回定位信息;需要正文和完整元数据时调用 get_note。按 pagination.next_page 翻页;去重 ID,重复游标/页码、无进展或中途失败不能声称全量完成。",
385
410
  inputSchema: {
386
411
  type: "object" as const,
387
412
  properties: {
413
+ ...noteDiscoveryProperties,
388
414
  topic_id: {
389
415
  type: "string",
390
416
  description: "知识库 ID",
@@ -471,6 +497,36 @@ const TOOLS: Tool[] = [
471
497
  },
472
498
  },
473
499
 
500
+ {
501
+ name: "get_note_marks",
502
+ description: "读取笔记标记(包含文字标记、照片等),与 Timeline 独立,不用时间线替代标记。",
503
+ inputSchema: { type: "object", properties: { note_id: { type: "string" } }, required: ["note_id"] },
504
+ },
505
+ {
506
+ name: "list_sprouts",
507
+ description: "按月份读取当前用户发芽报告;发芽不是标记数据。",
508
+ inputSchema: { type: "object", properties: { month: { type: "string", description: "YYYY-MM" }, since_id: { type: "string", description: "上一页返回的游标,原样传递" }, limit: {type: "integer", minimum: 1, maximum: 20} }, required: ["month"] },
509
+ },
510
+ {
511
+ name: "get_sprout",
512
+ description: "读取已授权用户发芽报告原文,id 来自 list_sprouts。",
513
+ inputSchema: { type: "object", properties: { id: { type: "string" } }, required: ["id"] },
514
+ },
515
+ {
516
+ name: "get_knowledge_file_capabilities",
517
+ description: "上传前查询当前配置允许的文件扩展名、MIME、大小、页数和独立日限额;不缓存为固定格式列表。",
518
+ inputSchema: { type: "object", properties: {} },
519
+ },
520
+ {
521
+ name: "get_knowledge_file_upload_token",
522
+ description: "获取一次 OSS 文件上传临时凭据。通过本地 getnote upload --token-file <file> --max-size-bytes <能力上限> 直接 PUT 到 OSS,无需再次 CLI 登录。凭据通过受控文件或 stdin 传入,不写命令参数或聊天;不要把文件字节传给云 MCP。",
523
+ inputSchema: { type: "object", properties: { mime_type: { type: "string", description: "能力接口返回的扩展名,如 HTML" } }, required: ["mime_type"] },
524
+ },
525
+ {
526
+ name: "upload_knowledge_file",
527
+ description: "OSS 直传成功后将原文件加入知识库,只接收元数据,不接收本地路径或 base64。返回处理中的资源不等于入库成功;用 list_topic_directories 查询同一 ID,直到 SUCCESS 或 FAIL。",
528
+ inputSchema: { type: "object", additionalProperties: false, properties: { topic_id: { type: "string" }, directory_id: { type: "string" }, file_name: { type: "string" }, file_type: { type: "string" }, md5: { type: "string" }, url: { type: "string" } }, required: ["topic_id", "directory_id", "file_name", "file_type", "md5", "url"] },
529
+ },
474
530
  // ── Image ──
475
531
  {
476
532
  name: "get_upload_config",
@@ -689,6 +745,7 @@ const TOOLS: Tool[] = [
689
745
  inputSchema: {
690
746
  type: "object" as const,
691
747
  properties: {
748
+ ...knowledgeLookupProperties,
692
749
  page: {
693
750
  type: "number",
694
751
  description: "页码,从 1 开始,默认 1",
@@ -776,7 +833,7 @@ async function handleTool(
776
833
  // ── Notes ──
777
834
  case "list_notes": {
778
835
  const cursor = (input.cursor as string | undefined);
779
- return client.listNotes({ cursor: cursor === "0" ? undefined : cursor });
836
+ return client.listNotes({ ...input, cursor: cursor === "0" ? undefined : cursor });
780
837
  }
781
838
  case "get_note": {
782
839
  return client.getNote(snowflakeID(input.id, "id"), input.image_quality as string | undefined);
@@ -784,9 +841,18 @@ async function handleTool(
784
841
  case "get_note_original": {
785
842
  const result = await client.getNote(snowflakeID(input.id, "id"));
786
843
  const note = result.note;
787
- const original = note.web_page?.content || note.audio?.original || note.content;
844
+ let original: string | undefined;
845
+ let original_source: string;
846
+ switch (note.note_type) {
847
+ case "ref": original = note.ref_content; original_source = "ref_content"; break;
848
+ case "plain_text": original = note.content; original_source = "content"; break;
849
+ case "link": original = note.web_page?.content; original_source = "web_page.content"; break;
850
+ case "audio":
851
+ case "local_audio": original = note.audio?.original; original_source = "audio.original"; break;
852
+ default: throw new Error(`Unsupported note type for original content: ${note.note_type}`);
853
+ }
788
854
  if (!original) throw new Error("Original content is not available for this note");
789
- return { id: note.id, note_type: note.note_type, title: note.title, original };
855
+ return { id: note.id, note_type: note.note_type, title: note.title, original, original_source };
790
856
  }
791
857
  case "get_note_transcript": {
792
858
  const result = await client.getNote(snowflakeID(input.id, "id"));
@@ -808,6 +874,11 @@ async function handleTool(
808
874
  if (!result.note.quick_note) throw new Error("Quick note is not available for this note");
809
875
  return { id: result.note.id, title: result.note.title, quick_note: result.note.quick_note };
810
876
  }
877
+ case "get_note_chapters": {
878
+ const result = await client.getNote(snowflakeID(input.id, "id"));
879
+ if (!result.note.chapter_timeline) throw new Error("Chapter timeline is not available for this note");
880
+ return { id: result.note.id, title: result.note.title, chapter_timeline: result.note.chapter_timeline };
881
+ }
811
882
  case "get_note_todos": {
812
883
  const result = await client.getNote(snowflakeID(input.id, "id"));
813
884
  return {
@@ -866,6 +937,7 @@ async function handleTool(
866
937
  // ── Knowledge ──
867
938
  case "list_topics": {
868
939
  return client.listTopics({
940
+ ...input,
869
941
  page: input.page as number | undefined,
870
942
  scope: input.scope as "DEFAULT" | "CUSTOMER" | "BOOKSPACE" | "TEAMSPACE" | undefined,
871
943
  });
@@ -879,6 +951,7 @@ async function handleTool(
879
951
  }
880
952
  case "list_topic_notes": {
881
953
  return client.listTopicNotes({
954
+ ...input,
882
955
  topic_id: input.topic_id as string,
883
956
  page: input.page as number | undefined,
884
957
  });
@@ -910,6 +983,12 @@ async function handleTool(
910
983
  }
911
984
 
912
985
  // ── Image ──
986
+ case "get_note_marks": return client.getNoteMarks(String(snowflakeID(input.note_id, "note_id")));
987
+ case "list_sprouts": return client.listSprouts(z.string().regex(/^\d{4}-\d{2}$/).parse(input.month), z.string().optional().parse(input.since_id), z.number().int().min(1).max(20).optional().parse(input.limit));
988
+ case "get_sprout": return client.getSprout(z.string().min(1).parse(input.id));
989
+ case "get_knowledge_file_capabilities": return client.getKnowledgeFileCapabilities();
990
+ case "get_knowledge_file_upload_token": return client.getKnowledgeFileUploadToken(z.string().min(1).parse(input.mime_type));
991
+ case "upload_knowledge_file": return client.uploadKnowledgeFile(z.object({ topic_id:z.string().min(1), directory_id:z.string().regex(/^\d+$/), file_name:z.string().min(1), file_type:z.string().min(1), md5:z.string().regex(/^[a-fA-F0-9]{32}$/), url:z.string().url() }).strict().parse(input));
913
992
  case "get_upload_config": {
914
993
  return client.getUploadConfig();
915
994
  }
@@ -1000,6 +1079,7 @@ async function handleTool(
1000
1079
  // ── Knowledge / Subscribe ──
1001
1080
  case "list_subscribe_topics": {
1002
1081
  return client.listSubscribeTopics({
1082
+ ...input,
1003
1083
  page: input.page as number | undefined,
1004
1084
  scope: input.scope as "DEFAULT" | "CUSTOMER" | "BOOKSPACE" | "TEAMSPACE" | undefined,
1005
1085
  });
@@ -9,6 +9,41 @@ import {
9
9
  } from "../dist/client.js";
10
10
  import { OPENAPI_MEMBERSHIP_PURCHASE_URL } from "../dist/membership.js";
11
11
 
12
+ test("file and distinct mark/sprout methods preserve routes and string IDs", async () => {
13
+ const received = [];
14
+ const server = http.createServer((req, res) => {
15
+ let body = '';
16
+ req.on('data', chunk => body += chunk);
17
+ req.on('end', () => {
18
+ received.push({url:req.url, method:req.method, body:body ? JSON.parse(body):null});
19
+ res.setHeader('content-type','application/json');
20
+ res.end(JSON.stringify({success:true,data:{status:'UPLOADING'}}));
21
+ });
22
+ });
23
+ await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
24
+ try {
25
+ const client = new GetNoteClient('key','client',`http://127.0.0.1:${server.address().port}`);
26
+ await client.getNoteMarks('1922071641760757698');
27
+ await client.listSprouts('2026-09', '1922071641760757698', 2);
28
+ await client.getSprout('sprout-alias');
29
+ await client.getKnowledgeFileCapabilities();
30
+ await client.getKnowledgeFileUploadToken('HTM');
31
+ const result = await client.uploadKnowledgeFile({topic_id:'alias',directory_id:'9000000000020341',file_name:'x.htm',file_type:'HTM',md5:'a'.repeat(32),url:'https://example.com/x.htm'});
32
+ assert.deepEqual(received.map(r=>r.url),[
33
+ '/open/api/v1/resource/note/marks?note_id=1922071641760757698',
34
+ '/open/api/v1/resource/note/sprouts?month=2026-09&since_id=1922071641760757698&limit=2',
35
+ '/open/api/v1/resource/note/sprout?id=sprout-alias',
36
+ '/open/api/v1/resource/knowledge/file/capabilities',
37
+ '/open/api/v1/resource/knowledge/file/upload_token?mime_type=HTM',
38
+ '/open/api/v1/resource/knowledge/file/upload',
39
+ ]);
40
+ assert.equal(received[5].body.directory_id,'9000000000020341');
41
+ assert.equal(received[5].method,'POST');
42
+ assert.equal(result.status,'UPLOADING');
43
+ assert.equal('file_base64' in received[5].body,false);
44
+ } finally { server.close(); }
45
+ });
46
+
12
47
  test("membership errors use the MCP-specific OpenAPI purchase channel", () => {
13
48
  assert.equal(
14
49
  OPENAPI_MEMBERSHIP_PURCHASE_URL,
@@ -142,3 +177,16 @@ test("OSS multipart fields use the signed names and order", async () => {
142
177
  server.close();
143
178
  }
144
179
  });
180
+
181
+
182
+ test("large-integer preservation never rewrites JSON-looking note text", () => {
183
+ const text = 'example: [1923625755277351496, -1923625755277351496] and "note_id":1923625755277351496, escaped \\"quote\\"';
184
+ const input = JSON.stringify({content:text,preview:text,nested:{quote:text}}).slice(0,-1)+',"ids":[1923625755277351496,-1923625755277351496],"decimal":1923625755277351.5,"exponent":1923625755277351496e-5}';
185
+ const parsed = parseJsonPreservingLargeIntegerStrings(input);
186
+ assert.equal(parsed.content,text);
187
+ assert.equal(parsed.preview,text);
188
+ assert.equal(parsed.nested.quote,text);
189
+ assert.deepEqual(parsed.ids,["1923625755277351496","-1923625755277351496"]);
190
+ assert.equal(parsed.decimal,1923625755277351.5);
191
+ assert.equal(parsed.exponent,1923625755277351496e-5);
192
+ });
@@ -0,0 +1,19 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { discoveryContract, verifyDiscovery } from '../dist/discovery.js';
4
+
5
+ test('discovery normalizes lookup and nanosecond intervals without altering source identity',()=>{
6
+ const c=discoveryContract('notes',{source:'dedao',reference_resource_type:'course_article',reference_resource_id:'9007199254740993',reference_article_url:'https://example.invalid/a?x=1#p',created_from:'2026-10-09T11:00:00.000000001+08:00',created_to:'2026-10-09T03:00:00.000000002Z'});
7
+ assert.equal(c.params.created_from,'2026-10-09T03:00:00.000000001Z');assert.equal(c.params.reference_resource_id,'9007199254740993');assert.equal(c.params.reference_article_url,'https://example.invalid/a?x=1#p');
8
+ const k=discoveryContract('topics',{scope:'BOOKSPACE',query:' 《AI 书》 ',author:' “作者” '});assert.equal(k.filters.query,'ai 书');assert.equal(k.filters.author,'作者');
9
+ for(const args of [{created_from:'2026-02-30T00:00:00Z'},{created_from:'2026-10-09T11:00:00'},{page_size:0},{page_size:101},{page:2},{topic_id:'t',page:2,cursor:'x'},{reference_resource_id:'9007199254740993'},{source:'dedao',reference_resource_type:'ebook',reference_resource_id:'9223372036854775808'},{created_from:'2026-10-09T03:00:00.000000002Z',created_to:'2026-10-09T03:00:00.000000001Z'}])assert.throws(()=>discoveryContract('notes',args),JSON.stringify(args));
10
+ assert.throws(()=>discoveryContract('topics',{author:'作者'}));
11
+ });
12
+
13
+ test('new contract fails closed for missing capability, filters, counts and continuation',()=>{
14
+ const c=discoveryContract('notes',{topic_id:'topic-x'});
15
+ const base={meta:{capabilities:['note.filters.v1','pagination.v1','note.reference.v1']},data:{notes:[],applied_filters:{topic_id:'topic-x'},pagination:{mode:'cursor',page:null,page_size:20,returned_count:0,total_count:null,has_more:false,next_cursor:null,next_page:null}}};
16
+ verifyDiscovery(base,c);
17
+ const changes=[x=>delete x.meta,x=>delete x.data.applied_filters,x=>x.data.applied_filters.topic_id='other',x=>x.data.pagination.returned_count=1,x=>delete x.data.pagination.total_count,x=>x.data.pagination.has_more=true,x=>x.data.pagination.next_cursor='stale',x=>x.meta.capabilities=x.meta.capabilities.filter(v=>v!=='note.reference.v1')];
18
+ for(const change of changes){const x=structuredClone(base);change(x);assert.throws(()=>verifyDiscovery(x,c));}
19
+ });
@@ -0,0 +1,53 @@
1
+ import assert from 'node:assert/strict';
2
+ import http from 'node:http';
3
+ import test from 'node:test';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
6
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
7
+
8
+ // Exercise the registered schema and real stdio tool handler through HTTP.
9
+ test('discovery tools forward selectors and reject false capability success', async () => {
10
+ let mode='supported';let received;
11
+ const api=http.createServer((req,res)=>{
12
+ const url=new URL(req.url,'http://localhost');received=Object.fromEntries(url.searchParams);
13
+ const filters=Object.fromEntries([...url.searchParams].filter(([key])=>!['page','page_size','cursor','id','image_quality'].includes(key)));
14
+ if(mode==='ignored')delete filters.note_type;
15
+ res.setHeader('content-type','application/json');
16
+ res.end(JSON.stringify({success:true,meta:{capabilities:mode==='old'?[]:['note.filters.v1','pagination.v1','note.reference.v1','knowledge.lookup.v1']},data:{notes:[],topics:[],note:{note_id:'9007199254740993',title:'',content_state:{content:'omitted',ref_content:'omitted'}},pagination:{mode:url.searchParams.has('page')?'page':'cursor',page:Number(url.searchParams.get('page')||1),page_size:Number(url.searchParams.get('page_size')||20),returned_count:0,total_count:null,has_more:false,next_cursor:null,next_page:null},applied_filters:filters}}));
17
+ });
18
+ await new Promise(resolve=>api.listen(0,'127.0.0.1',resolve));
19
+ const client=new Client({name:'discovery-contract',version:'1'});
20
+ const transport=new StdioClientTransport({command:process.execPath,args:[fileURLToPath(new URL('../dist/index.js',import.meta.url))],env:{...process.env,GETNOTE_API_KEY:'synthetic',GETNOTE_CLIENT_ID:'synthetic',GETNOTE_API_URL:`http://127.0.0.1:${api.address().port}`},stderr:'pipe'});
21
+ try {
22
+ await client.connect(transport);
23
+ const {tools}=await client.listTools();
24
+ const schemas=Object.fromEntries(tools.map(t=>[t.name,t.inputSchema.properties]));
25
+ for(const key of ['source','note_type','reference_resource_type','reference_resource_id','reference_article_url','topic_id','created_from','created_to','edited_from','edited_to','record_updated_from','record_updated_to','page_size'])assert.ok(schemas.list_notes[key],`missing list_notes schema: ${key}`);
26
+ for(const key of ['query','author','book_id','page_size'])assert.ok(schemas.list_topics[key],`missing lookup schema: ${key}`);
27
+ const selectors={source:'dedao',note_type:'ref',reference_resource_type:'course_article',reference_resource_id:'9007199254740993',reference_article_url:'https://example.invalid/a?x=1#p',created_from:'2026-10-09T03:00:00Z',page_size:7};
28
+ for(const [name,args] of [['list_notes',selectors],['list_topic_notes',{...selectors,topic_id:'topic-x',page:2}],['list_topics',{scope:'BOOKSPACE',query:'书名',author:'作者',book_id:'book-x',page_size:7}],['list_subscribe_topics',{scope:'BOOKSPACE',query:'书名',page_size:7}],['get_note',{id:'9007199254740993'}]]) {
29
+ const result=await client.callTool({name,arguments:args});assert.ok(!result.isError,result.content[0].text);
30
+ for(const [key,value]of Object.entries(args))assert.equal(received[key],String(value),`${name}.${key}`);
31
+ assert.ok(JSON.parse(result.content[0].text).meta.capabilities.includes('note.reference.v1'));
32
+ }
33
+ for(const bad of ['old','ignored']) {
34
+ mode=bad;const result=await client.callTool({name:'list_notes',arguments:selectors});assert.equal(result.isError,true,`${bad} must not return filtered success`);
35
+ }
36
+ mode='old';const legacy=await client.callTool({name:'list_notes',arguments:{cursor:'legacy-opaque'}});assert.ok(!legacy.isError,'legacy call must still work');
37
+ mode='supported';const bad=await client.callTool({name:'list_notes',arguments:{page_size:0}});assert.equal(bad.isError,true,'zero page_size invalid');
38
+ }finally{await client.close();api.closeAllConnections();await new Promise(resolve=>api.close(resolve));}
39
+ });
40
+
41
+ // Knowledge lookup does not return note references and must not require that capability.
42
+ test('knowledge lookup accepts the deployed knowledge capability contract', async () => {
43
+ const { discoveryContract, verifyDiscovery } = await import('../dist/discovery.js');
44
+ const contract = discoveryContract('topics', { scope: 'BOOKSPACE', page_size: 2 });
45
+ assert.deepEqual(contract.capabilities, ['pagination.v1', 'knowledge.lookup.v1']);
46
+ assert.doesNotThrow(() => verifyDiscovery({
47
+ meta: { capabilities: ['knowledge.lookup.v1', 'pagination.v1'] },
48
+ data: { topics: [], applied_filters: { scope: 'BOOKSPACE' }, pagination: {
49
+ mode: 'page', page: 1, page_size: 2, returned_count: 0, total_count: 0,
50
+ has_more: false, next_page: null, next_cursor: null
51
+ } }
52
+ }, contract));
53
+ });
@@ -0,0 +1,68 @@
1
+ import assert from 'node:assert/strict';
2
+ import http from 'node:http';
3
+ import test from 'node:test';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
6
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
7
+
8
+ test('stdio tools enforce metadata-only uploads and preserve business errors', async () => {
9
+ const received = [];
10
+ const api = http.createServer((req, res) => {
11
+ let body = '';
12
+ req.on('data', chunk => body += chunk);
13
+ req.on('end', () => {
14
+ received.push({ path: req.url, body: body && JSON.parse(body) });
15
+ res.setHeader('Content-Type', 'application/json');
16
+ if (req.url.includes('/note/detail')) {
17
+ res.end(JSON.stringify({success:true,data:{note:{id:'123',title:'chapters',chapter_timeline:{source:'summary_markdown_rules',items:[{start_ms:1000,title:'Opening'}]},timeline:{moments:[]}}}}));
18
+ return;
19
+ }
20
+ const token = req.url.includes('/upload_token');
21
+ res.end(JSON.stringify(token ? {
22
+ success: false, error: { code: 10000, message: 'daily file limit exceeded', reason: 'invalid_request', retryable: false }, request_id: 'quota-request',
23
+ } : { success: true, data: { status: 'UPLOADING', id: '9000000000020341' } }));
24
+ });
25
+ });
26
+ await new Promise(resolve => api.listen(0, '127.0.0.1', resolve));
27
+ const client = new Client({ name: 'protocol-regression', version: '1' });
28
+ const transport = new StdioClientTransport({
29
+ command: process.execPath,
30
+ args: [fileURLToPath(new URL('../dist/index.js', import.meta.url))],
31
+ env: { ...process.env, GETNOTE_API_KEY: 'test-key', GETNOTE_CLIENT_ID: 'test-client', GETNOTE_API_URL: `http://127.0.0.1:${api.address().port}` },
32
+ stderr: 'pipe',
33
+ });
34
+ try {
35
+ await client.connect(transport);
36
+ const { tools } = await client.listTools();
37
+ for (const name of ['get_note_marks', 'list_sprouts', 'get_sprout', 'get_knowledge_file_capabilities', 'get_knowledge_file_upload_token', 'upload_knowledge_file']) {
38
+ assert.ok(tools.some(tool => tool.name === name), name);
39
+ }
40
+ assert.equal(tools.find(tool => tool.name === 'upload_knowledge_file').inputSchema.additionalProperties, false);
41
+ const args = { topic_id: 'alias', directory_id: '9000000000020341', file_name: 'x.txt', file_type: 'TXT', md5: 'a'.repeat(32), url: 'https://example.test/x.txt' };
42
+ for (const extra of [{ file_base64: 'secret-file-bytes' }, { file_path: '/private/file' }]) {
43
+ const rejected = await client.callTool({ name: 'upload_knowledge_file', arguments: { ...args, ...extra } });
44
+ assert.equal(rejected.isError, true);
45
+ assert.equal(received.length, 0, 'invalid upload must not reach upstream');
46
+ assert.equal(JSON.stringify(rejected).includes('secret-file-bytes'), false);
47
+ }
48
+ const accepted = await client.callTool({ name: 'upload_knowledge_file', arguments: args });
49
+ assert.ok(!accepted.isError);
50
+ assert.deepEqual(received[0].body, args);
51
+ assert.match(accepted.content[0].text, /UPLOADING/);
52
+ assert.doesNotMatch(accepted.content[0].text, /SUCCESS/);
53
+ const quota = await client.callTool({ name: 'get_knowledge_file_upload_token', arguments: { mime_type: 'TXT' } });
54
+ assert.equal(quota.isError, true);
55
+ assert.match(quota.content[0].text, /quota-request/);
56
+ assert.match(quota.content[0].text, /invalid_request/);
57
+ assert.match(quota.content[0].text, /"retryable":\s*false/);
58
+ const chapters = await client.callTool({name:'get_note_chapters',arguments:{id:'123'}});
59
+ assert.ok(!chapters.isError);
60
+ const chapterData = JSON.parse(chapters.content[0].text);
61
+ assert.deepEqual(chapterData.chapter_timeline, {source:'summary_markdown_rules',items:[{start_ms:1000,title:'Opening'}]});
62
+ assert.equal(chapterData.timeline, undefined);
63
+ } finally {
64
+ await client.close();
65
+ api.closeAllConnections();
66
+ await new Promise(resolve => api.close(resolve));
67
+ }
68
+ });
@@ -0,0 +1,46 @@
1
+ import assert from 'node:assert/strict';
2
+ import http from 'node:http';
3
+ import test from 'node:test';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
6
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
7
+
8
+ test('get_note_original uses only the source selected by note_type', async () => {
9
+ const cases = [
10
+ { note_type: 'ref', content: 'personal comment', ref_content: 'quoted passage', want: 'quoted passage', source: 'ref_content' },
11
+ { note_type: 'ref', content: '', ref_content: 'quoted passage', want: 'quoted passage', source: 'ref_content' },
12
+ { note_type: 'ref', content: 'personal comment', ref_content: '', error: true },
13
+ { note_type: 'plain_text', content: 'typed text', ref_content: 'other', want: 'typed text', source: 'content' },
14
+ { note_type: 'link', content: 'AI summary', web_page: {url:'https://example.test',content:'web article'}, want: 'web article', source: 'web_page.content' },
15
+ { note_type: 'audio', content: 'AI summary', audio: {original:'raw transcript'}, want: 'raw transcript', source: 'audio.original' },
16
+ { note_type: 'local_audio', content: 'AI summary', audio: {original:'local raw transcript'}, want: 'local raw transcript', source: 'audio.original' },
17
+ { note_type: 'unknown', content: 'AI summary', error: true },
18
+ ];
19
+ let current = cases[0];
20
+ const api = http.createServer((_req, res) => {
21
+ res.setHeader('content-type', 'application/json');
22
+ res.end(JSON.stringify({success:true,data:{note:{id:'123',title:'Synthetic',source:'manual',tags:[],created_at:'',updated_at:'',...current}}}));
23
+ });
24
+ await new Promise(resolve => api.listen(0, '127.0.0.1', resolve));
25
+ const client = new Client({name:'original-regression',version:'1'});
26
+ const transport = new StdioClientTransport({command:process.execPath,args:[fileURLToPath(new URL('../dist/index.js',import.meta.url))],env:{...process.env,GETNOTE_API_KEY:'test-key',GETNOTE_CLIENT_ID:'test-client',GETNOTE_API_URL:`http://127.0.0.1:${api.address().port}`},stderr:'pipe'});
27
+ try {
28
+ await client.connect(transport);
29
+ for (const fixture of cases) {
30
+ current = fixture;
31
+ const response = await client.callTool({name:'get_note_original',arguments:{id:'123'}});
32
+ if (fixture.error) {
33
+ assert.equal(response.isError, true, fixture.note_type);
34
+ assert.match(response.content[0].text, /not available|unsupported/i);
35
+ } else {
36
+ assert.ok(!response.isError, fixture.note_type);
37
+ const data = JSON.parse(response.content[0].text);
38
+ assert.deepEqual(data, {id:'123',note_type:fixture.note_type,title:'Synthetic',original:fixture.want,original_source:fixture.source});
39
+ }
40
+ }
41
+ } finally {
42
+ await client.close();
43
+ api.closeAllConnections();
44
+ await new Promise(resolve => api.close(resolve));
45
+ }
46
+ });