@hiai-gg/docsmint 2.1.5 → 2.1.9

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 CHANGED
@@ -61,7 +61,7 @@ management belongs to the signed-in browser session.
61
61
 
62
62
  **Self-hosted alternative:** run [DocsMint with Docker](#quickstart), create an API
63
63
  key in its browser UI, and configure `HIAI_DOCS_URL` and `HIAI_DOCS_API_KEY` for
64
- `npx --yes --package @hiai-gg/docsmint docsmint-mcp`. Install Bun 1.4.4 or
64
+ `npx --yes --package https://github.com/HiAi-gg/docsmint/releases/download/v2.1.9/hiai-gg-docsmint-2.1.9.tgz docsmint-mcp`. Install Bun 1.4.4 or
65
65
  later to execute the published binary. The npm package is a stdio bridge to
66
66
  your own API; it does not install the DocsMint application or Cloud OAuth server.
67
67
  See the [MCP guide](https://github.com/HiAi-gg/docsmint/blob/main/packages/mcp-server/README.md)
@@ -88,7 +88,7 @@ is a separate listing.
88
88
 
89
89
  REST and HTTP MCP responses include a server-issued request ID in the
90
90
  X-Request-ID header. Include that ID when reporting a failed request.
91
- See the [2.1.5 release notes](docs/release/v2.1.5-notes.md).
91
+ See the [2.1.9 release notes](docs/release/v2.1.9-notes.md).
92
92
 
93
93
  ## Document version patch 2.1.4
94
94
 
@@ -291,7 +291,7 @@ Run the published stdio bridge against your own DocsMint API:
291
291
  "mcpServers": {
292
292
  "docsmint": {
293
293
  "command": "npx",
294
- "args": ["--yes", "--package", "@hiai-gg/docsmint", "docsmint-mcp"],
294
+ "args": ["--yes", "--package", "https://github.com/HiAi-gg/docsmint/releases/download/v2.1.9/hiai-gg-docsmint-2.1.9.tgz", "docsmint-mcp"],
295
295
  "env": {
296
296
  "HIAI_DOCS_URL": "http://localhost:50700",
297
297
  "HIAI_DOCS_API_KEY": "your-global-or-category-key"
@@ -308,7 +308,7 @@ checkout, all tools, prompts, resources, permissions, and REST mappings.
308
308
 
309
309
  ### Self-hosted HTTP
310
310
 
311
- The same 22-tool contract is also available at `/mcp` on your installation's
311
+ The same 24-tool contract is also available at `/mcp` on your installation's
312
312
  **public web origin**. With the default Compose ports, that is
313
313
  `http://localhost:50701/mcp`; with Caddy, use your normal application domain,
314
314
  such as `https://docs.example.com/mcp`. The web server streams requests to the
@@ -44105,6 +44105,7 @@ __export(exports_schema, {
44105
44105
  documentVisibilityEnum: () => documentVisibilityEnum,
44106
44106
  documents: () => documents,
44107
44107
  embeddingStatusEnum: () => embeddingStatusEnum,
44108
+ folderCreateOperations: () => folderCreateOperations,
44108
44109
  folderRelations: () => folderRelations,
44109
44110
  folders: () => folders,
44110
44111
  guestAccess: () => guestAccess,
@@ -44130,7 +44131,7 @@ __export(exports_schema, {
44130
44131
  versionRelations: () => versionRelations,
44131
44132
  versions: () => versions
44132
44133
  });
44133
- var vector4, tsvector, documentVisibilityEnum, shareRoleEnum, shareAccessModeEnum, shareGrantStatusEnum, embeddingStatusEnum, pipelineStageEnum, pipelineStatusEnum, lifecycleOperationKindEnum, lifecycleOperationStatusEnum, users, sessions, accounts, verifications, folders, folderRelations, documents, documentRelations, documentPipelineRuns, documentPipelineBatches, metadataReembedOutbox, documentKnowledgeSummaries, tags, tagRelations, categories, categoryRelations, documentTags, documentTagRelations, shareLinks, shareLinkRelations, guestAccess, guestAccessRelations, attachments, pendingAttachmentUploads, attachmentStorageCleanupOutbox, pendingAttachmentCleanupAuthorizations, attachmentRelations, versions, documentEmbeddings, documentEmbeddingRelations, apiKeys, apiKeyRelations, auditLog, lifecycleOperations, documentCreateOperations, versionRelations;
44134
+ var vector4, tsvector, documentVisibilityEnum, shareRoleEnum, shareAccessModeEnum, shareGrantStatusEnum, embeddingStatusEnum, pipelineStageEnum, pipelineStatusEnum, lifecycleOperationKindEnum, lifecycleOperationStatusEnum, users, sessions, accounts, verifications, folders, folderRelations, documents, documentRelations, documentPipelineRuns, documentPipelineBatches, metadataReembedOutbox, documentKnowledgeSummaries, tags, tagRelations, categories, categoryRelations, documentTags, documentTagRelations, shareLinks, shareLinkRelations, guestAccess, guestAccessRelations, attachments, pendingAttachmentUploads, attachmentStorageCleanupOutbox, pendingAttachmentCleanupAuthorizations, attachmentRelations, versions, documentEmbeddings, documentEmbeddingRelations, apiKeys, apiKeyRelations, auditLog, lifecycleOperations, documentCreateOperations, folderCreateOperations, versionRelations;
44134
44135
  var init_schema2 = __esm(() => {
44135
44136
  init_pg_core();
44136
44137
  init_drizzle_orm();
@@ -44755,6 +44756,18 @@ var init_schema2 = __esm(() => {
44755
44756
  uniqueIndex("document_create_operations_workspace_actor_key_idx").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
44756
44757
  uniqueIndex("document_create_operations_document_idx").on(table.documentId)
44757
44758
  ]);
44759
+ folderCreateOperations = pgTable("folder_create_operations", {
44760
+ id: uuid("id").primaryKey().defaultRandom(),
44761
+ workspaceId: text("workspace_id").notNull(),
44762
+ actorUserId: uuid("actor_user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
44763
+ idempotencyKey: text("idempotency_key").notNull(),
44764
+ folderId: uuid("folder_id").notNull(),
44765
+ requestFingerprint: text("request_fingerprint").notNull(),
44766
+ createdAt: timestamp("created_at").defaultNow().notNull()
44767
+ }, (table) => [
44768
+ uniqueIndex("folder_create_operations_workspace_actor_key_unique").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
44769
+ uniqueIndex("folder_create_operations_folder_idx").on(table.folderId)
44770
+ ]);
44758
44771
  versionRelations = relations(versions, ({ one }) => ({
44759
44772
  document: one(documents, {
44760
44773
  fields: [versions.documentId],
@@ -50475,6 +50488,9 @@ function ipv42(params) {
50475
50488
  function ipv62(params) {
50476
50489
  return _ipv6(ZodIPv6, params);
50477
50490
  }
50491
+ function base642(params) {
50492
+ return _base64(ZodBase64, params);
50493
+ }
50478
50494
  function number2(params) {
50479
50495
  return _number(ZodNumber, params);
50480
50496
  }
@@ -52839,10 +52855,10 @@ function base64Decode(data, alphabet) {
52839
52855
  }
52840
52856
  return Uint8Array.from(result);
52841
52857
  }
52842
- var base642, base64Url;
52858
+ var base643, base64Url;
52843
52859
  var init_base64 = __esm(() => {
52844
52860
  init_bytes();
52845
- base642 = {
52861
+ base643 = {
52846
52862
  encode(data, options = {}) {
52847
52863
  const alphabet = getAlphabet(false);
52848
52864
  return base64Encode(toUint8Array3(data), alphabet, options.padding ?? true);
@@ -165937,7 +165953,7 @@ var createHMAC = (algorithm = "SHA-256", encoding = "none") => {
165937
165953
  if (encoding === "hex")
165938
165954
  return hex.encode(signature);
165939
165955
  if (encoding === "base64")
165940
- return base642.encode(signature);
165956
+ return base643.encode(signature);
165941
165957
  if (encoding === "base64url" || encoding === "base64urlnopad")
165942
165958
  return base64Url.encode(signature, { padding: encoding !== "base64urlnopad" });
165943
165959
  return signature;
@@ -165948,7 +165964,7 @@ var createHMAC = (algorithm = "SHA-256", encoding = "none") => {
165948
165964
  if (encoding === "hex")
165949
165965
  signature = typeof signature === "string" ? hex.toBytes(signature) : signature;
165950
165966
  if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad")
165951
- signature = await base642.decode(signature);
165967
+ signature = await base643.decode(signature);
165952
165968
  return getWebcryptoSubtle().verify("HMAC", hmacKey, toBufferSource(signature), toBufferSource(data));
165953
165969
  }
165954
165970
  };
@@ -166674,7 +166690,7 @@ function createHash4(algorithm, encoding) {
166674
166690
  if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") {
166675
166691
  if (encoding.includes("url"))
166676
166692
  return base64Url.encode(hashBuffer, { padding: encoding !== "base64urlnopad" });
166677
- return base642.encode(hashBuffer);
166693
+ return base643.encode(hashBuffer);
166678
166694
  }
166679
166695
  return hashBuffer;
166680
166696
  } };
@@ -169865,7 +169881,7 @@ function formUrlEncode(value) {
169865
169881
  }
169866
169882
  function encodeBasicCredentials(clientId, clientSecret) {
169867
169883
  const payload = `${formUrlEncode(clientId)}:${formUrlEncode(clientSecret)}`;
169868
- return `Basic ${base642.encode(payload)}`;
169884
+ return `Basic ${base643.encode(payload)}`;
169869
169885
  }
169870
169886
 
169871
169887
  // ../../node_modules/.bun/@better-auth+core@1.7.15+1bcdd7fa41f3b4db/node_modules/@better-auth/core/dist/oauth2/client-assertion.mjs
@@ -173048,7 +173064,7 @@ var microsoft = (options) => {
173048
173064
  return;
173049
173065
  try {
173050
173066
  const pictureBuffer = await context.response.clone().arrayBuffer();
173051
- const pictureBase64 = base642.encode(pictureBuffer);
173067
+ const pictureBase64 = base643.encode(pictureBuffer);
173052
173068
  user.picture = `data:image/jpeg;base64, ${pictureBase64}`;
173053
173069
  } catch (e) {
173054
173070
  logger2.error(e && typeof e === "object" && "name" in e ? e.name : "", e);
@@ -178828,7 +178844,7 @@ function detectEnvironment() {
178828
178844
  }
178829
178845
  async function hashToBase64(data) {
178830
178846
  const buffer = await createHash4("SHA-256").digest(data);
178831
- return base642.encode(buffer);
178847
+ return base643.encode(buffer);
178832
178848
  }
178833
178849
  var generateId2 = (size) => {
178834
178850
  return createRandomStringGenerator("a-z", "A-Z", "0-9")(size || 32);
@@ -213830,6 +213846,8 @@ var listQuerySchema2 = documentListQuerySchema;
213830
213846
  var cursorListQuerySchema = object({
213831
213847
  ...documentListQueryFields,
213832
213848
  cursor: string2().min(1).optional(),
213849
+ view: _enum(["catalog"]).optional(),
213850
+ includeTotal: _enum(["true", "false"]).optional(),
213833
213851
  limit: exports_coerce.number().int().min(1).max(100).default(50),
213834
213852
  sortBy: _enum([
213835
213853
  "title",
@@ -214160,28 +214178,49 @@ var documentRoutes = new Elysia({ prefix: "/api" }).get("/documents", async ({ q
214160
214178
  }
214161
214179
  }
214162
214180
  try {
214163
- const [countResult, rows] = await withTenant(ctx, (tx) => Promise.all([
214164
- tx.select({ total: count() }).from(documents).where(and(...filteredConditions)),
214165
- tx.select({
214181
+ const includeTotal = parsed.data.includeTotal !== "false";
214182
+ const joinedSort = sortBy === "category" || sortBy === "folder";
214183
+ const [countResult, rows] = await withTenant(ctx, (tx) => {
214184
+ const projection = {
214166
214185
  id: documents.id,
214167
214186
  title: documents.title,
214168
214187
  content: sql`LEFT(${documents.content}, 200)`.as("content"),
214169
214188
  folderId: documents.folderId,
214170
- folderName: folders.name,
214171
214189
  categoryId: documents.categoryId,
214172
- effectiveCategoryId: effectiveDocumentCategoryValue(documents.categoryId, documents.folderId, ctx).as("effective_category_id"),
214173
- categoryName: categories.name,
214190
+ effectiveCategoryId: (effectiveCategoryId ? sql`${effectiveCategoryId}::uuid` : effectiveDocumentCategoryValue(documents.categoryId, documents.folderId, ctx)).as("effective_category_id"),
214174
214191
  createdAt: documents.createdAt,
214175
214192
  updatedAt: documents.updatedAt
214176
- }).from(documents).leftJoin(folders, eq(folders.id, documents.folderId)).leftJoin(categories, eq(categories.id, documents.categoryId)).where(and(...conditions)).orderBy(sortOrder === "asc" ? sql`${sortValue} asc nulls last` : sql`${sortValue} desc nulls last`, sortOrder === "asc" ? asc(documents.id) : desc(documents.id)).limit(limit + 1)
214177
- ]));
214193
+ };
214194
+ const order = [
214195
+ sortOrder === "asc" ? sql`${sortValue} asc nulls last` : sql`${sortValue} desc nulls last`,
214196
+ sortOrder === "asc" ? asc(documents.id) : desc(documents.id)
214197
+ ];
214198
+ const selected = tx.select(projection).from(documents).where(and(...conditions)).orderBy(...order).limit(limit + 1);
214199
+ const pageQuery = joinedSort ? tx.select({
214200
+ ...projection,
214201
+ folderName: folders.name,
214202
+ categoryName: categories.name
214203
+ }).from(documents).leftJoin(folders, eq(folders.id, documents.folderId)).leftJoin(categories, eq(categories.id, documents.categoryId)).where(and(...conditions)).orderBy(...order).limit(limit + 1) : selected;
214204
+ return Promise.all([
214205
+ includeTotal ? tx.select({ total: count() }).from(documents).where(and(...filteredConditions)) : Promise.resolve([]),
214206
+ pageQuery
214207
+ ]);
214208
+ });
214178
214209
  const hasMore = rows.length > limit;
214179
214210
  const page = rows.slice(0, limit);
214180
214211
  const last = page.at(-1);
214181
- const lastValue = last ? sortBy === "title" ? last.title.toLocaleLowerCase() : sortBy === "category" ? last.categoryName?.toLocaleLowerCase() ?? null : sortBy === "folder" ? last.folderName?.toLocaleLowerCase() ?? null : new Date(sortBy === "createdAt" ? last.createdAt : last.updatedAt).toISOString() : null;
214212
+ const lastValue = last ? sortBy === "title" ? last.title.toLocaleLowerCase() : sortBy === "category" ? ("categoryName" in last ? last.categoryName : null)?.toLocaleLowerCase() ?? null : sortBy === "folder" ? ("folderName" in last ? last.folderName : null)?.toLocaleLowerCase() ?? null : new Date(sortBy === "createdAt" ? last.createdAt : last.updatedAt).toISOString() : null;
214213
+ const compact = parsed.data.view === "catalog";
214214
+ const items = (await withDocumentLocationNames(ctx, compact ? page : await withTags(ctx, page))).map((row) => withDocumentPreview(row, ctx.workspaceId, config3.PUBLIC_APP_URL));
214182
214215
  return {
214183
- total: countResult[0]?.total ?? 0,
214184
- items: (await withDocumentLocationNames(ctx, await withTags(ctx, page))).map((row) => withDocumentPreview(row, ctx.workspaceId, config3.PUBLIC_APP_URL)),
214216
+ ...includeTotal ? { total: countResult[0]?.total ?? 0 } : {},
214217
+ items: compact ? items.map(({ id, title, preview, folderId, folderName }) => ({
214218
+ id,
214219
+ title,
214220
+ preview,
214221
+ folderId,
214222
+ folderName
214223
+ })) : items,
214185
214224
  nextCursor: hasMore && last ? encodeDocumentCursor({
214186
214225
  v: 2,
214187
214226
  sortBy,
@@ -216015,6 +216054,7 @@ var documentRoutes = new Elysia({ prefix: "/api" }).get("/documents", async ({ q
216015
216054
  // ../../backend/src/api/routes/folders.ts
216016
216055
  init_schema2();
216017
216056
  init_drizzle_orm();
216057
+ import { createHash as createHash8 } from "crypto";
216018
216058
  init_zod();
216019
216059
 
216020
216060
  // ../../backend/src/lib/folder-name.ts
@@ -216280,6 +216320,12 @@ var folderRoutes = new Elysia({ prefix: "/api/folders" }).get("/:id", async ({ p
216280
216320
  set.status = 400;
216281
216321
  return { error: "Invalid input", details: parsed.error.flatten() };
216282
216322
  }
216323
+ const idempotencyKey = documentCreateIdempotencyKey(request);
216324
+ if (idempotencyKey === "invalid") {
216325
+ set.status = 400;
216326
+ return { error: "Invalid Idempotency-Key" };
216327
+ }
216328
+ const workspaceIdentity = documentCreateWorkspaceIdentity(userId, ctx.workspaceId);
216283
216329
  try {
216284
216330
  const created = await withTenant(ctx, async (tx) => {
216285
216331
  await acquireTenantTopologyLock(tx, ctx);
@@ -216301,6 +216347,23 @@ var folderRoutes = new Elysia({ prefix: "/api/folders" }).get("/:id", async ({ p
216301
216347
  return { categoryNotFound: true };
216302
216348
  }
216303
216349
  }
216350
+ const requestFingerprint = createHash8("sha256").update(JSON.stringify([parsed.data.name, parentId, categoryId])).digest("hex");
216351
+ if (idempotencyKey) {
216352
+ const [operation] = await tx.select().from(folderCreateOperations).where(and(eq(folderCreateOperations.workspaceId, workspaceIdentity), eq(folderCreateOperations.actorUserId, userId), eq(folderCreateOperations.idempotencyKey, idempotencyKey))).limit(1);
216353
+ if (operation) {
216354
+ if (operation.requestFingerprint !== requestFingerprint) {
216355
+ return { idempotencyConflict: true };
216356
+ }
216357
+ const [row] = await tx.select().from(folders).where(and(eq(folders.id, operation.folderId), tenantOwnerCondition(folders.ownerId, folders.workspaceId, ctx))).limit(1);
216358
+ if (!row)
216359
+ return { idempotencyConflict: true };
216360
+ const currentCategory = await resolveFolderEffectiveCategory(tx, ctx, row.id);
216361
+ if (!isAuthorizedCategory(access, currentCategory ?? null)) {
216362
+ return { forbidden: true };
216363
+ }
216364
+ return { row, replay: true };
216365
+ }
216366
+ }
216304
216367
  const scopeKey = parentId ? `${userId}:parent:${parentId}` : `${userId}:category:${categoryId ?? "none"}`;
216305
216368
  await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${scopeKey}, 0))`);
216306
216369
  const scopeConditions = [
@@ -216320,8 +216383,25 @@ var folderRoutes = new Elysia({ prefix: "/api/folders" }).get("/:id", async ({ p
216320
216383
  parentId,
216321
216384
  categoryId
216322
216385
  }).returning();
216386
+ if (!row)
216387
+ throw new Error("Folder insert returned no row");
216388
+ if (idempotencyKey) {
216389
+ await tx.insert(folderCreateOperations).values({
216390
+ workspaceId: workspaceIdentity,
216391
+ actorUserId: userId,
216392
+ idempotencyKey,
216393
+ folderId: row.id,
216394
+ requestFingerprint
216395
+ });
216396
+ }
216323
216397
  return { row };
216324
216398
  });
216399
+ if ("idempotencyConflict" in created) {
216400
+ set.status = 409;
216401
+ return {
216402
+ error: "Folder creation request conflicts with a previous operation"
216403
+ };
216404
+ }
216325
216405
  if ("notFound" in created) {
216326
216406
  set.status = 404;
216327
216407
  return { error: "Parent folder not found" };
@@ -216334,7 +216414,7 @@ var folderRoutes = new Elysia({ prefix: "/api/folders" }).get("/:id", async ({ p
216334
216414
  set.status = 404;
216335
216415
  return { error: "Category not found" };
216336
216416
  }
216337
- set.status = 201;
216417
+ set.status = "replay" in created ? 200 : 201;
216338
216418
  return created.row;
216339
216419
  } catch (err) {
216340
216420
  const purgeFence = translateAccountPurgeFencedError(err, set);
@@ -217240,6 +217320,12 @@ class DocsClient {
217240
217320
  }, context);
217241
217321
  }
217242
217322
  async listDocuments(options = {}, context) {
217323
+ return this.listDocumentCursor(options, context);
217324
+ }
217325
+ async listCatalogDocuments(options = {}, context) {
217326
+ return this.listDocumentCursor(options, context, "catalog");
217327
+ }
217328
+ async listDocumentCursor(options, context, view) {
217243
217329
  return this.request("GET", "/api/documents/cursor", {
217244
217330
  query: this.cleanQuery({
217245
217331
  categoryId: options.categoryId,
@@ -217254,6 +217340,8 @@ class DocsClient {
217254
217340
  updatedTo: options.updatedTo,
217255
217341
  cursor: options.cursor,
217256
217342
  limit: options.limit,
217343
+ view,
217344
+ includeTotal: options.includeTotal === undefined ? undefined : String(options.includeTotal),
217257
217345
  sortBy: options.sortBy,
217258
217346
  sortOrder: options.sortOrder
217259
217347
  })
@@ -217464,6 +217552,12 @@ class DocsClient {
217464
217552
  async listAttachments(documentId, context) {
217465
217553
  return this.request("GET", `/api/documents/${encodeURIComponent(documentId)}/attachments`, undefined, context);
217466
217554
  }
217555
+ async fetchAttachment(id, context) {
217556
+ const response = await this.fetchRaw("GET", `/api/attachments/${encodeURIComponent(id)}/raw`, {}, context);
217557
+ if (!response.ok)
217558
+ throw await this.toApiError(response);
217559
+ return response;
217560
+ }
217467
217561
  async deleteAttachment(id, context) {
217468
217562
  await this.request("DELETE", `/api/attachments/${encodeURIComponent(id)}`, undefined, context);
217469
217563
  }
@@ -234462,6 +234556,12 @@ class DocsClient2 {
234462
234556
  }, context);
234463
234557
  }
234464
234558
  async listDocuments(options = {}, context) {
234559
+ return this.listDocumentCursor(options, context);
234560
+ }
234561
+ async listCatalogDocuments(options = {}, context) {
234562
+ return this.listDocumentCursor(options, context, "catalog");
234563
+ }
234564
+ async listDocumentCursor(options, context, view) {
234465
234565
  return this.request("GET", "/api/documents/cursor", {
234466
234566
  query: this.cleanQuery({
234467
234567
  categoryId: options.categoryId,
@@ -234476,6 +234576,8 @@ class DocsClient2 {
234476
234576
  updatedTo: options.updatedTo,
234477
234577
  cursor: options.cursor,
234478
234578
  limit: options.limit,
234579
+ view,
234580
+ includeTotal: options.includeTotal === undefined ? undefined : String(options.includeTotal),
234479
234581
  sortBy: options.sortBy,
234480
234582
  sortOrder: options.sortOrder
234481
234583
  })
@@ -234686,6 +234788,12 @@ class DocsClient2 {
234686
234788
  async listAttachments(documentId, context) {
234687
234789
  return this.request("GET", `/api/documents/${encodeURIComponent(documentId)}/attachments`, undefined, context);
234688
234790
  }
234791
+ async fetchAttachment(id, context) {
234792
+ const response = await this.fetchRaw("GET", `/api/attachments/${encodeURIComponent(id)}/raw`, {}, context);
234793
+ if (!response.ok)
234794
+ throw await this.toApiError(response);
234795
+ return response;
234796
+ }
234689
234797
  async deleteAttachment(id, context) {
234690
234798
  await this.request("DELETE", `/api/attachments/${encodeURIComponent(id)}`, undefined, context);
234691
234799
  }
@@ -235184,6 +235292,13 @@ var operationOutputSchemas = {
235184
235292
  permanently_delete_document: deleteAcknowledgmentSchema
235185
235293
  };
235186
235294
  var variant = (operation, result) => object({ operation: literal(operation), result });
235295
+ var attachment = object({
235296
+ id: string2().uuid(),
235297
+ filename: string2(),
235298
+ mimeType: string2(),
235299
+ size: number2().int().nonnegative(),
235300
+ url: string2()
235301
+ });
235187
235302
  var singleToolOutputSchemas = {
235188
235303
  delete_document: operationOutputSchemas.delete_document,
235189
235304
  delete_folder: operationOutputSchemas.delete_folder,
@@ -235205,6 +235320,11 @@ var singleToolOutputSchemas = {
235205
235320
  variant("markdown", operationOutputSchemas.export_document),
235206
235321
  variant("versions", operationOutputSchemas.get_version_history)
235207
235322
  ]),
235323
+ upload_document_image: attachment,
235324
+ check_document_attachments: strictObject({
235325
+ items: array2(attachment),
235326
+ verifiedAttachmentId: string2().uuid().optional()
235327
+ }),
235208
235328
  save_document: union2([
235209
235329
  variant("create", operationOutputSchemas.create_document),
235210
235330
  variant("update", operationOutputSchemas.update_document)
@@ -235306,6 +235426,40 @@ function sanitizeMcpRequestContext(context) {
235306
235426
  function createMcpDocsClient(docsClient, requestContext) {
235307
235427
  const context = sanitizeMcpRequestContext(requestContext);
235308
235428
  return {
235429
+ uploadDocumentImage: async (id, filename, mimeType, bytes) => {
235430
+ const descriptor = { filename, contentType: mimeType, size: bytes.byteLength };
235431
+ const upload = await docsClient.presignAttachment(id, descriptor, context);
235432
+ const response = await fetch(upload.url, {
235433
+ method: "PUT",
235434
+ body: new Blob([Uint8Array.from(bytes)], { type: mimeType }),
235435
+ redirect: "error",
235436
+ signal: context?.signal
235437
+ }).catch(() => {
235438
+ throw new Error("Could not send image bytes to DocsMint storage.");
235439
+ });
235440
+ await response.body?.cancel();
235441
+ if (!response.ok)
235442
+ throw new Error(`DocsMint storage rejected the image (${response.status}).`);
235443
+ return docsClient.confirmAttachment(id, {
235444
+ ...descriptor,
235445
+ key: upload.key,
235446
+ uploadToken: upload.uploadToken,
235447
+ quotaReservationId: upload.quotaReservationId
235448
+ }, context);
235449
+ },
235450
+ listAttachments: (id) => docsClient.listAttachments(id, context),
235451
+ verifyAttachment: async (id) => {
235452
+ const response = await docsClient.fetchAttachment(id, context);
235453
+ const reader = response.body?.getReader();
235454
+ if (!reader)
235455
+ throw new Error("The attachment response has no body.");
235456
+ try {
235457
+ if (!(await reader.read()).value?.byteLength)
235458
+ throw new Error("The attachment is empty.");
235459
+ } finally {
235460
+ await reader.cancel();
235461
+ }
235462
+ },
235309
235463
  getFolder: (id) => docsClient.getFolder(id, context),
235310
235464
  createTag: (input) => docsClient.createTag(input, context),
235311
235465
  updateTag: (id, input) => docsClient.updateTag(id, input, context),
@@ -235564,6 +235718,18 @@ var content50 = string2().describe("Markdown document content; an empty string c
235564
235718
  var read2 = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
235565
235719
  var write2 = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };
235566
235720
  var destructive = { ...write2, destructiveHint: true };
235721
+ function matchesImageType(bytes, mimeType) {
235722
+ switch (mimeType) {
235723
+ case "image/png":
235724
+ return bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
235725
+ case "image/jpeg":
235726
+ return bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;
235727
+ case "image/webp":
235728
+ return bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP";
235729
+ default:
235730
+ return false;
235731
+ }
235732
+ }
235567
235733
  function required22(value, name) {
235568
235734
  if (!value)
235569
235735
  throw new Error(`The injected legacy MCP client does not support ${name}; use a public DocsClient.`);
@@ -235599,6 +235765,32 @@ function registerCompactCapabilities(server, client, wrap) {
235599
235765
  const { action: _action, id, ...data } = input;
235600
235766
  return { operation: "update", result: await client.updateDocument(id, data) };
235601
235767
  });
235768
+ const maxImageBytes = 2 * 1024 * 1024;
235769
+ register("upload_document_image", "Upload one PNG, JPEG or WebP image to an existing editable document. Send the file bytes as base64, up to 2 MiB before encoding. Insert the returned url as an image using save_document. If the result is lost, check attachments before uploading again.", strictObject({
235770
+ documentId: uuid22,
235771
+ filename: string2().min(1).max(255).regex(/^[^/\\\u0000-\u001f\u007f]+$/).describe("Image file name with extension and without path segments."),
235772
+ mimeType: _enum(["image/png", "image/jpeg", "image/webp"]).describe("MIME type of the source image."),
235773
+ contentBase64: base642().min(4).max(Math.ceil(maxImageBytes / 3) * 4).describe("Base64 file bytes without a data: prefix.")
235774
+ }), write2, async ({ documentId, filename, mimeType, contentBase64 }) => {
235775
+ const bytes = Buffer.from(contentBase64, "base64");
235776
+ if (!bytes.length || bytes.length > maxImageBytes)
235777
+ throw new Error("Image must be between 1 byte and 2 MiB.");
235778
+ if (!matchesImageType(bytes, mimeType))
235779
+ throw new Error("Image bytes do not match the declared MIME type.");
235780
+ return required22(client.uploadDocumentImage, "upload_document_image")(documentId, filename, mimeType, bytes);
235781
+ });
235782
+ register("check_document_attachments", "List attachments on a readable document. Supply attachmentId to verify that this attachment belongs to the document and that its stored bytes can be opened with the current access.", strictObject({
235783
+ documentId: uuid22,
235784
+ attachmentId: uuid22.optional()
235785
+ }), read2, async ({ documentId, attachmentId }) => {
235786
+ const { items } = await required22(client.listAttachments, "check_document_attachments")(documentId);
235787
+ if (!attachmentId)
235788
+ return { items };
235789
+ if (!items.some((item) => item.id === attachmentId))
235790
+ throw new Error("Attachment not found in this document.");
235791
+ await required22(client.verifyAttachment, "check_document_attachments")(attachmentId);
235792
+ return { items, verifiedAttachmentId: attachmentId };
235793
+ });
235602
235794
  register("delete_document", "Move one document to trash without purging content or versions. Use batch_documents(action=trash) for multiple explicit IDs. Requires write access and an explicit delete request; permanently_delete_document is a separate irreversible action.", strictObject({ id: uuid22 }), destructive, async ({ id }) => {
235603
235795
  await required22(client.deleteDocument, "delete_document")(id);
235604
235796
  return { id, deleted: true };
@@ -235875,7 +236067,7 @@ function registerDocsmintMcpCapabilities(server, client, workspaceRouting, decor
235875
236067
  registerPromptsAndResources(server, client);
235876
236068
  }
235877
236069
  function createDocsmintMcpServer(options = {}) {
235878
- const server = new DocsMintMcpServer({ name: "docsmint", version: "2.1.5" });
236070
+ const server = new DocsMintMcpServer({ name: "docsmint", version: "2.1.9" });
235879
236071
  const client = options.docsClient ? createMcpDocsClient(options.docsClient, options.requestContext) : options.client ?? createMcpDocsClient(createDefaultDocsClient(), options.requestContext);
235880
236072
  registerDocsmintMcpCapabilities(server, client, options.workspaceRouting, options.decorateResult);
235881
236073
  return server;
@@ -242469,7 +242661,7 @@ var swaggerConfig = {
242469
242661
  },
242470
242662
  info: {
242471
242663
  title: "DocsMint API",
242472
- version: "2.1.5",
242664
+ version: "2.1.9",
242473
242665
  description: "Self-hosted AI-native knowledge workspace and installable PWA with hybrid search, GraphRAG, REST, SDK, CLI, and MCP access for people and AI agents.",
242474
242666
  contact: { name: "HiAi-gg", url: "https://github.com/HiAi-gg/docsmint" },
242475
242667
  license: {
@@ -38,6 +38,7 @@ __export(exports_schema, {
38
38
  documentVisibilityEnum: () => documentVisibilityEnum,
39
39
  documents: () => documents,
40
40
  embeddingStatusEnum: () => embeddingStatusEnum,
41
+ folderCreateOperations: () => folderCreateOperations,
41
42
  folderRelations: () => folderRelations,
42
43
  folders: () => folders,
43
44
  guestAccess: () => guestAccess,
@@ -686,6 +687,18 @@ var documentCreateOperations = pgTable("document_create_operations", {
686
687
  uniqueIndex("document_create_operations_workspace_actor_key_idx").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
687
688
  uniqueIndex("document_create_operations_document_idx").on(table.documentId)
688
689
  ]);
690
+ var folderCreateOperations = pgTable("folder_create_operations", {
691
+ id: uuid("id").primaryKey().defaultRandom(),
692
+ workspaceId: text("workspace_id").notNull(),
693
+ actorUserId: uuid("actor_user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
694
+ idempotencyKey: text("idempotency_key").notNull(),
695
+ folderId: uuid("folder_id").notNull(),
696
+ requestFingerprint: text("request_fingerprint").notNull(),
697
+ createdAt: timestamp("created_at").defaultNow().notNull()
698
+ }, (table) => [
699
+ uniqueIndex("folder_create_operations_workspace_actor_key_unique").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
700
+ uniqueIndex("folder_create_operations_folder_idx").on(table.folderId)
701
+ ]);
689
702
  var versionRelations = relations(versions, ({ one }) => ({
690
703
  document: one(documents, {
691
704
  fields: [versions.documentId],
@@ -38,6 +38,7 @@ __export(exports_schema, {
38
38
  documentVisibilityEnum: () => documentVisibilityEnum,
39
39
  documents: () => documents,
40
40
  embeddingStatusEnum: () => embeddingStatusEnum,
41
+ folderCreateOperations: () => folderCreateOperations,
41
42
  folderRelations: () => folderRelations,
42
43
  folders: () => folders,
43
44
  guestAccess: () => guestAccess,
@@ -686,6 +687,18 @@ var documentCreateOperations = pgTable("document_create_operations", {
686
687
  uniqueIndex("document_create_operations_workspace_actor_key_idx").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
687
688
  uniqueIndex("document_create_operations_document_idx").on(table.documentId)
688
689
  ]);
690
+ var folderCreateOperations = pgTable("folder_create_operations", {
691
+ id: uuid("id").primaryKey().defaultRandom(),
692
+ workspaceId: text("workspace_id").notNull(),
693
+ actorUserId: uuid("actor_user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
694
+ idempotencyKey: text("idempotency_key").notNull(),
695
+ folderId: uuid("folder_id").notNull(),
696
+ requestFingerprint: text("request_fingerprint").notNull(),
697
+ createdAt: timestamp("created_at").defaultNow().notNull()
698
+ }, (table) => [
699
+ uniqueIndex("folder_create_operations_workspace_actor_key_unique").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
700
+ uniqueIndex("folder_create_operations_folder_idx").on(table.folderId)
701
+ ]);
689
702
  var versionRelations = relations(versions, ({ one }) => ({
690
703
  document: one(documents, {
691
704
  fields: [versions.documentId],
@@ -38,6 +38,7 @@ __export(exports_schema, {
38
38
  documentVisibilityEnum: () => documentVisibilityEnum,
39
39
  documents: () => documents,
40
40
  embeddingStatusEnum: () => embeddingStatusEnum,
41
+ folderCreateOperations: () => folderCreateOperations,
41
42
  folderRelations: () => folderRelations,
42
43
  folders: () => folders,
43
44
  guestAccess: () => guestAccess,
@@ -686,6 +687,18 @@ var documentCreateOperations = pgTable("document_create_operations", {
686
687
  uniqueIndex("document_create_operations_workspace_actor_key_idx").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
687
688
  uniqueIndex("document_create_operations_document_idx").on(table.documentId)
688
689
  ]);
690
+ var folderCreateOperations = pgTable("folder_create_operations", {
691
+ id: uuid("id").primaryKey().defaultRandom(),
692
+ workspaceId: text("workspace_id").notNull(),
693
+ actorUserId: uuid("actor_user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
694
+ idempotencyKey: text("idempotency_key").notNull(),
695
+ folderId: uuid("folder_id").notNull(),
696
+ requestFingerprint: text("request_fingerprint").notNull(),
697
+ createdAt: timestamp("created_at").defaultNow().notNull()
698
+ }, (table) => [
699
+ uniqueIndex("folder_create_operations_workspace_actor_key_unique").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
700
+ uniqueIndex("folder_create_operations_folder_idx").on(table.folderId)
701
+ ]);
689
702
  var versionRelations = relations(versions, ({ one }) => ({
690
703
  document: one(documents, {
691
704
  fields: [versions.documentId],
package/dist/client.d.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  * failures (502 / 503 / 504 / timeout / network reset) are retried
8
8
  * with exponential backoff up to `config.retries` attempts.
9
9
  */
10
- import type { DocsApiKeyCreated, DocsApiKeyListResponse, DocsAttachment, DocsAttachmentConfirmInput, DocsAttachmentListResponse, DocsAttachmentPresignInput, DocsAttachmentPresignResponse, DocsCategory, DocsCategoryListItem, DocsCategoryInput, DocsCategoryUpdate, DocsDocument, DocsDocumentCreateInput, DocsDocumentCursorPage, DocsDocumentIndexRefresh, DocsDocumentIndexStatus, DocsDocumentKnowledgeSummary, DocsDocumentListResponse, DocsDocumentPipeline, DocsPipelineWarningRetry, DocsDocumentUpdateInput, DocsFolder, DocsFolderCreateInput, DocsFolderUpdateInput, DocsGraphEntitiesResponse, DocsGraphRelatedResponse, DocsGraphSearchResponse, DocsHealthResponse, DocsRequestContext, DocsSearchOptions, DocsSearchResponse, DocsSearchSuggestItem, DocsSharedContent, DocsShareLink, DocsShareListResponse, DocsShareRole, DocsTag, DocsTrashResponse, DocsVersion, DocsVersionDiff } from "./types.js";
10
+ import type { DocsApiKeyCreated, DocsApiKeyListResponse, DocsAttachment, DocsAttachmentConfirmInput, DocsAttachmentListResponse, DocsAttachmentPresignInput, DocsAttachmentPresignResponse, DocsCategory, DocsCategoryListItem, DocsCategoryInput, DocsCategoryUpdate, DocsDocument, DocsDocumentCreateInput, DocsDocumentCursorPage, DocsCatalogCursorPage, DocsDocumentIndexRefresh, DocsDocumentIndexStatus, DocsDocumentKnowledgeSummary, DocsDocumentListResponse, DocsDocumentPipeline, DocsPipelineWarningRetry, DocsDocumentUpdateInput, DocsFolder, DocsFolderCreateInput, DocsFolderUpdateInput, DocsGraphEntitiesResponse, DocsGraphRelatedResponse, DocsGraphSearchResponse, DocsHealthResponse, DocsRequestContext, DocsSearchOptions, DocsSearchResponse, DocsSearchSuggestItem, DocsSharedContent, DocsShareLink, DocsShareListResponse, DocsShareRole, DocsTag, DocsTrashResponse, DocsVersion, DocsVersionDiff } from "./types.js";
11
11
  export interface DocsClientConfig {
12
12
  /** Explicit API prefix. Existing clients keep /api; no endpoint probing is performed. */
13
13
  apiPrefix?: "/api" | "/api/v1";
@@ -81,9 +81,12 @@ export declare class DocsClient {
81
81
  categoryId?: string;
82
82
  cursor?: string;
83
83
  limit?: number;
84
+ includeTotal?: boolean;
84
85
  sortBy?: import("./types").DocsDocumentSortField;
85
86
  sortOrder?: import("./types").DocsSortOrder;
86
87
  }, context?: DocsRequestContext): Promise<DocsDocumentCursorPage>;
88
+ listCatalogDocuments(options?: Parameters<DocsClient["listDocuments"]>[0], context?: DocsRequestContext): Promise<DocsCatalogCursorPage>;
89
+ private listDocumentCursor;
87
90
  duplicateDoc(id: string, context?: DocsRequestContext): Promise<DocsDocument>;
88
91
  getDocumentPipeline(id: string, context?: DocsRequestContext): Promise<DocsDocumentPipeline>;
89
92
  retryDocumentPipelineWarnings(id: string, context?: DocsRequestContext): Promise<DocsPipelineWarningRetry>;
@@ -203,6 +206,8 @@ export declare class DocsClient {
203
206
  presignAttachment(documentId: string, input: DocsAttachmentPresignInput, context?: DocsRequestContext): Promise<DocsAttachmentPresignResponse>;
204
207
  confirmAttachment(documentId: string, input: DocsAttachmentConfirmInput, context?: DocsRequestContext): Promise<DocsAttachment>;
205
208
  listAttachments(documentId: string, context?: DocsRequestContext): Promise<DocsAttachmentListResponse>;
209
+ /** Fetch an authorized attachment without exposing its storage URL. */
210
+ fetchAttachment(id: string, context?: DocsRequestContext): Promise<Response>;
206
211
  deleteAttachment(id: string, context?: DocsRequestContext): Promise<void>;
207
212
  listVersions(documentId: string, options?: {
208
213
  onlySnapshots?: boolean;
package/dist/client.js CHANGED
@@ -151,6 +151,12 @@ export class DocsClient {
151
151
  * bound by the server to the authenticated workspace and category scope.
152
152
  */
153
153
  async listDocuments(options = {}, context) {
154
+ return this.listDocumentCursor(options, context);
155
+ }
156
+ async listCatalogDocuments(options = {}, context) {
157
+ return this.listDocumentCursor(options, context, "catalog");
158
+ }
159
+ async listDocumentCursor(options, context, view) {
154
160
  return this.request("GET", "/api/documents/cursor", {
155
161
  query: this.cleanQuery({
156
162
  categoryId: options.categoryId,
@@ -165,6 +171,8 @@ export class DocsClient {
165
171
  updatedTo: options.updatedTo,
166
172
  cursor: options.cursor,
167
173
  limit: options.limit,
174
+ view,
175
+ includeTotal: options.includeTotal === undefined ? undefined : String(options.includeTotal),
168
176
  sortBy: options.sortBy,
169
177
  sortOrder: options.sortOrder,
170
178
  }),
@@ -409,6 +417,13 @@ export class DocsClient {
409
417
  async listAttachments(documentId, context) {
410
418
  return this.request("GET", `/api/documents/${encodeURIComponent(documentId)}/attachments`, undefined, context);
411
419
  }
420
+ /** Fetch an authorized attachment without exposing its storage URL. */
421
+ async fetchAttachment(id, context) {
422
+ const response = await this.fetchRaw("GET", `/api/attachments/${encodeURIComponent(id)}/raw`, {}, context);
423
+ if (!response.ok)
424
+ throw await this.toApiError(response);
425
+ return response;
426
+ }
412
427
  async deleteAttachment(id, context) {
413
428
  await this.request("DELETE", `/api/attachments/${encodeURIComponent(id)}`, undefined, context);
414
429
  }
@@ -37535,6 +37535,7 @@ __export(exports_schema, {
37535
37535
  documentVisibilityEnum: () => documentVisibilityEnum,
37536
37536
  documents: () => documents,
37537
37537
  embeddingStatusEnum: () => embeddingStatusEnum,
37538
+ folderCreateOperations: () => folderCreateOperations,
37538
37539
  folderRelations: () => folderRelations,
37539
37540
  folders: () => folders,
37540
37541
  guestAccess: () => guestAccess,
@@ -38195,6 +38196,18 @@ var documentCreateOperations = pgTable("document_create_operations", {
38195
38196
  uniqueIndex("document_create_operations_workspace_actor_key_idx").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
38196
38197
  uniqueIndex("document_create_operations_document_idx").on(table.documentId)
38197
38198
  ]);
38199
+ var folderCreateOperations = pgTable("folder_create_operations", {
38200
+ id: uuid("id").primaryKey().defaultRandom(),
38201
+ workspaceId: text("workspace_id").notNull(),
38202
+ actorUserId: uuid("actor_user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
38203
+ idempotencyKey: text("idempotency_key").notNull(),
38204
+ folderId: uuid("folder_id").notNull(),
38205
+ requestFingerprint: text("request_fingerprint").notNull(),
38206
+ createdAt: timestamp("created_at").defaultNow().notNull()
38207
+ }, (table) => [
38208
+ uniqueIndex("folder_create_operations_workspace_actor_key_unique").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
38209
+ uniqueIndex("folder_create_operations_folder_idx").on(table.folderId)
38210
+ ]);
38198
38211
  var versionRelations = relations(versions, ({ one }) => ({
38199
38212
  document: one(documents, {
38200
38213
  fields: [versions.documentId],
package/dist/mcp-cli.js CHANGED
@@ -305,6 +305,12 @@ class DocsClient {
305
305
  }, context);
306
306
  }
307
307
  async listDocuments(options = {}, context) {
308
+ return this.listDocumentCursor(options, context);
309
+ }
310
+ async listCatalogDocuments(options = {}, context) {
311
+ return this.listDocumentCursor(options, context, "catalog");
312
+ }
313
+ async listDocumentCursor(options, context, view) {
308
314
  return this.request("GET", "/api/documents/cursor", {
309
315
  query: this.cleanQuery({
310
316
  categoryId: options.categoryId,
@@ -319,6 +325,8 @@ class DocsClient {
319
325
  updatedTo: options.updatedTo,
320
326
  cursor: options.cursor,
321
327
  limit: options.limit,
328
+ view,
329
+ includeTotal: options.includeTotal === undefined ? undefined : String(options.includeTotal),
322
330
  sortBy: options.sortBy,
323
331
  sortOrder: options.sortOrder
324
332
  })
@@ -529,6 +537,12 @@ class DocsClient {
529
537
  async listAttachments(documentId, context) {
530
538
  return this.request("GET", `/api/documents/${encodeURIComponent(documentId)}/attachments`, undefined, context);
531
539
  }
540
+ async fetchAttachment(id, context) {
541
+ const response = await this.fetchRaw("GET", `/api/attachments/${encodeURIComponent(id)}/raw`, {}, context);
542
+ if (!response.ok)
543
+ throw await this.toApiError(response);
544
+ return response;
545
+ }
532
546
  async deleteAttachment(id, context) {
533
547
  await this.request("DELETE", `/api/attachments/${encodeURIComponent(id)}`, undefined, context);
534
548
  }
@@ -1030,6 +1044,13 @@ var operationOutputSchemas = {
1030
1044
  permanently_delete_document: deleteAcknowledgmentSchema
1031
1045
  };
1032
1046
  var variant = (operation, result) => z.object({ operation: z.literal(operation), result });
1047
+ var attachment = z.object({
1048
+ id: z.string().uuid(),
1049
+ filename: z.string(),
1050
+ mimeType: z.string(),
1051
+ size: z.number().int().nonnegative(),
1052
+ url: z.string()
1053
+ });
1033
1054
  var singleToolOutputSchemas = {
1034
1055
  delete_document: operationOutputSchemas.delete_document,
1035
1056
  delete_folder: operationOutputSchemas.delete_folder,
@@ -1051,6 +1072,11 @@ var singleToolOutputSchemas = {
1051
1072
  variant("markdown", operationOutputSchemas.export_document),
1052
1073
  variant("versions", operationOutputSchemas.get_version_history)
1053
1074
  ]),
1075
+ upload_document_image: attachment,
1076
+ check_document_attachments: z.strictObject({
1077
+ items: z.array(attachment),
1078
+ verifiedAttachmentId: z.string().uuid().optional()
1079
+ }),
1054
1080
  save_document: z.union([
1055
1081
  variant("create", operationOutputSchemas.create_document),
1056
1082
  variant("update", operationOutputSchemas.update_document)
@@ -1159,6 +1185,40 @@ function sanitizeMcpRequestContext(context) {
1159
1185
  function createMcpDocsClient(docsClient, requestContext) {
1160
1186
  const context = sanitizeMcpRequestContext(requestContext);
1161
1187
  return {
1188
+ uploadDocumentImage: async (id, filename, mimeType, bytes) => {
1189
+ const descriptor = { filename, contentType: mimeType, size: bytes.byteLength };
1190
+ const upload = await docsClient.presignAttachment(id, descriptor, context);
1191
+ const response = await fetch(upload.url, {
1192
+ method: "PUT",
1193
+ body: new Blob([Uint8Array.from(bytes)], { type: mimeType }),
1194
+ redirect: "error",
1195
+ signal: context?.signal
1196
+ }).catch(() => {
1197
+ throw new Error("Could not send image bytes to DocsMint storage.");
1198
+ });
1199
+ await response.body?.cancel();
1200
+ if (!response.ok)
1201
+ throw new Error(`DocsMint storage rejected the image (${response.status}).`);
1202
+ return docsClient.confirmAttachment(id, {
1203
+ ...descriptor,
1204
+ key: upload.key,
1205
+ uploadToken: upload.uploadToken,
1206
+ quotaReservationId: upload.quotaReservationId
1207
+ }, context);
1208
+ },
1209
+ listAttachments: (id) => docsClient.listAttachments(id, context),
1210
+ verifyAttachment: async (id) => {
1211
+ const response = await docsClient.fetchAttachment(id, context);
1212
+ const reader = response.body?.getReader();
1213
+ if (!reader)
1214
+ throw new Error("The attachment response has no body.");
1215
+ try {
1216
+ if (!(await reader.read()).value?.byteLength)
1217
+ throw new Error("The attachment is empty.");
1218
+ } finally {
1219
+ await reader.cancel();
1220
+ }
1221
+ },
1162
1222
  getFolder: (id) => docsClient.getFolder(id, context),
1163
1223
  createTag: (input) => docsClient.createTag(input, context),
1164
1224
  updateTag: (id, input) => docsClient.updateTag(id, input, context),
@@ -1424,6 +1484,18 @@ var content = z4.string().describe("Markdown document content; an empty string c
1424
1484
  var read = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
1425
1485
  var write = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };
1426
1486
  var destructive = { ...write, destructiveHint: true };
1487
+ function matchesImageType(bytes, mimeType) {
1488
+ switch (mimeType) {
1489
+ case "image/png":
1490
+ return bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
1491
+ case "image/jpeg":
1492
+ return bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;
1493
+ case "image/webp":
1494
+ return bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP";
1495
+ default:
1496
+ return false;
1497
+ }
1498
+ }
1427
1499
  function required2(value, name) {
1428
1500
  if (!value)
1429
1501
  throw new Error(`The injected legacy MCP client does not support ${name}; use a public DocsClient.`);
@@ -1459,6 +1531,32 @@ function registerCompactCapabilities(server, client, wrap) {
1459
1531
  const { action: _action, id, ...data } = input;
1460
1532
  return { operation: "update", result: await client.updateDocument(id, data) };
1461
1533
  });
1534
+ const maxImageBytes = 2 * 1024 * 1024;
1535
+ register("upload_document_image", "Upload one PNG, JPEG or WebP image to an existing editable document. Send the file bytes as base64, up to 2 MiB before encoding. Insert the returned url as an image using save_document. If the result is lost, check attachments before uploading again.", z4.strictObject({
1536
+ documentId: uuid2,
1537
+ filename: z4.string().min(1).max(255).regex(/^[^/\\\u0000-\u001f\u007f]+$/).describe("Image file name with extension and without path segments."),
1538
+ mimeType: z4.enum(["image/png", "image/jpeg", "image/webp"]).describe("MIME type of the source image."),
1539
+ contentBase64: z4.base64().min(4).max(Math.ceil(maxImageBytes / 3) * 4).describe("Base64 file bytes without a data: prefix.")
1540
+ }), write, async ({ documentId, filename, mimeType, contentBase64 }) => {
1541
+ const bytes = Buffer.from(contentBase64, "base64");
1542
+ if (!bytes.length || bytes.length > maxImageBytes)
1543
+ throw new Error("Image must be between 1 byte and 2 MiB.");
1544
+ if (!matchesImageType(bytes, mimeType))
1545
+ throw new Error("Image bytes do not match the declared MIME type.");
1546
+ return required2(client.uploadDocumentImage, "upload_document_image")(documentId, filename, mimeType, bytes);
1547
+ });
1548
+ register("check_document_attachments", "List attachments on a readable document. Supply attachmentId to verify that this attachment belongs to the document and that its stored bytes can be opened with the current access.", z4.strictObject({
1549
+ documentId: uuid2,
1550
+ attachmentId: uuid2.optional()
1551
+ }), read, async ({ documentId, attachmentId }) => {
1552
+ const { items } = await required2(client.listAttachments, "check_document_attachments")(documentId);
1553
+ if (!attachmentId)
1554
+ return { items };
1555
+ if (!items.some((item) => item.id === attachmentId))
1556
+ throw new Error("Attachment not found in this document.");
1557
+ await required2(client.verifyAttachment, "check_document_attachments")(attachmentId);
1558
+ return { items, verifiedAttachmentId: attachmentId };
1559
+ });
1462
1560
  register("delete_document", "Move one document to trash without purging content or versions. Use batch_documents(action=trash) for multiple explicit IDs. Requires write access and an explicit delete request; permanently_delete_document is a separate irreversible action.", z4.strictObject({ id: uuid2 }), destructive, async ({ id }) => {
1463
1561
  await required2(client.deleteDocument, "delete_document")(id);
1464
1562
  return { id, deleted: true };
@@ -1687,7 +1785,7 @@ function registerDocsmintMcpCapabilities(server, client, workspaceRouting, decor
1687
1785
  registerPromptsAndResources(server, client);
1688
1786
  }
1689
1787
  function createDocsmintMcpServer(options = {}) {
1690
- const server = new DocsMintMcpServer({ name: "docsmint", version: "2.1.5" });
1788
+ const server = new DocsMintMcpServer({ name: "docsmint", version: "2.1.9" });
1691
1789
  const client = options.docsClient ? createMcpDocsClient(options.docsClient, options.requestContext) : options.client ?? createMcpDocsClient(createDefaultDocsClient(), options.requestContext);
1692
1790
  registerDocsmintMcpCapabilities(server, client, options.workspaceRouting, options.decorateResult);
1693
1791
  return server;
@@ -300,6 +300,12 @@ class DocsClient {
300
300
  }, context);
301
301
  }
302
302
  async listDocuments(options = {}, context) {
303
+ return this.listDocumentCursor(options, context);
304
+ }
305
+ async listCatalogDocuments(options = {}, context) {
306
+ return this.listDocumentCursor(options, context, "catalog");
307
+ }
308
+ async listDocumentCursor(options, context, view) {
303
309
  return this.request("GET", "/api/documents/cursor", {
304
310
  query: this.cleanQuery({
305
311
  categoryId: options.categoryId,
@@ -314,6 +320,8 @@ class DocsClient {
314
320
  updatedTo: options.updatedTo,
315
321
  cursor: options.cursor,
316
322
  limit: options.limit,
323
+ view,
324
+ includeTotal: options.includeTotal === undefined ? undefined : String(options.includeTotal),
317
325
  sortBy: options.sortBy,
318
326
  sortOrder: options.sortOrder
319
327
  })
@@ -524,6 +532,12 @@ class DocsClient {
524
532
  async listAttachments(documentId, context) {
525
533
  return this.request("GET", `/api/documents/${encodeURIComponent(documentId)}/attachments`, undefined, context);
526
534
  }
535
+ async fetchAttachment(id, context) {
536
+ const response = await this.fetchRaw("GET", `/api/attachments/${encodeURIComponent(id)}/raw`, {}, context);
537
+ if (!response.ok)
538
+ throw await this.toApiError(response);
539
+ return response;
540
+ }
527
541
  async deleteAttachment(id, context) {
528
542
  await this.request("DELETE", `/api/attachments/${encodeURIComponent(id)}`, undefined, context);
529
543
  }
@@ -1025,6 +1039,13 @@ var operationOutputSchemas = {
1025
1039
  permanently_delete_document: deleteAcknowledgmentSchema
1026
1040
  };
1027
1041
  var variant = (operation, result) => z.object({ operation: z.literal(operation), result });
1042
+ var attachment = z.object({
1043
+ id: z.string().uuid(),
1044
+ filename: z.string(),
1045
+ mimeType: z.string(),
1046
+ size: z.number().int().nonnegative(),
1047
+ url: z.string()
1048
+ });
1028
1049
  var singleToolOutputSchemas = {
1029
1050
  delete_document: operationOutputSchemas.delete_document,
1030
1051
  delete_folder: operationOutputSchemas.delete_folder,
@@ -1046,6 +1067,11 @@ var singleToolOutputSchemas = {
1046
1067
  variant("markdown", operationOutputSchemas.export_document),
1047
1068
  variant("versions", operationOutputSchemas.get_version_history)
1048
1069
  ]),
1070
+ upload_document_image: attachment,
1071
+ check_document_attachments: z.strictObject({
1072
+ items: z.array(attachment),
1073
+ verifiedAttachmentId: z.string().uuid().optional()
1074
+ }),
1049
1075
  save_document: z.union([
1050
1076
  variant("create", operationOutputSchemas.create_document),
1051
1077
  variant("update", operationOutputSchemas.update_document)
@@ -1157,6 +1183,40 @@ function sanitizeMcpRequestContext(context) {
1157
1183
  function createMcpDocsClient(docsClient, requestContext) {
1158
1184
  const context = sanitizeMcpRequestContext(requestContext);
1159
1185
  return {
1186
+ uploadDocumentImage: async (id, filename, mimeType, bytes) => {
1187
+ const descriptor = { filename, contentType: mimeType, size: bytes.byteLength };
1188
+ const upload = await docsClient.presignAttachment(id, descriptor, context);
1189
+ const response = await fetch(upload.url, {
1190
+ method: "PUT",
1191
+ body: new Blob([Uint8Array.from(bytes)], { type: mimeType }),
1192
+ redirect: "error",
1193
+ signal: context?.signal
1194
+ }).catch(() => {
1195
+ throw new Error("Could not send image bytes to DocsMint storage.");
1196
+ });
1197
+ await response.body?.cancel();
1198
+ if (!response.ok)
1199
+ throw new Error(`DocsMint storage rejected the image (${response.status}).`);
1200
+ return docsClient.confirmAttachment(id, {
1201
+ ...descriptor,
1202
+ key: upload.key,
1203
+ uploadToken: upload.uploadToken,
1204
+ quotaReservationId: upload.quotaReservationId
1205
+ }, context);
1206
+ },
1207
+ listAttachments: (id) => docsClient.listAttachments(id, context),
1208
+ verifyAttachment: async (id) => {
1209
+ const response = await docsClient.fetchAttachment(id, context);
1210
+ const reader = response.body?.getReader();
1211
+ if (!reader)
1212
+ throw new Error("The attachment response has no body.");
1213
+ try {
1214
+ if (!(await reader.read()).value?.byteLength)
1215
+ throw new Error("The attachment is empty.");
1216
+ } finally {
1217
+ await reader.cancel();
1218
+ }
1219
+ },
1160
1220
  getFolder: (id) => docsClient.getFolder(id, context),
1161
1221
  createTag: (input) => docsClient.createTag(input, context),
1162
1222
  updateTag: (id, input) => docsClient.updateTag(id, input, context),
@@ -1422,6 +1482,18 @@ var content = z4.string().describe("Markdown document content; an empty string c
1422
1482
  var read = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
1423
1483
  var write = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };
1424
1484
  var destructive = { ...write, destructiveHint: true };
1485
+ function matchesImageType(bytes, mimeType) {
1486
+ switch (mimeType) {
1487
+ case "image/png":
1488
+ return bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
1489
+ case "image/jpeg":
1490
+ return bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;
1491
+ case "image/webp":
1492
+ return bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP";
1493
+ default:
1494
+ return false;
1495
+ }
1496
+ }
1425
1497
  function required2(value, name) {
1426
1498
  if (!value)
1427
1499
  throw new Error(`The injected legacy MCP client does not support ${name}; use a public DocsClient.`);
@@ -1457,6 +1529,32 @@ function registerCompactCapabilities(server, client, wrap) {
1457
1529
  const { action: _action, id, ...data } = input;
1458
1530
  return { operation: "update", result: await client.updateDocument(id, data) };
1459
1531
  });
1532
+ const maxImageBytes = 2 * 1024 * 1024;
1533
+ register("upload_document_image", "Upload one PNG, JPEG or WebP image to an existing editable document. Send the file bytes as base64, up to 2 MiB before encoding. Insert the returned url as an image using save_document. If the result is lost, check attachments before uploading again.", z4.strictObject({
1534
+ documentId: uuid2,
1535
+ filename: z4.string().min(1).max(255).regex(/^[^/\\\u0000-\u001f\u007f]+$/).describe("Image file name with extension and without path segments."),
1536
+ mimeType: z4.enum(["image/png", "image/jpeg", "image/webp"]).describe("MIME type of the source image."),
1537
+ contentBase64: z4.base64().min(4).max(Math.ceil(maxImageBytes / 3) * 4).describe("Base64 file bytes without a data: prefix.")
1538
+ }), write, async ({ documentId, filename, mimeType, contentBase64 }) => {
1539
+ const bytes = Buffer.from(contentBase64, "base64");
1540
+ if (!bytes.length || bytes.length > maxImageBytes)
1541
+ throw new Error("Image must be between 1 byte and 2 MiB.");
1542
+ if (!matchesImageType(bytes, mimeType))
1543
+ throw new Error("Image bytes do not match the declared MIME type.");
1544
+ return required2(client.uploadDocumentImage, "upload_document_image")(documentId, filename, mimeType, bytes);
1545
+ });
1546
+ register("check_document_attachments", "List attachments on a readable document. Supply attachmentId to verify that this attachment belongs to the document and that its stored bytes can be opened with the current access.", z4.strictObject({
1547
+ documentId: uuid2,
1548
+ attachmentId: uuid2.optional()
1549
+ }), read, async ({ documentId, attachmentId }) => {
1550
+ const { items } = await required2(client.listAttachments, "check_document_attachments")(documentId);
1551
+ if (!attachmentId)
1552
+ return { items };
1553
+ if (!items.some((item) => item.id === attachmentId))
1554
+ throw new Error("Attachment not found in this document.");
1555
+ await required2(client.verifyAttachment, "check_document_attachments")(attachmentId);
1556
+ return { items, verifiedAttachmentId: attachmentId };
1557
+ });
1460
1558
  register("delete_document", "Move one document to trash without purging content or versions. Use batch_documents(action=trash) for multiple explicit IDs. Requires write access and an explicit delete request; permanently_delete_document is a separate irreversible action.", z4.strictObject({ id: uuid2 }), destructive, async ({ id }) => {
1461
1559
  await required2(client.deleteDocument, "delete_document")(id);
1462
1560
  return { id, deleted: true };
@@ -1624,6 +1722,8 @@ var capabilityCatalog = {
1624
1722
  "find_documents",
1625
1723
  "read_document",
1626
1724
  "save_document",
1725
+ "upload_document_image",
1726
+ "check_document_attachments",
1627
1727
  "delete_document",
1628
1728
  "list_workspace_structure",
1629
1729
  "save_folder",
@@ -1676,6 +1776,8 @@ function example(schema) {
1676
1776
  if (schema.type === "object" || schema.properties) {
1677
1777
  return Object.fromEntries(Object.entries(object2(schema.properties)).filter(([name]) => Array.isArray(schema.required) && schema.required.includes(name) || name === "title" || name === "name").map(([name, value]) => [name, example(object2(value))]));
1678
1778
  }
1779
+ if (schema.contentEncoding === "base64" || schema.format === "base64")
1780
+ return "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aCdwAAAAASUVORK5CYII=";
1679
1781
  if (schema.format === "uuid")
1680
1782
  return "11111111-1111-4111-8111-111111111111";
1681
1783
  if (schema.format === "date-time")
@@ -1885,7 +1987,7 @@ function registerDocsmintMcpCapabilities(server, client, workspaceRouting, decor
1885
1987
  registerPromptsAndResources(server, client);
1886
1988
  }
1887
1989
  function createDocsmintMcpServer(options = {}) {
1888
- const server = new DocsMintMcpServer({ name: "docsmint", version: "2.1.5" });
1990
+ const server = new DocsMintMcpServer({ name: "docsmint", version: "2.1.9" });
1889
1991
  const client = options.docsClient ? createMcpDocsClient(options.docsClient, options.requestContext) : options.client ?? createMcpDocsClient(createDefaultDocsClient(), options.requestContext);
1890
1992
  registerDocsmintMcpCapabilities(server, client, options.workspaceRouting, options.decorateResult);
1891
1993
  return server;
package/dist/types.d.ts CHANGED
@@ -83,6 +83,17 @@ export interface DocsDocumentCursorPage {
83
83
  items: DocsDocumentListItem[];
84
84
  nextCursor: string | null;
85
85
  }
86
+ export interface DocsCatalogCursorPage {
87
+ total?: number;
88
+ items: {
89
+ id: string;
90
+ title: string;
91
+ preview: string;
92
+ folderId: string | null;
93
+ folderName: string | null;
94
+ }[];
95
+ nextCursor: string | null;
96
+ }
86
97
  export type DocsDocumentSortField = "title" | "category" | "folder" | "updated" | "updatedAt" | "createdAt";
87
98
  export type DocsSortOrder = "asc" | "desc";
88
99
  export interface DocsFolder {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hiai-gg/docsmint",
3
3
  "mcpName": "io.github.HiAi-gg/docsmint",
4
- "version": "2.1.5",
4
+ "version": "2.1.9",
5
5
  "type": "module",
6
6
  "browser": {
7
7
  "./dist/backend-launcher.js": false,
@@ -25,7 +25,7 @@ import { registerSearch } from './commands/search.js';
25
25
  import { registerSnapshot } from './commands/snapshot.js';
26
26
  import { registerUpdate } from './commands/update.js';
27
27
 
28
- const VERSION = '2.1.5';
28
+ const VERSION = '2.1.9';
29
29
 
30
30
  const program = new Command();
31
31
  program.name('docsmint').description('CLI for the DocsMint knowledge workspace').version(VERSION);
@@ -998,6 +998,25 @@ export const documentCreateOperations = pgTable(
998
998
  ],
999
999
  );
1000
1000
 
1001
+ export const folderCreateOperations = pgTable(
1002
+ "folder_create_operations",
1003
+ {
1004
+ id: uuid("id").primaryKey().defaultRandom(),
1005
+ workspaceId: text("workspace_id").notNull(),
1006
+ actorUserId: uuid("actor_user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
1007
+ idempotencyKey: text("idempotency_key").notNull(),
1008
+ folderId: uuid("folder_id").notNull(),
1009
+ requestFingerprint: text("request_fingerprint").notNull(),
1010
+ createdAt: timestamp("created_at").defaultNow().notNull(),
1011
+ },
1012
+ (table) => [
1013
+ uniqueIndex("folder_create_operations_workspace_actor_key_unique").on(
1014
+ table.workspaceId, table.actorUserId, table.idempotencyKey,
1015
+ ),
1016
+ uniqueIndex("folder_create_operations_folder_idx").on(table.folderId),
1017
+ ],
1018
+ );
1019
+
1001
1020
  export const versionRelations = relations(versions, ({ one }) => ({
1002
1021
  document: one(documents, {
1003
1022
  fields: [versions.documentId],
package/server.json CHANGED
@@ -10,7 +10,7 @@
10
10
  "id": "1249550690",
11
11
  "subfolder": "packages/mcp-server"
12
12
  },
13
- "version": "2.1.5",
13
+ "version": "2.1.9",
14
14
  "icons": [
15
15
  {
16
16
  "src": "https://raw.githubusercontent.com/HiAi-gg/docsmint/main/frontend/static/logo-dark.png",
@@ -34,7 +34,7 @@
34
34
  "registryType": "npm",
35
35
  "registryBaseUrl": "https://registry.npmjs.org",
36
36
  "identifier": "@hiai-gg/docsmint",
37
- "version": "2.1.5",
37
+ "version": "2.1.9",
38
38
  "runtimeHint": "npx",
39
39
  "transport": {
40
40
  "type": "stdio"
@@ -87,7 +87,7 @@
87
87
  "licenseFile": "https://github.com/HiAi-gg/docsmint/blob/main/LICENSE",
88
88
  "documentationUrl": "https://docsmint.com/mcp/connect?source=mcp_registry",
89
89
  "catalog": {
90
- "tools": 22,
90
+ "tools": 24,
91
91
  "prompts": 2,
92
92
  "resources": 3
93
93
  }
@@ -31,4 +31,11 @@ Use this skill when an agent must create, organize, edit, or research documents
31
31
  5. Use `create_snapshot` before a substantial rewrite; choose a version through `read_document(view=versions)` before `restore_document_version`.
32
32
  6. Treat `delete_document`, `restore_trashed_document`, and `permanently_delete_document` as distinct lifecycle actions. Purge only on an explicit request.
33
33
 
34
+ ## Image attachments
35
+
36
+ 1. Read the document with `read_document(view=detail)`. Check existing files with `check_document_attachments` before retrying a previous upload.
37
+ 2. Call `upload_document_image` with `documentId`, `filename`, `mimeType`, and `contentBase64`. The document requires edit access. Supply PNG, JPEG or WebP bytes up to 2 MiB, without a data URL prefix.
38
+ 3. Insert the returned `url` as a Markdown image with descriptive alt text via `save_document(action=update)`, preserving the existing content.
39
+ 4. Reread the document and use `check_document_attachments` with the returned `attachmentId` to confirm the bytes open with the current access.
40
+
34
41
  DocsMint owns chunking, embeddings, multilingual hybrid retrieval, cross-encoder rerank, entity extraction, and GraphRAG indexing. Agents must use the MCP tools and never write those persistence layers directly.