@hiai-gg/docsmint 2.0.3 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +68 -3
  2. package/dist/backend/index.js +22540 -2807
  3. package/dist/backend-account-runtime-cleanup.js +2 -1
  4. package/dist/backend-api-key-facade.js +2 -1
  5. package/dist/backend-pipeline-cancellation.js +2 -1
  6. package/dist/client.d.ts +33 -7
  7. package/dist/client.js +55 -1
  8. package/dist/frontend/{HiAiEditor-DDpfdQEg.js → HiAiEditor-D6ad_auS.js} +2 -2
  9. package/dist/frontend/{SettingsDialog-DzlYW50I.js → SettingsDialog-B8Oswuqb.js} +4 -4
  10. package/dist/frontend/{Sidebar-rFiVen96.js → Sidebar-BV0IDqTS.js} +1 -1
  11. package/dist/frontend/api/settings.js +1 -1
  12. package/dist/frontend/app-shell.js +45 -36
  13. package/dist/frontend/{auth-client-CXR-7mIO.js → auth-client-C5EyWdAF.js} +416 -349
  14. package/dist/frontend/components/editor/compact-editor.js +1 -1
  15. package/dist/frontend/components/editor/document-editor.js +1 -1
  16. package/dist/frontend/components/settings.js +1 -1
  17. package/dist/frontend/components/sidebar.js +1 -1
  18. package/dist/frontend/{db-Dya0HRhS.js → db-CgTtukT4.js} +1 -1
  19. package/dist/frontend/{identity-BOA7Jejv.js → identity-CNhtuCJV.js} +1 -1
  20. package/dist/frontend/offline/identity.js +1 -1
  21. package/dist/frontend/{settings-BRcYFQa_.js → settings-CHx4wBwb.js} +1 -1
  22. package/dist/frontend-ssr/api/settings.js +1 -1
  23. package/dist/frontend-ssr/app-shell.js +2 -2
  24. package/dist/frontend-ssr/assets/{HiAiEditor-Bj6tiE97.js → HiAiEditor-Cj3B2Dt6.js} +2 -2
  25. package/dist/frontend-ssr/assets/{SettingsDialog-h4SFwpUa.js → SettingsDialog-DAT-Zxu0.js} +4 -4
  26. package/dist/frontend-ssr/assets/{Sidebar-BFBpsd3L.js → Sidebar-B_Ey6QNL.js} +1 -1
  27. package/dist/frontend-ssr/assets/{auth-client-BC4hSFKF.js → auth-client-CITU3xkE.js} +308 -227
  28. package/dist/frontend-ssr/assets/{db-C3rFdTZa.js → db-DxRzq-kx.js} +1 -1
  29. package/dist/frontend-ssr/assets/{identity-DNIo1bgc.js → identity-B7ngLQzZ.js} +1 -1
  30. package/dist/frontend-ssr/assets/{settings-DWCpfCPj.js → settings-BRxvn30Y.js} +1 -1
  31. package/dist/frontend-ssr/components/editor/compact-editor.js +1 -1
  32. package/dist/frontend-ssr/components/editor/document-editor.js +1 -1
  33. package/dist/frontend-ssr/components/settings.js +1 -1
  34. package/dist/frontend-ssr/components/sidebar.js +1 -1
  35. package/dist/frontend-ssr/offline/identity.js +1 -1
  36. package/dist/index.d.ts +1 -1
  37. package/dist/index.js +1 -1
  38. package/dist/lifecycle-runtime.js +4 -1
  39. package/dist/mcp-cli.js +301 -22
  40. package/dist/mcp-server.d.ts +92 -23
  41. package/dist/mcp-server.js +469 -22
  42. package/dist/types.d.ts +68 -1
  43. package/package.json +2 -2
  44. package/packages/cli/src/index.ts +1 -1
  45. package/packages/db/src/schema.ts +3 -1
  46. package/server.json +2 -2
@@ -1,6 +1,188 @@
1
1
  // @bun
2
- // ../mcp-server/src/server.ts
3
- import { McpServer } from "@modelcontextprotocol/server";
2
+ // ../mcp-server/src/argument-diagnostics.ts
3
+ import {
4
+ McpServer
5
+ } from "@modelcontextprotocol/server";
6
+ var contracts = new WeakMap;
7
+ function object(value) {
8
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
9
+ }
10
+ function captureMcpInputSchema(server, name, schema) {
11
+ let registered = contracts.get(server);
12
+ if (!registered) {
13
+ registered = new Map;
14
+ contracts.set(server, registered);
15
+ }
16
+ registered.set(name, {
17
+ validate: (value) => schema["~standard"].validate(value, undefined),
18
+ jsonSchema: () => schema["~standard"].jsonSchema.input({ target: "draft-2020-12" })
19
+ });
20
+ return schema;
21
+ }
22
+ var codes = new Set([
23
+ "invalid_type",
24
+ "too_big",
25
+ "too_small",
26
+ "invalid_format",
27
+ "not_multiple_of",
28
+ "unrecognized_keys",
29
+ "invalid_union",
30
+ "invalid_key",
31
+ "invalid_element",
32
+ "invalid_value",
33
+ "custom"
34
+ ]);
35
+ function diagnostics(tool, input, schemaValue, issues) {
36
+ const schema = object(schemaValue) ?? {};
37
+ const branches = Array.isArray(schema.oneOf) ? schema.oneOf.map((item) => object(item) ?? {}) : [schema];
38
+ const knownFields = new Set;
39
+ function fields(value) {
40
+ const item = object(value);
41
+ if (!item)
42
+ return;
43
+ for (const [name, child] of Object.entries(object(item.properties) ?? {})) {
44
+ knownFields.add(name);
45
+ fields(child);
46
+ }
47
+ if (item.items)
48
+ fields(item.items);
49
+ for (const key of ["oneOf", "anyOf", "allOf"])
50
+ if (Array.isArray(item[key]))
51
+ for (const child of item[key])
52
+ fields(child);
53
+ }
54
+ fields(schema);
55
+ const args = object(input) ?? {};
56
+ const selector = ["mode", "action", "view", "kind"].find((key) => branches.some((branch2) => {
57
+ const property = object(object(branch2.properties)?.[key]);
58
+ return property && (typeof property.const === "string" || Array.isArray(property.enum));
59
+ }));
60
+ const variants = branches.map((branch2) => {
61
+ const property = selector ? object(object(branch2.properties)?.[selector]) : undefined;
62
+ const values = property && typeof property.const === "string" ? [property.const] : Array.isArray(property?.enum) ? property.enum.filter((value) => typeof value === "string") : [];
63
+ return {
64
+ values,
65
+ required: Array.isArray(branch2.required) ? branch2.required.filter((value) => typeof value === "string" && knownFields.has(value)) : []
66
+ };
67
+ });
68
+ const selected = selector ? args[selector] : undefined;
69
+ const branch = typeof selected === "string" && variants.some((variant) => variant.values.includes(selected)) ? selected : null;
70
+ return {
71
+ tool,
72
+ branch,
73
+ expectedArgs: variants.map((variant) => ({
74
+ branches: variant.values,
75
+ required: variant.required
76
+ })),
77
+ issues: issues.slice(0, 32).map((value) => {
78
+ const issue = object(value) ?? {};
79
+ const path = Array.isArray(issue.path) ? issue.path.map((part) => object(part)?.key ?? part).filter((part) => typeof part === "string" ? knownFields.has(part) : typeof part === "number" && Number.isInteger(part) && part >= 0 && part < 1e4) : [];
80
+ return {
81
+ path,
82
+ code: typeof issue.code === "string" && codes.has(issue.code) ? issue.code : "invalid_argument"
83
+ };
84
+ })
85
+ };
86
+ }
87
+ function decorateMcpArgumentTransport(transport, server) {
88
+ const pending = new Map;
89
+ let closed = false;
90
+ let overflowed = false;
91
+ function remember(message) {
92
+ if (closed || overflowed)
93
+ return;
94
+ if (!("method" in message) || !("id" in message) || typeof message.id !== "string" && typeof message.id !== "number")
95
+ return;
96
+ const previous = pending.get(message.id);
97
+ if (previous) {
98
+ previous.count++;
99
+ previous.ambiguous = true;
100
+ previous.candidate = undefined;
101
+ return;
102
+ }
103
+ if (pending.size >= 1024) {
104
+ overflowed = true;
105
+ pending.clear();
106
+ return;
107
+ }
108
+ const params = "params" in message ? object(message.params) : undefined;
109
+ const name = params?.name;
110
+ const contract = message.method === "tools/call" && typeof name === "string" ? contracts.get(server)?.get(name) : undefined;
111
+ pending.set(message.id, {
112
+ count: 1,
113
+ ambiguous: false,
114
+ ...contract && typeof name === "string" ? { candidate: { tool: name, args: params?.arguments ?? {}, contract } } : {}
115
+ });
116
+ }
117
+ async function send(message, options) {
118
+ const id = "id" in message && (typeof message.id === "string" || typeof message.id === "number") && !("method" in message) ? message.id : undefined;
119
+ const entry = id === undefined ? undefined : pending.get(id);
120
+ let outgoing = message;
121
+ try {
122
+ const candidate = entry && !entry.ambiguous ? entry.candidate : undefined;
123
+ const result = "result" in message ? object(message.result) : undefined;
124
+ const block = result && Array.isArray(result.content) && result.content.length === 1 ? object(result.content[0]) : undefined;
125
+ if (id !== undefined && candidate && result?.isError === true && Object.keys(result).length === 2 && block?.type === "text" && Object.keys(block).length === 2 && typeof block.text === "string" && block.text.startsWith(`Input validation error: Invalid arguments for tool ${candidate.tool}:`)) {
126
+ try {
127
+ const validation = object(await candidate.contract.validate(candidate.args));
128
+ if (Array.isArray(validation?.issues) && validation.issues.length && !entry?.ambiguous && pending.get(id) === entry) {
129
+ const data = diagnostics(candidate.tool, candidate.args, candidate.contract.jsonSchema(), validation.issues);
130
+ outgoing = {
131
+ jsonrpc: "2.0",
132
+ id,
133
+ error: { code: -32602, message: "Invalid tool arguments", data }
134
+ };
135
+ }
136
+ } catch {}
137
+ }
138
+ await transport.send(outgoing, options);
139
+ } finally {
140
+ if (id !== undefined && entry && pending.get(id) === entry && --entry.count === 0)
141
+ pending.delete(id);
142
+ }
143
+ }
144
+ return new Proxy(transport, {
145
+ get(target, property) {
146
+ if (property === "send")
147
+ return send;
148
+ if (property === "close")
149
+ return async () => {
150
+ closed = true;
151
+ pending.clear();
152
+ await target.close();
153
+ };
154
+ const value = Reflect.get(target, property, target);
155
+ return typeof value === "function" ? value.bind(target) : value;
156
+ },
157
+ set(target, property, value) {
158
+ if (property === "onmessage")
159
+ return Reflect.set(target, property, (message, extra) => {
160
+ try {
161
+ remember(message);
162
+ } catch {
163
+ overflowed = true;
164
+ pending.clear();
165
+ }
166
+ if (typeof value === "function")
167
+ value(message, extra);
168
+ }, target);
169
+ if (property === "onclose")
170
+ return Reflect.set(target, property, () => {
171
+ closed = true;
172
+ pending.clear();
173
+ if (typeof value === "function")
174
+ value();
175
+ }, target);
176
+ return Reflect.set(target, property, value, target);
177
+ }
178
+ });
179
+ }
180
+
181
+ class DocsMintMcpServer extends McpServer {
182
+ connect(transport) {
183
+ return super.connect(decorateMcpArgumentTransport(transport, this));
184
+ }
185
+ }
4
186
 
5
187
  // dist/client.js
6
188
  var docsApiErrorBrand = Symbol.for("io.github.hiai-gg.docsmint.DocsApiError");
@@ -53,11 +235,15 @@ class DocsTimeoutError extends DocsNetworkError {
53
235
  class DocsClient {
54
236
  config;
55
237
  constructor(config) {
238
+ if (config.apiPrefix !== undefined && config.apiPrefix !== "/api" && config.apiPrefix !== "/api/v1") {
239
+ throw new Error("DocsClient: apiPrefix must be /api or /api/v1");
240
+ }
56
241
  if (!config.baseUrl) {
57
242
  throw new Error("DocsClient: `baseUrl` is required");
58
243
  }
59
244
  this.config = {
60
245
  baseUrl: config.baseUrl.replace(/\/+$/, ""),
246
+ apiPrefix: config.apiPrefix ?? "/api",
61
247
  apiKey: config.apiKey,
62
248
  requestContext: this.snapshotContext(config.requestContext),
63
249
  fetch: config.fetch ?? fetch,
@@ -97,6 +283,16 @@ class DocsClient {
97
283
  return this.request("GET", "/api/documents", {
98
284
  query: this.cleanQuery({
99
285
  folderId: options?.folderId,
286
+ categoryId: options?.categoryId,
287
+ visibility: options?.visibility,
288
+ rootOnly: options?.rootOnly,
289
+ tagIds: options?.tagIds?.join(","),
290
+ tagMatch: options?.tagMatch,
291
+ q: options?.q,
292
+ updatedFrom: options?.updatedFrom,
293
+ updatedTo: options?.updatedTo,
294
+ sortBy: options?.sortBy,
295
+ sortOrder: options?.sortOrder,
100
296
  tag: options?.tag,
101
297
  page: options?.page,
102
298
  limit: options?.limit
@@ -107,6 +303,15 @@ class DocsClient {
107
303
  return this.request("GET", "/api/documents/cursor", {
108
304
  query: this.cleanQuery({
109
305
  categoryId: options.categoryId,
306
+ folderId: options.folderId,
307
+ rootOnly: options.rootOnly,
308
+ tag: options.tag,
309
+ tagIds: options.tagIds?.join(","),
310
+ tagMatch: options.tagMatch,
311
+ visibility: options.visibility,
312
+ q: options.q,
313
+ updatedFrom: options.updatedFrom,
314
+ updatedTo: options.updatedTo,
110
315
  cursor: options.cursor,
111
316
  limit: options.limit,
112
317
  sortBy: options.sortBy,
@@ -138,6 +343,14 @@ class DocsClient {
138
343
  async unpublishDoc(id, context) {
139
344
  return this.request("POST", `/api/documents/${encodeURIComponent(id)}/unpublish`, undefined, context);
140
345
  }
346
+ async exportDocWithMetadata(id, context) {
347
+ const response = await this.fetchRaw("GET", `/api/documents/${encodeURIComponent(id)}/export`, { query: { format: "json" } }, context);
348
+ if (!response.ok)
349
+ throw await this.toApiError(response);
350
+ if (response.headers.get("content-type")?.includes("json"))
351
+ return response.json();
352
+ return { markdown: await response.text() };
353
+ }
141
354
  async exportDoc(id, context) {
142
355
  return this.getDocMarkdown(id, context);
143
356
  }
@@ -221,6 +434,12 @@ class DocsClient {
221
434
  async revokeApiKey(id, context) {
222
435
  return this.request("DELETE", `/api/keys/${encodeURIComponent(id)}`, undefined, context);
223
436
  }
437
+ async whoami(context) {
438
+ return this.request("GET", "/api/whoami", undefined, context);
439
+ }
440
+ async listWorkspaces(context) {
441
+ return this.request("GET", "/api/workspaces", undefined, context);
442
+ }
224
443
  async search(query, options, context) {
225
444
  return this.request("GET", "/api/search", {
226
445
  query: this.cleanQuery({
@@ -236,7 +455,8 @@ class DocsClient {
236
455
  graph: options?.graph,
237
456
  graphHops: options?.graphHops,
238
457
  graphBoost: options?.graphBoost,
239
- includeChunks: options?.includeChunks
458
+ includeChunks: options?.includeChunks,
459
+ includeDiagnostics: options?.includeDiagnostics
240
460
  })
241
461
  }, context);
242
462
  }
@@ -426,7 +646,8 @@ class DocsClient {
426
646
  throw this.wrapNetworkError(lastError, requestContext?.requestId);
427
647
  }
428
648
  buildUrl(path, query) {
429
- let url = `${this.config.baseUrl}${path}`;
649
+ const resolvedPath = path.startsWith("/api/") ? `${this.config.apiPrefix}${path.slice(4)}` : path;
650
+ let url = `${this.config.baseUrl}${resolvedPath}`;
430
651
  if (query && Object.keys(query).length > 0) {
431
652
  const params = new URLSearchParams;
432
653
  for (const [key, value] of Object.entries(query)) {
@@ -720,6 +941,12 @@ var folderSchema = z.looseObject({
720
941
  documents: z.array(documentListItemSchema).optional()
721
942
  });
722
943
  var exportedDocumentSchema = z.looseObject({
944
+ id: z.string().optional(),
945
+ title: z.string().optional(),
946
+ updatedAt: z.string().optional(),
947
+ workspaceId: z.string().nullable().optional(),
948
+ workspaceSlug: z.string().nullable().optional(),
949
+ url: z.string().nullable().optional(),
723
950
  markdown: z.string(),
724
951
  filename: z.string().optional()
725
952
  });
@@ -948,7 +1175,9 @@ function createMcpDocsClient(docsClient, requestContext) {
948
1175
  search: (params) => docsClient.search(params.query, {
949
1176
  folder: params.folder,
950
1177
  tags: params.tags?.join(","),
951
- limit: params.limit
1178
+ limit: params.limit,
1179
+ includeChunks: params.includeChunks,
1180
+ includeDiagnostics: params.includeDiagnostics
952
1181
  }, context),
953
1182
  getDocument: (id) => docsClient.getDoc(id, context),
954
1183
  createDocument: (input) => docsClient.createDoc({
@@ -969,7 +1198,7 @@ function createMcpDocsClient(docsClient, requestContext) {
969
1198
  refreshDocumentIndex: (documentId) => docsClient.refreshDocumentIndex(documentId, context),
970
1199
  createSnapshot: (documentId, input) => docsClient.createSnapshot(documentId, input, context),
971
1200
  getVersionHistory: (documentId, onlySnapshots) => docsClient.listVersions(documentId, { onlySnapshots }, context),
972
- exportDocument: async (id) => ({ markdown: await docsClient.exportDoc(id, context) })
1201
+ exportDocument: (id) => docsClient.exportDocWithMetadata(id, context)
973
1202
  };
974
1203
  }
975
1204
  function createDefaultDocsClient() {
@@ -986,6 +1215,31 @@ var client = new Proxy({}, {
986
1215
 
987
1216
  // ../mcp-server/src/client-routing-schema.ts
988
1217
  import { z as z2 } from "zod";
1218
+ function canonical(value) {
1219
+ if (Array.isArray(value))
1220
+ return `[${value.map(canonical).join(",")}]`;
1221
+ if (value && typeof value === "object")
1222
+ return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(",")}}`;
1223
+ return JSON.stringify(value) ?? "null";
1224
+ }
1225
+ function mergePropertyVariants(values) {
1226
+ const unique = [
1227
+ ...new Map(values.map((value) => [canonical(value), value])).values()
1228
+ ];
1229
+ if (unique.length === 1)
1230
+ return unique[0];
1231
+ const literalObjects = unique.filter((value) => value && typeof value === "object" && ("const" in value));
1232
+ if (literalObjects.length === unique.length) {
1233
+ const withoutConst = literalObjects.map(({ const: _literal, ...rest }) => rest);
1234
+ if (withoutConst.every((value) => canonical(value) === canonical(withoutConst[0]))) {
1235
+ return {
1236
+ ...withoutConst[0],
1237
+ enum: literalObjects.map((value) => value.const)
1238
+ };
1239
+ }
1240
+ }
1241
+ return { anyOf: unique };
1242
+ }
989
1243
  function hoistObjectUnionClosure(schema) {
990
1244
  const variants = schema.oneOf;
991
1245
  if (!Array.isArray(variants) || !variants.every((variant2) => typeof variant2 === "object" && variant2 !== null && variant2.type === "object" && variant2.additionalProperties === false && typeof variant2.properties === "object" && variant2.properties !== null))
@@ -1003,7 +1257,7 @@ function hoistObjectUnionClosure(schema) {
1003
1257
  type: "object",
1004
1258
  properties: Object.fromEntries([...propertyVariants].map(([key, values]) => [
1005
1259
  key,
1006
- values.length === 1 ? values[0] : { anyOf: values }
1260
+ mergePropertyVariants(values)
1007
1261
  ])),
1008
1262
  additionalProperties: false,
1009
1263
  oneOf: variants.map((variant2) => {
@@ -1031,11 +1285,21 @@ function withClientRoutingSchema(schema) {
1031
1285
  const { workspaceId, ...args } = value;
1032
1286
  const selected = selector.safeParse(workspaceId);
1033
1287
  if (!selected.success)
1034
- return { issues: selected.error.issues };
1288
+ return {
1289
+ issues: selected.error.issues.map((issue) => ({
1290
+ ...issue,
1291
+ path: ["workspaceId", ...issue.path]
1292
+ }))
1293
+ };
1035
1294
  const validated = await standard.validate(args, options);
1036
1295
  if (validated.issues)
1037
1296
  return validated;
1038
- return { value: { ...validated.value, ...selected.data ? { workspaceId: selected.data } : {} } };
1297
+ return {
1298
+ value: {
1299
+ ...validated.value,
1300
+ ...selected.data ? { workspaceId: selected.data } : {}
1301
+ }
1302
+ };
1039
1303
  },
1040
1304
  jsonSchema: {
1041
1305
  ...standard.jsonSchema,
@@ -1044,11 +1308,17 @@ function withClientRoutingSchema(schema) {
1044
1308
  const routingProperty = z2.toJSONSchema(selector);
1045
1309
  return {
1046
1310
  ...published,
1047
- properties: { ...published.properties, workspaceId: routingProperty },
1311
+ properties: {
1312
+ ...published.properties,
1313
+ workspaceId: routingProperty
1314
+ },
1048
1315
  ...Array.isArray(published.oneOf) ? {
1049
1316
  oneOf: published.oneOf.map((branch) => ({
1050
1317
  ...branch,
1051
- properties: { ...branch.properties, workspaceId: routingProperty }
1318
+ properties: {
1319
+ ...branch.properties,
1320
+ workspaceId: routingProperty
1321
+ }
1052
1322
  }))
1053
1323
  } : {}
1054
1324
  };
@@ -1124,13 +1394,13 @@ function registerBatchAndWorkspaceCapabilities(server, client2, wrap) {
1124
1394
  }
1125
1395
  server.registerTool("batch_documents", {
1126
1396
  description: "Use for multiple explicitly selected documents that need the same action; for one document prefer the matching single-document tool. Accepts 1\u201325 IDs for automation compatibility. Supports move, set_category, add_tag, remove_tag, trash, restore, or refresh_index. Processes sequentially through the existing API with a permission check per document and a per-ID result; partial success is possible. Stops after authentication or rate-limit failure. Never expands a search result or permanently purges documents; version restore is separate.",
1127
- inputSchema: withClientRoutingSchema(batchInput),
1397
+ inputSchema: captureMcpInputSchema(server, "batch_documents", withClientRoutingSchema(batchInput)),
1128
1398
  outputSchema: toolOutputSchemas.batch_documents,
1129
1399
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }
1130
1400
  }, wrap("batch_documents", batch, toolOutputSchemas.batch_documents));
1131
1401
  server.registerTool("get_workspace_item", {
1132
1402
  description: "Read one visible folder, category, or tag by UUID. Folder uses its direct API getter; category and tag lookup uses the complete permission-filtered lists. An absent or out-of-scope ID is reported as not found. Use list_workspace_structure to discover IDs first.",
1133
- inputSchema: withClientRoutingSchema(z3.strictObject({ kind: z3.enum(["folder", "category", "tag"]).describe("The workspace resource type to read by ID."), id: uuid })),
1403
+ inputSchema: captureMcpInputSchema(server, "get_workspace_item", withClientRoutingSchema(z3.strictObject({ kind: z3.enum(["folder", "category", "tag"]).describe("The workspace resource type to read by ID."), id: uuid }))),
1134
1404
  outputSchema: toolOutputSchemas.get_workspace_item,
1135
1405
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }
1136
1406
  }, wrap("get_workspace_item", async ({ kind, id }) => {
@@ -1159,11 +1429,11 @@ function required2(value, name) {
1159
1429
  }
1160
1430
  function registerCompactCapabilities(server, client2, wrap) {
1161
1431
  function register(name, description, inputSchema, annotations, handler) {
1162
- server.registerTool(name, { description, inputSchema: withClientRoutingSchema(inputSchema), outputSchema: toolOutputSchemas[name], annotations }, wrap(name, handler, toolOutputSchemas[name]));
1432
+ server.registerTool(name, { description, inputSchema: captureMcpInputSchema(server, name, withClientRoutingSchema(inputSchema)), outputSchema: toolOutputSchemas[name], annotations }, wrap(name, handler, toolOutputSchemas[name]));
1163
1433
  }
1164
1434
  register("find_documents", "Find readable documents in the active scope. Use mode=list for paginated browsing by folder or tag UUID; use mode=search for hybrid text and semantic retrieval with tag names.", z4.discriminatedUnion("mode", [
1165
- z4.strictObject({ mode: z4.literal("list").describe("Select the list operation explicitly."), folderId: uuid2.optional(), tag: uuid2.optional(), page: z4.number().int().min(1).optional().describe("One-based page number; defaults to the API first page."), limit: z4.number().int().min(1).max(1000).optional().describe("Maximum documents per page, up to 1000.") }),
1166
- z4.strictObject({ mode: z4.literal("search").describe("Select the search operation explicitly."), query: text.describe("Text to search in the original language."), folder: z4.string().optional().describe("Optional folder UUID filter for search."), tags: z4.array(z4.string()).optional().describe("Optional tag names; all supplied names must match."), limit: z4.number().int().min(1).max(100).optional().describe("Maximum results to return, up to 100.") })
1435
+ z4.strictObject({ mode: z4.literal("list").describe("Select the list operation explicitly."), folderId: uuid2.optional(), categoryId: uuid2.optional().describe("Filter by effective category UUID, including inherited folder placement."), visibility: z4.enum(["private", "shared", "public"]).optional().describe("Optional document visibility filter; never expands access."), rootOnly: z4.boolean().optional().describe("Return only documents without a folder; cannot combine with folderId."), tag: uuid2.optional(), tagIds: z4.array(uuid2).min(1).optional().describe("Filter by tag UUIDs; cannot combine with the legacy tag field."), tagMatch: z4.enum(["all", "any"]).optional().describe("Require all supplied tags by default, or any supplied tag."), q: z4.string().optional().describe("Literal case-insensitive title/content filter; does not invoke semantic search."), updatedFrom: z4.iso.datetime({ offset: true }).optional().describe("Inclusive updated timestamp lower bound, with timezone."), updatedTo: z4.iso.datetime({ offset: true }).optional().describe("Exclusive updated timestamp upper bound, with timezone."), sortBy: z4.enum(["updatedAt", "createdAt", "title"]).optional().describe("Stable server-side sort field; defaults to updatedAt."), sortOrder: z4.enum(["asc", "desc"]).optional().describe("Sort direction, descending by default with an ID tie-breaker."), page: z4.number().int().min(1).optional().describe("One-based page number; defaults to the API first page."), limit: z4.number().int().min(1).max(1000).optional().describe("Maximum documents per page, up to 1000.") }),
1436
+ z4.strictObject({ mode: z4.literal("search").describe("Select the search operation explicitly."), query: text.describe("Text to search in the original language."), includeDiagnostics: z4.boolean().optional().describe("Include redacted diagnostic details; omitted by default."), includeChunks: z4.boolean().optional().describe("Include matching text chunks only when requested."), folder: z4.string().optional().describe("Optional folder UUID filter for search."), tags: z4.array(z4.string()).optional().describe("Optional tag names; all supplied names must match."), limit: z4.number().int().min(1).max(100).optional().describe("Maximum results to return, up to 100.") })
1167
1437
  ]), read, async (input) => input.mode === "list" ? { operation: "list", result: await client2.listDocuments(input) } : { operation: "search", result: await client2.search(input) });
1168
1438
  register("read_document", "Read one document by UUID. Choose detail for content and metadata, markdown for portable export, or versions for saved revisions and snapshots. All views are read-only.", z4.discriminatedUnion("view", [
1169
1439
  z4.strictObject({ view: z4.literal("detail").describe("Select the detail operation explicitly."), id: uuid2 }),
@@ -1381,9 +1651,181 @@ var capabilityCatalog = {
1381
1651
  "docsmint://workspace/catalog"
1382
1652
  ]
1383
1653
  };
1654
+ // ../mcp-server/src/catalog.ts
1655
+ import {
1656
+ InMemoryTransport
1657
+ } from "@modelcontextprotocol/server";
1658
+ function object2(value) {
1659
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
1660
+ }
1661
+ function example(schema) {
1662
+ if ("const" in schema)
1663
+ return schema.const;
1664
+ if (Array.isArray(schema.enum))
1665
+ return schema.enum[0];
1666
+ if (Array.isArray(schema.anyOf))
1667
+ return example(object2(schema.anyOf[0]));
1668
+ if (schema.type === "null")
1669
+ return null;
1670
+ if (schema.type === "boolean")
1671
+ return false;
1672
+ if (schema.type === "number" || schema.type === "integer")
1673
+ return Math.max(1, Number(schema.minimum ?? 1));
1674
+ if (schema.type === "array")
1675
+ return [example(object2(schema.items))];
1676
+ if (schema.type === "object" || schema.properties) {
1677
+ 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
+ }
1679
+ if (schema.format === "uuid")
1680
+ return "11111111-1111-4111-8111-111111111111";
1681
+ if (schema.format === "date-time")
1682
+ return "2026-01-01T00:00:00.000Z";
1683
+ return "Example";
1684
+ }
1685
+ async function generateDocsmintMcpCatalog() {
1686
+ const docsClient = new DocsClient({
1687
+ baseUrl: "https://catalog.invalid",
1688
+ retries: 1,
1689
+ fetch: async () => {
1690
+ throw new Error("Catalog generation must not access document storage");
1691
+ }
1692
+ });
1693
+ const server = createDocsmintMcpServer({ docsClient });
1694
+ const [peer, transport] = InMemoryTransport.createLinkedPair();
1695
+ let id = 0;
1696
+ const waiting = new Map;
1697
+ peer.onmessage = (message) => {
1698
+ if (!("id" in message) || typeof message.id !== "number")
1699
+ return;
1700
+ const pending = waiting.get(message.id);
1701
+ if (!pending)
1702
+ return;
1703
+ waiting.delete(message.id);
1704
+ if ("error" in message)
1705
+ pending.reject(new Error("MCP catalog discovery failed"));
1706
+ else if ("result" in message)
1707
+ pending.resolve(object2(message.result));
1708
+ };
1709
+ async function rpc(method, params = {}) {
1710
+ const requestId = ++id;
1711
+ const result = new Promise((resolve, reject) => waiting.set(requestId, { resolve, reject }));
1712
+ await peer.send({ jsonrpc: "2.0", id: requestId, method, params });
1713
+ return result;
1714
+ }
1715
+ async function collect(method, field) {
1716
+ const values = [];
1717
+ const seen = new Set;
1718
+ let cursor;
1719
+ do {
1720
+ const page = await rpc(method, cursor ? { cursor } : {});
1721
+ if (!Array.isArray(page[field]))
1722
+ throw new Error(`Invalid ${method} discovery result`);
1723
+ values.push(...page[field]);
1724
+ cursor = typeof page.nextCursor === "string" ? page.nextCursor : undefined;
1725
+ if (cursor && seen.has(cursor))
1726
+ throw new Error(`Repeated ${method} discovery cursor`);
1727
+ if (cursor)
1728
+ seen.add(cursor);
1729
+ } while (cursor);
1730
+ return values;
1731
+ }
1732
+ try {
1733
+ await Promise.all([peer.start(), server.connect(transport)]);
1734
+ const initialized = await rpc("initialize", {
1735
+ protocolVersion: "2025-06-18",
1736
+ capabilities: {},
1737
+ clientInfo: { name: "docsmint-catalog-generator", version: "1" }
1738
+ });
1739
+ await peer.send({ jsonrpc: "2.0", method: "notifications/initialized" });
1740
+ const tools = await collect("tools/list", "tools");
1741
+ const prompts = await collect("prompts/list", "prompts");
1742
+ const resources = await collect("resources/list", "resources");
1743
+ const info = object2(initialized.serverInfo);
1744
+ if (typeof info.name !== "string" || typeof info.version !== "string")
1745
+ throw new Error("Missing MCP server identity");
1746
+ return {
1747
+ server: { name: info.name, version: info.version },
1748
+ tools: tools.map((tool) => {
1749
+ const schema = object2(tool.inputSchema);
1750
+ const branches = Array.isArray(schema.oneOf) ? schema.oneOf : [schema];
1751
+ return {
1752
+ ...tool,
1753
+ examples: branches.map((branch) => object2(example(object2(branch))))
1754
+ };
1755
+ }),
1756
+ prompts,
1757
+ resources
1758
+ };
1759
+ } finally {
1760
+ await peer.close();
1761
+ await server.close();
1762
+ }
1763
+ }
1764
+ // ../mcp-server/src/http.ts
1765
+ import { AsyncLocalStorage } from "async_hooks";
1766
+ import { createMcpHandler } from "@modelcontextprotocol/server";
1767
+ function createDocsmintMcpHttpHandler(options) {
1768
+ const servers = new AsyncLocalStorage;
1769
+ const transport = createMcpHandler(async () => {
1770
+ const server = servers.getStore();
1771
+ if (!server)
1772
+ throw new Error("MCP request context unavailable");
1773
+ return server;
1774
+ }, { legacy: "stateless", responseMode: "json", onerror: options.onerror });
1775
+ return {
1776
+ close: () => transport.close(),
1777
+ async fetch(request) {
1778
+ const canonical2 = new URL(request.url);
1779
+ if (canonical2.pathname.endsWith("/mcp/")) {
1780
+ canonical2.pathname = canonical2.pathname.slice(0, -1);
1781
+ request = new Request(canonical2, request);
1782
+ }
1783
+ const origin = request.headers.get("origin");
1784
+ const allowed = !origin || options.allowedOrigins.includes(origin);
1785
+ const cors = new Headers({ Vary: "Origin" });
1786
+ if (origin && allowed)
1787
+ cors.set("Access-Control-Allow-Origin", origin);
1788
+ function finish(response) {
1789
+ const headers = new Headers(response.headers);
1790
+ headers.set("Vary", [headers.get("Vary"), "Origin"].filter(Boolean).join(", "));
1791
+ for (const [name, value] of cors)
1792
+ if (name !== "vary")
1793
+ headers.set(name, value);
1794
+ return new Response(response.body, {
1795
+ status: response.status,
1796
+ statusText: response.statusText,
1797
+ headers
1798
+ });
1799
+ }
1800
+ if (options.enabled === false)
1801
+ return finish(new Response(null, { status: 404 }));
1802
+ if (!allowed)
1803
+ return finish(Response.json({ error: "Origin not allowed" }, { status: 403 }));
1804
+ if (request.method === "OPTIONS") {
1805
+ cors.set("Access-Control-Allow-Methods", "POST, OPTIONS");
1806
+ cors.set("Access-Control-Allow-Headers", "Authorization, Content-Type, MCP-Protocol-Version, X-Docsmint-Workspace");
1807
+ return new Response(null, { status: 204, headers: cors });
1808
+ }
1809
+ if (request.method !== "POST")
1810
+ return finish(new Response(null, {
1811
+ status: 405,
1812
+ headers: { Allow: "POST, OPTIONS" }
1813
+ }));
1814
+ try {
1815
+ const server = await options.createServer(request);
1816
+ if (server instanceof Response)
1817
+ return finish(server);
1818
+ return finish(await servers.run(server, () => transport.fetch(request)));
1819
+ } catch (error) {
1820
+ options.onerror?.(error instanceof Error ? error : new Error("MCP transport failure"));
1821
+ return finish(Response.json({ error: "MCP transport failure" }, { status: 500 }));
1822
+ }
1823
+ }
1824
+ };
1825
+ }
1384
1826
 
1385
1827
  // ../mcp-server/src/server.ts
1386
- function wrapHandler(name, handler, outputSchema, workspaceRouting) {
1828
+ function wrapHandler(name, handler, outputSchema, workspaceRouting, decorateResult) {
1387
1829
  return async (args) => {
1388
1830
  try {
1389
1831
  const { workspaceId, ...data } = args;
@@ -1401,12 +1843,15 @@ function wrapHandler(name, handler, outputSchema, workspaceRouting) {
1401
1843
  } else {
1402
1844
  output = await handler(data);
1403
1845
  }
1846
+ if (decorateResult)
1847
+ output = await decorateResult(name, output);
1404
1848
  const parsedOutput = outputSchema ? await outputSchema.safeParseAsync(output) : undefined;
1405
1849
  if (parsedOutput && !parsedOutput.success) {
1406
1850
  throw new Error(`Tool '${name}' returned a result outside its published output schema`);
1407
1851
  }
1852
+ const result = parsedOutput?.success ? parsedOutput.data : output;
1408
1853
  return {
1409
- content: [{ type: "text", text: JSON.stringify(output, null, 2) }],
1854
+ content: [{ type: "text", text: JSON.stringify(result) }],
1410
1855
  ...parsedOutput?.success ? { structuredContent: parsedOutput.data } : {}
1411
1856
  };
1412
1857
  } catch (error) {
@@ -1434,20 +1879,22 @@ function wrapHandler(name, handler, outputSchema, workspaceRouting) {
1434
1879
  }
1435
1880
  };
1436
1881
  }
1437
- function registerDocsmintMcpCapabilities(server, client2, workspaceRouting) {
1438
- const wrap = (name, handler, outputSchema) => wrapHandler(name, handler, outputSchema, workspaceRouting);
1882
+ function registerDocsmintMcpCapabilities(server, client2, workspaceRouting, decorateResult) {
1883
+ const wrap = (name, handler, outputSchema) => wrapHandler(name, handler, outputSchema, workspaceRouting, decorateResult);
1439
1884
  registerCompactCapabilities(server, client2, wrap);
1440
1885
  registerPromptsAndResources(server, client2);
1441
1886
  }
1442
1887
  function createDocsmintMcpServer(options = {}) {
1443
- const server = new McpServer({ name: "docsmint", version: "2.0.3" });
1888
+ const server = new DocsMintMcpServer({ name: "docsmint", version: "2.1.0" });
1444
1889
  const client2 = options.docsClient ? createMcpDocsClient(options.docsClient, options.requestContext) : options.client ?? createMcpDocsClient(createDefaultDocsClient(), options.requestContext);
1445
- registerDocsmintMcpCapabilities(server, client2, options.workspaceRouting);
1890
+ registerDocsmintMcpCapabilities(server, client2, options.workspaceRouting, options.decorateResult);
1446
1891
  return server;
1447
1892
  }
1448
1893
  export {
1449
1894
  capabilityCatalog,
1895
+ createDocsmintMcpHttpHandler,
1450
1896
  createDocsmintMcpServer,
1451
1897
  createMcpScopedResult,
1898
+ generateDocsmintMcpCatalog,
1452
1899
  registerDocsmintMcpCapabilities
1453
1900
  };