@getnote/mcp 1.9.1 → 1.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -27
- package/dist/client.d.ts +67 -5
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +78 -4
- package/dist/discovery.d.ts +9 -1
- package/dist/discovery.d.ts.map +1 -1
- package/dist/discovery.js +34 -5
- package/dist/experience.d.ts +25 -0
- package/dist/experience.d.ts.map +1 -0
- package/dist/experience.js +46 -0
- package/dist/index.js +35 -9
- package/dist/read-retry.d.ts +11 -0
- package/dist/read-retry.d.ts.map +1 -0
- package/dist/read-retry.js +36 -0
- package/package.json +1 -1
- package/src/client.ts +91 -26
- package/src/discovery.ts +23 -6
- package/src/experience.ts +31 -0
- package/src/index.ts +35 -9
- package/src/read-retry.ts +27 -0
- package/test/error-metadata.test.mjs +47 -0
- package/test/experience.test.mjs +43 -0
- package/test/read-retry.test.mjs +38 -0
package/src/discovery.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
import {decimalID} from "./experience";
|
|
2
3
|
|
|
3
4
|
const text = z.string().trim().min(1);
|
|
4
5
|
const integer = z.number().int().positive();
|
|
@@ -6,6 +7,7 @@ const times = ["created_from", "created_to", "edited_from", "edited_to", "record
|
|
|
6
7
|
export const noteSelectors = {
|
|
7
8
|
source: text.optional(), note_type: text.optional(),
|
|
8
9
|
reference_resource_type: text.optional(), reference_resource_id: text.optional(),
|
|
10
|
+
reference_course_type: text.optional(), reference_course_id: text.optional(),
|
|
9
11
|
reference_article_url: z.string().url().refine(v => /^https?:\/\//.test(v)).optional(),
|
|
10
12
|
topic_id: text.optional(), page_size: integer.max(100).optional(),
|
|
11
13
|
created_from: text.optional(), created_to: text.optional(), edited_from: text.optional(), edited_to: text.optional(),
|
|
@@ -15,7 +17,7 @@ export type NoteDiscoveryOptions = z.infer<ReturnType<typeof noteSchema>>;
|
|
|
15
17
|
function noteSchema() { return z.object({ ...noteSelectors, page: integer.optional(), cursor: z.string().min(1).optional() }).strict(); }
|
|
16
18
|
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
19
|
export type LookupOptions = z.infer<typeof lookupSchema>;
|
|
18
|
-
export type DiscoveryKind = "notes" | "topicNotes" | "topics" | "detail";
|
|
20
|
+
export type DiscoveryKind = "notes" | "topicNotes" | "topics" | "detail" | "references";
|
|
19
21
|
export type DiscoveryContract = { params: Record<string, unknown>; filters: Record<string, string>; capabilities: string[]; kind: DiscoveryKind };
|
|
20
22
|
|
|
21
23
|
export function normalizeLookup(value: string): string {
|
|
@@ -40,14 +42,18 @@ function timestamp(value: string): { text: string; epoch: bigint } {
|
|
|
40
42
|
export function discoveryContract(kind: DiscoveryKind, input: Record<string, unknown>): DiscoveryContract | undefined {
|
|
41
43
|
const values = Object.fromEntries(Object.entries(input).filter(([, v]) => v !== undefined));
|
|
42
44
|
const legacy = kind === "topics" ? ["page", "scope"] : kind === "detail" ? ["id", "image_quality"] : kind === "topicNotes" ? ["topic_id", "page"] : ["cursor"];
|
|
43
|
-
if (
|
|
45
|
+
if (kind!=="references"&&!Object.keys(values).some(k => !legacy.includes(k))) return undefined;
|
|
44
46
|
let params: Record<string, unknown>;
|
|
45
47
|
const filters: Record<string, string> = {};
|
|
46
48
|
if (kind === "detail") {
|
|
47
49
|
params = z.object({ id: z.union([text, z.number().int().safe()]), image_quality: z.enum(["original"]).optional() }).strict().parse(values);
|
|
48
50
|
return { params, filters, capabilities: ["note.reference.v1"], kind };
|
|
49
51
|
}
|
|
50
|
-
if (kind === "
|
|
52
|
+
if (kind === "references") {
|
|
53
|
+
params=z.object({source:z.literal("dedao"),resource_type:z.literal("course"),query:text.optional(),author:text.optional(),match_mode:z.enum(["exact","prefix"]).default("exact"),page_size:integer.max(100).default(20),cursor:text.max(4096).optional()}).strict().parse(values);
|
|
54
|
+
if(!params.query&&!params.author)throw new Error("course lookup requires query or author");
|
|
55
|
+
for(const key of ["query","author"])if(typeof params[key]==="string"&&Array.from(params[key] as string).length>200)throw new Error("course lookup exceeds input budget");
|
|
56
|
+
} else if (kind === "topics") {
|
|
51
57
|
params = { scope: "DEFAULT", page: 1, page_size: 20, ...lookupSchema.parse(values) };
|
|
52
58
|
if (params.scope !== "BOOKSPACE" && (params.author || params.book_id)) throw new Error("author and book_id require BOOKSPACE");
|
|
53
59
|
for (const key of ["query", "author"]) if (typeof params[key] === "string") params[key] = normalizeLookup(params[key] as string);
|
|
@@ -55,6 +61,10 @@ export function discoveryContract(kind: DiscoveryKind, input: Record<string, unk
|
|
|
55
61
|
params = { page_size: 20, ...(kind === "topicNotes" ? { page: 1 } : {}), ...noteSchema().parse(values) };
|
|
56
62
|
if (kind === "topicNotes" && !params.topic_id) throw new Error("topic_id is required");
|
|
57
63
|
if (params.page && (!params.topic_id || params.cursor)) throw new Error("page requires topic_id and cannot be combined with cursor");
|
|
64
|
+
if(params.reference_course_type||params.reference_course_id){
|
|
65
|
+
if(params.reference_course_type!=="66"||!params.reference_course_id||params.source!=="dedao"||params.topic_id)throw new Error("course requires source=dedao, paired type66 and ID; topic intersection unsupported");
|
|
66
|
+
params.reference_course_id=decimalID(String(params.reference_course_id));
|
|
67
|
+
}
|
|
58
68
|
if (params.reference_resource_id) {
|
|
59
69
|
if (!params.source || !params.reference_resource_type) throw new Error("reference ID requires source and resource type");
|
|
60
70
|
const id = String(params.reference_resource_id);
|
|
@@ -66,9 +76,11 @@ export function discoveryContract(kind: DiscoveryKind, input: Record<string, unk
|
|
|
66
76
|
}
|
|
67
77
|
for (const [key, value] of Object.entries(params)) if (!["cursor", "page", "page_size"].includes(key)) filters[key] = String(value);
|
|
68
78
|
const capabilities = ["pagination.v1"];
|
|
69
|
-
if
|
|
79
|
+
if(kind==="references")capabilities.push("reference.resources.v1");
|
|
80
|
+
else if (kind === "topics") capabilities.push("knowledge.lookup.v1");
|
|
70
81
|
else if (Object.keys(filters).length) capabilities.push("note.filters.v1");
|
|
71
|
-
if (kind !== "topics") capabilities.push("note.reference.v1");
|
|
82
|
+
if (kind !== "topics"&&kind!=="references") capabilities.push("note.reference.v1");
|
|
83
|
+
if(params.reference_course_type||params.reference_course_id)capabilities.push("note.course_filter.v1");
|
|
72
84
|
return { params, filters, capabilities, kind };
|
|
73
85
|
}
|
|
74
86
|
|
|
@@ -84,8 +96,13 @@ export function verifyDiscovery(body: unknown, contract: DiscoveryContract): voi
|
|
|
84
96
|
if (!applied.success) throw new Error("server did not return applied_filters");
|
|
85
97
|
for (const [key, value] of Object.entries(contract.filters)) if (applied.data[key] !== value) throw new Error(`server did not apply ${key}`);
|
|
86
98
|
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);
|
|
87
|
-
const items = data[contract.kind === "topics" ? "topics" : "notes"];
|
|
99
|
+
const items = data[contract.kind === "topics" ? "topics" : contract.kind==="references"?"resources":"notes"];
|
|
88
100
|
const page = contract.params.page;
|
|
89
101
|
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");
|
|
90
102
|
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");
|
|
103
|
+
if(contract.kind==="references"){
|
|
104
|
+
if(p.total_count!==null)throw new Error("course reference total must be unknown");
|
|
105
|
+
if(p.has_more&&p.next_cursor===contract.params.cursor)throw new Error("reference cursor did not advance");
|
|
106
|
+
for(const item of items){const v=z.object({course_type:text,course_id:text}).parse(item);decimalID(v.course_id)}
|
|
107
|
+
}
|
|
91
108
|
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import {z} from "zod";
|
|
2
|
+
|
|
3
|
+
export function decimalID(value: string): string {
|
|
4
|
+
if (!/^\d+$/.test(value) || BigInt(value) <= 0n || BigInt(value) > 9223372036854775807n) throw new Error("ID must be a positive signed-64-bit decimal string");
|
|
5
|
+
return BigInt(value).toString();
|
|
6
|
+
}
|
|
7
|
+
const batchSchema=z.object({ids:z.array(z.string()).min(1).max(200),fields:z.array(z.enum(["content","ref_content","reference","original"])).optional(),max_total_chars:z.number().int().min(1).max(64000).optional()}).strict();
|
|
8
|
+
export type BatchDetailOptions=z.infer<typeof batchSchema>;
|
|
9
|
+
export function normalizeBatch(input:BatchDetailOptions):BatchDetailOptions {
|
|
10
|
+
const out=batchSchema.parse(input);out.ids=[...new Set(out.ids.map(decimalID))];
|
|
11
|
+
if(out.ids.length>20)throw new Error("batch supports at most20 unique IDs");
|
|
12
|
+
return out;
|
|
13
|
+
}
|
|
14
|
+
export interface SearchOptions {response_mode?:string;max_snippet_chars?:number}
|
|
15
|
+
export function validateSearchOptions(input:SearchOptions):void {
|
|
16
|
+
if(input.response_mode===undefined&&input.max_snippet_chars===undefined)return;
|
|
17
|
+
if(input.response_mode!=="snippet")throw new Error("response_mode must be snippet when requesting snippets");
|
|
18
|
+
if(input.max_snippet_chars!==undefined&&(!Number.isInteger(input.max_snippet_chars)||input.max_snippet_chars<100||input.max_snippet_chars>1000))throw new Error("max_snippet_chars must be 100..1000");
|
|
19
|
+
}
|
|
20
|
+
export function verifyExperience(body:unknown,path:string,request:unknown):void {
|
|
21
|
+
const input=request as (SearchOptions&{ids?:string[]})|undefined;
|
|
22
|
+
const cap=path==="/resource/note/batch-detail"?"note.batch_detail.v1":input?.response_mode==="snippet"?"search.snippet.v1":undefined;
|
|
23
|
+
if(!cap)return;
|
|
24
|
+
const parsed=z.object({meta:z.object({capabilities:z.array(z.string())}),data:z.record(z.unknown())}).safeParse(body);
|
|
25
|
+
if(!parsed.success||!parsed.data.meta.capabilities.includes(cap))throw new Error(`server does not support ${cap}; new mode was not accepted`);
|
|
26
|
+
const data=parsed.data.data;
|
|
27
|
+
if(cap==="note.batch_detail.v1"){
|
|
28
|
+
const items=z.array(z.object({note_id:z.string(),status:z.string().min(1)})).parse(data.items);
|
|
29
|
+
if(items.length!==input?.ids?.length||items.some((item,i)=>item.note_id!==input.ids?.[i]))throw new Error("batch response lost identities or order");
|
|
30
|
+
}else if(data.response_mode!=="snippet"||data.max_snippet_chars!==(input?.max_snippet_chars??400))throw new Error("server ignored snippet options");
|
|
31
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -123,10 +123,12 @@ function snowflakeID(value: unknown, field: string): string | number {
|
|
|
123
123
|
|
|
124
124
|
const noteDiscoveryProperties = {
|
|
125
125
|
page: { type: "integer", minimum: 1, description: "知识库内可用页码;与 cursor 互斥" },
|
|
126
|
-
source: { type: "string", description: "
|
|
127
|
-
note_type: { type: "string", description: "
|
|
126
|
+
source: { type: "string", description: "笔记真实来源精确筛选:vendor_moan=AI录音台/墨案MOAN录音台,getseed=GetSeed录音卡(长录音与闪念),dedao=得到。查设备全部笔记只加来源,不额外限定audio/meeting;未限定设备时不加设备来源。" },
|
|
127
|
+
note_type: { type: "string", description: "真实类型精确筛选:ref=引用划线,audio=即时/普通录音,local_audio=上传音频文件,class_audio=自己录制的课堂笔记,meeting=会议,internal_record=内录,recorder_audio/recorder_flash_audio=录音卡长录音/闪念。录音不默认限定dedao或课程。" },
|
|
128
128
|
reference_resource_type: { type: "string", description: "引用资源类型,如 ebook、course_article、audio_book" },
|
|
129
129
|
reference_resource_id: { type: "string", description: "引用资源 ID,必须字符串;同时传 source 和 reference_resource_type" },
|
|
130
|
+
reference_course_type:{type:"string",description:"课程容器类型,当前66;与reference_course_id配对,source=dedao,个人笔记,不与topic_id组合"},
|
|
131
|
+
reference_course_id:{type:"string",description:"真实课程容器ID字符串,来自list_reference_resources;不使用课节resource_id替代"},
|
|
130
132
|
reference_article_url: { type: "string", description: "文章 URL 精确筛选,保留 query 和 fragment" },
|
|
131
133
|
topic_id: { type: "string", description: "知识库 ID,限定授权范围" },
|
|
132
134
|
page_size: { type: "integer", minimum: 1, maximum: 100, description: "每页 1–100 条,默认 20" },
|
|
@@ -138,20 +140,34 @@ const knowledgeLookupProperties = {
|
|
|
138
140
|
book_id: { type: "string", description: "书籍 ID 字符串,限 BOOKSPACE" },
|
|
139
141
|
page_size: noteDiscoveryProperties.page_size,
|
|
140
142
|
};
|
|
143
|
+
const snippetProperties={
|
|
144
|
+
response_mode:{type:"string",enum:["snippet"],description:"显式摘要模式;不传保持旧正文。需search.snippet.v1,不支持课程内语义筛选"},
|
|
145
|
+
max_snippet_chars:{type:"integer",minimum:100,maximum:1000,description:"每个命中的Unicode码点上限,默认400;需response_mode=snippet,full只表示完整片段"},
|
|
146
|
+
};
|
|
141
147
|
|
|
142
148
|
const TOOLS: Tool[] = [
|
|
149
|
+
{
|
|
150
|
+
name:"list_reference_resources",
|
|
151
|
+
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未知,不冒充全站课程列表或课程内语义搜索。",
|
|
152
|
+
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},
|
|
153
|
+
},
|
|
154
|
+
{
|
|
155
|
+
name:"get_notes",
|
|
156
|
+
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。",
|
|
157
|
+
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},
|
|
158
|
+
},
|
|
143
159
|
// ── Notes ──
|
|
144
160
|
{
|
|
145
161
|
name: "list_notes",
|
|
146
162
|
description:
|
|
147
|
-
"
|
|
163
|
+
"按来源、引用资源或知识库查找笔记。列表只返回定位信息;少量个人笔记正文按需用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表示未知。",
|
|
148
164
|
inputSchema: {
|
|
149
165
|
type: "object" as const,
|
|
150
166
|
properties: {
|
|
151
167
|
...noteDiscoveryProperties,
|
|
152
168
|
cursor: {
|
|
153
169
|
type: "string",
|
|
154
|
-
description: "
|
|
170
|
+
description: "首次省略。来源/类型/时间等新筛选使用pagination.next_cursor,保持原条件和page_size,直到has_more=false;仅旧默认列表沿旧响应cursor继续。不转换、不复用其他来源游标。",
|
|
155
171
|
},
|
|
156
172
|
},
|
|
157
173
|
required: [],
|
|
@@ -183,7 +199,7 @@ const TOOLS: Tool[] = [
|
|
|
183
199
|
},
|
|
184
200
|
{
|
|
185
201
|
name: "get_note_transcript",
|
|
186
|
-
description: "
|
|
202
|
+
description: "直接读取录音台、录音卡及录音、会议或课堂笔记的转写原文;设备来源先用list_notes.source定位。没有转写时明确返回不可用,不用AI总结代替。",
|
|
187
203
|
inputSchema: { type: "object" as const, properties: { id: { type: ["string", "number"], description: "笔记 ID,推荐十进制字符串" } }, required: ["id"] },
|
|
188
204
|
},
|
|
189
205
|
{
|
|
@@ -362,7 +378,7 @@ const TOOLS: Tool[] = [
|
|
|
362
378
|
// ── Knowledge / Topics ──
|
|
363
379
|
{
|
|
364
380
|
name: "list_topics",
|
|
365
|
-
description: "
|
|
381
|
+
description: "获取用户创建、拥有或加入的知识库列表,默认DEFAULT;查书名/书籍作者显式scope=BOOKSPACE,query只匹配书名、author匹配书籍作者,二者AND,只有作者线索就只传author。返回topics[]、has_more、total,完整分页并核对book_info。无匹配且用户未限定只查自有时,用list_subscribe_topics保留全部条件补查;仍无匹配再按list_notes的引用来源路线补查,不能把空书库当账号没有划线。用户限定具体知识库时保留原范围;来源作者冲突保留为待核验候选。",
|
|
366
382
|
inputSchema: {
|
|
367
383
|
type: "object" as const,
|
|
368
384
|
properties: {
|
|
@@ -741,7 +757,7 @@ const TOOLS: Tool[] = [
|
|
|
741
757
|
{
|
|
742
758
|
name: "list_subscribe_topics",
|
|
743
759
|
description:
|
|
744
|
-
"
|
|
760
|
+
"获取当前用户真实订阅的他人知识库,不含自己创建的库。默认DEFAULT;书籍显式BOOKSPACE,保留query/author/book_id及分页。自有书库无匹配时可补查这里;仍无匹配且用户未限定只查订阅库时,按list_notes的个人引用来源路线核对候选,保留已知平台/时间,不能把空库当没有笔记。返回topics[]、has_more、total。",
|
|
745
761
|
inputSchema: {
|
|
746
762
|
type: "object" as const,
|
|
747
763
|
properties: {
|
|
@@ -781,6 +797,7 @@ const TOOLS: Tool[] = [
|
|
|
781
797
|
inputSchema: {
|
|
782
798
|
type: "object" as const,
|
|
783
799
|
properties: {
|
|
800
|
+
...snippetProperties,
|
|
784
801
|
query: {
|
|
785
802
|
type: "string",
|
|
786
803
|
description: "搜索关键词或语义描述(必填)",
|
|
@@ -801,6 +818,7 @@ const TOOLS: Tool[] = [
|
|
|
801
818
|
inputSchema: {
|
|
802
819
|
type: "object" as const,
|
|
803
820
|
properties: {
|
|
821
|
+
...snippetProperties,
|
|
804
822
|
topic_id: {
|
|
805
823
|
type: "string",
|
|
806
824
|
description: "知识库 ID(来自 list_topics 的 topic_id 字段)(必填)",
|
|
@@ -830,6 +848,8 @@ async function handleTool(
|
|
|
830
848
|
client: GetNoteClient
|
|
831
849
|
): Promise<unknown> {
|
|
832
850
|
switch (name) {
|
|
851
|
+
case "list_reference_resources":return client.listReferenceResources(input as Parameters<GetNoteClient["listReferenceResources"]>[0]);
|
|
852
|
+
case "get_notes":return client.getNotes(input as Parameters<GetNoteClient["getNotes"]>[0]);
|
|
833
853
|
// ── Notes ──
|
|
834
854
|
case "list_notes": {
|
|
835
855
|
const cursor = (input.cursor as string | undefined);
|
|
@@ -1093,12 +1113,16 @@ async function handleTool(
|
|
|
1093
1113
|
// ── Recall / Search ──
|
|
1094
1114
|
case "recall": {
|
|
1095
1115
|
return client.recall({
|
|
1116
|
+
response_mode:input.response_mode as string|undefined,
|
|
1117
|
+
max_snippet_chars:input.max_snippet_chars as number|undefined,
|
|
1096
1118
|
query: input.query as string,
|
|
1097
1119
|
top_k: input.top_k as number | undefined,
|
|
1098
1120
|
});
|
|
1099
1121
|
}
|
|
1100
1122
|
case "recall_knowledge": {
|
|
1101
1123
|
return client.recallKnowledge({
|
|
1124
|
+
response_mode:input.response_mode as string|undefined,
|
|
1125
|
+
max_snippet_chars:input.max_snippet_chars as number|undefined,
|
|
1102
1126
|
topic_id: input.topic_id as string,
|
|
1103
1127
|
query: input.query as string,
|
|
1104
1128
|
top_k: input.top_k as number | undefined,
|
|
@@ -1135,12 +1159,12 @@ async function main() {
|
|
|
1135
1159
|
}));
|
|
1136
1160
|
|
|
1137
1161
|
// Call tool
|
|
1138
|
-
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
1162
|
+
server.setRequestHandler(CallToolRequestSchema, async (request,extra) => {
|
|
1139
1163
|
const { name, arguments: args } = request.params;
|
|
1140
1164
|
const input = (args ?? {}) as ToolInput;
|
|
1141
1165
|
|
|
1142
1166
|
try {
|
|
1143
|
-
const result = await handleTool(name, input, client);
|
|
1167
|
+
const result = await handleTool(name, input, client.withSignal(extra.signal));
|
|
1144
1168
|
return {
|
|
1145
1169
|
content: [
|
|
1146
1170
|
{
|
|
@@ -1161,6 +1185,8 @@ async function main() {
|
|
|
1161
1185
|
field: err.field,
|
|
1162
1186
|
constraint: err.constraint,
|
|
1163
1187
|
expected_type: err.expectedType,
|
|
1188
|
+
supported_values: err.supportedValues,
|
|
1189
|
+
retry_after_seconds: err.retryAfterSeconds,
|
|
1164
1190
|
};
|
|
1165
1191
|
if (err.code === 10201) {
|
|
1166
1192
|
errPayload.membership_url = OPENAPI_MEMBERSHIP_PURCHASE_URL;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export interface ReadFailure {httpStatus?:number;code:number;reason:string;retryable:boolean;retryAfterSeconds?:number;waitProvided?:boolean}
|
|
2
|
+
const getPaths=new Set([
|
|
3
|
+
"/resource/note/list","/resource/note/detail","/resource/note/marks","/resource/note/sprouts","/resource/note/sprout",
|
|
4
|
+
"/resource/reference/list","/resource/knowledge/list","/resource/knowledge/subscribe/list","/resource/knowledge/notes","/resource/knowledge/directories",
|
|
5
|
+
"/resource/knowledge/file/capabilities","/resource/knowledge/bloggers","/resource/knowledge/blogger/contents","/resource/knowledge/blogger/content/detail",
|
|
6
|
+
"/resource/knowledge/lives","/resource/knowledge/live/detail","/resource/rate-limit/quota"
|
|
7
|
+
]);
|
|
8
|
+
const postPaths=new Set(["/resource/recall","/resource/recall/knowledge","/resource/note/batch-detail"]);
|
|
9
|
+
export function readRetryDelay(method:string,path:string,error:ReadFailure,attempt:number,waited:number):number|undefined {
|
|
10
|
+
if(attempt>=2||waited>=5000||error.httpStatus!==429||!error.retryable)return;
|
|
11
|
+
const qpsLimit=error.code===10202&&["qps_exceeded","qps_global_exceeded","qps_bucket_exceeded"].includes(error.reason);
|
|
12
|
+
if(!qpsLimit&&!(error.code===10005&&error.reason==="rate_limited"))return;
|
|
13
|
+
if(!(method==="GET"?getPaths.has(path):method==="POST"&&postPaths.has(path)))return;
|
|
14
|
+
if(error.waitProvided&&error.retryAfterSeconds===undefined)return;
|
|
15
|
+
const wait=error.retryAfterSeconds;
|
|
16
|
+
if(wait!==undefined&&(!Number.isSafeInteger(wait)||wait<0||wait>(5000-waited)/1000))return;
|
|
17
|
+
const delay=(wait===undefined?200*2**attempt:wait*1000)+1+Math.floor(Math.random()*50);
|
|
18
|
+
return delay<=5000-waited?delay:undefined;
|
|
19
|
+
}
|
|
20
|
+
export async function waitForReadRetry(delay:number,signal?:AbortSignal):Promise<void>{
|
|
21
|
+
signal?.throwIfAborted();
|
|
22
|
+
await new Promise<void>((resolve,reject)=>{
|
|
23
|
+
const abort=()=>{clearTimeout(timer);signal?.removeEventListener("abort",abort);reject(signal?.reason??new Error("cancelled"))};
|
|
24
|
+
const timer=setTimeout(()=>{signal?.removeEventListener("abort",abort);resolve()},delay);
|
|
25
|
+
signal?.addEventListener("abort",abort,{once:true});
|
|
26
|
+
});
|
|
27
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
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
|
+
import {GetNoteClient, GetNoteAPIError} from '../dist/client.js';
|
|
8
|
+
|
|
9
|
+
test('experience error metadata survives business and HTTP failures', async t => {
|
|
10
|
+
for (const [name, status, header, bodyWait, want] of [
|
|
11
|
+
['body',200,undefined,12,12],['header',429,'9',undefined,9],
|
|
12
|
+
['later body',429,'9',12,12],['later header',429,'15',12,15],
|
|
13
|
+
['invalid',429,'garbage',undefined,undefined],['negative',429,'-1',undefined,undefined],
|
|
14
|
+
['overflow',429,'999999999999999999999999',undefined,undefined],
|
|
15
|
+
]) await t.test(name, async () => {
|
|
16
|
+
const server = http.createServer((req,res) => {
|
|
17
|
+
if(header !== undefined)res.setHeader('Retry-After',header);
|
|
18
|
+
res.writeHead(status,{'content-type':'application/json'});
|
|
19
|
+
res.end(JSON.stringify({success:false,error:{code:10202,reason:'qps_exceeded',message:'wait',retryable:true,supported_values:['dedao'],retry_after_seconds:bodyWait,future_field:true},request_id:'req-advice'}));
|
|
20
|
+
});
|
|
21
|
+
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
|
|
22
|
+
try {
|
|
23
|
+
const client = new GetNoteClient('key','client',`http://127.0.0.1:${server.address().port}`);
|
|
24
|
+
await assert.rejects(()=>client.getNote('123'),err=>{
|
|
25
|
+
assert(err instanceof GetNoteAPIError);assert.equal(err.requestId,'req-advice');
|
|
26
|
+
assert.equal(err.retryAfterSeconds,want);assert.deepEqual(err.supportedValues,['dedao']);return true;
|
|
27
|
+
});
|
|
28
|
+
} finally {server.closeAllConnections();await new Promise(resolve=>server.close(resolve));}
|
|
29
|
+
});
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test('experience stdio tool retains public error advice fields', async () => {
|
|
33
|
+
const server=http.createServer((req,res)=>{
|
|
34
|
+
res.writeHead(200,{'content-type':'application/json','retry-after':'9'});
|
|
35
|
+
res.end(JSON.stringify({success:false,error:{code:10000,reason:'invalid_request',message:'bad source',retryable:false,field:'source',supported_values:['dedao'],retry_after_seconds:12},request_id:'req-tool'}));
|
|
36
|
+
});
|
|
37
|
+
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
|
|
38
|
+
const client=new Client({name:'experience-errors',version:'1'});
|
|
39
|
+
const transport=new StdioClientTransport({command:process.execPath,args:[fileURLToPath(new URL('../dist/index.js',import.meta.url))],env:{...process.env,GETNOTE_API_KEY:'key',GETNOTE_CLIENT_ID:'client',GETNOTE_API_URL:`http://127.0.0.1:${server.address().port}`},stderr:'pipe'});
|
|
40
|
+
try {
|
|
41
|
+
await client.connect(transport);
|
|
42
|
+
const result=await client.callTool({name:'get_note',arguments:{id:'123'}});
|
|
43
|
+
assert.equal(result.isError,true);const data=JSON.parse(result.content[0].text);
|
|
44
|
+
assert.equal(data.request_id,'req-tool');assert.equal(data.field,'source');
|
|
45
|
+
assert.deepEqual(data.supported_values,['dedao']);assert.equal(data.retry_after_seconds,12);
|
|
46
|
+
} finally {await client.close();server.closeAllConnections();await new Promise(resolve=>server.close(resolve));}
|
|
47
|
+
});
|
|
@@ -0,0 +1,43 @@
|
|
|
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
|
+
import {GetNoteClient} from '../dist/client.js';
|
|
8
|
+
|
|
9
|
+
test('course, batch and snippet contracts survive the actual stdio tools', async()=>{
|
|
10
|
+
let mode='supported';let requests=[];
|
|
11
|
+
const api=http.createServer(async(req,res)=>{
|
|
12
|
+
const url=new URL(req.url,'http://localhost');const chunks=[];for await(const c of req)chunks.push(c);
|
|
13
|
+
const body=chunks.length?JSON.parse(Buffer.concat(chunks)):undefined;
|
|
14
|
+
requests.push({path:url.pathname,query:Object.fromEntries(url.searchParams),body});
|
|
15
|
+
const filters=Object.fromEntries([...url.searchParams].filter(([k])=>!['page_size','cursor'].includes(k)));
|
|
16
|
+
const caps=mode==='old'?[]:['pagination.v1','note.filters.v1','note.reference.v1','reference.resources.v1','note.course_filter.v1','note.batch_detail.v1','search.snippet.v1','future.v2'];
|
|
17
|
+
if(mode==='ignored')delete filters.reference_course_id;
|
|
18
|
+
let data={notes:[],applied_filters:filters,pagination:{mode:'cursor',page:null,page_size:20,returned_count:0,total_count:null,has_more:false,next_cursor:null,next_page:null}};
|
|
19
|
+
if(url.pathname.endsWith('/reference/list')) data={...data,resources:[],pagination:{...data.pagination,has_more:true,next_cursor:'next'}};
|
|
20
|
+
if(url.pathname.endsWith('/note/batch-detail'))data={items:[{note_id:'9007199254740993',status:'ok',note:{note_id:'9007199254740993',original:{source:'ref_content',content:'中😀'},future_note:true}},{note_id:'2',status:'deferred_budget'}],pending_ids:['2'],partial:true,max_total_chars:32000,max_total_bytes:1048576};
|
|
21
|
+
if(url.pathname.endsWith('/recall'))data=body?.response_mode?{response_mode:'snippet',max_snippet_chars:100,max_total_bytes:1048576,results:[{resource_type:'future_type',snippet:'中😀',snippet_source:'unknown',truncated:false,content_state:{content:'omitted',snippet:'full'},future_hit:true}]}:{results:[{note_id:'1',content:'legacy body'}]};
|
|
22
|
+
res.setHeader('content-type','application/json');res.end(JSON.stringify({success:true,meta:{capabilities:caps},data}));
|
|
23
|
+
});await new Promise(r=>api.listen(0,'127.0.0.1',r));
|
|
24
|
+
const client=new Client({name:'experience',version:'1'});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'});
|
|
25
|
+
try{
|
|
26
|
+
await client.connect(transport);const {tools}=await client.listTools();const schemas=Object.fromEntries(tools.map(t=>[t.name,t.inputSchema]));
|
|
27
|
+
for(const name of ['list_reference_resources','get_notes'])assert.ok(schemas[name],`missing ${name}`);
|
|
28
|
+
for(const key of ['reference_course_type','reference_course_id'])assert.ok(schemas.list_notes.properties[key]);
|
|
29
|
+
assert.ok(schemas.recall.properties.response_mode);assert.ok(schemas.recall_knowledge.properties.max_snippet_chars);
|
|
30
|
+
const cases=[['list_reference_resources',{source:'dedao',resource_type:'course',query:'课程'}],['list_notes',{source:'dedao',reference_course_type:'66',reference_course_id:'9007199254740993'}],['get_notes',{ids:['9007199254740993','0002','2'],fields:['original']}],['recall',{query:'AI',response_mode:'snippet',max_snippet_chars:100}]];
|
|
31
|
+
for(const [name,args]of cases){const result=await client.callTool({name,arguments:args});assert.ok(!result.isError,result.content[0].text);const data=JSON.parse(result.content[0].text);if(name==='list_reference_resources'){assert.equal(data.pagination.has_more,true);assert.equal(data.resources.length,0)}if(name==='get_notes'){assert.deepEqual(requests.at(-1).body.ids,['9007199254740993','2']);assert.deepEqual(data.pending_ids,['2']);assert.equal(data.items[0].note.future_note,true)}if(name==='recall'){assert.equal(data.results[0].future_hit,true);assert.ok(!('content'in data.results[0]))}}
|
|
32
|
+
for(const bad of ['old','ignored']){mode=bad;const r=await client.callTool({name:'list_notes',arguments:cases[1][1]});assert.equal(r.isError,true,`${bad} silently accepted course filter`)}
|
|
33
|
+
mode='old';const legacy=await client.callTool({name:'recall',arguments:{query:'AI'}});assert.ok(!legacy.isError);assert.equal(requests.at(-1).body.response_mode,undefined);assert.equal(JSON.parse(legacy.content[0].text).results[0].content,'legacy body');
|
|
34
|
+
const count=requests.length;const invalid=await client.callTool({name:'list_notes',arguments:{...cases[1][1],topic_id:'kb'}});assert.equal(invalid.isError,true);assert.equal(requests.length,count);
|
|
35
|
+
}finally{await client.close();api.closeAllConnections();await new Promise(r=>api.close(r))}
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test('new-only request validation preserves large IDs and budgets',async()=>{
|
|
39
|
+
const client=new GetNoteClient('k','c','http://127.0.0.1:1');
|
|
40
|
+
for(const ids of [[],['9223372036854775808'],[9007199254740992],Array.from({length:21},(_,i)=>String(i+1))])await assert.rejects(()=>client.getNotes({ids}));
|
|
41
|
+
await assert.rejects(()=>client.getNotes({ids:['1'],max_total_chars:0}));
|
|
42
|
+
await assert.rejects(()=>client.recall({query:'AI',max_snippet_chars:400}));
|
|
43
|
+
});
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
import test from 'node:test';
|
|
4
|
+
import {GetNoteClient,GetNoteAPIError} from '../dist/client.js';
|
|
5
|
+
import {readRetryDelay} from '../dist/read-retry.js';
|
|
6
|
+
|
|
7
|
+
test('outer read retry is bounded and never replays writes or quota',async t=>{
|
|
8
|
+
for(const [name,kind,wait,code,reason,retryable,want]of [
|
|
9
|
+
['read','read','0',10202,'qps_exceeded',true,3],['batch','batch','0',10202,'qps_exceeded',true,3],
|
|
10
|
+
['global-qps','read','0',10202,'qps_global_exceeded',true,3],['bucket-qps','read','0',10202,'qps_bucket_exceeded',true,3],
|
|
11
|
+
['global-qps-write','write','0',10202,'qps_global_exceeded',true,1],['bucket-qps-token','token','0',10202,'qps_bucket_exceeded',true,1],
|
|
12
|
+
['write','write','0',10202,'qps_exceeded',true,1],['token','token','0',10202,'qps_exceeded',true,1],
|
|
13
|
+
['quota','read','0',10203,'quota_exhausted',true,1],['long','read','60',10202,'qps_exceeded',true,1],
|
|
14
|
+
['nonretryable','read','0',10202,'qps_exceeded',false,1],['unknown','read','0',10202,'future_limit',true,1],
|
|
15
|
+
])await t.test(name,async()=>{
|
|
16
|
+
let calls=0;const api=http.createServer((req,res)=>{calls++;res.writeHead(429,{'content-type':'application/json','retry-after':wait});res.end(JSON.stringify({success:false,error:{code,reason,retryable,message:'wait'},request_id:'req-last'}))});await new Promise(r=>api.listen(0,'127.0.0.1',r));
|
|
17
|
+
try{const c=new GetNoteClient('k','c',`http://127.0.0.1:${api.address().port}`);let invoke=()=>c.getNote('1');if(kind==='batch')invoke=()=>c.getNotes({ids:['1']});if(kind==='write')invoke=()=>c.saveNote({content:'one write'});if(kind==='token')invoke=()=>c.getKnowledgeFileUploadToken('pdf');await assert.rejects(invoke,e=>e instanceof GetNoteAPIError&&e.requestId==='req-last');assert.equal(calls,want)}finally{api.closeAllConnections();await new Promise(r=>api.close(r))}
|
|
18
|
+
});
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
test('read cancellation stops waiting and retains last API advice',async()=>{
|
|
22
|
+
let calls=0;const controller=new AbortController();const api=http.createServer((req,res)=>{calls++;res.writeHead(429,{'content-type':'application/json','retry-after':'1'});res.end(JSON.stringify({success:false,error:{code:10202,reason:'qps_exceeded',retryable:true,message:'wait'},request_id:'req-cancel'}));setTimeout(()=>controller.abort(),30)});await new Promise(r=>api.listen(0,'127.0.0.1',r));
|
|
23
|
+
try{const c=new GetNoteClient('k','c',`http://127.0.0.1:${api.address().port}`).withSignal(controller.signal);const start=Date.now();await assert.rejects(()=>c.getNote('1'),e=>e instanceof GetNoteAPIError&&e.requestId==='req-cancel'&&e.retryAfterSeconds===1);assert.equal(calls,1);assert.ok(Date.now()-start<500)}finally{api.closeAllConnections();await new Promise(r=>api.close(r))}
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test('retry budget never undercuts a server wait or retries unknown reads',()=>{
|
|
27
|
+
const hint={httpStatus:429,code:10202,reason:'qps_exceeded',retryable:true,retryAfterSeconds:2,waitProvided:true};
|
|
28
|
+
assert.equal(readRetryDelay('GET','/resource/note/detail',hint,1,3100),undefined);
|
|
29
|
+
assert.equal(readRetryDelay('GET','/resource/future-action',hint,0,0),undefined);
|
|
30
|
+
assert.equal(readRetryDelay('POST','/resource/note/save',hint,0,0),undefined);
|
|
31
|
+
assert.equal(readRetryDelay('GET','/resource/note/detail',hint,2,0),undefined);
|
|
32
|
+
const delay=readRetryDelay('GET','/resource/note/detail',hint,0,0);assert.ok(delay>2000&&delay<=2050);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test('cancellation during a retrying HTTP request also retains last advice',async()=>{
|
|
36
|
+
let calls=0;const controller=new AbortController();const api=http.createServer((req,res)=>{calls++;if(calls===1){res.writeHead(429,{'content-type':'application/json','retry-after':'0'});res.end(JSON.stringify({success:false,error:{code:10202,reason:'qps_exceeded',retryable:true,message:'wait'},request_id:'req-before-cancel'}));return}controller.abort();res.end('{}')});await new Promise(r=>api.listen(0,'127.0.0.1',r));
|
|
37
|
+
try{const c=new GetNoteClient('k','c',`http://127.0.0.1:${api.address().port}`).withSignal(controller.signal);await assert.rejects(()=>c.getNote('1'),e=>e instanceof GetNoteAPIError&&e.requestId==='req-before-cancel'&&e.retryAfterSeconds===0);assert.equal(calls,2)}finally{api.closeAllConnections();await new Promise(r=>api.close(r))}
|
|
38
|
+
});
|