@milaboratories/pl-mcp-server 53.1.0 → 55.0.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 (208) hide show
  1. package/README.md +30 -37
  2. package/dist/_virtual/_rolldown/runtime.cjs +22 -0
  3. package/dist/agent-tables.cjs +116 -0
  4. package/dist/agent-tables.cjs.map +1 -0
  5. package/dist/agent-tables.js +115 -0
  6. package/dist/agent-tables.js.map +1 -0
  7. package/dist/instructions.cjs +16 -12
  8. package/dist/instructions.cjs.map +1 -1
  9. package/dist/instructions.js +16 -12
  10. package/dist/instructions.js.map +1 -1
  11. package/dist/package.cjs +1 -1
  12. package/dist/package.js +1 -1
  13. package/dist/project-holds.cjs +122 -0
  14. package/dist/project-holds.cjs.map +1 -0
  15. package/dist/project-holds.js +122 -0
  16. package/dist/project-holds.js.map +1 -0
  17. package/dist/project-list.cjs +16 -0
  18. package/dist/project-list.cjs.map +1 -0
  19. package/dist/project-list.js +16 -0
  20. package/dist/project-list.js.map +1 -0
  21. package/dist/server-log.cjs +48 -18
  22. package/dist/server-log.cjs.map +1 -1
  23. package/dist/server-log.js +48 -19
  24. package/dist/server-log.js.map +1 -1
  25. package/dist/server.cjs +71 -18
  26. package/dist/server.cjs.map +1 -1
  27. package/dist/server.d.ts +37 -24
  28. package/dist/server.d.ts.map +1 -1
  29. package/dist/server.js +71 -19
  30. package/dist/server.js.map +1 -1
  31. package/dist/tools/agent-tables.cjs +424 -0
  32. package/dist/tools/agent-tables.cjs.map +1 -0
  33. package/dist/tools/agent-tables.js +417 -0
  34. package/dist/tools/agent-tables.js.map +1 -0
  35. package/dist/tools/await.cjs +216 -72
  36. package/dist/tools/await.cjs.map +1 -1
  37. package/dist/tools/await.js +212 -74
  38. package/dist/tools/await.js.map +1 -1
  39. package/dist/tools/block-action-context.cjs +14 -9
  40. package/dist/tools/block-action-context.cjs.map +1 -1
  41. package/dist/tools/block-action-context.js +14 -9
  42. package/dist/tools/block-action-context.js.map +1 -1
  43. package/dist/tools/block-api.cjs +17 -2
  44. package/dist/tools/block-api.cjs.map +1 -1
  45. package/dist/tools/block-api.js +17 -3
  46. package/dist/tools/block-api.js.map +1 -1
  47. package/dist/tools/block-params.cjs +275 -6
  48. package/dist/tools/block-params.cjs.map +1 -1
  49. package/dist/tools/block-params.js +273 -8
  50. package/dist/tools/block-params.js.map +1 -1
  51. package/dist/tools/block-state.cjs +343 -57
  52. package/dist/tools/block-state.cjs.map +1 -1
  53. package/dist/tools/block-state.js +337 -61
  54. package/dist/tools/block-state.js.map +1 -1
  55. package/dist/tools/block-storage.cjs +153 -0
  56. package/dist/tools/block-storage.cjs.map +1 -0
  57. package/dist/tools/block-storage.js +147 -0
  58. package/dist/tools/block-storage.js.map +1 -0
  59. package/dist/tools/block-updates.cjs +405 -0
  60. package/dist/tools/block-updates.cjs.map +1 -0
  61. package/dist/tools/block-updates.js +397 -0
  62. package/dist/tools/block-updates.js.map +1 -0
  63. package/dist/tools/blocks.cjs +199 -76
  64. package/dist/tools/blocks.cjs.map +1 -1
  65. package/dist/tools/blocks.js +193 -76
  66. package/dist/tools/blocks.js.map +1 -1
  67. package/dist/tools/data-query.cjs +470 -101
  68. package/dist/tools/data-query.cjs.map +1 -1
  69. package/dist/tools/data-query.js +465 -106
  70. package/dist/tools/data-query.js.map +1 -1
  71. package/dist/tools/errors.cjs +21 -0
  72. package/dist/tools/errors.cjs.map +1 -0
  73. package/dist/tools/errors.js +20 -0
  74. package/dist/tools/errors.js.map +1 -0
  75. package/dist/tools/files.cjs +643 -0
  76. package/dist/tools/files.cjs.map +1 -0
  77. package/dist/tools/files.js +613 -0
  78. package/dist/tools/files.js.map +1 -0
  79. package/dist/tools/ids.cjs +72 -0
  80. package/dist/tools/ids.cjs.map +1 -1
  81. package/dist/tools/ids.js +63 -2
  82. package/dist/tools/ids.js.map +1 -1
  83. package/dist/tools/imports.cjs +195 -0
  84. package/dist/tools/imports.cjs.map +1 -0
  85. package/dist/tools/imports.js +186 -0
  86. package/dist/tools/imports.js.map +1 -0
  87. package/dist/tools/logs.cjs +111 -30
  88. package/dist/tools/logs.cjs.map +1 -1
  89. package/dist/tools/logs.js +108 -31
  90. package/dist/tools/logs.js.map +1 -1
  91. package/dist/tools/paging.cjs +27 -0
  92. package/dist/tools/paging.cjs.map +1 -0
  93. package/dist/tools/paging.js +26 -0
  94. package/dist/tools/paging.js.map +1 -0
  95. package/dist/tools/params-merge.cjs +106 -0
  96. package/dist/tools/params-merge.cjs.map +1 -0
  97. package/dist/tools/params-merge.js +106 -0
  98. package/dist/tools/params-merge.js.map +1 -0
  99. package/dist/tools/project-template.cjs +75 -0
  100. package/dist/tools/project-template.cjs.map +1 -0
  101. package/dist/tools/project-template.js +72 -0
  102. package/dist/tools/project-template.js.map +1 -0
  103. package/dist/tools/projects.cjs +68 -38
  104. package/dist/tools/projects.cjs.map +1 -1
  105. package/dist/tools/projects.js +69 -40
  106. package/dist/tools/projects.js.map +1 -1
  107. package/dist/tools/readiness.cjs +104 -0
  108. package/dist/tools/readiness.cjs.map +1 -0
  109. package/dist/tools/readiness.js +99 -0
  110. package/dist/tools/readiness.js.map +1 -0
  111. package/dist/tools/result-pool.cjs +260 -0
  112. package/dist/tools/result-pool.cjs.map +1 -0
  113. package/dist/tools/result-pool.js +252 -0
  114. package/dist/tools/result-pool.js.map +1 -0
  115. package/dist/tools/sandbox.cjs +112 -14
  116. package/dist/tools/sandbox.cjs.map +1 -1
  117. package/dist/tools/sandbox.js +110 -15
  118. package/dist/tools/sandbox.js.map +1 -1
  119. package/dist/tools/sdk-types.cjs +24 -0
  120. package/dist/tools/sdk-types.cjs.map +1 -0
  121. package/dist/tools/sdk-types.js +24 -0
  122. package/dist/tools/sdk-types.js.map +1 -0
  123. package/dist/tools/settle.cjs +155 -0
  124. package/dist/tools/settle.cjs.map +1 -0
  125. package/dist/tools/settle.js +148 -0
  126. package/dist/tools/settle.js.map +1 -0
  127. package/dist/tools/tokens.cjs +49 -8
  128. package/dist/tools/tokens.cjs.map +1 -1
  129. package/dist/tools/tokens.js +45 -9
  130. package/dist/tools/tokens.js.map +1 -1
  131. package/dist/tools/types.cjs +62 -11
  132. package/dist/tools/types.cjs.map +1 -1
  133. package/dist/tools/types.js +60 -12
  134. package/dist/tools/types.js.map +1 -1
  135. package/dist/tools/value-outline.cjs +119 -0
  136. package/dist/tools/value-outline.cjs.map +1 -0
  137. package/dist/tools/value-outline.js +117 -0
  138. package/dist/tools/value-outline.js.map +1 -0
  139. package/package.json +9 -8
  140. package/src/agent-tables.test.ts +246 -0
  141. package/src/agent-tables.ts +145 -0
  142. package/src/instructions.ts +16 -12
  143. package/src/project-holds.test.ts +362 -0
  144. package/src/project-holds.ts +207 -0
  145. package/src/project-list.test.ts +38 -0
  146. package/src/project-list.ts +25 -0
  147. package/src/server-log.test.ts +71 -6
  148. package/src/server-log.ts +58 -27
  149. package/src/server.logging.test.ts +46 -51
  150. package/src/server.test.ts +166 -22
  151. package/src/server.ts +97 -37
  152. package/src/tools/agent-tables.test.ts +650 -0
  153. package/src/tools/agent-tables.ts +673 -0
  154. package/src/tools/await.test.ts +287 -0
  155. package/src/tools/await.ts +393 -122
  156. package/src/tools/block-action-context.ts +17 -13
  157. package/src/tools/block-api.ts +19 -4
  158. package/src/tools/block-params.test.ts +828 -0
  159. package/src/tools/block-params.ts +626 -10
  160. package/src/tools/block-state.test.ts +480 -0
  161. package/src/tools/block-state.ts +678 -83
  162. package/src/tools/block-storage.test.ts +270 -0
  163. package/src/tools/block-storage.ts +195 -0
  164. package/src/tools/block-updates.test.ts +605 -0
  165. package/src/tools/block-updates.ts +751 -0
  166. package/src/tools/blocks.test.ts +169 -22
  167. package/src/tools/blocks.ts +354 -113
  168. package/src/tools/data-query.test.ts +641 -0
  169. package/src/tools/data-query.ts +839 -145
  170. package/src/tools/errors.test.ts +33 -0
  171. package/src/tools/errors.ts +23 -0
  172. package/src/tools/files.test.ts +842 -0
  173. package/src/tools/files.ts +990 -0
  174. package/src/tools/ids.test.ts +87 -0
  175. package/src/tools/ids.ts +89 -1
  176. package/src/tools/imports.ts +304 -0
  177. package/src/tools/logs.test.ts +70 -0
  178. package/src/tools/logs.ts +154 -44
  179. package/src/tools/paging.test.ts +39 -0
  180. package/src/tools/paging.ts +39 -0
  181. package/src/tools/params-merge.test.ts +274 -0
  182. package/src/tools/params-merge.ts +149 -0
  183. package/src/tools/project-template.test.ts +230 -0
  184. package/src/tools/project-template.ts +135 -0
  185. package/src/tools/projects.test.ts +122 -0
  186. package/src/tools/projects.ts +136 -48
  187. package/src/tools/readiness.test.ts +195 -0
  188. package/src/tools/readiness.ts +189 -0
  189. package/src/tools/result-pool.test.ts +377 -0
  190. package/src/tools/result-pool.ts +483 -0
  191. package/src/tools/sandbox.test.ts +128 -10
  192. package/src/tools/sandbox.ts +132 -18
  193. package/src/tools/sdk-types.ts +54 -0
  194. package/src/tools/settle.test.ts +340 -0
  195. package/src/tools/settle.ts +312 -0
  196. package/src/tools/tokens.ts +74 -9
  197. package/src/tools/types.ts +84 -12
  198. package/src/tools/value-outline.ts +143 -0
  199. package/dist/tools/screenshot.cjs +0 -44
  200. package/dist/tools/screenshot.cjs.map +0 -1
  201. package/dist/tools/screenshot.js +0 -44
  202. package/dist/tools/screenshot.js.map +0 -1
  203. package/dist/tools/ui-interaction.cjs +0 -140
  204. package/dist/tools/ui-interaction.cjs.map +0 -1
  205. package/dist/tools/ui-interaction.js +0 -140
  206. package/dist/tools/ui-interaction.js.map +0 -1
  207. package/src/tools/screenshot.ts +0 -61
  208. package/src/tools/ui-interaction.ts +0 -184
@@ -1,3 +1,4 @@
1
+ const require_value_outline = require("./value-outline.cjs");
1
2
  // src/tools/types.ts
2
3
  /**
3
4
  * Makes the author markers of one writer: every call returns a marker with `authorId` and the next
@@ -39,27 +40,74 @@ const hints = {
39
40
  destructiveHint: true,
40
41
  idempotentHint: true,
41
42
  openWorldHint: false
42
- },
43
- /** Acts on the application window or runs given code: the effect depends on what it hits. */
44
- unpredictable: {
45
- readOnlyHint: false,
46
- destructiveHint: true,
47
- idempotentHint: false,
48
- openWorldHint: false
49
43
  }
50
44
  };
51
- function textResult(data) {
45
+ /** How long one driver read of a tool (a table, a column's values, a file) may take. */
46
+ const READ_TIMEOUT_MS = 6e4;
47
+ /** The signal of one driver read: the tool call's, and {@link READ_TIMEOUT_MS}. */
48
+ function readSignal(callSignal) {
49
+ const timeout = AbortSignal.timeout(READ_TIMEOUT_MS);
50
+ return callSignal === void 0 ? timeout : AbortSignal.any([callSignal, timeout]);
51
+ }
52
+ /** The most characters the text of a tool result may have. */
53
+ const RESULT_CHAR_LIMIT = 6e4;
54
+ /** What a tool says when its result is over {@link RESULT_CHAR_LIMIT} and it has no better hint. */
55
+ const DEFAULT_OVER_LIMIT_HINT = "Ask for a part of it: use `transform` where the tool has one (get_block_state, await_block_done, query_table), or narrower arguments.";
56
+ /**
57
+ * Returns the result of a tool: `data` as JSON text. Every tool result goes through here, so two
58
+ * rules hold for all of them:
59
+ *
60
+ * - binary data is replaced by `{bytes: N}` (see {@link stripBytes}): it never helps an agent and
61
+ * its JSON is many times its size;
62
+ * - a result over {@link RESULT_CHAR_LIMIT} characters is replaced by an outline of it (keys, types
63
+ * and sizes, see {@link outlineValue}) with `hint`, saying how to ask for a part. It is not an
64
+ * error: the agent learns what is there and asks again.
65
+ */
66
+ function textResult(data, options = {}) {
67
+ const value = require_value_outline.stripBytes(data);
68
+ const text = JSON.stringify(value) ?? "null";
69
+ if (text.length <= 6e4) return { content: [{
70
+ type: "text",
71
+ text
72
+ }] };
52
73
  return { content: [{
53
74
  type: "text",
54
- text: JSON.stringify(data)
75
+ text: JSON.stringify(overLimitOutline(value, text.length, options.hint))
55
76
  }] };
56
77
  }
57
- /** Return an MCP error result with an actionable hint for the AI agent. */
78
+ /** What stands for a result over the limit; the outline loses depth until it fits. */
79
+ function overLimitOutline(value, chars, hint) {
80
+ const head = {
81
+ resultTooLarge: true,
82
+ chars,
83
+ limit: RESULT_CHAR_LIMIT,
84
+ note: "The result is over the size limit; this outline shows its keys, types and sizes (chars).",
85
+ hint: hint ?? DEFAULT_OVER_LIMIT_HINT
86
+ };
87
+ for (const maxDepth of [
88
+ 3,
89
+ 2,
90
+ 1,
91
+ 0
92
+ ]) {
93
+ const outlined = {
94
+ ...head,
95
+ outline: require_value_outline.outlineValue(value, { maxDepth })
96
+ };
97
+ if (require_value_outline.jsonChars(outlined) <= 6e4) return outlined;
98
+ }
99
+ return head;
100
+ }
101
+ /**
102
+ * Return an MCP error result with an actionable hint for the AI agent. The text is cut at
103
+ * {@link RESULT_CHAR_LIMIT} characters.
104
+ */
58
105
  function errorResult(message, hint) {
106
+ const full = hint ? `${message}\n\nHint: ${hint}` : message;
59
107
  return {
60
108
  content: [{
61
109
  type: "text",
62
- text: hint ? `${message}\n\nHint: ${hint}` : message
110
+ text: full.length <= 6e4 ? full : `${full.slice(0, 59960)}… [cut: ${full.length} chars in all]`
63
111
  }],
64
112
  isError: true
65
113
  };
@@ -90,10 +138,13 @@ function isTimedOutResult(result) {
90
138
  function transformFailedResult(error, hint) {
91
139
  return errorResult(`Transform failed: ${error instanceof Error ? error.message : String(error)}`, hint);
92
140
  }
141
+ exports.READ_TIMEOUT_MS = READ_TIMEOUT_MS;
142
+ exports.RESULT_CHAR_LIMIT = RESULT_CHAR_LIMIT;
93
143
  exports.authorMarkerSource = authorMarkerSource;
94
144
  exports.errorResult = errorResult;
95
145
  exports.hints = hints;
96
146
  exports.isTimedOutResult = isTimedOutResult;
147
+ exports.readSignal = readSignal;
97
148
  exports.textResult = textResult;
98
149
  exports.timedOutResult = timedOutResult;
99
150
  exports.transformFailedResult = transformFailedResult;
@@ -1 +1 @@
1
- {"version":3,"file":"types.cjs","names":[],"sources":["../../src/tools/types.ts"],"sourcesContent":["import type {\n AuthorMarker,\n MiddleLayer,\n Project,\n ProjectId,\n ProjectListEntry,\n} from \"@milaboratories/pl-middle-layer\";\nimport type {\n Icon,\n RegisteredTool,\n ScopeChallengeHandler,\n StandardSchemaWithJSON,\n ToolAnnotations,\n ToolCallback,\n} from \"@modelcontextprotocol/server\";\nimport type { McpInstanceId, PlMcpServerCallbacks } from \"../server\";\n\nexport type { AuthorMarker };\n\nexport interface ToolContext {\n getMl: () => MiddleLayer | null;\n requireMl: () => MiddleLayer;\n resolveProject: (projectId: ProjectId) => Promise<ProjectListEntry>;\n getOpenedProject: (projectId: ProjectId) => Promise<Project>;\n callbacks: PlMcpServerCallbacks;\n /**\n * Returns the marker for the next write made through MCP. All writes of one server instance carry\n * the same `authorId`, whichever client asked for them, and a `localVersion` that grows with\n * every call.\n */\n getAuthorMarker: () => AuthorMarker;\n}\n\n/**\n * What a tool is registered with: the `registerTool` of an `McpServer`, in its form that takes\n * schemas. The `register*Tools` functions get this and not the server, so that every tool they\n * register goes through whatever the server put around the registration (the call log).\n */\nexport interface ToolRegistrar {\n registerTool<\n OutputArgs extends StandardSchemaWithJSON,\n InputArgs extends StandardSchemaWithJSON | undefined = undefined,\n >(\n name: string,\n config: {\n title?: string;\n description?: string;\n inputSchema?: InputArgs;\n outputSchema?: OutputArgs;\n annotations?: ToolAnnotations;\n icons?: Icon[];\n scopeChallenge?: ScopeChallengeHandler;\n _meta?: Record<string, unknown>;\n },\n cb: ToolCallback<InputArgs>,\n ): RegisteredTool;\n}\n\n/**\n * Makes the author markers of one writer: every call returns a marker with `authorId` and the next\n * `localVersion`, counted from 1.\n */\nexport function authorMarkerSource(authorId: McpInstanceId): () => AuthorMarker {\n let localVersion = 0;\n return () => ({ authorId, localVersion: ++localVersion });\n}\n\n/**\n * The four behaviour hints of a tool, all stated. A client reads a missing hint as the worst case\n * (not read-only, destructive, not idempotent, open world), so no tool leaves one out.\n */\nexport type ToolHints = {\n /** The tool changes nothing. */\n readOnlyHint: boolean;\n /** The tool may replace or discard existing data or work, not only add to it. */\n destructiveHint: boolean;\n /** Calling the tool again with the same arguments changes nothing further. */\n idempotentHint: boolean;\n /** The tool reaches beyond the application and the backend it is connected to. */\n openWorldHint: boolean;\n};\n\n/** The hint sets tools choose from. A tool that fits none spreads the nearest one and overrides. */\nexport const hints = {\n /** Reads state; safe to call in parallel and to repeat. */\n read: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Adds something or starts something; a second call does it again. Loses nothing. */\n additive: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n /** Puts the application into a state; a second call changes nothing. Loses nothing. */\n idempotent: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Replaces or discards data, configuration or running work; a second call changes nothing more. */\n destructive: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Acts on the application window or runs given code: the effect depends on what it hits. */\n unpredictable: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n },\n} as const satisfies Record<string, ToolHints>;\n\nexport function textResult(data: unknown) {\n return {\n content: [{ type: \"text\" as const, text: JSON.stringify(data) }],\n };\n}\n\n/** Return an MCP error result with an actionable hint for the AI agent. */\nexport function errorResult(message: string, hint?: string) {\n const text = hint ? `${message}\\n\\nHint: ${hint}` : message;\n return {\n content: [{ type: \"text\" as const, text }],\n isError: true,\n };\n}\n\n/** The results made by {@link timedOutResult}. */\nconst timedOutResults = new WeakSet<object>();\n\n/**\n * Returns the result of a tool that waited for something and ran out of time: the JSON of `data`\n * with `timedOut: true` in front. It is not an error result, the caller is expected to wait again.\n * The server's log recognises such a result with {@link isTimedOutResult}.\n */\nexport function timedOutResult(data: Record<string, unknown>) {\n const result = textResult({ timedOut: true, ...data });\n timedOutResults.add(result);\n return result;\n}\n\n/** Whether `result` was made by {@link timedOutResult}. */\nexport function isTimedOutResult(result: unknown): boolean {\n return typeof result === \"object\" && result !== null && timedOutResults.has(result);\n}\n\n/**\n * Returns the error result of a tool whose `transform` failed: `Transform failed: ` and the whole\n * error, then `hint`. The agent needs the whole error to fix its expression.\n */\nexport function transformFailedResult(error: unknown, hint: string) {\n return errorResult(\n `Transform failed: ${error instanceof Error ? error.message : String(error)}`,\n hint,\n );\n}\n"],"mappings":";;;;;AA8DA,SAAgB,mBAAmB,UAA6C;CAC9E,IAAI,eAAe;CACnB,cAAc;EAAE;EAAU,cAAc,EAAE;CAAa;AACzD;;AAkBA,MAAa,QAAQ;;CAEnB,MAAM;EACJ,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,UAAU;EACR,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,YAAY;EACV,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,aAAa;EACX,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,eAAe;EACb,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;AACF;AAEA,SAAgB,WAAW,MAAe;CACxC,OAAO,EACL,SAAS,CAAC;EAAE,MAAM;EAAiB,MAAM,KAAK,UAAU,IAAI;CAAE,CAAC,EACjE;AACF;;AAGA,SAAgB,YAAY,SAAiB,MAAe;CAE1D,OAAO;EACL,SAAS,CAAC;GAAE,MAAM;GAAiB,MAFxB,OAAO,GAAG,QAAQ,YAAY,SAAS;EAEV,CAAC;EACzC,SAAS;CACX;AACF;;AAGA,MAAM,kCAAkB,IAAI,QAAgB;;;;;;AAO5C,SAAgB,eAAe,MAA+B;CAC5D,MAAM,SAAS,WAAW;EAAE,UAAU;EAAM,GAAG;CAAK,CAAC;CACrD,gBAAgB,IAAI,MAAM;CAC1B,OAAO;AACT;;AAGA,SAAgB,iBAAiB,QAA0B;CACzD,OAAO,OAAO,WAAW,YAAY,WAAW,QAAQ,gBAAgB,IAAI,MAAM;AACpF;;;;;AAMA,SAAgB,sBAAsB,OAAgB,MAAc;CAClE,OAAO,YACL,qBAAqB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KAC1E,IACF;AACF"}
1
+ {"version":3,"file":"types.cjs","names":["stripBytes","outlineValue","jsonChars"],"sources":["../../src/tools/types.ts"],"sourcesContent":["import type {\n AuthorMarker,\n MiddleLayer,\n Project,\n ProjectHolder,\n ProjectId,\n ProjectListEntry,\n} from \"@milaboratories/pl-middle-layer\";\nimport type {\n Icon,\n RegisteredTool,\n ScopeChallengeHandler,\n StandardSchemaWithJSON,\n ToolAnnotations,\n ToolCallback,\n} from \"@modelcontextprotocol/server\";\nimport type { AgentTables } from \"../agent-tables\";\nimport type { McpInstanceId, PlMcpServerCallbacks } from \"../server\";\nimport { jsonChars, outlineValue, stripBytes } from \"./value-outline\";\n\nexport type { AuthorMarker };\n\nexport interface ToolContext {\n getMl: () => MiddleLayer | null;\n requireMl: () => MiddleLayer;\n resolveProject: (projectId: ProjectId) => Promise<ProjectListEntry>;\n /**\n * Runs `fn` on the project, loading it when it is not loaded. The server holds the project\n * while `fn` runs, so neither the application nor anyone else can unload it under the call.\n * `fn` is also given the middle layer the project is of, which the server took when the call\n * started: its drivers are the ones that know the project's handles.\n */\n withProject: <T>(\n projectId: ProjectId,\n fn: (project: Project, ml: MiddleLayer) => Promise<T>,\n ) => Promise<T>;\n /**\n * The tables agents built with create_table, by handle: reads find their project here, and\n * the server gives them back when they expire, are dropped or lose their project.\n */\n agentTables: AgentTables;\n /** The holder of this server's holds, as the middle layer's `projectHolders` lists them. */\n projectHolder: ProjectHolder;\n /** How many tool calls of this server are working on the project now. */\n callsInFlight: (projectId: ProjectId) => number;\n callbacks: PlMcpServerCallbacks;\n /**\n * Returns the marker for the next write made through MCP. All writes of one server instance carry\n * the same `authorId`, whichever client asked for them, and a `localVersion` that grows with\n * every call.\n */\n getAuthorMarker: () => AuthorMarker;\n}\n\n/**\n * What a tool is registered with: the `registerTool` of an `McpServer`, in its form that takes\n * schemas. The `register*Tools` functions get this and not the server, so that every tool they\n * register goes through whatever the server put around the registration (the call log).\n */\nexport interface ToolRegistrar {\n registerTool<\n OutputArgs extends StandardSchemaWithJSON,\n InputArgs extends StandardSchemaWithJSON | undefined = undefined,\n >(\n name: string,\n config: {\n title?: string;\n description?: string;\n inputSchema?: InputArgs;\n outputSchema?: OutputArgs;\n annotations?: ToolAnnotations;\n icons?: Icon[];\n scopeChallenge?: ScopeChallengeHandler;\n _meta?: Record<string, unknown>;\n },\n cb: ToolCallback<InputArgs>,\n ): RegisteredTool;\n}\n\n/**\n * Makes the author markers of one writer: every call returns a marker with `authorId` and the next\n * `localVersion`, counted from 1.\n */\nexport function authorMarkerSource(authorId: McpInstanceId): () => AuthorMarker {\n let localVersion = 0;\n return () => ({ authorId, localVersion: ++localVersion });\n}\n\n/**\n * The four behaviour hints of a tool, all stated. A client reads a missing hint as the worst case\n * (not read-only, destructive, not idempotent, open world), so no tool leaves one out.\n */\nexport type ToolHints = {\n /** The tool changes nothing. */\n readOnlyHint: boolean;\n /** The tool may replace or discard existing data or work, not only add to it. */\n destructiveHint: boolean;\n /** Calling the tool again with the same arguments changes nothing further. */\n idempotentHint: boolean;\n /** The tool reaches beyond the application and the backend it is connected to. */\n openWorldHint: boolean;\n};\n\n/** The hint sets tools choose from. A tool that fits none spreads the nearest one and overrides. */\nexport const hints = {\n /** Reads state; safe to call in parallel and to repeat. */\n read: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Adds something or starts something; a second call does it again. Loses nothing. */\n additive: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n /** Puts the application into a state; a second call changes nothing. Loses nothing. */\n idempotent: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Replaces or discards data, configuration or running work; a second call changes nothing more. */\n destructive: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n} as const satisfies Record<string, ToolHints>;\n\n/** How long one driver read of a tool (a table, a column's values, a file) may take. */\nexport const READ_TIMEOUT_MS = 60_000;\n\n/** The signal of one driver read: the tool call's, and {@link READ_TIMEOUT_MS}. */\nexport function readSignal(callSignal: AbortSignal | undefined): AbortSignal {\n const timeout = AbortSignal.timeout(READ_TIMEOUT_MS);\n return callSignal === undefined ? timeout : AbortSignal.any([callSignal, timeout]);\n}\n\n/** The most characters the text of a tool result may have. */\nexport const RESULT_CHAR_LIMIT = 60_000;\n\n/** What a tool says when its result is over {@link RESULT_CHAR_LIMIT} and it has no better hint. */\nconst DEFAULT_OVER_LIMIT_HINT =\n \"Ask for a part of it: use `transform` where the tool has one (get_block_state, \" +\n \"await_block_done, query_table), or narrower arguments.\";\n\n/**\n * Returns the result of a tool: `data` as JSON text. Every tool result goes through here, so two\n * rules hold for all of them:\n *\n * - binary data is replaced by `{bytes: N}` (see {@link stripBytes}): it never helps an agent and\n * its JSON is many times its size;\n * - a result over {@link RESULT_CHAR_LIMIT} characters is replaced by an outline of it (keys, types\n * and sizes, see {@link outlineValue}) with `hint`, saying how to ask for a part. It is not an\n * error: the agent learns what is there and asks again.\n */\nexport function textResult(data: unknown, options: { hint?: string } = {}) {\n const value = stripBytes(data);\n const text = JSON.stringify(value) ?? \"null\";\n if (text.length <= RESULT_CHAR_LIMIT) return { content: [{ type: \"text\" as const, text }] };\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(overLimitOutline(value, text.length, options.hint)),\n },\n ],\n };\n}\n\n/** What stands for a result over the limit; the outline loses depth until it fits. */\nfunction overLimitOutline(value: unknown, chars: number, hint: string | undefined) {\n const head = {\n resultTooLarge: true,\n chars,\n limit: RESULT_CHAR_LIMIT,\n note: \"The result is over the size limit; this outline shows its keys, types and sizes (chars).\",\n hint: hint ?? DEFAULT_OVER_LIMIT_HINT,\n };\n for (const maxDepth of [3, 2, 1, 0]) {\n const outlined = { ...head, outline: outlineValue(value, { maxDepth }) };\n if (jsonChars(outlined) <= RESULT_CHAR_LIMIT) return outlined;\n }\n return head;\n}\n\n/**\n * Return an MCP error result with an actionable hint for the AI agent. The text is cut at\n * {@link RESULT_CHAR_LIMIT} characters.\n */\nexport function errorResult(message: string, hint?: string) {\n const full = hint ? `${message}\\n\\nHint: ${hint}` : message;\n const text =\n full.length <= RESULT_CHAR_LIMIT\n ? full\n : `${full.slice(0, RESULT_CHAR_LIMIT - 40)}… [cut: ${full.length} chars in all]`;\n return {\n content: [{ type: \"text\" as const, text }],\n isError: true,\n };\n}\n\n/** The results made by {@link timedOutResult}. */\nconst timedOutResults = new WeakSet<object>();\n\n/**\n * Returns the result of a tool that waited for something and ran out of time: the JSON of `data`\n * with `timedOut: true` in front. It is not an error result, the caller is expected to wait again.\n * The server's log recognises such a result with {@link isTimedOutResult}.\n */\nexport function timedOutResult(data: Record<string, unknown>) {\n const result = textResult({ timedOut: true, ...data });\n timedOutResults.add(result);\n return result;\n}\n\n/** Whether `result` was made by {@link timedOutResult}. */\nexport function isTimedOutResult(result: unknown): boolean {\n return typeof result === \"object\" && result !== null && timedOutResults.has(result);\n}\n\n/**\n * Returns the error result of a tool whose `transform` failed: `Transform failed: ` and the whole\n * error, then `hint`. The agent needs the whole error to fix its expression.\n */\nexport function transformFailedResult(error: unknown, hint: string) {\n return errorResult(\n `Transform failed: ${error instanceof Error ? error.message : String(error)}`,\n hint,\n );\n}\n"],"mappings":";;;;;;AAmFA,SAAgB,mBAAmB,UAA6C;CAC9E,IAAI,eAAe;CACnB,cAAc;EAAE;EAAU,cAAc,EAAE;CAAa;AACzD;;AAkBA,MAAa,QAAQ;;CAEnB,MAAM;EACJ,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,UAAU;EACR,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,YAAY;EACV,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,aAAa;EACX,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;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gB,eAAe,MAA+B;CAC5D,MAAM,SAAS,WAAW;EAAE,UAAU;EAAM,GAAG;CAAK,CAAC;CACrD,gBAAgB,IAAI,MAAM;CAC1B,OAAO;AACT;;AAGA,SAAgB,iBAAiB,QAA0B;CACzD,OAAO,OAAO,WAAW,YAAY,WAAW,QAAQ,gBAAgB,IAAI,MAAM;AACpF;;;;;AAMA,SAAgB,sBAAsB,OAAgB,MAAc;CAClE,OAAO,YACL,qBAAqB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KAC1E,IACF;AACF"}
@@ -1,3 +1,4 @@
1
+ import { jsonChars, outlineValue, stripBytes } from "./value-outline.js";
1
2
  // src/tools/types.ts
2
3
  /**
3
4
  * Makes the author markers of one writer: every call returns a marker with `authorId` and the next
@@ -39,27 +40,74 @@ const hints = {
39
40
  destructiveHint: true,
40
41
  idempotentHint: true,
41
42
  openWorldHint: false
42
- },
43
- /** Acts on the application window or runs given code: the effect depends on what it hits. */
44
- unpredictable: {
45
- readOnlyHint: false,
46
- destructiveHint: true,
47
- idempotentHint: false,
48
- openWorldHint: false
49
43
  }
50
44
  };
51
- function textResult(data) {
45
+ /** How long one driver read of a tool (a table, a column's values, a file) may take. */
46
+ const READ_TIMEOUT_MS = 6e4;
47
+ /** The signal of one driver read: the tool call's, and {@link READ_TIMEOUT_MS}. */
48
+ function readSignal(callSignal) {
49
+ const timeout = AbortSignal.timeout(READ_TIMEOUT_MS);
50
+ return callSignal === void 0 ? timeout : AbortSignal.any([callSignal, timeout]);
51
+ }
52
+ /** The most characters the text of a tool result may have. */
53
+ const RESULT_CHAR_LIMIT = 6e4;
54
+ /** What a tool says when its result is over {@link RESULT_CHAR_LIMIT} and it has no better hint. */
55
+ const DEFAULT_OVER_LIMIT_HINT = "Ask for a part of it: use `transform` where the tool has one (get_block_state, await_block_done, query_table), or narrower arguments.";
56
+ /**
57
+ * Returns the result of a tool: `data` as JSON text. Every tool result goes through here, so two
58
+ * rules hold for all of them:
59
+ *
60
+ * - binary data is replaced by `{bytes: N}` (see {@link stripBytes}): it never helps an agent and
61
+ * its JSON is many times its size;
62
+ * - a result over {@link RESULT_CHAR_LIMIT} characters is replaced by an outline of it (keys, types
63
+ * and sizes, see {@link outlineValue}) with `hint`, saying how to ask for a part. It is not an
64
+ * error: the agent learns what is there and asks again.
65
+ */
66
+ function textResult(data, options = {}) {
67
+ const value = stripBytes(data);
68
+ const text = JSON.stringify(value) ?? "null";
69
+ if (text.length <= 6e4) return { content: [{
70
+ type: "text",
71
+ text
72
+ }] };
52
73
  return { content: [{
53
74
  type: "text",
54
- text: JSON.stringify(data)
75
+ text: JSON.stringify(overLimitOutline(value, text.length, options.hint))
55
76
  }] };
56
77
  }
57
- /** Return an MCP error result with an actionable hint for the AI agent. */
78
+ /** What stands for a result over the limit; the outline loses depth until it fits. */
79
+ function overLimitOutline(value, chars, hint) {
80
+ const head = {
81
+ resultTooLarge: true,
82
+ chars,
83
+ limit: RESULT_CHAR_LIMIT,
84
+ note: "The result is over the size limit; this outline shows its keys, types and sizes (chars).",
85
+ hint: hint ?? DEFAULT_OVER_LIMIT_HINT
86
+ };
87
+ for (const maxDepth of [
88
+ 3,
89
+ 2,
90
+ 1,
91
+ 0
92
+ ]) {
93
+ const outlined = {
94
+ ...head,
95
+ outline: outlineValue(value, { maxDepth })
96
+ };
97
+ if (jsonChars(outlined) <= 6e4) return outlined;
98
+ }
99
+ return head;
100
+ }
101
+ /**
102
+ * Return an MCP error result with an actionable hint for the AI agent. The text is cut at
103
+ * {@link RESULT_CHAR_LIMIT} characters.
104
+ */
58
105
  function errorResult(message, hint) {
106
+ const full = hint ? `${message}\n\nHint: ${hint}` : message;
59
107
  return {
60
108
  content: [{
61
109
  type: "text",
62
- text: hint ? `${message}\n\nHint: ${hint}` : message
110
+ text: full.length <= 6e4 ? full : `${full.slice(0, 59960)}… [cut: ${full.length} chars in all]`
63
111
  }],
64
112
  isError: true
65
113
  };
@@ -90,6 +138,6 @@ function isTimedOutResult(result) {
90
138
  function transformFailedResult(error, hint) {
91
139
  return errorResult(`Transform failed: ${error instanceof Error ? error.message : String(error)}`, hint);
92
140
  }
93
- export { authorMarkerSource, errorResult, hints, isTimedOutResult, textResult, timedOutResult, transformFailedResult };
141
+ export { READ_TIMEOUT_MS, RESULT_CHAR_LIMIT, authorMarkerSource, errorResult, hints, isTimedOutResult, readSignal, textResult, timedOutResult, transformFailedResult };
94
142
 
95
143
  //# sourceMappingURL=types.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":[],"sources":["../../src/tools/types.ts"],"sourcesContent":["import type {\n AuthorMarker,\n MiddleLayer,\n Project,\n ProjectId,\n ProjectListEntry,\n} from \"@milaboratories/pl-middle-layer\";\nimport type {\n Icon,\n RegisteredTool,\n ScopeChallengeHandler,\n StandardSchemaWithJSON,\n ToolAnnotations,\n ToolCallback,\n} from \"@modelcontextprotocol/server\";\nimport type { McpInstanceId, PlMcpServerCallbacks } from \"../server\";\n\nexport type { AuthorMarker };\n\nexport interface ToolContext {\n getMl: () => MiddleLayer | null;\n requireMl: () => MiddleLayer;\n resolveProject: (projectId: ProjectId) => Promise<ProjectListEntry>;\n getOpenedProject: (projectId: ProjectId) => Promise<Project>;\n callbacks: PlMcpServerCallbacks;\n /**\n * Returns the marker for the next write made through MCP. All writes of one server instance carry\n * the same `authorId`, whichever client asked for them, and a `localVersion` that grows with\n * every call.\n */\n getAuthorMarker: () => AuthorMarker;\n}\n\n/**\n * What a tool is registered with: the `registerTool` of an `McpServer`, in its form that takes\n * schemas. The `register*Tools` functions get this and not the server, so that every tool they\n * register goes through whatever the server put around the registration (the call log).\n */\nexport interface ToolRegistrar {\n registerTool<\n OutputArgs extends StandardSchemaWithJSON,\n InputArgs extends StandardSchemaWithJSON | undefined = undefined,\n >(\n name: string,\n config: {\n title?: string;\n description?: string;\n inputSchema?: InputArgs;\n outputSchema?: OutputArgs;\n annotations?: ToolAnnotations;\n icons?: Icon[];\n scopeChallenge?: ScopeChallengeHandler;\n _meta?: Record<string, unknown>;\n },\n cb: ToolCallback<InputArgs>,\n ): RegisteredTool;\n}\n\n/**\n * Makes the author markers of one writer: every call returns a marker with `authorId` and the next\n * `localVersion`, counted from 1.\n */\nexport function authorMarkerSource(authorId: McpInstanceId): () => AuthorMarker {\n let localVersion = 0;\n return () => ({ authorId, localVersion: ++localVersion });\n}\n\n/**\n * The four behaviour hints of a tool, all stated. A client reads a missing hint as the worst case\n * (not read-only, destructive, not idempotent, open world), so no tool leaves one out.\n */\nexport type ToolHints = {\n /** The tool changes nothing. */\n readOnlyHint: boolean;\n /** The tool may replace or discard existing data or work, not only add to it. */\n destructiveHint: boolean;\n /** Calling the tool again with the same arguments changes nothing further. */\n idempotentHint: boolean;\n /** The tool reaches beyond the application and the backend it is connected to. */\n openWorldHint: boolean;\n};\n\n/** The hint sets tools choose from. A tool that fits none spreads the nearest one and overrides. */\nexport const hints = {\n /** Reads state; safe to call in parallel and to repeat. */\n read: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Adds something or starts something; a second call does it again. Loses nothing. */\n additive: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n /** Puts the application into a state; a second call changes nothing. Loses nothing. */\n idempotent: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Replaces or discards data, configuration or running work; a second call changes nothing more. */\n destructive: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Acts on the application window or runs given code: the effect depends on what it hits. */\n unpredictable: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n },\n} as const satisfies Record<string, ToolHints>;\n\nexport function textResult(data: unknown) {\n return {\n content: [{ type: \"text\" as const, text: JSON.stringify(data) }],\n };\n}\n\n/** Return an MCP error result with an actionable hint for the AI agent. */\nexport function errorResult(message: string, hint?: string) {\n const text = hint ? `${message}\\n\\nHint: ${hint}` : message;\n return {\n content: [{ type: \"text\" as const, text }],\n isError: true,\n };\n}\n\n/** The results made by {@link timedOutResult}. */\nconst timedOutResults = new WeakSet<object>();\n\n/**\n * Returns the result of a tool that waited for something and ran out of time: the JSON of `data`\n * with `timedOut: true` in front. It is not an error result, the caller is expected to wait again.\n * The server's log recognises such a result with {@link isTimedOutResult}.\n */\nexport function timedOutResult(data: Record<string, unknown>) {\n const result = textResult({ timedOut: true, ...data });\n timedOutResults.add(result);\n return result;\n}\n\n/** Whether `result` was made by {@link timedOutResult}. */\nexport function isTimedOutResult(result: unknown): boolean {\n return typeof result === \"object\" && result !== null && timedOutResults.has(result);\n}\n\n/**\n * Returns the error result of a tool whose `transform` failed: `Transform failed: ` and the whole\n * error, then `hint`. The agent needs the whole error to fix its expression.\n */\nexport function transformFailedResult(error: unknown, hint: string) {\n return errorResult(\n `Transform failed: ${error instanceof Error ? error.message : String(error)}`,\n hint,\n );\n}\n"],"mappings":";;;;;AA8DA,SAAgB,mBAAmB,UAA6C;CAC9E,IAAI,eAAe;CACnB,cAAc;EAAE;EAAU,cAAc,EAAE;CAAa;AACzD;;AAkBA,MAAa,QAAQ;;CAEnB,MAAM;EACJ,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,UAAU;EACR,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,YAAY;EACV,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,aAAa;EACX,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,eAAe;EACb,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;AACF;AAEA,SAAgB,WAAW,MAAe;CACxC,OAAO,EACL,SAAS,CAAC;EAAE,MAAM;EAAiB,MAAM,KAAK,UAAU,IAAI;CAAE,CAAC,EACjE;AACF;;AAGA,SAAgB,YAAY,SAAiB,MAAe;CAE1D,OAAO;EACL,SAAS,CAAC;GAAE,MAAM;GAAiB,MAFxB,OAAO,GAAG,QAAQ,YAAY,SAAS;EAEV,CAAC;EACzC,SAAS;CACX;AACF;;AAGA,MAAM,kCAAkB,IAAI,QAAgB;;;;;;AAO5C,SAAgB,eAAe,MAA+B;CAC5D,MAAM,SAAS,WAAW;EAAE,UAAU;EAAM,GAAG;CAAK,CAAC;CACrD,gBAAgB,IAAI,MAAM;CAC1B,OAAO;AACT;;AAGA,SAAgB,iBAAiB,QAA0B;CACzD,OAAO,OAAO,WAAW,YAAY,WAAW,QAAQ,gBAAgB,IAAI,MAAM;AACpF;;;;;AAMA,SAAgB,sBAAsB,OAAgB,MAAc;CAClE,OAAO,YACL,qBAAqB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KAC1E,IACF;AACF"}
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../src/tools/types.ts"],"sourcesContent":["import type {\n AuthorMarker,\n MiddleLayer,\n Project,\n ProjectHolder,\n ProjectId,\n ProjectListEntry,\n} from \"@milaboratories/pl-middle-layer\";\nimport type {\n Icon,\n RegisteredTool,\n ScopeChallengeHandler,\n StandardSchemaWithJSON,\n ToolAnnotations,\n ToolCallback,\n} from \"@modelcontextprotocol/server\";\nimport type { AgentTables } from \"../agent-tables\";\nimport type { McpInstanceId, PlMcpServerCallbacks } from \"../server\";\nimport { jsonChars, outlineValue, stripBytes } from \"./value-outline\";\n\nexport type { AuthorMarker };\n\nexport interface ToolContext {\n getMl: () => MiddleLayer | null;\n requireMl: () => MiddleLayer;\n resolveProject: (projectId: ProjectId) => Promise<ProjectListEntry>;\n /**\n * Runs `fn` on the project, loading it when it is not loaded. The server holds the project\n * while `fn` runs, so neither the application nor anyone else can unload it under the call.\n * `fn` is also given the middle layer the project is of, which the server took when the call\n * started: its drivers are the ones that know the project's handles.\n */\n withProject: <T>(\n projectId: ProjectId,\n fn: (project: Project, ml: MiddleLayer) => Promise<T>,\n ) => Promise<T>;\n /**\n * The tables agents built with create_table, by handle: reads find their project here, and\n * the server gives them back when they expire, are dropped or lose their project.\n */\n agentTables: AgentTables;\n /** The holder of this server's holds, as the middle layer's `projectHolders` lists them. */\n projectHolder: ProjectHolder;\n /** How many tool calls of this server are working on the project now. */\n callsInFlight: (projectId: ProjectId) => number;\n callbacks: PlMcpServerCallbacks;\n /**\n * Returns the marker for the next write made through MCP. All writes of one server instance carry\n * the same `authorId`, whichever client asked for them, and a `localVersion` that grows with\n * every call.\n */\n getAuthorMarker: () => AuthorMarker;\n}\n\n/**\n * What a tool is registered with: the `registerTool` of an `McpServer`, in its form that takes\n * schemas. The `register*Tools` functions get this and not the server, so that every tool they\n * register goes through whatever the server put around the registration (the call log).\n */\nexport interface ToolRegistrar {\n registerTool<\n OutputArgs extends StandardSchemaWithJSON,\n InputArgs extends StandardSchemaWithJSON | undefined = undefined,\n >(\n name: string,\n config: {\n title?: string;\n description?: string;\n inputSchema?: InputArgs;\n outputSchema?: OutputArgs;\n annotations?: ToolAnnotations;\n icons?: Icon[];\n scopeChallenge?: ScopeChallengeHandler;\n _meta?: Record<string, unknown>;\n },\n cb: ToolCallback<InputArgs>,\n ): RegisteredTool;\n}\n\n/**\n * Makes the author markers of one writer: every call returns a marker with `authorId` and the next\n * `localVersion`, counted from 1.\n */\nexport function authorMarkerSource(authorId: McpInstanceId): () => AuthorMarker {\n let localVersion = 0;\n return () => ({ authorId, localVersion: ++localVersion });\n}\n\n/**\n * The four behaviour hints of a tool, all stated. A client reads a missing hint as the worst case\n * (not read-only, destructive, not idempotent, open world), so no tool leaves one out.\n */\nexport type ToolHints = {\n /** The tool changes nothing. */\n readOnlyHint: boolean;\n /** The tool may replace or discard existing data or work, not only add to it. */\n destructiveHint: boolean;\n /** Calling the tool again with the same arguments changes nothing further. */\n idempotentHint: boolean;\n /** The tool reaches beyond the application and the backend it is connected to. */\n openWorldHint: boolean;\n};\n\n/** The hint sets tools choose from. A tool that fits none spreads the nearest one and overrides. */\nexport const hints = {\n /** Reads state; safe to call in parallel and to repeat. */\n read: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Adds something or starts something; a second call does it again. Loses nothing. */\n additive: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n /** Puts the application into a state; a second call changes nothing. Loses nothing. */\n idempotent: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Replaces or discards data, configuration or running work; a second call changes nothing more. */\n destructive: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n} as const satisfies Record<string, ToolHints>;\n\n/** How long one driver read of a tool (a table, a column's values, a file) may take. */\nexport const READ_TIMEOUT_MS = 60_000;\n\n/** The signal of one driver read: the tool call's, and {@link READ_TIMEOUT_MS}. */\nexport function readSignal(callSignal: AbortSignal | undefined): AbortSignal {\n const timeout = AbortSignal.timeout(READ_TIMEOUT_MS);\n return callSignal === undefined ? timeout : AbortSignal.any([callSignal, timeout]);\n}\n\n/** The most characters the text of a tool result may have. */\nexport const RESULT_CHAR_LIMIT = 60_000;\n\n/** What a tool says when its result is over {@link RESULT_CHAR_LIMIT} and it has no better hint. */\nconst DEFAULT_OVER_LIMIT_HINT =\n \"Ask for a part of it: use `transform` where the tool has one (get_block_state, \" +\n \"await_block_done, query_table), or narrower arguments.\";\n\n/**\n * Returns the result of a tool: `data` as JSON text. Every tool result goes through here, so two\n * rules hold for all of them:\n *\n * - binary data is replaced by `{bytes: N}` (see {@link stripBytes}): it never helps an agent and\n * its JSON is many times its size;\n * - a result over {@link RESULT_CHAR_LIMIT} characters is replaced by an outline of it (keys, types\n * and sizes, see {@link outlineValue}) with `hint`, saying how to ask for a part. It is not an\n * error: the agent learns what is there and asks again.\n */\nexport function textResult(data: unknown, options: { hint?: string } = {}) {\n const value = stripBytes(data);\n const text = JSON.stringify(value) ?? \"null\";\n if (text.length <= RESULT_CHAR_LIMIT) return { content: [{ type: \"text\" as const, text }] };\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(overLimitOutline(value, text.length, options.hint)),\n },\n ],\n };\n}\n\n/** What stands for a result over the limit; the outline loses depth until it fits. */\nfunction overLimitOutline(value: unknown, chars: number, hint: string | undefined) {\n const head = {\n resultTooLarge: true,\n chars,\n limit: RESULT_CHAR_LIMIT,\n note: \"The result is over the size limit; this outline shows its keys, types and sizes (chars).\",\n hint: hint ?? DEFAULT_OVER_LIMIT_HINT,\n };\n for (const maxDepth of [3, 2, 1, 0]) {\n const outlined = { ...head, outline: outlineValue(value, { maxDepth }) };\n if (jsonChars(outlined) <= RESULT_CHAR_LIMIT) return outlined;\n }\n return head;\n}\n\n/**\n * Return an MCP error result with an actionable hint for the AI agent. The text is cut at\n * {@link RESULT_CHAR_LIMIT} characters.\n */\nexport function errorResult(message: string, hint?: string) {\n const full = hint ? `${message}\\n\\nHint: ${hint}` : message;\n const text =\n full.length <= RESULT_CHAR_LIMIT\n ? full\n : `${full.slice(0, RESULT_CHAR_LIMIT - 40)}… [cut: ${full.length} chars in all]`;\n return {\n content: [{ type: \"text\" as const, text }],\n isError: true,\n };\n}\n\n/** The results made by {@link timedOutResult}. */\nconst timedOutResults = new WeakSet<object>();\n\n/**\n * Returns the result of a tool that waited for something and ran out of time: the JSON of `data`\n * with `timedOut: true` in front. It is not an error result, the caller is expected to wait again.\n * The server's log recognises such a result with {@link isTimedOutResult}.\n */\nexport function timedOutResult(data: Record<string, unknown>) {\n const result = textResult({ timedOut: true, ...data });\n timedOutResults.add(result);\n return result;\n}\n\n/** Whether `result` was made by {@link timedOutResult}. */\nexport function isTimedOutResult(result: unknown): boolean {\n return typeof result === \"object\" && result !== null && timedOutResults.has(result);\n}\n\n/**\n * Returns the error result of a tool whose `transform` failed: `Transform failed: ` and the whole\n * error, then `hint`. The agent needs the whole error to fix its expression.\n */\nexport function transformFailedResult(error: unknown, hint: string) {\n return errorResult(\n `Transform failed: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AE,GAAG;GAAM,SAAS,aAAa,OAAO,EAAE,SAAS,CAAC;EAAE;EACvE,IAAI,UAAU,QAAQ,KAAA,KAAwB,OAAO;CACvD;CACA,OAAO;AACT;;;;;AAMA,SAAgB,YAAY,SAAiB,MAAe;CAC1D,MAAM,OAAO,OAAO,GAAG,QAAQ,YAAY,SAAS;CAKpD,OAAO;EACL,SAAS,CAAC;GAAE,MAAM;GAAiB,MAJnC,KAAK,UAAA,MACD,OACA,GAAG,KAAK,MAAM,GAAG,KAAsB,EAAE,UAAU,KAAK,OAAO;EAE3B,CAAC;EACzC,SAAS;CACX;AACF;;AAGA,MAAM,kCAAkB,IAAI,QAAgB;;;;;;AAO5C,SAAgB,eAAe,MAA+B;CAC5D,MAAM,SAAS,WAAW;EAAE,UAAU;EAAM,GAAG;CAAK,CAAC;CACrD,gBAAgB,IAAI,MAAM;CAC1B,OAAO;AACT;;AAGA,SAAgB,iBAAiB,QAA0B;CACzD,OAAO,OAAO,WAAW,YAAY,WAAW,QAAQ,gBAAgB,IAAI,MAAM;AACpF;;;;;AAMA,SAAgB,sBAAsB,OAAgB,MAAc;CAClE,OAAO,YACL,qBAAqB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KAC1E,IACF;AACF"}
@@ -0,0 +1,119 @@
1
+ // src/tools/value-outline.ts
2
+ /** Whether `v` has a `toJSON` of its own kind (a `Date`), which `JSON.stringify` calls. */
3
+ function hasToJson(v) {
4
+ return "toJSON" in v && typeof v.toJSON === "function";
5
+ }
6
+ /**
7
+ * Returns `value` with every piece of live binary data replaced by `{bytes: N}`: typed arrays,
8
+ * Buffers and `ArrayBuffer`s. What such data became after it went through JSON is plain data and
9
+ * stays. Parts that hold no binary data are returned as they are, not copied.
10
+ */
11
+ function stripBytes(value) {
12
+ const inProgress = /* @__PURE__ */ new Set();
13
+ function walk(v) {
14
+ if (v === null || typeof v !== "object") return v;
15
+ if (ArrayBuffer.isView(v)) return { bytes: v.byteLength };
16
+ if (v instanceof ArrayBuffer) return { bytes: v.byteLength };
17
+ if (hasToJson(v)) return v;
18
+ if (inProgress.has(v)) return v;
19
+ inProgress.add(v);
20
+ try {
21
+ if (Array.isArray(v)) {
22
+ let out;
23
+ for (let i = 0; i < v.length; i++) {
24
+ const next = walk(v[i]);
25
+ if (next !== v[i]) {
26
+ out ??= v.slice();
27
+ out[i] = next;
28
+ }
29
+ }
30
+ return out ?? v;
31
+ }
32
+ let changed = false;
33
+ const entries = Object.entries(v).map(([key, item]) => {
34
+ const next = walk(item);
35
+ if (next !== item) changed = true;
36
+ return [key, next];
37
+ });
38
+ return changed ? Object.fromEntries(entries) : v;
39
+ } finally {
40
+ inProgress.delete(v);
41
+ }
42
+ }
43
+ return walk(value);
44
+ }
45
+ /** The JSON length of `value`; 0 for what JSON has no text for. */
46
+ function jsonChars(value) {
47
+ try {
48
+ return JSON.stringify(value)?.length ?? 0;
49
+ } catch {
50
+ return 0;
51
+ }
52
+ }
53
+ /**
54
+ * Outlines `value`: for each object its keys with their types and JSON sizes, for each array its
55
+ * length and the outline of its first element. Bounded in depth, keys per object and nodes in all.
56
+ */
57
+ function outlineValue(value, options = {}) {
58
+ const maxDepth = options.maxDepth ?? 3;
59
+ const maxKeys = options.maxKeys ?? 40;
60
+ let budget = options.maxNodes ?? 400;
61
+ function walk(v, depth) {
62
+ budget--;
63
+ const chars = jsonChars(v);
64
+ if (v === null || v === void 0) return {
65
+ type: "null",
66
+ chars
67
+ };
68
+ if (typeof v === "boolean") return {
69
+ type: "boolean",
70
+ chars
71
+ };
72
+ if (typeof v === "number" || typeof v === "bigint") return {
73
+ type: "number",
74
+ chars
75
+ };
76
+ if (typeof v === "string") return {
77
+ type: "string",
78
+ chars
79
+ };
80
+ if (Array.isArray(v)) {
81
+ const outline = {
82
+ type: "array",
83
+ chars,
84
+ length: v.length
85
+ };
86
+ if (v.length > 0 && depth < maxDepth && budget > 0) outline.first = walk(v[0], depth + 1);
87
+ return outline;
88
+ }
89
+ if (typeof v === "object") {
90
+ const entries = Object.entries(v);
91
+ const outline = {
92
+ type: "object",
93
+ chars,
94
+ keys: entries.length
95
+ };
96
+ if (entries.length > 0 && depth < maxDepth && budget > 0) {
97
+ const fields = [];
98
+ for (const [key, item] of entries) {
99
+ if (fields.length >= maxKeys || budget <= 0) break;
100
+ fields.push([key, walk(item, depth + 1)]);
101
+ }
102
+ const shown = fields.length;
103
+ outline.fields = Object.fromEntries(fields);
104
+ if (shown < entries.length) outline.moreKeys = entries.length - shown;
105
+ }
106
+ return outline;
107
+ }
108
+ return {
109
+ type: "null",
110
+ chars
111
+ };
112
+ }
113
+ return walk(value, 0);
114
+ }
115
+ exports.jsonChars = jsonChars;
116
+ exports.outlineValue = outlineValue;
117
+ exports.stripBytes = stripBytes;
118
+
119
+ //# sourceMappingURL=value-outline.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"value-outline.cjs","names":[],"sources":["../../src/tools/value-outline.ts"],"sourcesContent":["/**\n * Shapes of values the tools return: binary data replaced by its size, and outlines that stand for\n * values too large to return. Has no dependencies, so both the shared result path and the block\n * view use it.\n */\n\n/** What binary data is replaced with in a tool result. */\nexport type BytesStub = { bytes: number };\n\n/** Whether `v` has a `toJSON` of its own kind (a `Date`), which `JSON.stringify` calls. */\nfunction hasToJson(v: object): boolean {\n return \"toJSON\" in v && typeof v.toJSON === \"function\";\n}\n\n/**\n * Returns `value` with every piece of live binary data replaced by `{bytes: N}`: typed arrays,\n * Buffers and `ArrayBuffer`s. What such data became after it went through JSON is plain data and\n * stays. Parts that hold no binary data are returned as they are, not copied.\n */\nexport function stripBytes(value: unknown): unknown {\n const inProgress = new Set<object>();\n\n function walk(v: unknown): unknown {\n if (v === null || typeof v !== \"object\") return v;\n if (ArrayBuffer.isView(v)) return { bytes: v.byteLength } satisfies BytesStub;\n if (v instanceof ArrayBuffer) return { bytes: v.byteLength } satisfies BytesStub;\n if (hasToJson(v)) return v;\n // A cycle cannot be serialized anyway; leave it for JSON.stringify to report.\n if (inProgress.has(v)) return v;\n inProgress.add(v);\n try {\n if (Array.isArray(v)) {\n let out: unknown[] | undefined;\n for (let i = 0; i < v.length; i++) {\n const next = walk(v[i]);\n if (next !== v[i]) {\n out ??= v.slice();\n out[i] = next;\n }\n }\n return out ?? v;\n }\n let changed = false;\n const entries = Object.entries(v).map(([key, item]) => {\n const next = walk(item);\n if (next !== item) changed = true;\n return [key, next] as const;\n });\n // `Object.fromEntries` defines own keys: a key such as `__proto__` stays a key of the copy.\n return changed ? Object.fromEntries(entries) : v;\n } finally {\n inProgress.delete(v);\n }\n }\n\n return walk(value);\n}\n\n/** The JSON length of `value`; 0 for what JSON has no text for. */\nexport function jsonChars(value: unknown): number {\n try {\n return JSON.stringify(value)?.length ?? 0;\n } catch {\n return 0;\n }\n}\n\n/**\n * An outline of a value: its type and JSON size and, for objects and arrays, what they hold, down\n * to a depth. It stands for a value too large to return.\n */\nexport type ValueOutline =\n | { type: \"null\" | \"boolean\" | \"number\" | \"string\"; chars: number }\n | {\n type: \"object\";\n chars: number;\n keys: number;\n /** The outlines of the first keys, while the depth and the node budget last. */\n fields?: Record<string, ValueOutline>;\n /** How many keys `fields` leaves out. */\n moreKeys?: number;\n }\n | {\n type: \"array\";\n chars: number;\n length: number;\n /** The outline of the first element, while the depth and the node budget last. */\n first?: ValueOutline;\n };\n\n/** Limits of {@link outlineValue}. */\nexport type OutlineOptions = {\n /** How many levels below the root get outlined (default 3). */\n maxDepth?: number;\n /** How many keys of one object get outlined (default 40). */\n maxKeys?: number;\n /** How many outlines in total (default 400); the outline stays bounded whatever the value. */\n maxNodes?: number;\n};\n\n/**\n * Outlines `value`: for each object its keys with their types and JSON sizes, for each array its\n * length and the outline of its first element. Bounded in depth, keys per object and nodes in all.\n */\nexport function outlineValue(value: unknown, options: OutlineOptions = {}): ValueOutline {\n const maxDepth = options.maxDepth ?? 3;\n const maxKeys = options.maxKeys ?? 40;\n let budget = options.maxNodes ?? 400;\n\n function walk(v: unknown, depth: number): ValueOutline {\n budget--;\n const chars = jsonChars(v);\n if (v === null || v === undefined) return { type: \"null\", chars };\n if (typeof v === \"boolean\") return { type: \"boolean\", chars };\n if (typeof v === \"number\" || typeof v === \"bigint\") return { type: \"number\", chars };\n if (typeof v === \"string\") return { type: \"string\", chars };\n if (Array.isArray(v)) {\n const outline: ValueOutline = { type: \"array\", chars, length: v.length };\n if (v.length > 0 && depth < maxDepth && budget > 0) outline.first = walk(v[0], depth + 1);\n return outline;\n }\n if (typeof v === \"object\") {\n const entries = Object.entries(v);\n const outline: ValueOutline = { type: \"object\", chars, keys: entries.length };\n if (entries.length > 0 && depth < maxDepth && budget > 0) {\n const fields: [string, ValueOutline][] = [];\n for (const [key, item] of entries) {\n if (fields.length >= maxKeys || budget <= 0) break;\n fields.push([key, walk(item, depth + 1)]);\n }\n const shown = fields.length;\n // `Object.fromEntries` defines own keys: a key such as `__proto__` stays a key of the outline.\n outline.fields = Object.fromEntries(fields);\n if (shown < entries.length) outline.moreKeys = entries.length - shown;\n }\n return outline;\n }\n // Functions and symbols: JSON drops them.\n return { type: \"null\", chars };\n }\n\n return walk(value, 0);\n}\n"],"mappings":";;AAUA,SAAS,UAAU,GAAoB;CACrC,OAAO,YAAY,KAAK,OAAO,EAAE,WAAW;AAC9C;;;;;;AAOA,SAAgB,WAAW,OAAyB;CAClD,MAAM,6BAAa,IAAI,IAAY;CAEnC,SAAS,KAAK,GAAqB;EACjC,IAAI,MAAM,QAAQ,OAAO,MAAM,UAAU,OAAO;EAChD,IAAI,YAAY,OAAO,CAAC,GAAG,OAAO,EAAE,OAAO,EAAE,WAAW;EACxD,IAAI,aAAa,aAAa,OAAO,EAAE,OAAO,EAAE,WAAW;EAC3D,IAAI,UAAU,CAAC,GAAG,OAAO;EAEzB,IAAI,WAAW,IAAI,CAAC,GAAG,OAAO;EAC9B,WAAW,IAAI,CAAC;EAChB,IAAI;GACF,IAAI,MAAM,QAAQ,CAAC,GAAG;IACpB,IAAI;IACJ,KAAK,IAAI,IAAI,GAAG,IA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AS,GAAG,QAAQ,QAAQ,KAAK,EAAE,IAAI,QAAQ,CAAC;GACxF,OAAO;EACT;EACA,IAAI,OAAO,MAAM,UAAU;GACzB,MAAM,UAAU,OAAO,QAAQ,CAAC;GAChC,MAAM,UAAwB;IAAE,MAAM;IAAU;IAAO,MAAM,QAAQ;GAAO;GAC5E,IAAI,QAAQ,SAAS,KAAK,QAAQ,YAAY,SAAS,GAAG;IACxD,MAAM,SAAmC,CAAC;IAC1C,KAAK,MAAM,CAAC,KAAK,SAAS,SAAS;KACjC,IAAI,OAAO,UAAU,WAAW,UAAU,GAAG;KAC7C,OAAO,KAAK,CAAC,KAAK,KAAK,MAAM,QAAQ,CAAC,CAAC,CAAC;IAC1C;IACA,MAAM,QAAQ,OAAO;IAErB,QAAQ,SAAS,OAAO,YAAY,MAAM;IAC1C,IAAI,QAAQ,QAAQ,QAAQ,QAAQ,WAAW,QAAQ,SAAS;GAClE;GACA,OAAO;EACT;EAEA,OAAO;GAAE,MAAM;GAAQ;EAAM;CAC/B;CAEA,OAAO,KAAK,OAAO,CAAC;AACtB"}
@@ -0,0 +1,117 @@
1
+ // src/tools/value-outline.ts
2
+ /** Whether `v` has a `toJSON` of its own kind (a `Date`), which `JSON.stringify` calls. */
3
+ function hasToJson(v) {
4
+ return "toJSON" in v && typeof v.toJSON === "function";
5
+ }
6
+ /**
7
+ * Returns `value` with every piece of live binary data replaced by `{bytes: N}`: typed arrays,
8
+ * Buffers and `ArrayBuffer`s. What such data became after it went through JSON is plain data and
9
+ * stays. Parts that hold no binary data are returned as they are, not copied.
10
+ */
11
+ function stripBytes(value) {
12
+ const inProgress = /* @__PURE__ */ new Set();
13
+ function walk(v) {
14
+ if (v === null || typeof v !== "object") return v;
15
+ if (ArrayBuffer.isView(v)) return { bytes: v.byteLength };
16
+ if (v instanceof ArrayBuffer) return { bytes: v.byteLength };
17
+ if (hasToJson(v)) return v;
18
+ if (inProgress.has(v)) return v;
19
+ inProgress.add(v);
20
+ try {
21
+ if (Array.isArray(v)) {
22
+ let out;
23
+ for (let i = 0; i < v.length; i++) {
24
+ const next = walk(v[i]);
25
+ if (next !== v[i]) {
26
+ out ??= v.slice();
27
+ out[i] = next;
28
+ }
29
+ }
30
+ return out ?? v;
31
+ }
32
+ let changed = false;
33
+ const entries = Object.entries(v).map(([key, item]) => {
34
+ const next = walk(item);
35
+ if (next !== item) changed = true;
36
+ return [key, next];
37
+ });
38
+ return changed ? Object.fromEntries(entries) : v;
39
+ } finally {
40
+ inProgress.delete(v);
41
+ }
42
+ }
43
+ return walk(value);
44
+ }
45
+ /** The JSON length of `value`; 0 for what JSON has no text for. */
46
+ function jsonChars(value) {
47
+ try {
48
+ return JSON.stringify(value)?.length ?? 0;
49
+ } catch {
50
+ return 0;
51
+ }
52
+ }
53
+ /**
54
+ * Outlines `value`: for each object its keys with their types and JSON sizes, for each array its
55
+ * length and the outline of its first element. Bounded in depth, keys per object and nodes in all.
56
+ */
57
+ function outlineValue(value, options = {}) {
58
+ const maxDepth = options.maxDepth ?? 3;
59
+ const maxKeys = options.maxKeys ?? 40;
60
+ let budget = options.maxNodes ?? 400;
61
+ function walk(v, depth) {
62
+ budget--;
63
+ const chars = jsonChars(v);
64
+ if (v === null || v === void 0) return {
65
+ type: "null",
66
+ chars
67
+ };
68
+ if (typeof v === "boolean") return {
69
+ type: "boolean",
70
+ chars
71
+ };
72
+ if (typeof v === "number" || typeof v === "bigint") return {
73
+ type: "number",
74
+ chars
75
+ };
76
+ if (typeof v === "string") return {
77
+ type: "string",
78
+ chars
79
+ };
80
+ if (Array.isArray(v)) {
81
+ const outline = {
82
+ type: "array",
83
+ chars,
84
+ length: v.length
85
+ };
86
+ if (v.length > 0 && depth < maxDepth && budget > 0) outline.first = walk(v[0], depth + 1);
87
+ return outline;
88
+ }
89
+ if (typeof v === "object") {
90
+ const entries = Object.entries(v);
91
+ const outline = {
92
+ type: "object",
93
+ chars,
94
+ keys: entries.length
95
+ };
96
+ if (entries.length > 0 && depth < maxDepth && budget > 0) {
97
+ const fields = [];
98
+ for (const [key, item] of entries) {
99
+ if (fields.length >= maxKeys || budget <= 0) break;
100
+ fields.push([key, walk(item, depth + 1)]);
101
+ }
102
+ const shown = fields.length;
103
+ outline.fields = Object.fromEntries(fields);
104
+ if (shown < entries.length) outline.moreKeys = entries.length - shown;
105
+ }
106
+ return outline;
107
+ }
108
+ return {
109
+ type: "null",
110
+ chars
111
+ };
112
+ }
113
+ return walk(value, 0);
114
+ }
115
+ export { jsonChars, outlineValue, stripBytes };
116
+
117
+ //# sourceMappingURL=value-outline.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"value-outline.js","names":[],"sources":["../../src/tools/value-outline.ts"],"sourcesContent":["/**\n * Shapes of values the tools return: binary data replaced by its size, and outlines that stand for\n * values too large to return. Has no dependencies, so both the shared result path and the block\n * view use it.\n */\n\n/** What binary data is replaced with in a tool result. */\nexport type BytesStub = { bytes: number };\n\n/** Whether `v` has a `toJSON` of its own kind (a `Date`), which `JSON.stringify` calls. */\nfunction hasToJson(v: object): boolean {\n return \"toJSON\" in v && typeof v.toJSON === \"function\";\n}\n\n/**\n * Returns `value` with every piece of live binary data replaced by `{bytes: N}`: typed arrays,\n * Buffers and `ArrayBuffer`s. What such data became after it went through JSON is plain data and\n * stays. Parts that hold no binary data are returned as they are, not copied.\n */\nexport function stripBytes(value: unknown): unknown {\n const inProgress = new Set<object>();\n\n function walk(v: unknown): unknown {\n if (v === null || typeof v !== \"object\") return v;\n if (ArrayBuffer.isView(v)) return { bytes: v.byteLength } satisfies BytesStub;\n if (v instanceof ArrayBuffer) return { bytes: v.byteLength } satisfies BytesStub;\n if (hasToJson(v)) return v;\n // A cycle cannot be serialized anyway; leave it for JSON.stringify to report.\n if (inProgress.has(v)) return v;\n inProgress.add(v);\n try {\n if (Array.isArray(v)) {\n let out: unknown[] | undefined;\n for (let i = 0; i < v.length; i++) {\n const next = walk(v[i]);\n if (next !== v[i]) {\n out ??= v.slice();\n out[i] = next;\n }\n }\n return out ?? v;\n }\n let changed = false;\n const entries = Object.entries(v).map(([key, item]) => {\n const next = walk(item);\n if (next !== item) changed = true;\n return [key, next] as const;\n });\n // `Object.fromEntries` defines own keys: a key such as `__proto__` stays a key of the copy.\n return changed ? Object.fromEntries(entries) : v;\n } finally {\n inProgress.delete(v);\n }\n }\n\n return walk(value);\n}\n\n/** The JSON length of `value`; 0 for what JSON has no text for. */\nexport function jsonChars(value: unknown): number {\n try {\n return JSON.stringify(value)?.length ?? 0;\n } catch {\n return 0;\n }\n}\n\n/**\n * An outline of a value: its type and JSON size and, for objects and arrays, what they hold, down\n * to a depth. It stands for a value too large to return.\n */\nexport type ValueOutline =\n | { type: \"null\" | \"boolean\" | \"number\" | \"string\"; chars: number }\n | {\n type: \"object\";\n chars: number;\n keys: number;\n /** The outlines of the first keys, while the depth and the node budget last. */\n fields?: Record<string, ValueOutline>;\n /** How many keys `fields` leaves out. */\n moreKeys?: number;\n }\n | {\n type: \"array\";\n chars: number;\n length: number;\n /** The outline of the first element, while the depth and the node budget last. */\n first?: ValueOutline;\n };\n\n/** Limits of {@link outlineValue}. */\nexport type OutlineOptions = {\n /** How many levels below the root get outlined (default 3). */\n maxDepth?: number;\n /** How many keys of one object get outlined (default 40). */\n maxKeys?: number;\n /** How many outlines in total (default 400); the outline stays bounded whatever the value. */\n maxNodes?: number;\n};\n\n/**\n * Outlines `value`: for each object its keys with their types and JSON sizes, for each array its\n * length and the outline of its first element. Bounded in depth, keys per object and nodes in all.\n */\nexport function outlineValue(value: unknown, options: OutlineOptions = {}): ValueOutline {\n const maxDepth = options.maxDepth ?? 3;\n const maxKeys = options.maxKeys ?? 40;\n let budget = options.maxNodes ?? 400;\n\n function walk(v: unknown, depth: number): ValueOutline {\n budget--;\n const chars = jsonChars(v);\n if (v === null || v === undefined) return { type: \"null\", chars };\n if (typeof v === \"boolean\") return { type: \"boolean\", chars };\n if (typeof v === \"number\" || typeof v === \"bigint\") return { type: \"number\", chars };\n if (typeof v === \"string\") return { type: \"string\", chars };\n if (Array.isArray(v)) {\n const outline: ValueOutline = { type: \"array\", chars, length: v.length };\n if (v.length > 0 && depth < maxDepth && budget > 0) outline.first = walk(v[0], depth + 1);\n return outline;\n }\n if (typeof v === \"object\") {\n const entries = Object.entries(v);\n const outline: ValueOutline = { type: \"object\", chars, keys: entries.length };\n if (entries.length > 0 && depth < maxDepth && budget > 0) {\n const fields: [string, ValueOutline][] = [];\n for (const [key, item] of entries) {\n if (fields.length >= maxKeys || budget <= 0) break;\n fields.push([key, walk(item, depth + 1)]);\n }\n const shown = fields.length;\n // `Object.fromEntries` defines own keys: a key such as `__proto__` stays a key of the outline.\n outline.fields = Object.fromEntries(fields);\n if (shown < entries.length) outline.moreKeys = entries.length - shown;\n }\n return outline;\n }\n // Functions and symbols: JSON drops them.\n return { type: \"null\", chars };\n }\n\n return walk(value, 0);\n}\n"],"mappings":";;AAUA,SAAS,UAAU,GAAoB;CACrC,OAAO,YAAY,KAAK,OAAO,EAAE,WAAW;AAC9C;;;;;;AAOA,SAAgB,WAAW,OAAyB;CAClD,MAAM,6BAAa,IAAI,IAAY;CAEnC,SAAS,KAAK,GAAqB;EACjC,IAAI,MAAM,QAAQ,OAAO,MAAM,UAAU,OAAO;EAChD,IAAI,YAAY,OAAO,CAAC,GAAG,OAAO,EAAE,OAAO,EAAE,WAAW;EACxD,IAAI,aAAa,aAAa,OAAO,EAAE,OAAO,EAAE,WAAW;EAC3D,IAAI,UAAU,CAAC,GAAG,OAAO;EAEzB,IAAI,WAAW,IAAI,CAAC,GAAG,OAAO;EAC9B,WAAW,IAAI,CAAC;EAChB,IAAI;GACF,IAAI,MAAM,QAAQ,CAAC,GAAG;IACpB,IAAI;IACJ,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;KACjC,MAAM,OAAO,KAAK,EAAE,EAAE;KACtB,IAAI,SAAS,EAAE,IAAI;MACjB,QAAQ,EAAE,MAAM;MAChB,IAAI,KAAK;KACX;IACF;IACA,OAAO,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AwB;IAAE,MAAM;IAAU;IAAO,MAAM,QAAQ;GAAO;GAC5E,IAAI,QAAQ,SAAS,KAAK,QAAQ,YAAY,SAAS,GAAG;IACxD,MAAM,SAAmC,CAAC;IAC1C,KAAK,MAAM,CAAC,KAAK,SAAS,SAAS;KACjC,IAAI,OAAO,UAAU,WAAW,UAAU,GAAG;KAC7C,OAAO,KAAK,CAAC,KAAK,KAAK,MAAM,QAAQ,CAAC,CAAC,CAAC;IAC1C;IACA,MAAM,QAAQ,OAAO;IAErB,QAAQ,SAAS,OAAO,YAAY,MAAM;IAC1C,IAAI,QAAQ,QAAQ,QAAQ,QAAQ,WAAW,QAAQ,SAAS;GAClE;GACA,OAAO;EACT;EAEA,OAAO;GAAE,MAAM;GAAQ;EAAM;CAC/B;CAEA,OAAO,KAAK,OAAO,CAAC;AACtB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@milaboratories/pl-mcp-server",
3
- "version": "53.1.0",
3
+ "version": "55.0.0",
4
4
  "description": "MCP server for Platforma Desktop",
5
5
  "keywords": [],
6
6
  "license": "UNLICENSED",
@@ -20,20 +20,21 @@
20
20
  },
21
21
  "dependencies": {
22
22
  "@milaboratories/helpers": "1.14.7",
23
+ "@milaboratories/pl-model-common": "1.60.0",
23
24
  "@modelcontextprotocol/node": "^2.1.2",
24
25
  "@modelcontextprotocol/server": "^2.4.0",
26
+ "es-toolkit": "^1.39.10",
25
27
  "quickjs-emscripten": "npm:@milaboratories-poc/quickjs-emscripten@0.32.1-bytecode.1",
26
28
  "zod": "^4.6.7"
27
29
  },
28
30
  "devDependencies": {
29
31
  "@milaboratories/build-configs": "2.0.3",
30
- "@milaboratories/pl-errors": "1.5.0",
31
- "@milaboratories/pl-middle-layer": "2.9.0",
32
- "@milaboratories/pl-model-common": "1.60.0",
33
- "@milaboratories/ts-builder": "1.8.0",
32
+ "@milaboratories/pl-errors": "1.5.1",
33
+ "@milaboratories/pl-middle-layer": "2.11.0",
34
+ "@milaboratories/ts-builder": "1.9.0",
34
35
  "@milaboratories/ts-configs": "1.4.1",
35
36
  "@modelcontextprotocol/client": "^2.4.0",
36
- "@platforma-sdk/model": "1.96.1",
37
+ "@platforma-sdk/model": "1.97.0",
37
38
  "@types/node": "~24.19.2",
38
39
  "@vitest/coverage-istanbul": "^4.1.12",
39
40
  "shx": "^0.4.0",
@@ -41,8 +42,8 @@
41
42
  "vitest": "^4.1.12"
42
43
  },
43
44
  "peerDependencies": {
44
- "@milaboratories/pl-middle-layer": ">=2.9.0",
45
- "@platforma-sdk/model": ">=1.96.1"
45
+ "@milaboratories/pl-middle-layer": ">=2.11.0",
46
+ "@platforma-sdk/model": ">=1.97.0"
46
47
  },
47
48
  "engines": {
48
49
  "node": ">=24"