@getnote/mcp 1.9.0 → 1.10.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.
package/dist/discovery.js CHANGED
@@ -5,12 +5,14 @@ exports.normalizeLookup = normalizeLookup;
5
5
  exports.discoveryContract = discoveryContract;
6
6
  exports.verifyDiscovery = verifyDiscovery;
7
7
  const zod_1 = require("zod");
8
+ const experience_1 = require("./experience");
8
9
  const text = zod_1.z.string().trim().min(1);
9
10
  const integer = zod_1.z.number().int().positive();
10
11
  const times = ["created_from", "created_to", "edited_from", "edited_to", "record_updated_from", "record_updated_to"];
11
12
  exports.noteSelectors = {
12
13
  source: text.optional(), note_type: text.optional(),
13
14
  reference_resource_type: text.optional(), reference_resource_id: text.optional(),
15
+ reference_course_type: text.optional(), reference_course_id: text.optional(),
14
16
  reference_article_url: zod_1.z.string().url().refine(v => /^https?:\/\//.test(v)).optional(),
15
17
  topic_id: text.optional(), page_size: integer.max(100).optional(),
16
18
  created_from: text.optional(), created_to: text.optional(), edited_from: text.optional(), edited_to: text.optional(),
@@ -43,7 +45,7 @@ function timestamp(value) {
43
45
  function discoveryContract(kind, input) {
44
46
  const values = Object.fromEntries(Object.entries(input).filter(([, v]) => v !== undefined));
45
47
  const legacy = kind === "topics" ? ["page", "scope"] : kind === "detail" ? ["id", "image_quality"] : kind === "topicNotes" ? ["topic_id", "page"] : ["cursor"];
46
- if (!Object.keys(values).some(k => !legacy.includes(k)))
48
+ if (kind !== "references" && !Object.keys(values).some(k => !legacy.includes(k)))
47
49
  return undefined;
48
50
  let params;
49
51
  const filters = {};
@@ -51,7 +53,15 @@ function discoveryContract(kind, input) {
51
53
  params = zod_1.z.object({ id: zod_1.z.union([text, zod_1.z.number().int().safe()]), image_quality: zod_1.z.enum(["original"]).optional() }).strict().parse(values);
52
54
  return { params, filters, capabilities: ["note.reference.v1"], kind };
53
55
  }
54
- if (kind === "topics") {
56
+ if (kind === "references") {
57
+ params = zod_1.z.object({ source: zod_1.z.literal("dedao"), resource_type: zod_1.z.literal("course"), query: text.optional(), author: text.optional(), match_mode: zod_1.z.enum(["exact", "prefix"]).default("exact"), page_size: integer.max(100).default(20), cursor: text.max(4096).optional() }).strict().parse(values);
58
+ if (!params.query && !params.author)
59
+ throw new Error("course lookup requires query or author");
60
+ for (const key of ["query", "author"])
61
+ if (typeof params[key] === "string" && Array.from(params[key]).length > 200)
62
+ throw new Error("course lookup exceeds input budget");
63
+ }
64
+ else if (kind === "topics") {
55
65
  params = { scope: "DEFAULT", page: 1, page_size: 20, ...lookupSchema.parse(values) };
56
66
  if (params.scope !== "BOOKSPACE" && (params.author || params.book_id))
57
67
  throw new Error("author and book_id require BOOKSPACE");
@@ -65,6 +75,11 @@ function discoveryContract(kind, input) {
65
75
  throw new Error("topic_id is required");
66
76
  if (params.page && (!params.topic_id || params.cursor))
67
77
  throw new Error("page requires topic_id and cannot be combined with cursor");
78
+ if (params.reference_course_type || params.reference_course_id) {
79
+ if (params.reference_course_type !== "66" || !params.reference_course_id || params.source !== "dedao" || params.topic_id)
80
+ throw new Error("course requires source=dedao, paired type66 and ID; topic intersection unsupported");
81
+ params.reference_course_id = (0, experience_1.decimalID)(String(params.reference_course_id));
82
+ }
68
83
  if (params.reference_resource_id) {
69
84
  if (!params.source || !params.reference_resource_type)
70
85
  throw new Error("reference ID requires source and resource type");
@@ -87,12 +102,16 @@ function discoveryContract(kind, input) {
87
102
  if (!["cursor", "page", "page_size"].includes(key))
88
103
  filters[key] = String(value);
89
104
  const capabilities = ["pagination.v1"];
90
- if (kind === "topics")
105
+ if (kind === "references")
106
+ capabilities.push("reference.resources.v1");
107
+ else if (kind === "topics")
91
108
  capabilities.push("knowledge.lookup.v1");
92
109
  else if (Object.keys(filters).length)
93
110
  capabilities.push("note.filters.v1");
94
- if (kind !== "topics")
111
+ if (kind !== "topics" && kind !== "references")
95
112
  capabilities.push("note.reference.v1");
113
+ if (params.reference_course_type || params.reference_course_id)
114
+ capabilities.push("note.course_filter.v1");
96
115
  return { params, filters, capabilities, kind };
97
116
  }
98
117
  function verifyDiscovery(body, contract) {
@@ -105,18 +124,30 @@ function verifyDiscovery(body, contract) {
105
124
  if (contract.kind === "detail")
106
125
  return;
107
126
  const data = envelope.data.data;
108
- const applied = zod_1.z.record(zod_1.z.string()).safeParse(data.applied_filters);
127
+ // Responses also contain typed flags such as exclude_mine; only requested
128
+ // string selectors must match the contract, without coercion.
129
+ const applied = zod_1.z.record(zod_1.z.unknown()).safeParse(data.applied_filters);
109
130
  if (!applied.success)
110
131
  throw new Error("server did not return applied_filters");
111
132
  for (const [key, value] of Object.entries(contract.filters))
112
133
  if (applied.data[key] !== value)
113
134
  throw new Error(`server did not apply ${key}`);
114
135
  const p = zod_1.z.object({ mode: zod_1.z.enum(["page", "cursor"]), page: integer.nullable(), page_size: integer.max(100), returned_count: zod_1.z.number().int().nonnegative(), total_count: zod_1.z.number().int().nonnegative().nullable(), has_more: zod_1.z.boolean(), next_page: integer.nullable(), next_cursor: zod_1.z.string().min(1).nullable() }).parse(data.pagination);
115
- const items = data[contract.kind === "topics" ? "topics" : "notes"];
136
+ const items = data[contract.kind === "topics" ? "topics" : contract.kind === "references" ? "resources" : "notes"];
116
137
  const page = contract.params.page;
117
138
  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))
118
139
  throw new Error("invalid discovery pagination response");
119
140
  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)
120
141
  throw new Error("invalid discovery continuation");
142
+ if (contract.kind === "references") {
143
+ if (p.total_count !== null)
144
+ throw new Error("course reference total must be unknown");
145
+ if (p.has_more && p.next_cursor === contract.params.cursor)
146
+ throw new Error("reference cursor did not advance");
147
+ for (const item of items) {
148
+ const v = zod_1.z.object({ course_type: text, course_id: text }).parse(item);
149
+ (0, experience_1.decimalID)(v.course_id);
150
+ }
151
+ }
121
152
  }
122
153
  //# sourceMappingURL=discovery.js.map
@@ -0,0 +1,25 @@
1
+ import { z } from "zod";
2
+ export declare function decimalID(value: string): string;
3
+ declare const batchSchema: z.ZodObject<{
4
+ ids: z.ZodArray<z.ZodString, "many">;
5
+ fields: z.ZodOptional<z.ZodArray<z.ZodEnum<["content", "ref_content", "reference", "original"]>, "many">>;
6
+ max_total_chars: z.ZodOptional<z.ZodNumber>;
7
+ }, "strict", z.ZodTypeAny, {
8
+ ids: string[];
9
+ fields?: ("content" | "ref_content" | "reference" | "original")[] | undefined;
10
+ max_total_chars?: number | undefined;
11
+ }, {
12
+ ids: string[];
13
+ fields?: ("content" | "ref_content" | "reference" | "original")[] | undefined;
14
+ max_total_chars?: number | undefined;
15
+ }>;
16
+ export type BatchDetailOptions = z.infer<typeof batchSchema>;
17
+ export declare function normalizeBatch(input: BatchDetailOptions): BatchDetailOptions;
18
+ export interface SearchOptions {
19
+ response_mode?: string;
20
+ max_snippet_chars?: number;
21
+ }
22
+ export declare function validateSearchOptions(input: SearchOptions): void;
23
+ export declare function verifyExperience(body: unknown, path: string, request: unknown): void;
24
+ export {};
25
+ //# sourceMappingURL=experience.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"experience.d.ts","sourceRoot":"","sources":["../src/experience.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,CAAC,EAAC,MAAM,KAAK,CAAC;AAEtB,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAG/C;AACD,QAAA,MAAM,WAAW;;;;;;;;;;;;EAA+M,CAAC;AACjO,MAAM,MAAM,kBAAkB,GAAC,CAAC,CAAC,KAAK,CAAC,OAAO,WAAW,CAAC,CAAC;AAC3D,wBAAgB,cAAc,CAAC,KAAK,EAAC,kBAAkB,GAAE,kBAAkB,CAI1E;AACD,MAAM,WAAW,aAAa;IAAE,aAAa,CAAC,EAAC,MAAM,CAAC;IAAA,iBAAiB,CAAC,EAAC,MAAM,CAAA;CAAC;AAChF,wBAAgB,qBAAqB,CAAC,KAAK,EAAC,aAAa,GAAE,IAAI,CAI9D;AACD,wBAAgB,gBAAgB,CAAC,IAAI,EAAC,OAAO,EAAC,IAAI,EAAC,MAAM,EAAC,OAAO,EAAC,OAAO,GAAE,IAAI,CAW9E"}
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.decimalID = decimalID;
4
+ exports.normalizeBatch = normalizeBatch;
5
+ exports.validateSearchOptions = validateSearchOptions;
6
+ exports.verifyExperience = verifyExperience;
7
+ const zod_1 = require("zod");
8
+ function decimalID(value) {
9
+ if (!/^\d+$/.test(value) || BigInt(value) <= 0n || BigInt(value) > 9223372036854775807n)
10
+ throw new Error("ID must be a positive signed-64-bit decimal string");
11
+ return BigInt(value).toString();
12
+ }
13
+ const batchSchema = zod_1.z.object({ ids: zod_1.z.array(zod_1.z.string()).min(1).max(200), fields: zod_1.z.array(zod_1.z.enum(["content", "ref_content", "reference", "original"])).optional(), max_total_chars: zod_1.z.number().int().min(1).max(64000).optional() }).strict();
14
+ function normalizeBatch(input) {
15
+ const out = batchSchema.parse(input);
16
+ out.ids = [...new Set(out.ids.map(decimalID))];
17
+ if (out.ids.length > 20)
18
+ throw new Error("batch supports at most20 unique IDs");
19
+ return out;
20
+ }
21
+ function validateSearchOptions(input) {
22
+ if (input.response_mode === undefined && input.max_snippet_chars === undefined)
23
+ return;
24
+ if (input.response_mode !== "snippet")
25
+ throw new Error("response_mode must be snippet when requesting snippets");
26
+ if (input.max_snippet_chars !== undefined && (!Number.isInteger(input.max_snippet_chars) || input.max_snippet_chars < 100 || input.max_snippet_chars > 1000))
27
+ throw new Error("max_snippet_chars must be 100..1000");
28
+ }
29
+ function verifyExperience(body, path, request) {
30
+ const input = request;
31
+ const cap = path === "/resource/note/batch-detail" ? "note.batch_detail.v1" : input?.response_mode === "snippet" ? "search.snippet.v1" : undefined;
32
+ if (!cap)
33
+ return;
34
+ const parsed = zod_1.z.object({ meta: zod_1.z.object({ capabilities: zod_1.z.array(zod_1.z.string()) }), data: zod_1.z.record(zod_1.z.unknown()) }).safeParse(body);
35
+ if (!parsed.success || !parsed.data.meta.capabilities.includes(cap))
36
+ throw new Error(`server does not support ${cap}; new mode was not accepted`);
37
+ const data = parsed.data.data;
38
+ if (cap === "note.batch_detail.v1") {
39
+ const items = zod_1.z.array(zod_1.z.object({ note_id: zod_1.z.string(), status: zod_1.z.string().min(1) })).parse(data.items);
40
+ if (items.length !== input?.ids?.length || items.some((item, i) => item.note_id !== input.ids?.[i]))
41
+ throw new Error("batch response lost identities or order");
42
+ }
43
+ else if (data.response_mode !== "snippet" || data.max_snippet_chars !== (input?.max_snippet_chars ?? 400))
44
+ throw new Error("server ignored snippet options");
45
+ }
46
+ //# sourceMappingURL=experience.js.map
package/dist/index.js CHANGED
@@ -134,25 +134,41 @@ function snowflakeID(value, field) {
134
134
  const noteDiscoveryProperties = {
135
135
  page: { type: "integer", minimum: 1, description: "知识库内可用页码;与 cursor 互斥" },
136
136
  source: { type: "string", description: "来源平台精确筛选,如 dedao" },
137
- note_type: { type: "string", description: "笔记真实类型精确筛选,如 ref" },
137
+ note_type: { type: "string", description: "真实类型精确筛选:ref=引用划线,audio=即时/普通录音,local_audio=上传音频文件,class_audio=自己录制的课堂笔记,meeting=会议,internal_record=内录,recorder_audio/recorder_flash_audio=录音卡长录音/闪念。录音不默认限定dedao或课程。" },
138
138
  reference_resource_type: { type: "string", description: "引用资源类型,如 ebook、course_article、audio_book" },
139
139
  reference_resource_id: { type: "string", description: "引用资源 ID,必须字符串;同时传 source 和 reference_resource_type" },
140
+ reference_course_type: { type: "string", description: "课程容器类型,当前66;与reference_course_id配对,source=dedao,个人笔记,不与topic_id组合" },
141
+ reference_course_id: { type: "string", description: "真实课程容器ID字符串,来自list_reference_resources;不使用课节resource_id替代" },
140
142
  reference_article_url: { type: "string", description: "文章 URL 精确筛选,保留 query 和 fragment" },
141
143
  topic_id: { type: "string", description: "知识库 ID,限定授权范围" },
142
144
  page_size: { type: "integer", minimum: 1, maximum: 100, description: "每页 1–100 条,默认 20" },
143
145
  ...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 不包含;三种时间轴独立" }])),
144
146
  };
145
147
  const knowledgeLookupProperties = {
146
- query: { type: "string", description: "按知识库名/书名定位;多候选须核对书名、作者和 book_id" },
147
- author: { type: "string", description: "书籍作者,限 BOOKSPACE" },
148
+ query: { type: "string", description: "只匹配知识库名/书名,不匹配作者;与 author 同时传时为 AND。多候选须核对书名、作者和 book_id" },
149
+ author: { type: "string", description: "书籍作者,限 BOOKSPACE;只有作者线索时只传 author,不猜书名或把作者填进 query" },
148
150
  book_id: { type: "string", description: "书籍 ID 字符串,限 BOOKSPACE" },
149
151
  page_size: noteDiscoveryProperties.page_size,
150
152
  };
153
+ const snippetProperties = {
154
+ response_mode: { type: "string", enum: ["snippet"], description: "显式摘要模式;不传保持旧正文。需search.snippet.v1,不支持课程内语义筛选" },
155
+ max_snippet_chars: { type: "integer", minimum: 100, maximum: 1000, description: "每个命中的Unicode码点上限,默认400;需response_mode=snippet,full只表示完整片段" },
156
+ };
151
157
  const TOOLS = [
158
+ {
159
+ name: "list_reference_resources",
160
+ description: "按课程名/老师定位有个人笔记的得到课程,不需要知识库。query仅课程名exact/prefix,author精确,二者AND且至少一个;用返回course_type+course_id筛选list_notes。核对reference.resources.v1与applied_filters,空页has_more=true仍沿next_cursor继续。保留每页partial/warnings及候选metadata_state;course_directory_no_lessons表示目录缺课节,末页has_more=false仍不能宣称找全老师的全部课程。total未知,不冒充全站课程列表或课程内语义搜索。",
161
+ inputSchema: { type: "object", properties: { source: { type: "string", enum: ["dedao"] }, resource_type: { type: "string", enum: ["course"] }, query: { type: "string", description: "课程名,author可单独提供" }, author: { type: "string", description: "老师准确姓名,与query为AND" }, match_mode: { type: "string", enum: ["exact", "prefix"], description: "只控制课程名,默认exact" }, page_size: noteDiscoveryProperties.page_size, cursor: { type: "string", description: "原样保留的游标,继续时保持全部筛选" } }, required: ["source", "resource_type"], additionalProperties: false },
162
+ },
163
+ {
164
+ name: "get_notes",
165
+ description: "单次后端批量读取最多20个去重个人笔记ID,保持顺序。默认content/ref_content/reference,original需显式选择;引用原文ref_content,content是评论。默认32000/最多64000Unicode码点及1MiB。逐条保留ok/unavailable/failed/deferred_budget、content_state、pending_ids和partial,成功调用不代表每条读完;整条超预算按需改用旧get_note,不自动并发20次。不批量开放知识库共享权限。需note.batch_detail.v1。",
166
+ inputSchema: { type: "object", properties: { ids: { type: "array", items: { type: "string", description: "正int64十进制字符串,不能传JS Number" }, minItems: 1, maxItems: 200 }, fields: { type: "array", items: { type: "string", enum: ["content", "ref_content", "reference", "original"] } }, max_total_chars: { type: "integer", minimum: 1, maximum: 64000, description: "正文Unicode码点预算,默认32000;不会截断成功项" } }, required: ["ids"], additionalProperties: false },
167
+ },
152
168
  // ── Notes ──
153
169
  {
154
170
  name: "list_notes",
155
- description: "按来源、引用资源或知识库查找笔记。列表只返回定位信息;需要正文和完整元数据时调用 get_note。新查询须核对 meta.capabilities、applied_filters,按 pagination.next_cursor 翻页到 has_more=false 才能说全量完成。total_count=null 表示未知,不能用本页条数代替全库总数。",
171
+ description: "按来源、引用资源或知识库查找笔记。列表只返回定位信息;少量个人笔记正文按需用get_notes,知识库共享笔记保持get_note原权限路径。新查询核对meta.capabilities、applied_filters并按pagination.next_cursor翻页;partial/warnings未解决时末页也不代表来源完整。书库无匹配可按note_type=ref列定位信息,在真实reference中核对书籍作者/书名/book_id;保留时间、平台和知识库范围,平台未知不自加dedao,一次发现最多5页,未遍历完说明未查完。book_info.author与reference.author冲突须分别标注,候选不直接认定作者身份。total_count=null表示未知。",
156
172
  inputSchema: {
157
173
  type: "object",
158
174
  properties: {
@@ -365,7 +381,7 @@ const TOOLS = [
365
381
  // ── Knowledge / Topics ──
366
382
  {
367
383
  name: "list_topics",
368
- description: "获取用户创建、拥有或加入的知识库列表。默认只返回普通知识库(DEFAULT);可用 scope 指定客户档案、书籍或团队知识库。返回 topics[]、has_more、total。",
384
+ description: "获取用户创建、拥有或加入的知识库列表,默认DEFAULT;查书名/书籍作者显式scope=BOOKSPACE,query只匹配书名、author匹配书籍作者,二者AND,只有作者线索就只传author。返回topics[]、has_more、total,完整分页并核对book_info。无匹配且用户未限定只查自有时,用list_subscribe_topics保留全部条件补查;仍无匹配再按list_notes的引用来源路线补查,不能把空书库当账号没有划线。用户限定具体知识库时保留原范围;来源作者冲突保留为待核验候选。",
369
385
  inputSchema: {
370
386
  type: "object",
371
387
  properties: {
@@ -726,7 +742,7 @@ const TOOLS = [
726
742
  // ── Knowledge / Subscribe ──
727
743
  {
728
744
  name: "list_subscribe_topics",
729
- description: "获取当前用户真实订阅的他人知识库列表,不包含自己创建的知识库。默认只返回 DEFAULT;可用 scope 指定其他类型。返回 topics[]、has_more、total。",
745
+ description: "获取当前用户真实订阅的他人知识库,不含自己创建的库。默认DEFAULT;书籍显式BOOKSPACE,保留query/author/book_id及分页。自有书库无匹配时可补查这里;仍无匹配且用户未限定只查订阅库时,按list_notes的个人引用来源路线核对候选,保留已知平台/时间,不能把空库当没有笔记。返回topics[]、has_more、total。",
730
746
  inputSchema: {
731
747
  type: "object",
732
748
  properties: {
@@ -762,6 +778,7 @@ const TOOLS = [
762
778
  inputSchema: {
763
779
  type: "object",
764
780
  properties: {
781
+ ...snippetProperties,
765
782
  query: {
766
783
  type: "string",
767
784
  description: "搜索关键词或语义描述(必填)",
@@ -781,6 +798,7 @@ const TOOLS = [
781
798
  inputSchema: {
782
799
  type: "object",
783
800
  properties: {
801
+ ...snippetProperties,
784
802
  topic_id: {
785
803
  type: "string",
786
804
  description: "知识库 ID(来自 list_topics 的 topic_id 字段)(必填)",
@@ -801,6 +819,8 @@ const TOOLS = [
801
819
  ];
802
820
  async function handleTool(name, input, client) {
803
821
  switch (name) {
822
+ case "list_reference_resources": return client.listReferenceResources(input);
823
+ case "get_notes": return client.getNotes(input);
804
824
  // ── Notes ──
805
825
  case "list_notes": {
806
826
  const cursor = input.cursor;
@@ -1073,12 +1093,16 @@ async function handleTool(name, input, client) {
1073
1093
  // ── Recall / Search ──
1074
1094
  case "recall": {
1075
1095
  return client.recall({
1096
+ response_mode: input.response_mode,
1097
+ max_snippet_chars: input.max_snippet_chars,
1076
1098
  query: input.query,
1077
1099
  top_k: input.top_k,
1078
1100
  });
1079
1101
  }
1080
1102
  case "recall_knowledge": {
1081
1103
  return client.recallKnowledge({
1104
+ response_mode: input.response_mode,
1105
+ max_snippet_chars: input.max_snippet_chars,
1082
1106
  topic_id: input.topic_id,
1083
1107
  query: input.query,
1084
1108
  top_k: input.top_k,
@@ -1106,11 +1130,11 @@ async function main() {
1106
1130
  tools: TOOLS,
1107
1131
  }));
1108
1132
  // Call tool
1109
- server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
1133
+ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request, extra) => {
1110
1134
  const { name, arguments: args } = request.params;
1111
1135
  const input = (args ?? {});
1112
1136
  try {
1113
- const result = await handleTool(name, input, client);
1137
+ const result = await handleTool(name, input, client.withSignal(extra.signal));
1114
1138
  return {
1115
1139
  content: [
1116
1140
  {
@@ -1132,6 +1156,8 @@ async function main() {
1132
1156
  field: err.field,
1133
1157
  constraint: err.constraint,
1134
1158
  expected_type: err.expectedType,
1159
+ supported_values: err.supportedValues,
1160
+ retry_after_seconds: err.retryAfterSeconds,
1135
1161
  };
1136
1162
  if (err.code === 10201) {
1137
1163
  errPayload.membership_url = membership_js_1.OPENAPI_MEMBERSHIP_PURCHASE_URL;
@@ -0,0 +1,11 @@
1
+ export interface ReadFailure {
2
+ httpStatus?: number;
3
+ code: number;
4
+ reason: string;
5
+ retryable: boolean;
6
+ retryAfterSeconds?: number;
7
+ waitProvided?: boolean;
8
+ }
9
+ export declare function readRetryDelay(method: string, path: string, error: ReadFailure, attempt: number, waited: number): number | undefined;
10
+ export declare function waitForReadRetry(delay: number, signal?: AbortSignal): Promise<void>;
11
+ //# sourceMappingURL=read-retry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read-retry.d.ts","sourceRoot":"","sources":["../src/read-retry.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,WAAW;IAAE,UAAU,CAAC,EAAC,MAAM,CAAC;IAAA,IAAI,EAAC,MAAM,CAAC;IAAA,MAAM,EAAC,MAAM,CAAC;IAAA,SAAS,EAAC,OAAO,CAAC;IAAA,iBAAiB,CAAC,EAAC,MAAM,CAAC;IAAA,YAAY,CAAC,EAAC,OAAO,CAAA;CAAC;AAQ7I,wBAAgB,cAAc,CAAC,MAAM,EAAC,MAAM,EAAC,IAAI,EAAC,MAAM,EAAC,KAAK,EAAC,WAAW,EAAC,OAAO,EAAC,MAAM,EAAC,MAAM,EAAC,MAAM,GAAE,MAAM,GAAC,SAAS,CAUxH;AACD,wBAAsB,gBAAgB,CAAC,KAAK,EAAC,MAAM,EAAC,MAAM,CAAC,EAAC,WAAW,GAAE,OAAO,CAAC,IAAI,CAAC,CAOrF"}
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readRetryDelay = readRetryDelay;
4
+ exports.waitForReadRetry = waitForReadRetry;
5
+ const getPaths = new Set([
6
+ "/resource/note/list", "/resource/note/detail", "/resource/note/marks", "/resource/note/sprouts", "/resource/note/sprout",
7
+ "/resource/reference/list", "/resource/knowledge/list", "/resource/knowledge/subscribe/list", "/resource/knowledge/notes", "/resource/knowledge/directories",
8
+ "/resource/knowledge/file/capabilities", "/resource/knowledge/bloggers", "/resource/knowledge/blogger/contents", "/resource/knowledge/blogger/content/detail",
9
+ "/resource/knowledge/lives", "/resource/knowledge/live/detail", "/resource/rate-limit/quota"
10
+ ]);
11
+ const postPaths = new Set(["/resource/recall", "/resource/recall/knowledge", "/resource/note/batch-detail"]);
12
+ function readRetryDelay(method, path, error, attempt, waited) {
13
+ if (attempt >= 2 || waited >= 5000 || error.httpStatus !== 429 || !error.retryable)
14
+ return;
15
+ const qpsLimit = error.code === 10202 && ["qps_exceeded", "qps_global_exceeded", "qps_bucket_exceeded"].includes(error.reason);
16
+ if (!qpsLimit && !(error.code === 10005 && error.reason === "rate_limited"))
17
+ return;
18
+ if (!(method === "GET" ? getPaths.has(path) : method === "POST" && postPaths.has(path)))
19
+ return;
20
+ if (error.waitProvided && error.retryAfterSeconds === undefined)
21
+ return;
22
+ const wait = error.retryAfterSeconds;
23
+ if (wait !== undefined && (!Number.isSafeInteger(wait) || wait < 0 || wait > (5000 - waited) / 1000))
24
+ return;
25
+ const delay = (wait === undefined ? 200 * 2 ** attempt : wait * 1000) + 1 + Math.floor(Math.random() * 50);
26
+ return delay <= 5000 - waited ? delay : undefined;
27
+ }
28
+ async function waitForReadRetry(delay, signal) {
29
+ signal?.throwIfAborted();
30
+ await new Promise((resolve, reject) => {
31
+ const abort = () => { clearTimeout(timer); signal?.removeEventListener("abort", abort); reject(signal?.reason ?? new Error("cancelled")); };
32
+ const timer = setTimeout(() => { signal?.removeEventListener("abort", abort); resolve(); }, delay);
33
+ signal?.addEventListener("abort", abort, { once: true });
34
+ });
35
+ }
36
+ //# sourceMappingURL=read-retry.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getnote/mcp",
3
- "version": "1.9.0",
3
+ "version": "1.10.0",
4
4
  "description": "MCP server for 得到大脑(Get笔记) — manage notes and knowledge bases from AI assistants",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
package/src/client.ts CHANGED
@@ -1,8 +1,26 @@
1
1
  import axios, { AxiosInstance, AxiosError } from "axios";
2
2
  import { discoveryContract, verifyDiscovery, NoteDiscoveryOptions, LookupOptions, DiscoveryKind } from "./discovery";
3
+ import {BatchDetailOptions,SearchOptions,normalizeBatch,validateSearchOptions,verifyExperience} from "./experience";
4
+ import {readRetryDelay,waitForReadRetry} from "./read-retry";
3
5
 
4
6
  const DEFAULT_BASE_URL = "https://openapi.biji.com/open/api/v1";
5
7
 
8
+ function retryAfterSeconds(body: unknown, header: unknown): number | undefined {
9
+ let wait = typeof body === "number" && Number.isSafeInteger(body) && body >= 0 ? body : undefined;
10
+ if (typeof header !== "string" || !header.trim()) return wait;
11
+ const value = header.trim();
12
+ let seconds: number | undefined;
13
+ if (/^\d+$/.test(value)) {
14
+ const parsed = Number(value);
15
+ if (Number.isSafeInteger(parsed)) seconds = parsed;
16
+ } else if (/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(value)) {
17
+ const date = Date.parse(value);
18
+ if (Number.isFinite(date)) seconds = Math.max(0, Math.ceil((date - Date.now()) / 1000));
19
+ }
20
+ if (seconds !== undefined) wait = Math.max(wait ?? 0, seconds);
21
+ return wait;
22
+ }
23
+
6
24
  function normalizeBaseURL(value?: string): string {
7
25
  const base = (value || DEFAULT_BASE_URL).replace(/\/+$/, "");
8
26
  if (base.endsWith("/open/api/v1")) return base;
@@ -32,6 +50,8 @@ export function parseJsonPreservingLargeIntegerStrings(data: unknown) {
32
50
  }
33
51
 
34
52
  export class GetNoteAPIError extends Error {
53
+ httpStatus?:number;
54
+ waitProvided=false;
35
55
  constructor(
36
56
  public readonly code: number,
37
57
  public readonly reason: string,
@@ -40,13 +60,19 @@ export class GetNoteAPIError extends Error {
40
60
  public readonly retryable: boolean = false,
41
61
  public readonly field?: string,
42
62
  public readonly constraint?: string,
43
- public readonly expectedType?: string
63
+ public readonly expectedType?: string,
64
+ public readonly supportedValues?: string[],
65
+ public readonly retryAfterSeconds?: number
44
66
  ) {
45
67
  super(message);
46
68
  this.name = "GetNoteAPIError";
47
69
  }
48
70
  }
49
71
 
72
+ function apiFailure(err:APIErrorBody|undefined,requestID:string|undefined,status:number,header:unknown):GetNoteAPIError {
73
+ return Object.assign(new GetNoteAPIError(err?.code??-1,err?.reason??"unknown",err?.message??"API request failed",requestID,err?.retryable??false,err?.field,err?.constraint,err?.expected_type,err?.supported_values,retryAfterSeconds(err?.retry_after_seconds,header)),{httpStatus:status,waitProvided:err?.retry_after_seconds!==undefined||header!==undefined});
74
+ }
75
+
50
76
  export class GetNoteClient {
51
77
  async getNoteMarks(note_id: string) {
52
78
  return this.request<unknown>("GET", "/resource/note/marks", { note_id });
@@ -67,6 +93,12 @@ export class GetNoteClient {
67
93
  return this.request<unknown>("POST", "/resource/knowledge/file/upload", undefined, data);
68
94
  }
69
95
  private http: AxiosInstance;
96
+ private requestSignal?:AbortSignal;
97
+
98
+ withSignal(signal:AbortSignal):GetNoteClient {
99
+ // Per-call view shares the HTTP transport, never another call's signal.
100
+ return Object.assign(Object.create(Object.getPrototypeOf(this)),this,{requestSignal:signal});
101
+ }
70
102
 
71
103
  constructor(apiKey: string, clientId: string, baseURL?: string) {
72
104
  this.http = axios.create({
@@ -89,12 +121,32 @@ export class GetNoteClient {
89
121
  }
90
122
 
91
123
  private async request<T>(
124
+ method:"GET"|"POST",path:string,params?:Record<string,unknown>,data?:unknown
125
+ ):Promise<T>{
126
+ let waited=0;let lastError:GetNoteAPIError|undefined;
127
+ for(let attempt=0;;attempt++){
128
+ try {
129
+ this.requestSignal?.throwIfAborted();
130
+ return await this.requestOnce<T>(method,path,params,data);
131
+ }catch(err){
132
+ if(this.requestSignal?.aborted&&lastError)throw Object.assign(lastError,{cause:this.requestSignal.reason});
133
+ if(!(err instanceof GetNoteAPIError))throw err;
134
+ const delay=readRetryDelay(method,path,err,attempt,waited);
135
+ if(delay===undefined)throw err;
136
+ lastError=err;const start=performance.now();
137
+ try {await waitForReadRetry(delay,this.requestSignal)}catch(cause){throw Object.assign(err,{cause})}
138
+ waited+=performance.now()-start;
139
+ }
140
+ }
141
+ }
142
+
143
+ private async requestOnce<T>(
92
144
  method: "GET" | "POST",
93
145
  path: string,
94
146
  params?: Record<string, unknown>,
95
147
  data?: unknown
96
148
  ): Promise<T> {
97
- const kinds: Record<string, DiscoveryKind> = { "/resource/note/list": "notes", "/resource/note/detail": "detail", "/resource/knowledge/notes": "topicNotes", "/resource/knowledge/list": "topics", "/resource/knowledge/subscribe/list": "topics" };
149
+ const kinds: Record<string, DiscoveryKind> = { "/resource/note/list": "notes", "/resource/note/detail": "detail", "/resource/knowledge/notes": "topicNotes", "/resource/knowledge/list": "topics", "/resource/knowledge/subscribe/list": "topics", "/resource/reference/list":"references" };
98
150
  const contract = method === "GET" && kinds[path] ? discoveryContract(kinds[path], params || {}) : undefined;
99
151
  if (contract) params = contract.params;
100
152
  try {
@@ -109,24 +161,17 @@ export class GetNoteClient {
109
161
  url: path,
110
162
  params,
111
163
  data,
164
+ signal:this.requestSignal,
112
165
  });
113
166
 
114
167
  const body = res.data;
115
168
  if (!body.success) {
116
169
  const err = body.error;
117
- throw new GetNoteAPIError(
118
- err?.code ?? -1,
119
- err?.reason ?? "unknown",
120
- err?.message ?? "API request failed",
121
- body.request_id,
122
- err?.retryable ?? false,
123
- err?.field,
124
- err?.constraint,
125
- err?.expected_type
126
- );
170
+ throw apiFailure(err,body.request_id,res.status,res.headers["retry-after"]);
127
171
  }
128
172
 
129
173
  if (contract) verifyDiscovery(body, contract);
174
+ verifyExperience(body,path,data);
130
175
  // Keep the verified envelope capabilities visible to the Agent.
131
176
  if (body.meta?.capabilities && typeof body.data === "object" && body.data !== null && !Array.isArray(body.data)) {
132
177
  return { ...body.data, meta: body.meta };
@@ -142,16 +187,7 @@ export class GetNoteClient {
142
187
  request_id?: string;
143
188
  };
144
189
  if (body?.error) {
145
- throw new GetNoteAPIError(
146
- body.error.code,
147
- body.error.reason,
148
- body.error.message,
149
- body.request_id,
150
- body.error.retryable ?? false,
151
- body.error.field,
152
- body.error.constraint,
153
- body.error.expected_type
154
- );
190
+ throw apiFailure(body.error,body.request_id,err.response.status,err.response.headers["retry-after"]);
155
191
  }
156
192
  throw new Error(`HTTP ${err.response.status}: ${err.message}`);
157
193
  }
@@ -166,6 +202,14 @@ export class GetNoteClient {
166
202
  return this.request<ListNotesResp>("GET", "/resource/note/list", { ...params });
167
203
  }
168
204
 
205
+ async listReferenceResources(params:{source:string;resource_type:string;query?:string;author?:string;match_mode?:string;page_size?:number;cursor?:string}){
206
+ return this.request<ReferenceResourcesResp>("GET","/resource/reference/list",params);
207
+ }
208
+
209
+ async getNotes(body:BatchDetailOptions){
210
+ return this.request<BatchDetailResp>("POST","/resource/note/batch-detail",undefined,normalizeBatch(body));
211
+ }
212
+
169
213
  async getNote(id: string | number, image_quality?: string) {
170
214
  return this.request<GetNoteResp>("GET", "/resource/note/detail", { id, image_quality });
171
215
  }
@@ -445,11 +489,13 @@ export class GetNoteClient {
445
489
 
446
490
  // ─── Recall / Search ─────────────────────────────────────────────────────
447
491
 
448
- async recall(body: { query: string; top_k?: number }) {
492
+ async recall(body: { query: string; top_k?: number }&SearchOptions) {
493
+ validateSearchOptions(body);
449
494
  return this.request<RecallResp>("POST", "/resource/recall", undefined, body);
450
495
  }
451
496
 
452
- async recallKnowledge(body: { topic_id: string; query: string; top_k?: number }) {
497
+ async recallKnowledge(body: { topic_id: string; query: string; top_k?: number }&SearchOptions) {
498
+ validateSearchOptions(body);
453
499
  return this.request<RecallResp>("POST", "/resource/recall/knowledge", undefined, body);
454
500
  }
455
501
  }
@@ -463,6 +509,7 @@ export interface TagInfo {
463
509
  }
464
510
 
465
511
  export interface NoteReference {
512
+ course?:{type:string;id:string;title?:string;author?:string;[key:string]:unknown};
466
513
  source: string; resource_type: string; ptype: number; resource_id?: string;
467
514
  title?: string; author?: string; url?: string; original_note_id?: string;
468
515
  is_source_private: boolean; book_id?: string;
@@ -479,9 +526,10 @@ export interface DiscoveryMetadata {
479
526
  metadata_state?: { reference: string; topics: string };
480
527
  }
481
528
  export interface DiscoveryResponse {
529
+ total_scope?:string;
482
530
  meta?: { capabilities: string[]; timestamp?: number };
483
531
  pagination?: { mode: "page" | "cursor"; page: number | null; page_size: number; returned_count: number; total_count: number | null; has_more: boolean; next_page: number | null; next_cursor: string | null };
484
- applied_filters?: Record<string, string>;
532
+ applied_filters?: Record<string, unknown>;
485
533
  warnings?: unknown[];
486
534
  }
487
535
 
@@ -887,6 +935,8 @@ interface APIErrorBody {
887
935
  field?: string;
888
936
  constraint?: string;
889
937
  expected_type?: string;
938
+ supported_values?: string[];
939
+ retry_after_seconds?: number;
890
940
  }
891
941
 
892
942
  export interface UpdateNoteResp {
@@ -900,9 +950,9 @@ export interface UpdateNoteResp {
900
950
  export interface RecallResultItem {
901
951
  note_id?: string;
902
952
  resource_id?: string;
903
- note_type: "NOTE" | "FILE" | "BLOGGER" | "LIVE" | "URL" | "DEDAO";
953
+ note_type: string;
904
954
  title: string;
905
- content: string;
955
+ content?: string;
906
956
  created_at: string;
907
957
  page_no?: number;
908
958
  resource_type?: string;
@@ -911,9 +961,14 @@ export interface RecallResultItem {
911
961
  snippet?: string;
912
962
  snippet_source?: string;
913
963
  score?: number | null;
964
+ truncated?:boolean;
965
+ content_state?:{content:string;snippet:string};
914
966
  }
915
967
 
916
968
  export interface RecallResp extends DiscoveryResponse {
969
+ response_mode?:string;
970
+ max_snippet_chars?:number;
971
+ max_total_bytes?:number;
917
972
  results: RecallResultItem[];
918
973
  result_mode?: string;
919
974
  is_exhaustive?: boolean;
@@ -921,3 +976,13 @@ export interface RecallResp extends DiscoveryResponse {
921
976
  distinct_note_count?: number;
922
977
  partial?: boolean;
923
978
  }
979
+
980
+ export interface ReferenceResourcesResp extends DiscoveryResponse {
981
+ resources:Array<{source:string;resource_type:string;course_type:string;course_id:string;title:string;author:string;url:string;has_notes:boolean;metadata_state:string;[key:string]:unknown}>;
982
+ partial:boolean;
983
+ }
984
+ export interface BatchDetailResp extends DiscoveryResponse {
985
+ items:Array<{note_id:string;status:string;note?:Record<string,unknown>;[key:string]:unknown}>;
986
+ pending_ids:string[];
987
+ total_chars:number;max_total_chars:number;max_total_bytes:number;partial:boolean;
988
+ }