@getnote/mcp 1.10.1 → 1.11.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/dist/client.js CHANGED
@@ -42,6 +42,8 @@ const axios_1 = __importDefault(require("axios"));
42
42
  const discovery_1 = require("./discovery");
43
43
  const experience_1 = require("./experience");
44
44
  const read_retry_1 = require("./read-retry");
45
+ const admission_1 = require("./admission");
46
+ const upload_operation_1 = require("./upload-operation");
45
47
  const DEFAULT_BASE_URL = "https://openapi.biji.com/open/api/v1";
46
48
  function retryAfterSeconds(body, header) {
47
49
  let wait = typeof body === "number" && Number.isSafeInteger(body) && body >= 0 ? body : undefined;
@@ -99,9 +101,14 @@ class GetNoteAPIError extends Error {
99
101
  expectedType;
100
102
  supportedValues;
101
103
  retryAfterSeconds;
104
+ rateLimitDetail;
102
105
  httpStatus;
103
106
  waitProvided = false;
104
- constructor(code, reason, message, requestId, retryable = false, field, constraint, expectedType, supportedValues, retryAfterSeconds) {
107
+ operationId;
108
+ uploadKind;
109
+ recoveryAdvice;
110
+ queryTool;
111
+ constructor(code, reason, message, requestId, retryable = false, field, constraint, expectedType, supportedValues, retryAfterSeconds, rateLimitDetail) {
105
112
  super(message);
106
113
  this.code = code;
107
114
  this.reason = reason;
@@ -112,12 +119,13 @@ class GetNoteAPIError extends Error {
112
119
  this.expectedType = expectedType;
113
120
  this.supportedValues = supportedValues;
114
121
  this.retryAfterSeconds = retryAfterSeconds;
122
+ this.rateLimitDetail = rateLimitDetail;
115
123
  this.name = "GetNoteAPIError";
116
124
  }
117
125
  }
118
126
  exports.GetNoteAPIError = GetNoteAPIError;
119
127
  function apiFailure(err, requestID, status, header) {
120
- 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 });
128
+ 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), err?.rate_limit_detail), { httpStatus: status, waitProvided: err?.retry_after_seconds !== undefined || header !== undefined });
121
129
  }
122
130
  class GetNoteClient {
123
131
  async getNoteMarks(note_id) {
@@ -130,64 +138,216 @@ class GetNoteClient {
130
138
  return this.request("GET", "/resource/note/sprout", { id });
131
139
  }
132
140
  async getKnowledgeFileCapabilities() {
133
- return this.request("GET", "/resource/knowledge/file/capabilities");
141
+ return this.uploadConfiguration('file');
134
142
  }
135
- async getKnowledgeFileUploadToken(mime_type) {
136
- return this.request("GET", "/resource/knowledge/file/upload_token", { mime_type });
143
+ async getKnowledgeFileUploadToken(mime_type, operation_id) {
144
+ return this.uploadCredential('file', { mime_type }, operation_id);
137
145
  }
146
+ async getKnowledgeFileUploadOperation(operation_id) { return this.getOperation('file', operation_id); }
147
+ async getUploadOperation(operation_id) { return this.getOperation('image', operation_id); }
138
148
  async uploadKnowledgeFile(data) {
139
149
  return this.request("POST", "/resource/knowledge/file/upload", undefined, data);
140
150
  }
141
151
  http;
142
152
  requestSignal;
153
+ identity;
154
+ uploadRuntimeCache = {};
155
+ async uploadConfiguration(kind, allowRetry = true) {
156
+ const path = upload_operation_1.uploadRoutes[kind] + (kind === 'image' ? '/config' : '/capabilities');
157
+ const config = await this.request('GET', path, undefined, undefined, undefined, allowRetry);
158
+ this.uploadRuntimeCache[kind] = { runtime: config?.runtime, at: Date.now() };
159
+ return config;
160
+ }
161
+ async recoveryRuntime(kind) {
162
+ if (!this.uploadRuntimeCache[kind] || Date.now() - this.uploadRuntimeCache[kind].at > 5 * 60 * 1000) {
163
+ try {
164
+ await this.uploadConfiguration(kind, false);
165
+ }
166
+ catch (error) {
167
+ // Old servers may omit config. File capabilities additionally require
168
+ // topic.read, while a topic.write-only grant may still issue once without
169
+ // claiming replay support. Explicit operation IDs still fail unsupported.
170
+ if (error instanceof GetNoteAPIError && (error.httpStatus === 404 || kind === 'file' && error.httpStatus === 403))
171
+ this.uploadRuntimeCache[kind] = { at: Date.now() };
172
+ else
173
+ throw error;
174
+ }
175
+ }
176
+ return this.uploadRuntimeCache[kind]?.runtime;
177
+ }
178
+ operationAdvice(error, kind, id) {
179
+ error.operationId = id;
180
+ error.uploadKind = kind;
181
+ error.recoveryAdvice = 'Keep the original operation_id and query the original upload operation; do not mint a new key or upload again. Preserve uploaded objects and the same note client_request_id after save rate limits. Pending tasks are not complete.';
182
+ error.queryTool = kind === 'image' ? 'get_upload_operation' : 'get_knowledge_file_upload_operation';
183
+ return error;
184
+ }
185
+ operationFailure(kind, id, reason, original) {
186
+ const error = new GetNoteAPIError(original?.code ?? -1, reason, 'Original upload operation is not confirmed or no longer recoverable; query its original operation_id.', original?.requestId, false, original?.field, original?.constraint, original?.expectedType, original?.supportedValues, original?.retryAfterSeconds, original?.rateLimitDetail);
187
+ error.httpStatus = original?.httpStatus;
188
+ return this.operationAdvice(error, kind, id);
189
+ }
190
+ usableCredential(kind, id, value, outerDeadline, original) {
191
+ if (!value || typeof value !== 'object' || Array.isArray(value))
192
+ throw this.operationFailure(kind, id, 'credential_operation_unconfirmed', original);
193
+ const credential = value;
194
+ if (credential.operation_id !== undefined && credential.operation_id !== id)
195
+ throw this.operationFailure(kind, id, 'credential_operation_conflict', original);
196
+ let deadline = outerDeadline;
197
+ if (credential.resume_until !== undefined) {
198
+ if (typeof credential.resume_until !== 'string' || !Number.isFinite(Date.parse(credential.resume_until)))
199
+ throw this.operationFailure(kind, id, 'credential_operation_unconfirmed', original);
200
+ if (deadline === undefined || Date.parse(credential.resume_until) < Date.parse(deadline))
201
+ deadline = credential.resume_until;
202
+ }
203
+ if (deadline === undefined || !Number.isFinite(Date.parse(deadline)))
204
+ throw this.operationFailure(kind, id, 'credential_operation_unconfirmed', original);
205
+ if (Date.parse(deadline) <= Date.now())
206
+ throw this.operationFailure(kind, id, 'credential_operation_expired', original);
207
+ return { ...credential, operation_id: id, resume_until: deadline };
208
+ }
209
+ async lookupOperation(kind, id, original) {
210
+ let view;
211
+ try {
212
+ view = await this.request('GET', upload_operation_1.uploadRoutes[kind] + '/upload_operation', { operation_id: id });
213
+ }
214
+ catch (error) {
215
+ throw this.operationFailure(kind, id, error instanceof GetNoteAPIError ? error.reason : 'credential_operation_unconfirmed', original ?? (error instanceof GetNoteAPIError ? error : undefined));
216
+ }
217
+ const deadline = Date.parse(view?.resume_until);
218
+ if (view?.operation_id !== id || view.state !== 'issued' || !Number.isFinite(deadline) || deadline <= Date.now() || !view.credential || typeof view.credential !== 'object' || Array.isArray(view.credential)) {
219
+ throw this.operationFailure(kind, id, view?.state === 'expired' || Number.isFinite(deadline) && deadline <= Date.now() ? 'credential_operation_expired' : 'credential_operation_unconfirmed', original);
220
+ }
221
+ const credential = this.usableCredential(kind, id, view.credential, view.resume_until, original);
222
+ return { ...view, resume_until: credential.resume_until, credential };
223
+ }
224
+ async getOperation(kind, operation_id) {
225
+ (0, upload_operation_1.validateOperationID)(operation_id);
226
+ if (!(0, upload_operation_1.supportsRecovery)(await this.recoveryRuntime(kind), kind))
227
+ throw this.operationFailure(kind, operation_id, 'upload_operation_unsupported');
228
+ return this.lookupOperation(kind, operation_id);
229
+ }
230
+ async uploadCredential(kind, params, operation_id) {
231
+ if (operation_id !== undefined)
232
+ (0, upload_operation_1.validateOperationID)(operation_id);
233
+ const supported = (0, upload_operation_1.supportsRecovery)(await this.recoveryRuntime(kind), kind);
234
+ if (!supported) {
235
+ if (operation_id !== undefined)
236
+ throw this.operationFailure(kind, operation_id, 'upload_operation_unsupported');
237
+ return this.request('GET', upload_operation_1.uploadRoutes[kind] + '/upload_token', params);
238
+ }
239
+ const id = operation_id ?? (0, upload_operation_1.newOperationID)();
240
+ try {
241
+ const credential = await this.request('GET', upload_operation_1.uploadRoutes[kind] + '/upload_token', params, undefined, { 'Idempotency-Key': id });
242
+ return this.usableCredential(kind, id, credential);
243
+ }
244
+ catch (error) {
245
+ if (error instanceof GetNoteAPIError) {
246
+ if (!['credential_operation_unconfirmed', 'credential_operation_unavailable', 'unexpected_http_response'].includes(error.reason))
247
+ throw this.operationAdvice(error, kind, id);
248
+ }
249
+ else if (this.requestSignal?.aborted) {
250
+ throw this.operationFailure(kind, id, 'credential_operation_unconfirmed');
251
+ }
252
+ const recovered = await this.lookupOperation(kind, id, error instanceof GetNoteAPIError ? error : undefined);
253
+ return { ...recovered.credential, operation_id: id, resume_until: recovered.resume_until };
254
+ }
255
+ }
143
256
  withSignal(signal) {
144
257
  // Per-call view shares the HTTP transport, never another call's signal.
145
258
  return Object.assign(Object.create(Object.getPrototypeOf(this)), this, { requestSignal: signal });
146
259
  }
147
260
  constructor(apiKey, clientId, baseURL) {
261
+ const normalized = normalizeBaseURL(baseURL || process.env.GETNOTE_API_URL);
262
+ this.identity = (0, admission_1.authorizationIdentity)(normalized, `Bearer ${apiKey}`, clientId);
148
263
  this.http = axios_1.default.create({
149
- baseURL: normalizeBaseURL(baseURL || process.env.GETNOTE_API_URL),
264
+ baseURL: normalized,
150
265
  headers: {
151
266
  Authorization: `Bearer ${apiKey}`,
152
267
  "X-Client-ID": clientId,
153
268
  "Content-Type": "application/json",
154
269
  },
155
270
  timeout: 30000,
271
+ // Credential GETs issue side effects: redirects must not bypass the
272
+ // negotiated operation or the single-issuance recovery path.
273
+ maxRedirects: 0,
156
274
  });
157
- this.http.defaults.transformResponse = [parseJsonPreservingLargeIntegerStrings];
275
+ this.http.defaults.transformResponse = [(data, _headers, status) => {
276
+ try {
277
+ return parseJsonPreservingLargeIntegerStrings(data);
278
+ }
279
+ catch (error) {
280
+ // A legacy missing route may return plain text or HTML. Preserve its
281
+ // verified HTTP status instead of losing it to a JSON SyntaxError.
282
+ if (status !== undefined && status >= 300)
283
+ return data;
284
+ throw error;
285
+ }
286
+ }];
158
287
  this.http.interceptors.response.use((res) => res, (err) => {
159
288
  throw err;
160
289
  });
161
290
  }
162
- async request(method, path, params, data) {
163
- let waited = 0;
164
- let lastError;
165
- for (let attempt = 0;; attempt++) {
166
- try {
167
- this.requestSignal?.throwIfAborted();
168
- return await this.requestOnce(method, path, params, data);
169
- }
170
- catch (err) {
171
- if (this.requestSignal?.aborted && lastError)
172
- throw Object.assign(lastError, { cause: this.requestSignal.reason });
173
- if (!(err instanceof GetNoteAPIError))
174
- throw err;
175
- const delay = (0, read_retry_1.readRetryDelay)(method, path, err, attempt, waited);
176
- if (delay === undefined)
177
- throw err;
178
- lastError = err;
179
- const start = performance.now();
291
+ async request(method, path, params, data, headers, allowRetry = true) {
292
+ // Snapshot caller-owned values once, before waiting or retrying.
293
+ params = params === undefined ? undefined : structuredClone(params);
294
+ data = data === undefined ? undefined : structuredClone(data);
295
+ return (0, admission_1.inAuthorizationQueue)(this.identity, this.requestSignal, async (queue) => {
296
+ let waited = 0;
297
+ let lastError;
298
+ let pacingBudgetExceeded = false;
299
+ for (let attempt = 0;; attempt++) {
180
300
  try {
181
- await (0, read_retry_1.waitForReadRetry)(delay, this.requestSignal);
301
+ this.requestSignal?.throwIfAborted();
302
+ const pacingStarted = performance.now();
303
+ if (!await (0, admission_1.pace)(queue, (0, read_retry_1.operationBucket)(method, path), this.requestSignal, lastError ? 5000 - waited : Infinity)) {
304
+ pacingBudgetExceeded = true;
305
+ throw lastError;
306
+ }
307
+ if (lastError)
308
+ waited += performance.now() - pacingStarted;
309
+ const result = await this.requestOnce(method, path, params, data, headers);
310
+ (0, admission_1.learnPolicy)(queue, result);
311
+ return result;
182
312
  }
183
- catch (cause) {
184
- throw Object.assign(err, { cause });
313
+ catch (err) {
314
+ if (this.requestSignal?.aborted && lastError)
315
+ throw Object.assign(lastError, { cause: this.requestSignal.reason });
316
+ if (pacingBudgetExceeded || !(err instanceof GetNoteAPIError))
317
+ throw err;
318
+ const detail = err.rateLimitDetail;
319
+ if (detail && typeof detail === 'object' && detail.dimension === 'qps')
320
+ (0, admission_1.learnRate)(queue, detail.bucket, detail.sustained_rate_per_second);
321
+ const qps = detail?.dimension === 'qps' || err.rateLimitDetail === undefined && ((err.code === 10202 && ['qps_exceeded', 'qps_global_exceeded', 'qps_bucket_exceeded'].includes(err.reason)) || (err.code === 10005 && err.reason === 'rate_limited'));
322
+ if (qps) {
323
+ const bucket = typeof detail?.bucket === 'string' && ['global', 'read', 'write', 'write_note', 'upload_credential'].includes(detail.bucket) ? detail.bucket : err.reason === 'qps_global_exceeded' ? 'global' : (0, read_retry_1.operationBucket)(method, path);
324
+ const waits = [0];
325
+ if (err.retryAfterSeconds !== undefined)
326
+ waits.push(err.retryAfterSeconds * 1000);
327
+ for (const [key, scale] of [['retry_after_ms', 1], ['retry_after_seconds', 1000]]) {
328
+ const value = detail?.[key];
329
+ if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0)
330
+ waits.push(value * scale);
331
+ }
332
+ (0, admission_1.learnCooldown)(queue, bucket, Math.max(...waits));
333
+ }
334
+ const delay = allowRetry ? (0, read_retry_1.readRetryDelay)(method, path, err, attempt, waited, headers?.['Idempotency-Key']) : undefined;
335
+ if (delay === undefined)
336
+ throw err;
337
+ lastError = err;
338
+ const start = performance.now();
339
+ try {
340
+ await (0, read_retry_1.waitForReadRetry)(delay, this.requestSignal);
341
+ }
342
+ catch (cause) {
343
+ throw Object.assign(err, { cause });
344
+ }
345
+ waited += performance.now() - start;
185
346
  }
186
- waited += performance.now() - start;
187
347
  }
188
- }
348
+ });
189
349
  }
190
- async requestOnce(method, path, params, data) {
350
+ async requestOnce(method, path, params, data, headers) {
191
351
  const kinds = { "/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" };
192
352
  const contract = method === "GET" && kinds[path] ? (0, discovery_1.discoveryContract)(kinds[path], params || {}) : undefined;
193
353
  if (contract)
@@ -199,6 +359,7 @@ class GetNoteClient {
199
359
  params,
200
360
  data,
201
361
  signal: this.requestSignal,
362
+ headers,
202
363
  });
203
364
  const body = res.data;
204
365
  if (!body.success) {
@@ -222,7 +383,7 @@ class GetNoteClient {
222
383
  if (body?.error) {
223
384
  throw apiFailure(body.error, body.request_id, err.response.status, err.response.headers["retry-after"]);
224
385
  }
225
- throw new Error(`HTTP ${err.response.status}: ${err.message}`);
386
+ throw apiFailure({ code: -1, reason: 'unexpected_http_response', message: `HTTP ${err.response.status}: API response unavailable` }, undefined, err.response.status, err.response.headers["retry-after"]);
226
387
  }
227
388
  throw err;
228
389
  }
@@ -263,10 +424,11 @@ class GetNoteClient {
263
424
  }
264
425
  // ─── Image ───────────────────────────────────────────────────────────────
265
426
  async getUploadConfig() {
266
- return this.request("GET", "/resource/image/config");
427
+ return this.uploadConfiguration('image');
267
428
  }
268
429
  async getUploadToken(params) {
269
- return this.request("GET", "/resource/image/upload_token", { count: params.count, mime_type: params.mime_type });
430
+ const credential = await this.uploadCredential('image', { count: params.count, mime_type: params.mime_type }, params.operation_id);
431
+ return credential;
270
432
  }
271
433
  /**
272
434
  * 上传图片到 OSS(使用预签名 URL)
@@ -291,6 +453,9 @@ class GetNoteClient {
291
453
  });
292
454
  const response = await axios_1.default.post(token.host, form, {
293
455
  headers: form.getHeaders(),
456
+ signal: this.requestSignal,
457
+ timeout: 30000,
458
+ maxRedirects: 0,
294
459
  maxBodyLength: Infinity,
295
460
  validateStatus: () => true,
296
461
  });
@@ -310,13 +475,21 @@ class GetNoteClient {
310
475
  * @param mimeType MIME 类型(如 png, jpg)
311
476
  * @returns 上传结果(包含 image_id 和 access_url)
312
477
  */
313
- async uploadImage(imageData, mimeType = "png") {
478
+ async uploadImage(imageData, mimeType = "png", operation_id) {
314
479
  // 1. 获取上传凭证(现在直接返回单个对象)
315
- const token = await this.getUploadToken({ mime_type: mimeType });
480
+ const token = await this.getUploadToken({ mime_type: mimeType, operation_id });
316
481
  // 2. 上传到 OSS
317
- const { image_id } = await this.uploadImageToOSS(token, imageData);
318
- // 3. 返回结果
319
- return { image_id, access_url: token.access_url };
482
+ let image_id;
483
+ try {
484
+ ({ image_id } = await this.uploadImageToOSS(token, imageData));
485
+ }
486
+ catch (error) {
487
+ if (token.operation_id)
488
+ throw this.operationFailure('image', token.operation_id, 'upload_result_unconfirmed');
489
+ throw error;
490
+ }
491
+ // 3. Preserve the original operation, never print the credential itself.
492
+ return { image_id, access_url: token.access_url, operation_id: token.operation_id, resume_until: token.resume_until };
320
493
  }
321
494
  // ─── Knowledge / Topics ─────────────────────────────────────────────────
322
495
  async listTopics(params) {
package/dist/index.js CHANGED
@@ -49,6 +49,9 @@ const client_js_1 = require("./client.js");
49
49
  const membership_js_1 = require("./membership.js");
50
50
  const node_fs_1 = require("node:fs");
51
51
  const node_path_1 = require("node:path");
52
+ const operationIDSchema = { type: 'string', pattern: '^[A-Za-z0-9._:-]{1,128}$', minLength: 1, maxLength: 128, description: '可选的原上传操作标识;恢复时必须复用。仅服务器协商支持时可用,不支持时明确失败。' };
53
+ const recoveryDescription = '保留已上传对象和同一笔记 client_request_id;保存遇限流不要重新上传。凭据敏感,不得放进聊天、日志或命令参数。任务 pending/processing 不等于完成。恢复仅查询原 operation_id,不能自动申请新 key。';
54
+ const operationIDInput = zod_1.z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/);
52
55
  const pkg = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(__dirname, "..", "package.json"), "utf-8"));
53
56
  const SERVER_VERSION = pkg.version;
54
57
  // ─── Security ────────────────────────────────────────────────────────────────
@@ -535,14 +538,24 @@ const TOOLS = [
535
538
  description: "上传前查询当前配置允许的文件扩展名、MIME、大小、页数和独立日限额;不缓存为固定格式列表。",
536
539
  inputSchema: { type: "object", properties: {} },
537
540
  },
541
+ {
542
+ name: "get_knowledge_file_upload_operation",
543
+ description: "仅查询原知识库文件上传凭据操作。" + recoveryDescription,
544
+ inputSchema: { type: 'object', properties: { operation_id: operationIDSchema }, required: ['operation_id'] },
545
+ },
546
+ {
547
+ name: "get_upload_operation",
548
+ description: "仅查询原图片上传凭据操作。" + recoveryDescription,
549
+ inputSchema: { type: 'object', properties: { operation_id: operationIDSchema }, required: ['operation_id'] },
550
+ },
538
551
  {
539
552
  name: "get_knowledge_file_upload_token",
540
- description: "获取一次 OSS 文件上传临时凭据。通过本地 getnote upload --token-file <file> --max-size-bytes <能力上限> 直接 PUT 到 OSS,无需再次 CLI 登录。凭据通过受控文件或 stdin 传入,不写命令参数或聊天;不要把文件字节传给云 MCP。",
541
- inputSchema: { type: "object", properties: { mime_type: { type: "string", description: "能力接口返回的扩展名,如 HTML" } }, required: ["mime_type"] },
553
+ description: recoveryDescription + "获取一次 OSS 文件上传临时凭据。通过本地 getnote upload --token-file <file> --max-size-bytes <能力上限> 直接 PUT 到 OSS,无需再次 CLI 登录。凭据通过受控文件或 stdin 传入,不写命令参数或聊天;不要把文件字节传给云 MCP。",
554
+ inputSchema: { type: "object", properties: { mime_type: { type: "string", description: "能力接口返回的扩展名,如 HTML" }, operation_id: operationIDSchema }, required: ["mime_type"] },
542
555
  },
543
556
  {
544
557
  name: "upload_knowledge_file",
545
- description: "OSS 直传成功后将原文件加入知识库,只接收元数据,不接收本地路径或 base64。返回处理中的资源不等于入库成功;用 list_topic_directories 查询同一 ID,直到 SUCCESS 或 FAIL。",
558
+ description: recoveryDescription + "OSS 直传成功后将原文件加入知识库,只接收元数据,不接收本地路径或 base64。返回处理中的资源不等于入库成功;用 list_topic_directories 查询同一 ID,直到 SUCCESS 或 FAIL。",
546
559
  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"] },
547
560
  },
548
561
  // ── Image ──
@@ -557,10 +570,11 @@ const TOOLS = [
557
570
  },
558
571
  {
559
572
  name: "get_upload_token",
560
- description: "获取 OSS 图片上传凭证。返回 accessid/host/policy/signature 等字段,用于 multipart/form-data POST 上传图片到阿里云 OSS。上传成功后获取 image_id,再用 save_note 创建图片笔记。⚠️ mime_type 必须与实际文件格式一致,否则 OSS 签名失败。",
573
+ description: recoveryDescription + "获取 OSS 图片上传凭证。返回 accessid/host/policy/signature 等字段,用于 multipart/form-data POST 上传图片到阿里云 OSS。上传成功后获取 image_id,再用 save_note 创建图片笔记。⚠️ mime_type 必须与实际文件格式一致,否则 OSS 签名失败。",
561
574
  inputSchema: {
562
575
  type: "object",
563
576
  properties: {
577
+ operation_id: operationIDSchema,
564
578
  mime_type: {
565
579
  type: "string",
566
580
  enum: ["jpg", "png", "gif", "webp", "jpeg"],
@@ -577,10 +591,11 @@ const TOOLS = [
577
591
  },
578
592
  {
579
593
  name: "upload_image",
580
- description: "上传图片到 OSS。返回 image_url(用于创建图片笔记的 image_urls 参数)。",
594
+ description: recoveryDescription + "上传图片到 OSS。返回 image_url(用于创建图片笔记的 image_urls 参数)。",
581
595
  inputSchema: {
582
596
  type: "object",
583
597
  properties: {
598
+ operation_id: operationIDSchema,
584
599
  image_path: {
585
600
  type: "string",
586
601
  description: "本地图片文件路径。出于安全考虑仅接受相对路径:不允许绝对路径(以 / 或 \\ 开头)、不允许包含 \"..\" 的路径段、不允许 null byte。默认限制在当前工作目录内;若设置了环境变量 GETNOTE_MCP_ALLOWED_ROOT,则限制在指定目录内。符号链接解析后也不得离开该目录。",
@@ -994,7 +1009,9 @@ async function handleTool(name, input, client) {
994
1009
  case "list_sprouts": return client.listSprouts(zod_1.z.string().regex(/^\d{4}-\d{2}$/).parse(input.month), zod_1.z.string().optional().parse(input.since_id), zod_1.z.number().int().min(1).max(20).optional().parse(input.limit));
995
1010
  case "get_sprout": return client.getSprout(zod_1.z.string().min(1).parse(input.id));
996
1011
  case "get_knowledge_file_capabilities": return client.getKnowledgeFileCapabilities();
997
- case "get_knowledge_file_upload_token": return client.getKnowledgeFileUploadToken(zod_1.z.string().min(1).parse(input.mime_type));
1012
+ case "get_upload_operation": return client.getUploadOperation(operationIDInput.parse(input.operation_id));
1013
+ case "get_knowledge_file_upload_operation": return client.getKnowledgeFileUploadOperation(operationIDInput.parse(input.operation_id));
1014
+ case "get_knowledge_file_upload_token": return client.getKnowledgeFileUploadToken(zod_1.z.string().min(1).parse(input.mime_type), operationIDInput.optional().parse(input.operation_id));
998
1015
  case "upload_knowledge_file": return client.uploadKnowledgeFile(zod_1.z.object({ topic_id: zod_1.z.string().min(1), directory_id: zod_1.z.string().regex(/^\d+$/), file_name: zod_1.z.string().min(1), file_type: zod_1.z.string().min(1), md5: zod_1.z.string().regex(/^[a-fA-F0-9]{32}$/), url: zod_1.z.string().url() }).strict().parse(input));
999
1016
  case "get_upload_config": {
1000
1017
  return client.getUploadConfig();
@@ -1003,6 +1020,7 @@ async function handleTool(name, input, client) {
1003
1020
  return client.getUploadToken({
1004
1021
  mime_type: input.mime_type,
1005
1022
  count: input.count,
1023
+ operation_id: operationIDInput.optional().parse(input.operation_id),
1006
1024
  });
1007
1025
  }
1008
1026
  case "upload_image": {
@@ -1022,11 +1040,13 @@ async function handleTool(name, input, client) {
1022
1040
  }
1023
1041
  // mime_type 传扩展名格式(如 png、jpg)
1024
1042
  const mimeType = input.mime_type || "png";
1025
- const result = await client.uploadImage(imageData, mimeType);
1043
+ const result = await client.uploadImage(imageData, mimeType, operationIDInput.optional().parse(input.operation_id));
1026
1044
  return {
1027
1045
  success: true,
1028
1046
  image_url: result.access_url, // 用于创建图片笔记
1029
- image_id: result.image_id // OSS 回调返回的 ID
1047
+ image_id: result.image_id, // OSS 回调返回的 ID
1048
+ operation_id: result.operation_id,
1049
+ resume_until: result.resume_until
1030
1050
  };
1031
1051
  }
1032
1052
  // ── Knowledge / Bloggers ──
@@ -1135,11 +1155,15 @@ async function main() {
1135
1155
  const input = (args ?? {});
1136
1156
  try {
1137
1157
  const result = await handleTool(name, input, client.withSignal(extra.signal));
1158
+ const batch = result;
1159
+ const rejected = (name === "batch_add_notes_to_topic" || name === "remove_note_from_topic")
1160
+ && Array.isArray(batch?.failed_note_ids) && batch.failed_note_ids.length > 0;
1138
1161
  return {
1162
+ ...(rejected ? { isError: true } : {}),
1139
1163
  content: [
1140
1164
  {
1141
1165
  type: "text",
1142
- text: JSON.stringify(result, null, 2),
1166
+ text: JSON.stringify(rejected ? { ...result, error: true, reason: "knowledge_notes_rejected", retryable: false, message: "Some notes were rejected; inspect failed_note_ids and the actual success count. Do not retry the entire batch." } : result, null, 2),
1143
1167
  },
1144
1168
  ],
1145
1169
  };
@@ -1158,6 +1182,11 @@ async function main() {
1158
1182
  expected_type: err.expectedType,
1159
1183
  supported_values: err.supportedValues,
1160
1184
  retry_after_seconds: err.retryAfterSeconds,
1185
+ rate_limit_detail: err.rateLimitDetail,
1186
+ operation_id: err.operationId,
1187
+ upload_kind: err.uploadKind,
1188
+ recovery_advice: err.recoveryAdvice,
1189
+ query_tool: err.queryTool,
1161
1190
  };
1162
1191
  if (err.code === 10201) {
1163
1192
  errPayload.membership_url = membership_js_1.OPENAPI_MEMBERSHIP_PURCHASE_URL;
@@ -5,7 +5,9 @@ export interface ReadFailure {
5
5
  retryable: boolean;
6
6
  retryAfterSeconds?: number;
7
7
  waitProvided?: boolean;
8
+ rateLimitDetail?: unknown;
8
9
  }
9
- export declare function readRetryDelay(method: string, path: string, error: ReadFailure, attempt: number, waited: number): number | undefined;
10
+ export declare function operationBucket(method: string, path: string): string;
11
+ export declare function readRetryDelay(method: string, path: string, error: ReadFailure, attempt: number, waited: number, idempotencyKey?: string): number | undefined;
10
12
  export declare function waitForReadRetry(delay: number, signal?: AbortSignal): Promise<void>;
11
13
  //# sourceMappingURL=read-retry.d.ts.map
@@ -1 +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"}
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,CAAC;IAAA,eAAe,CAAC,EAAC,OAAO,CAAA;CAAC;AAetK,wBAAgB,eAAe,CAAC,MAAM,EAAC,MAAM,EAAC,IAAI,EAAC,MAAM,GAAE,MAAM,CAIhE;AACD,wBAAgB,cAAc,CAAC,MAAM,EAAC,MAAM,EAAC,IAAI,EAAC,MAAM,EAAC,KAAK,EAAC,WAAW,EAAC,OAAO,EAAC,MAAM,EAAC,MAAM,EAAC,MAAM,EAAC,cAAc,CAAC,EAAC,MAAM,GAAE,MAAM,GAAC,SAAS,CA0B/I;AACD,wBAAsB,gBAAgB,CAAC,KAAK,EAAC,MAAM,EAAC,MAAM,CAAC,EAAC,WAAW,GAAE,OAAO,CAAC,IAAI,CAAC,CAOrF"}
@@ -1,17 +1,56 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.operationBucket = operationBucket;
3
4
  exports.readRetryDelay = readRetryDelay;
4
5
  exports.waitForReadRetry = waitForReadRetry;
5
6
  const getPaths = new Set([
6
7
  "/resource/note/list", "/resource/note/detail", "/resource/note/marks", "/resource/note/sprouts", "/resource/note/sprout",
7
8
  "/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/image/config", "/resource/image/upload_operation", "/resource/knowledge/file/upload_operation", "/resource/knowledge/file/capabilities", "/resource/knowledge/bloggers", "/resource/knowledge/blogger/contents", "/resource/knowledge/blogger/content/detail",
9
10
  "/resource/knowledge/lives", "/resource/knowledge/live/detail", "/resource/rate-limit/quota"
10
11
  ]);
11
12
  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)
13
+ const writePaths = new Set([
14
+ '/resource/note/save', '/resource/note/delete', '/resource/note/update', '/resource/note/task/progress',
15
+ '/resource/note/tags/add', '/resource/note/tags/delete', '/resource/note/sharing',
16
+ '/resource/knowledge/create', '/resource/knowledge/note/batch-add', '/resource/knowledge/note/remove',
17
+ '/resource/knowledge/directory/create', '/resource/knowledge/directory/update', '/resource/knowledge/directory/delete',
18
+ '/resource/knowledge/blogger/follow', '/resource/knowledge/live/follow', '/resource/knowledge/file/upload'
19
+ ]);
20
+ function operationBucket(method, path) {
21
+ if (path.endsWith('/upload_token'))
22
+ return 'upload_credential';
23
+ if (path === '/resource/note/save')
24
+ return 'write_note';
25
+ return method === 'GET' || postPaths.has(path) ? 'read' : 'write';
26
+ }
27
+ function readRetryDelay(method, path, error, attempt, waited, idempotencyKey) {
28
+ if (attempt >= 2 || waited >= 5000 || error.httpStatus !== 429 || error.retryable !== true)
14
29
  return;
30
+ if (error.rateLimitDetail !== undefined) {
31
+ const d = error.rateLimitDetail;
32
+ if (!d || typeof d !== 'object' || Array.isArray(d) || d.dimension !== 'qps' || d.request_execution !== 'not_started' || d.retry_action !== 'retry_same_operation' || d.retryable !== true)
33
+ return;
34
+ const knownRead = method === 'GET' && getPaths.has(path) || method === 'POST' && postPaths.has(path);
35
+ const knownWrite = method === 'POST' && writePaths.has(path);
36
+ const credential = method === 'GET' && ['/resource/image/upload_token', '/resource/knowledge/file/upload_token'].includes(path) && !!idempotencyKey;
37
+ if (!knownRead && !knownWrite && !credential)
38
+ return;
39
+ const waits = [];
40
+ for (const [key, scale] of [['retry_after_ms', 1], ['retry_after_seconds', 1000]]) {
41
+ if (d[key] !== undefined) {
42
+ if (typeof d[key] !== 'number' || !Number.isSafeInteger(d[key]) || d[key] < 0)
43
+ return;
44
+ waits.push(d[key] * scale);
45
+ }
46
+ }
47
+ if (error.waitProvided && error.retryAfterSeconds === undefined)
48
+ return;
49
+ if (error.retryAfterSeconds !== undefined)
50
+ waits.push(error.retryAfterSeconds * 1000);
51
+ const delay = (waits.length ? Math.max(...waits) : 200 * 2 ** attempt) + 1 + Math.floor(Math.random() * 50);
52
+ return delay <= 5000 - waited ? delay : undefined;
53
+ }
15
54
  const qpsLimit = error.code === 10202 && ["qps_exceeded", "qps_global_exceeded", "qps_bucket_exceeded"].includes(error.reason);
16
55
  if (!qpsLimit && !(error.code === 10005 && error.reason === "rate_limited"))
17
56
  return;
@@ -0,0 +1,24 @@
1
+ export type UploadKind = 'image' | 'file';
2
+ export declare const uploadRoutes: {
3
+ image: string;
4
+ file: string;
5
+ };
6
+ export interface UploadRuntime {
7
+ governance_enabled?: boolean;
8
+ operation_replay?: boolean;
9
+ idempotency_header?: string;
10
+ operation_status_endpoint?: string;
11
+ [key: string]: unknown;
12
+ }
13
+ export interface UploadOperation {
14
+ operation_id: string;
15
+ upload_id?: string;
16
+ state: string;
17
+ resume_until: string;
18
+ credential?: Record<string, unknown>;
19
+ [key: string]: unknown;
20
+ }
21
+ export declare function validateOperationID(value: string): string;
22
+ export declare function supportsRecovery(runtime: UploadRuntime | undefined, kind: UploadKind): boolean;
23
+ export declare function newOperationID(): string;
24
+ //# sourceMappingURL=upload-operation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload-operation.d.ts","sourceRoot":"","sources":["../src/upload-operation.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,UAAU,GAAC,OAAO,GAAC,MAAM,CAAC;AACtC,eAAO,MAAM,YAAY;;;CAA0D,CAAC;AACpF,MAAM,WAAW,aAAa;IAC5B,kBAAkB,CAAC,EAAC,OAAO,CAAC;IAAA,gBAAgB,CAAC,EAAC,OAAO,CAAC;IAAA,kBAAkB,CAAC,EAAC,MAAM,CAAC;IAAA,yBAAyB,CAAC,EAAC,MAAM,CAAC;IACnH,CAAC,GAAG,EAAC,MAAM,GAAE,OAAO,CAAC;CACtB;AACD,MAAM,WAAW,eAAe;IAC9B,YAAY,EAAC,MAAM,CAAC;IAAA,SAAS,CAAC,EAAC,MAAM,CAAC;IAAA,KAAK,EAAC,MAAM,CAAC;IAAA,YAAY,EAAC,MAAM,CAAC;IAAA,UAAU,CAAC,EAAC,MAAM,CAAC,MAAM,EAAC,OAAO,CAAC,CAAC;IAC1G,CAAC,GAAG,EAAC,MAAM,GAAE,OAAO,CAAC;CACtB;AACD,wBAAgB,mBAAmB,CAAC,KAAK,EAAC,MAAM,GAAE,MAAM,CAGvD;AACD,wBAAgB,gBAAgB,CAAC,OAAO,EAAC,aAAa,GAAC,SAAS,EAAC,IAAI,EAAC,UAAU,GAAE,OAAO,CAExF;AACD,wBAAgB,cAAc,IAAG,MAAM,CAAsB"}
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.uploadRoutes = void 0;
4
+ exports.validateOperationID = validateOperationID;
5
+ exports.supportsRecovery = supportsRecovery;
6
+ exports.newOperationID = newOperationID;
7
+ const node_crypto_1 = require("node:crypto");
8
+ exports.uploadRoutes = { image: '/resource/image', file: '/resource/knowledge/file' };
9
+ function validateOperationID(value) {
10
+ if (typeof value !== 'string' || !(/^[A-Za-z0-9._:-]{1,128}$/).test(value))
11
+ throw new Error('operation_id must match ^[A-Za-z0-9._:-]{1,128}$');
12
+ return value;
13
+ }
14
+ function supportsRecovery(runtime, kind) {
15
+ return runtime?.governance_enabled === true && runtime?.operation_replay === true && runtime.idempotency_header === 'Idempotency-Key' && runtime.operation_status_endpoint === '/open/api/v1' + exports.uploadRoutes[kind] + '/upload_operation';
16
+ }
17
+ function newOperationID() { return (0, node_crypto_1.randomUUID)(); }
18
+ //# sourceMappingURL=upload-operation.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getnote/mcp",
3
- "version": "1.10.1",
3
+ "version": "1.11.1",
4
4
  "description": "MCP server for 得到大脑(Get笔记) — manage notes and knowledge bases from AI assistants",
5
5
  "main": "dist/index.js",
6
6
  "bin": {