lurqrun 0.1.5 → 0.1.7

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 (192) hide show
  1. package/README.md +23 -13
  2. package/dist/auditHandler-JCOJSUYW.js +23 -0
  3. package/dist/bin/lurq.js +3085 -17723
  4. package/dist/browserAuth-B6G27USY.js +95 -0
  5. package/dist/cache-DKI34SVS.js +12 -0
  6. package/dist/check-2FDGUOV7.js +192 -0
  7. package/dist/checkUpgrade-F2WESBPM.js +103 -0
  8. package/dist/chunk-2VMOWSRY.js +300 -0
  9. package/dist/chunk-3GHJR7XR.js +2049 -0
  10. package/dist/chunk-3N3Q3DSW.js +214 -0
  11. package/dist/chunk-4ESO33J6.js +34 -0
  12. package/dist/chunk-4F7ZESPO.js +132 -0
  13. package/dist/chunk-4KCPOMG6.js +68 -0
  14. package/dist/chunk-4ZYCIMY4.js +155 -0
  15. package/dist/chunk-63MUJNZL.js +318 -0
  16. package/dist/chunk-6AAEVQ7I.js +6336 -0
  17. package/dist/chunk-6EQ3ARXA.js +304 -0
  18. package/dist/chunk-6L3U7DZ5.js +23 -0
  19. package/dist/chunk-AHBP533R.js +220 -0
  20. package/dist/chunk-B43LCXBM.js +223 -0
  21. package/dist/chunk-BCANRN5B.js +33 -0
  22. package/dist/chunk-BUALU27S.js +123 -0
  23. package/dist/chunk-BULZAX2U.js +1554 -0
  24. package/dist/chunk-BV32UNLL.js +154 -0
  25. package/dist/chunk-C6GLE626.js +160 -0
  26. package/dist/chunk-CIDWNUAP.js +145 -0
  27. package/dist/chunk-CUP36ND3.js +2126 -0
  28. package/dist/chunk-CW5HJ3LX.js +96 -0
  29. package/dist/chunk-DB2VF5UD.js +315 -0
  30. package/dist/chunk-DWAGCNEL.js +210 -0
  31. package/dist/chunk-EA3DP5HG.js +293 -0
  32. package/dist/chunk-ELGCAM7P.js +184 -0
  33. package/dist/chunk-FW6BD2NO.js +1915 -0
  34. package/dist/chunk-GE37NVLN.js +15 -0
  35. package/dist/chunk-GPTKSNR6.js +171 -0
  36. package/dist/chunk-GRJXQBQZ.js +793 -0
  37. package/dist/chunk-HWBBVLOT.js +92 -0
  38. package/dist/chunk-I2JUKN6Z.js +24 -0
  39. package/dist/chunk-I3M2KJXB.js +56 -0
  40. package/dist/chunk-IQ4SDKKY.js +733 -0
  41. package/dist/chunk-J5FZYN4A.js +116 -0
  42. package/dist/chunk-L6N4JFW2.js +263 -0
  43. package/dist/chunk-LBFGSSF2.js +126 -0
  44. package/dist/chunk-LEGPB7DO.js +81 -0
  45. package/dist/chunk-LO35HLQZ.js +219 -0
  46. package/dist/chunk-LRD4GBYE.js +73 -0
  47. package/dist/chunk-LUAKDHLZ.js +40 -0
  48. package/dist/chunk-LYMPYETA.js +965 -0
  49. package/dist/chunk-M6NYEXCW.js +38 -0
  50. package/dist/chunk-MHUEVBVO.js +35 -0
  51. package/dist/chunk-MYGSLK44.js +37 -0
  52. package/dist/chunk-NH5I4KHH.js +201 -0
  53. package/dist/chunk-OQS4GUSI.js +1391 -0
  54. package/dist/chunk-PSX3GIAN.js +176 -0
  55. package/dist/chunk-Q5VPF4WI.js +26 -0
  56. package/dist/chunk-QKGYDMWB.js +7409 -0
  57. package/dist/chunk-QSL6QN5X.js +115 -0
  58. package/dist/chunk-SHCEBP3J.js +107 -0
  59. package/dist/chunk-SJOVFF7B.js +201 -0
  60. package/dist/chunk-ST2X2GYN.js +373 -0
  61. package/dist/chunk-TNTXWSYA.js +19 -0
  62. package/dist/chunk-U5AT3TD4.js +2128 -0
  63. package/dist/chunk-UDVNA7EA.js +483 -0
  64. package/dist/chunk-VL2E5T2A.js +109 -0
  65. package/dist/chunk-VLRHFMGJ.js +58 -0
  66. package/dist/chunk-WHX2ZFCG.js +4048 -0
  67. package/dist/chunk-WQ23REYT.js +37 -0
  68. package/dist/chunk-XBIDMHSK.js +15425 -0
  69. package/dist/chunk-Y5GI7RL3.js +66 -0
  70. package/dist/client-IRKAMDYZ.js +15 -0
  71. package/dist/commands-FIL5ET6P.js +911 -0
  72. package/dist/compat-R3UTFQ5Q.js +201 -0
  73. package/dist/dashboardIssue-WYYMBFIB.js +192 -0
  74. package/dist/diff-GZA2774U.js +13 -0
  75. package/dist/dist-4XXIXHHZ.js +12945 -0
  76. package/dist/e2b-FVPHDULZ.js +172 -0
  77. package/dist/extract-NKGKLIVT.js +444 -0
  78. package/dist/fetch-QYTUJVG2.js +22 -0
  79. package/dist/firstTouch-QQTJH4QX.js +55 -0
  80. package/dist/handlers-GEJAVZDK.js +53 -0
  81. package/dist/http-ETPYMBGD.js +5360 -0
  82. package/dist/ingestQueue-VKN4KBIF.js +35 -0
  83. package/dist/install-EK3W2COX.js +20 -0
  84. package/dist/installSkill-VQJWJVCL.js +52 -0
  85. package/dist/inventory-5AWSLJYU.js +31 -0
  86. package/dist/local-XPZMRH5R.js +13 -0
  87. package/dist/mcp-3JHD5SUZ.js +472 -0
  88. package/dist/mcpHandlers-QFN4MCFL.js +22 -0
  89. package/dist/mcpScan-QZHWENIP.js +1871 -0
  90. package/dist/mcpScanWorkflow-JPYCBGC4.js +81 -0
  91. package/dist/mcpStack-BYJCZNIV.js +20 -0
  92. package/dist/packages-THVFMWFP.js +42 -0
  93. package/dist/plan-V4OEI3J4.js +463 -0
  94. package/dist/planView-JRXGCG2N.js +79 -0
  95. package/dist/policy-3P6BGRDN.js +115 -0
  96. package/dist/references-6N7VEPHT.js +14 -0
  97. package/dist/release-4U4ABNSJ.js +128 -0
  98. package/dist/remote-YGCXYI4V.js +32 -0
  99. package/dist/reportRuns-CKQQYLY4.js +64 -0
  100. package/dist/sandbox-MEZLAODF.js +39 -0
  101. package/dist/server-KFUD5X57.js +55 -0
  102. package/dist/surface-V62GE554.js +141 -0
  103. package/dist/surface-YL6O67W3.js +36 -0
  104. package/dist/surfaceHandlers-X2IZKA3E.js +20 -0
  105. package/dist/typecheck-X7U5ELMR.js +268 -0
  106. package/dist/types-M5JP2W3D.js +10 -0
  107. package/dist/uninstall-P7RGBX6G.js +174 -0
  108. package/dist/upgrade-NQ5IWFZB.js +596 -0
  109. package/dist/upgradePlan-A4LRKLEG.js +146 -0
  110. package/dist/userConfig-Z3GQE776.js +20 -0
  111. package/dist/watch-DGFMWUDL.js +214 -0
  112. package/package.json +41 -26
  113. package/templates/agent-rules.md +4 -4
  114. package/templates/skill-instructions.md +18 -14
  115. package/dist/bin/lurq.js.map +0 -1
  116. package/dist/index.d.ts +0 -764
  117. package/dist/index.js +0 -17992
  118. package/dist/index.js.map +0 -1
  119. package/drizzle/0000_confused_fabian_cortez.sql +0 -54
  120. package/drizzle/0001_aspiring_timeslip.sql +0 -15
  121. package/drizzle/0002_lyrical_lila_cheney.sql +0 -14
  122. package/drizzle/0003_violet_giant_girl.sql +0 -14
  123. package/drizzle/0004_slim_valeria_richards.sql +0 -15
  124. package/drizzle/0005_petite_luke_cage.sql +0 -12
  125. package/drizzle/0006_calm_nighthawk.sql +0 -3
  126. package/drizzle/0007_slimy_naoko.sql +0 -1
  127. package/drizzle/0008_peaceful_tigra.sql +0 -1
  128. package/drizzle/0009_smooth_harrier.sql +0 -10
  129. package/drizzle/0010_curved_amphibian.sql +0 -2
  130. package/drizzle/0011_compat_provenance_closures.sql +0 -11
  131. package/drizzle/0012_api_surfaces.sql +0 -9
  132. package/drizzle/0013_nice_thanos.sql +0 -1
  133. package/drizzle/0014_luxuriant_malcolm_colcord.sql +0 -10
  134. package/drizzle/0015_past_fat_cobra.sql +0 -11
  135. package/drizzle/0016_futuristic_junta.sql +0 -50
  136. package/drizzle/0017_absent_grandmaster.sql +0 -20
  137. package/drizzle/0018_rainy_proemial_gods.sql +0 -1
  138. package/drizzle/0019_dashing_korvac.sql +0 -11
  139. package/drizzle/0020_normal_vulture.sql +0 -3
  140. package/drizzle/0021_dazzling_blue_shield.sql +0 -17
  141. package/drizzle/0022_massive_ghost_rider.sql +0 -24
  142. package/drizzle/0023_next_shatterstar.sql +0 -1
  143. package/drizzle/0024_dusty_maelstrom.sql +0 -15
  144. package/drizzle/0025_gifted_harpoon.sql +0 -5
  145. package/drizzle/0026_awesome_mordo.sql +0 -1
  146. package/drizzle/0027_charming_ulik.sql +0 -2
  147. package/drizzle/0028_romantic_loners.sql +0 -2
  148. package/drizzle/0029_busy_korvac.sql +0 -16
  149. package/drizzle/0030_steady_mathemanic.sql +0 -6
  150. package/drizzle/0031_redundant_maginty.sql +0 -2
  151. package/drizzle/0032_stack_resolutions.sql +0 -14
  152. package/drizzle/0033_graceful_tyger_tiger.sql +0 -3
  153. package/drizzle/0034_api_key_scopes.sql +0 -1
  154. package/drizzle/0035_policy_audit.sql +0 -21
  155. package/drizzle/meta/0000_snapshot.json +0 -370
  156. package/drizzle/meta/0001_snapshot.json +0 -482
  157. package/drizzle/meta/0002_snapshot.json +0 -575
  158. package/drizzle/meta/0003_snapshot.json +0 -667
  159. package/drizzle/meta/0004_snapshot.json +0 -769
  160. package/drizzle/meta/0005_snapshot.json +0 -864
  161. package/drizzle/meta/0006_snapshot.json +0 -882
  162. package/drizzle/meta/0007_snapshot.json +0 -876
  163. package/drizzle/meta/0008_snapshot.json +0 -882
  164. package/drizzle/meta/0009_snapshot.json +0 -948
  165. package/drizzle/meta/0010_snapshot.json +0 -969
  166. package/drizzle/meta/0011_snapshot.json +0 -1049
  167. package/drizzle/meta/0012_snapshot.json +0 -1115
  168. package/drizzle/meta/0013_snapshot.json +0 -1121
  169. package/drizzle/meta/0014_snapshot.json +0 -1190
  170. package/drizzle/meta/0015_snapshot.json +0 -1280
  171. package/drizzle/meta/0016_snapshot.json +0 -1683
  172. package/drizzle/meta/0017_snapshot.json +0 -1834
  173. package/drizzle/meta/0018_snapshot.json +0 -1834
  174. package/drizzle/meta/0019_snapshot.json +0 -1909
  175. package/drizzle/meta/0020_snapshot.json +0 -1921
  176. package/drizzle/meta/0021_snapshot.json +0 -2045
  177. package/drizzle/meta/0022_snapshot.json +0 -2246
  178. package/drizzle/meta/0023_snapshot.json +0 -2252
  179. package/drizzle/meta/0024_snapshot.json +0 -2375
  180. package/drizzle/meta/0025_snapshot.json +0 -2407
  181. package/drizzle/meta/0026_snapshot.json +0 -2413
  182. package/drizzle/meta/0027_snapshot.json +0 -2425
  183. package/drizzle/meta/0028_snapshot.json +0 -2438
  184. package/drizzle/meta/0029_snapshot.json +0 -2546
  185. package/drizzle/meta/0030_snapshot.json +0 -2586
  186. package/drizzle/meta/0031_snapshot.json +0 -2598
  187. package/drizzle/meta/0032_snapshot.json +0 -2699
  188. package/drizzle/meta/0033_snapshot.json +0 -2712
  189. package/drizzle/meta/0034_snapshot.json +0 -2719
  190. package/drizzle/meta/0035_snapshot.json +0 -2869
  191. package/drizzle/meta/_journal.json +0 -258
  192. package/src/data/seed.json +0 -253
@@ -0,0 +1,2126 @@
1
+ import { createRequire as __lurqCreateRequire } from 'node:module'; const require = __lurqCreateRequire(import.meta.url);
2
+ import {
3
+ handleAudit
4
+ } from "./chunk-IQ4SDKKY.js";
5
+ import {
6
+ AjvJsonSchemaValidator,
7
+ Protocol,
8
+ ReadBuffer,
9
+ assertClientRequestTaskCapability,
10
+ assertToolsCallTaskCapability,
11
+ getLiteralValue,
12
+ getObjectShape,
13
+ getParseErrorMessage,
14
+ getSchemaDescription,
15
+ isSchemaOptional,
16
+ isZ4Schema,
17
+ mergeCapabilities,
18
+ normalizeObjectSchema,
19
+ objectFromShape,
20
+ safeParse,
21
+ safeParseAsync,
22
+ serializeMessage,
23
+ toJsonSchemaCompat
24
+ } from "./chunk-XBIDMHSK.js";
25
+ import {
26
+ searchCapabilities
27
+ } from "./chunk-L6N4JFW2.js";
28
+ import {
29
+ handleMcpDrift,
30
+ handleMcpSurface
31
+ } from "./chunk-3N3Q3DSW.js";
32
+ import {
33
+ handleDiffSurface,
34
+ handleResolveSurface
35
+ } from "./chunk-DB2VF5UD.js";
36
+ import {
37
+ CallToolRequestSchema,
38
+ CallToolResultSchema,
39
+ CompleteRequestSchema,
40
+ CreateMessageResultSchema,
41
+ CreateMessageResultWithToolsSchema,
42
+ CreateTaskResultSchema,
43
+ ElicitResultSchema,
44
+ EmptyResultSchema,
45
+ ErrorCode,
46
+ GetPromptRequestSchema,
47
+ InitializeRequestSchema,
48
+ InitializedNotificationSchema,
49
+ LATEST_PROTOCOL_VERSION,
50
+ ListPromptsRequestSchema,
51
+ ListResourceTemplatesRequestSchema,
52
+ ListResourcesRequestSchema,
53
+ ListRootsResultSchema,
54
+ ListToolsRequestSchema,
55
+ LoggingLevelSchema,
56
+ McpError,
57
+ ReadResourceRequestSchema,
58
+ SUPPORTED_PROTOCOL_VERSIONS,
59
+ SetLevelRequestSchema,
60
+ assertCompleteRequestPrompt,
61
+ assertCompleteRequestResourceTemplate
62
+ } from "./chunk-6AAEVQ7I.js";
63
+ import {
64
+ handleDiagram
65
+ } from "./chunk-4F7ZESPO.js";
66
+ import {
67
+ handleCompare,
68
+ handleCompat,
69
+ handleEvaluate,
70
+ handlePolicy,
71
+ handleReportOutcome,
72
+ handleUsage,
73
+ handleVerify
74
+ } from "./chunk-BULZAX2U.js";
75
+ import {
76
+ createDb
77
+ } from "./chunk-WQ23REYT.js";
78
+ import {
79
+ ownerUsageDaily
80
+ } from "./chunk-LYMPYETA.js";
81
+ import {
82
+ require_semver
83
+ } from "./chunk-3GHJR7XR.js";
84
+ import {
85
+ external_exports,
86
+ getConfig
87
+ } from "./chunk-GRJXQBQZ.js";
88
+ import {
89
+ ZodOptional
90
+ } from "./chunk-WHX2ZFCG.js";
91
+ import {
92
+ logger
93
+ } from "./chunk-MYGSLK44.js";
94
+ import {
95
+ SERVER_NAME,
96
+ VERSION
97
+ } from "./chunk-GPTKSNR6.js";
98
+ import {
99
+ __toESM,
100
+ init_esm_shims
101
+ } from "./chunk-I3M2KJXB.js";
102
+
103
+ // src/mcp/server.ts
104
+ init_esm_shims();
105
+
106
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js
107
+ init_esm_shims();
108
+
109
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js
110
+ init_esm_shims();
111
+
112
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js
113
+ init_esm_shims();
114
+ var ExperimentalServerTasks = class {
115
+ constructor(_server) {
116
+ this._server = _server;
117
+ }
118
+ /**
119
+ * Sends a request and returns an AsyncGenerator that yields response messages.
120
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
121
+ *
122
+ * This method provides streaming access to request processing, allowing you to
123
+ * observe intermediate task status updates for task-augmented requests.
124
+ *
125
+ * @param request - The request to send
126
+ * @param resultSchema - Zod schema for validating the result
127
+ * @param options - Optional request options (timeout, signal, task creation params, etc.)
128
+ * @returns AsyncGenerator that yields ResponseMessage objects
129
+ *
130
+ * @experimental
131
+ */
132
+ requestStream(request, resultSchema, options) {
133
+ return this._server.requestStream(request, resultSchema, options);
134
+ }
135
+ /**
136
+ * Sends a sampling request and returns an AsyncGenerator that yields response messages.
137
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
138
+ *
139
+ * For task-augmented requests, yields 'taskCreated' and 'taskStatus' messages
140
+ * before the final result.
141
+ *
142
+ * @example
143
+ * ```typescript
144
+ * const stream = server.experimental.tasks.createMessageStream({
145
+ * messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }],
146
+ * maxTokens: 100
147
+ * }, {
148
+ * onprogress: (progress) => {
149
+ * // Handle streaming tokens via progress notifications
150
+ * console.log('Progress:', progress.message);
151
+ * }
152
+ * });
153
+ *
154
+ * for await (const message of stream) {
155
+ * switch (message.type) {
156
+ * case 'taskCreated':
157
+ * console.log('Task created:', message.task.taskId);
158
+ * break;
159
+ * case 'taskStatus':
160
+ * console.log('Task status:', message.task.status);
161
+ * break;
162
+ * case 'result':
163
+ * console.log('Final result:', message.result);
164
+ * break;
165
+ * case 'error':
166
+ * console.error('Error:', message.error);
167
+ * break;
168
+ * }
169
+ * }
170
+ * ```
171
+ *
172
+ * @param params - The sampling request parameters
173
+ * @param options - Optional request options (timeout, signal, task creation params, onprogress, etc.)
174
+ * @returns AsyncGenerator that yields ResponseMessage objects
175
+ *
176
+ * @experimental
177
+ */
178
+ createMessageStream(params, options) {
179
+ const clientCapabilities = this._server.getClientCapabilities();
180
+ if ((params.tools || params.toolChoice) && !clientCapabilities?.sampling?.tools) {
181
+ throw new Error("Client does not support sampling tools capability.");
182
+ }
183
+ if (params.messages.length > 0) {
184
+ const lastMessage = params.messages[params.messages.length - 1];
185
+ const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];
186
+ const hasToolResults = lastContent.some((c) => c.type === "tool_result");
187
+ const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0;
188
+ const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : [];
189
+ const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use");
190
+ if (hasToolResults) {
191
+ if (lastContent.some((c) => c.type !== "tool_result")) {
192
+ throw new Error("The last message must contain only tool_result content if any is present");
193
+ }
194
+ if (!hasPreviousToolUse) {
195
+ throw new Error("tool_result blocks are not matching any tool_use from the previous message");
196
+ }
197
+ }
198
+ if (hasPreviousToolUse) {
199
+ const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id));
200
+ const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId));
201
+ if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) {
202
+ throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match");
203
+ }
204
+ }
205
+ }
206
+ return this.requestStream({
207
+ method: "sampling/createMessage",
208
+ params
209
+ }, CreateMessageResultSchema, options);
210
+ }
211
+ /**
212
+ * Sends an elicitation request and returns an AsyncGenerator that yields response messages.
213
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
214
+ *
215
+ * For task-augmented requests (especially URL-based elicitation), yields 'taskCreated'
216
+ * and 'taskStatus' messages before the final result.
217
+ *
218
+ * @example
219
+ * ```typescript
220
+ * const stream = server.experimental.tasks.elicitInputStream({
221
+ * mode: 'url',
222
+ * message: 'Please authenticate',
223
+ * elicitationId: 'auth-123',
224
+ * url: 'https://example.com/auth'
225
+ * }, {
226
+ * task: { ttl: 300000 } // Task-augmented for long-running auth flow
227
+ * });
228
+ *
229
+ * for await (const message of stream) {
230
+ * switch (message.type) {
231
+ * case 'taskCreated':
232
+ * console.log('Task created:', message.task.taskId);
233
+ * break;
234
+ * case 'taskStatus':
235
+ * console.log('Task status:', message.task.status);
236
+ * break;
237
+ * case 'result':
238
+ * console.log('User action:', message.result.action);
239
+ * break;
240
+ * case 'error':
241
+ * console.error('Error:', message.error);
242
+ * break;
243
+ * }
244
+ * }
245
+ * ```
246
+ *
247
+ * @param params - The elicitation request parameters
248
+ * @param options - Optional request options (timeout, signal, task creation params, etc.)
249
+ * @returns AsyncGenerator that yields ResponseMessage objects
250
+ *
251
+ * @experimental
252
+ */
253
+ elicitInputStream(params, options) {
254
+ const clientCapabilities = this._server.getClientCapabilities();
255
+ const mode = params.mode ?? "form";
256
+ switch (mode) {
257
+ case "url": {
258
+ if (!clientCapabilities?.elicitation?.url) {
259
+ throw new Error("Client does not support url elicitation.");
260
+ }
261
+ break;
262
+ }
263
+ case "form": {
264
+ if (!clientCapabilities?.elicitation?.form) {
265
+ throw new Error("Client does not support form elicitation.");
266
+ }
267
+ break;
268
+ }
269
+ }
270
+ const normalizedParams = mode === "form" && params.mode === void 0 ? { ...params, mode: "form" } : params;
271
+ return this.requestStream({
272
+ method: "elicitation/create",
273
+ params: normalizedParams
274
+ }, ElicitResultSchema, options);
275
+ }
276
+ /**
277
+ * Gets the current status of a task.
278
+ *
279
+ * @param taskId - The task identifier
280
+ * @param options - Optional request options
281
+ * @returns The task status
282
+ *
283
+ * @experimental
284
+ */
285
+ async getTask(taskId, options) {
286
+ return this._server.getTask({ taskId }, options);
287
+ }
288
+ /**
289
+ * Retrieves the result of a completed task.
290
+ *
291
+ * @param taskId - The task identifier
292
+ * @param resultSchema - Zod schema for validating the result
293
+ * @param options - Optional request options
294
+ * @returns The task result
295
+ *
296
+ * @experimental
297
+ */
298
+ async getTaskResult(taskId, resultSchema, options) {
299
+ return this._server.getTaskResult({ taskId }, resultSchema, options);
300
+ }
301
+ /**
302
+ * Lists tasks with optional pagination.
303
+ *
304
+ * @param cursor - Optional pagination cursor
305
+ * @param options - Optional request options
306
+ * @returns List of tasks with optional next cursor
307
+ *
308
+ * @experimental
309
+ */
310
+ async listTasks(cursor, options) {
311
+ return this._server.listTasks(cursor ? { cursor } : void 0, options);
312
+ }
313
+ /**
314
+ * Cancels a running task.
315
+ *
316
+ * @param taskId - The task identifier
317
+ * @param options - Optional request options
318
+ *
319
+ * @experimental
320
+ */
321
+ async cancelTask(taskId, options) {
322
+ return this._server.cancelTask({ taskId }, options);
323
+ }
324
+ };
325
+
326
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js
327
+ var Server = class extends Protocol {
328
+ /**
329
+ * Initializes this server with the given name and version information.
330
+ */
331
+ constructor(_serverInfo, options) {
332
+ super(options);
333
+ this._serverInfo = _serverInfo;
334
+ this._loggingLevels = /* @__PURE__ */ new Map();
335
+ this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index]));
336
+ this.isMessageIgnored = (level, sessionId) => {
337
+ const currentLevel = this._loggingLevels.get(sessionId);
338
+ return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false;
339
+ };
340
+ this._capabilities = options?.capabilities ?? {};
341
+ this._instructions = options?.instructions;
342
+ this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();
343
+ this.setRequestHandler(InitializeRequestSchema, (request) => this._oninitialize(request));
344
+ this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.());
345
+ if (this._capabilities.logging) {
346
+ this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => {
347
+ const transportSessionId = extra.sessionId || extra.requestInfo?.headers["mcp-session-id"] || void 0;
348
+ const { level } = request.params;
349
+ const parseResult = LoggingLevelSchema.safeParse(level);
350
+ if (parseResult.success) {
351
+ this._loggingLevels.set(transportSessionId, parseResult.data);
352
+ }
353
+ return {};
354
+ });
355
+ }
356
+ }
357
+ /**
358
+ * Access experimental features.
359
+ *
360
+ * WARNING: These APIs are experimental and may change without notice.
361
+ *
362
+ * @experimental
363
+ */
364
+ get experimental() {
365
+ if (!this._experimental) {
366
+ this._experimental = {
367
+ tasks: new ExperimentalServerTasks(this)
368
+ };
369
+ }
370
+ return this._experimental;
371
+ }
372
+ /**
373
+ * Registers new capabilities. This can only be called before connecting to a transport.
374
+ *
375
+ * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
376
+ */
377
+ registerCapabilities(capabilities) {
378
+ if (this.transport) {
379
+ throw new Error("Cannot register capabilities after connecting to transport");
380
+ }
381
+ this._capabilities = mergeCapabilities(this._capabilities, capabilities);
382
+ }
383
+ /**
384
+ * Override request handler registration to enforce server-side validation for tools/call.
385
+ */
386
+ setRequestHandler(requestSchema, handler) {
387
+ const shape = getObjectShape(requestSchema);
388
+ const methodSchema = shape?.method;
389
+ if (!methodSchema) {
390
+ throw new Error("Schema is missing a method literal");
391
+ }
392
+ let methodValue;
393
+ if (isZ4Schema(methodSchema)) {
394
+ const v4Schema = methodSchema;
395
+ const v4Def = v4Schema._zod?.def;
396
+ methodValue = v4Def?.value ?? v4Schema.value;
397
+ } else {
398
+ const v3Schema = methodSchema;
399
+ const legacyDef = v3Schema._def;
400
+ methodValue = legacyDef?.value ?? v3Schema.value;
401
+ }
402
+ if (typeof methodValue !== "string") {
403
+ throw new Error("Schema method literal must be a string");
404
+ }
405
+ const method = methodValue;
406
+ if (method === "tools/call") {
407
+ const wrappedHandler = async (request, extra) => {
408
+ const validatedRequest = safeParse(CallToolRequestSchema, request);
409
+ if (!validatedRequest.success) {
410
+ const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
411
+ throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`);
412
+ }
413
+ const { params } = validatedRequest.data;
414
+ const result = await Promise.resolve(handler(request, extra));
415
+ if (params.task) {
416
+ const taskValidationResult = safeParse(CreateTaskResultSchema, result);
417
+ if (!taskValidationResult.success) {
418
+ const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
419
+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
420
+ }
421
+ return taskValidationResult.data;
422
+ }
423
+ const validationResult = safeParse(CallToolResultSchema, result);
424
+ if (!validationResult.success) {
425
+ const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
426
+ throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`);
427
+ }
428
+ return validationResult.data;
429
+ };
430
+ return super.setRequestHandler(requestSchema, wrappedHandler);
431
+ }
432
+ return super.setRequestHandler(requestSchema, handler);
433
+ }
434
+ assertCapabilityForMethod(method) {
435
+ switch (method) {
436
+ case "sampling/createMessage":
437
+ if (!this._clientCapabilities?.sampling) {
438
+ throw new Error(`Client does not support sampling (required for ${method})`);
439
+ }
440
+ break;
441
+ case "elicitation/create":
442
+ if (!this._clientCapabilities?.elicitation) {
443
+ throw new Error(`Client does not support elicitation (required for ${method})`);
444
+ }
445
+ break;
446
+ case "roots/list":
447
+ if (!this._clientCapabilities?.roots) {
448
+ throw new Error(`Client does not support listing roots (required for ${method})`);
449
+ }
450
+ break;
451
+ case "ping":
452
+ break;
453
+ }
454
+ }
455
+ assertNotificationCapability(method) {
456
+ switch (method) {
457
+ case "notifications/message":
458
+ if (!this._capabilities.logging) {
459
+ throw new Error(`Server does not support logging (required for ${method})`);
460
+ }
461
+ break;
462
+ case "notifications/resources/updated":
463
+ case "notifications/resources/list_changed":
464
+ if (!this._capabilities.resources) {
465
+ throw new Error(`Server does not support notifying about resources (required for ${method})`);
466
+ }
467
+ break;
468
+ case "notifications/tools/list_changed":
469
+ if (!this._capabilities.tools) {
470
+ throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);
471
+ }
472
+ break;
473
+ case "notifications/prompts/list_changed":
474
+ if (!this._capabilities.prompts) {
475
+ throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);
476
+ }
477
+ break;
478
+ case "notifications/elicitation/complete":
479
+ if (!this._clientCapabilities?.elicitation?.url) {
480
+ throw new Error(`Client does not support URL elicitation (required for ${method})`);
481
+ }
482
+ break;
483
+ case "notifications/cancelled":
484
+ break;
485
+ case "notifications/progress":
486
+ break;
487
+ }
488
+ }
489
+ assertRequestHandlerCapability(method) {
490
+ if (!this._capabilities) {
491
+ return;
492
+ }
493
+ switch (method) {
494
+ case "completion/complete":
495
+ if (!this._capabilities.completions) {
496
+ throw new Error(`Server does not support completions (required for ${method})`);
497
+ }
498
+ break;
499
+ case "logging/setLevel":
500
+ if (!this._capabilities.logging) {
501
+ throw new Error(`Server does not support logging (required for ${method})`);
502
+ }
503
+ break;
504
+ case "prompts/get":
505
+ case "prompts/list":
506
+ if (!this._capabilities.prompts) {
507
+ throw new Error(`Server does not support prompts (required for ${method})`);
508
+ }
509
+ break;
510
+ case "resources/list":
511
+ case "resources/templates/list":
512
+ case "resources/read":
513
+ if (!this._capabilities.resources) {
514
+ throw new Error(`Server does not support resources (required for ${method})`);
515
+ }
516
+ break;
517
+ case "tools/call":
518
+ case "tools/list":
519
+ if (!this._capabilities.tools) {
520
+ throw new Error(`Server does not support tools (required for ${method})`);
521
+ }
522
+ break;
523
+ case "tasks/get":
524
+ case "tasks/list":
525
+ case "tasks/result":
526
+ case "tasks/cancel":
527
+ if (!this._capabilities.tasks) {
528
+ throw new Error(`Server does not support tasks capability (required for ${method})`);
529
+ }
530
+ break;
531
+ case "ping":
532
+ case "initialize":
533
+ break;
534
+ }
535
+ }
536
+ assertTaskCapability(method) {
537
+ assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, "Client");
538
+ }
539
+ assertTaskHandlerCapability(method) {
540
+ if (!this._capabilities) {
541
+ return;
542
+ }
543
+ assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, "Server");
544
+ }
545
+ async _oninitialize(request) {
546
+ const requestedVersion = request.params.protocolVersion;
547
+ this._clientCapabilities = request.params.capabilities;
548
+ this._clientVersion = request.params.clientInfo;
549
+ const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION;
550
+ return {
551
+ protocolVersion,
552
+ capabilities: this.getCapabilities(),
553
+ serverInfo: this._serverInfo,
554
+ ...this._instructions && { instructions: this._instructions }
555
+ };
556
+ }
557
+ /**
558
+ * After initialization has completed, this will be populated with the client's reported capabilities.
559
+ */
560
+ getClientCapabilities() {
561
+ return this._clientCapabilities;
562
+ }
563
+ /**
564
+ * After initialization has completed, this will be populated with information about the client's name and version.
565
+ */
566
+ getClientVersion() {
567
+ return this._clientVersion;
568
+ }
569
+ getCapabilities() {
570
+ return this._capabilities;
571
+ }
572
+ async ping() {
573
+ return this.request({ method: "ping" }, EmptyResultSchema);
574
+ }
575
+ // Implementation
576
+ async createMessage(params, options) {
577
+ if (params.tools || params.toolChoice) {
578
+ if (!this._clientCapabilities?.sampling?.tools) {
579
+ throw new Error("Client does not support sampling tools capability.");
580
+ }
581
+ }
582
+ if (params.messages.length > 0) {
583
+ const lastMessage = params.messages[params.messages.length - 1];
584
+ const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];
585
+ const hasToolResults = lastContent.some((c) => c.type === "tool_result");
586
+ const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0;
587
+ const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : [];
588
+ const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use");
589
+ if (hasToolResults) {
590
+ if (lastContent.some((c) => c.type !== "tool_result")) {
591
+ throw new Error("The last message must contain only tool_result content if any is present");
592
+ }
593
+ if (!hasPreviousToolUse) {
594
+ throw new Error("tool_result blocks are not matching any tool_use from the previous message");
595
+ }
596
+ }
597
+ if (hasPreviousToolUse) {
598
+ const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id));
599
+ const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId));
600
+ if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) {
601
+ throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match");
602
+ }
603
+ }
604
+ }
605
+ if (params.tools) {
606
+ return this.request({ method: "sampling/createMessage", params }, CreateMessageResultWithToolsSchema, options);
607
+ }
608
+ return this.request({ method: "sampling/createMessage", params }, CreateMessageResultSchema, options);
609
+ }
610
+ /**
611
+ * Creates an elicitation request for the given parameters.
612
+ * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`.
613
+ * @param params The parameters for the elicitation request.
614
+ * @param options Optional request options.
615
+ * @returns The result of the elicitation request.
616
+ */
617
+ async elicitInput(params, options) {
618
+ const mode = params.mode ?? "form";
619
+ switch (mode) {
620
+ case "url": {
621
+ if (!this._clientCapabilities?.elicitation?.url) {
622
+ throw new Error("Client does not support url elicitation.");
623
+ }
624
+ const urlParams = params;
625
+ return this.request({ method: "elicitation/create", params: urlParams }, ElicitResultSchema, options);
626
+ }
627
+ case "form": {
628
+ if (!this._clientCapabilities?.elicitation?.form) {
629
+ throw new Error("Client does not support form elicitation.");
630
+ }
631
+ const formParams = params.mode === "form" ? params : { ...params, mode: "form" };
632
+ const result = await this.request({ method: "elicitation/create", params: formParams }, ElicitResultSchema, options);
633
+ if (result.action === "accept" && result.content && formParams.requestedSchema) {
634
+ try {
635
+ const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema);
636
+ const validationResult = validator(result.content);
637
+ if (!validationResult.valid) {
638
+ throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`);
639
+ }
640
+ } catch (error) {
641
+ if (error instanceof McpError) {
642
+ throw error;
643
+ }
644
+ throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`);
645
+ }
646
+ }
647
+ return result;
648
+ }
649
+ }
650
+ }
651
+ /**
652
+ * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete`
653
+ * notification for the specified elicitation ID.
654
+ *
655
+ * @param elicitationId The ID of the elicitation to mark as complete.
656
+ * @param options Optional notification options. Useful when the completion notification should be related to a prior request.
657
+ * @returns A function that emits the completion notification when awaited.
658
+ */
659
+ createElicitationCompletionNotifier(elicitationId, options) {
660
+ if (!this._clientCapabilities?.elicitation?.url) {
661
+ throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");
662
+ }
663
+ return () => this.notification({
664
+ method: "notifications/elicitation/complete",
665
+ params: {
666
+ elicitationId
667
+ }
668
+ }, options);
669
+ }
670
+ async listRoots(params, options) {
671
+ return this.request({ method: "roots/list", params }, ListRootsResultSchema, options);
672
+ }
673
+ /**
674
+ * Sends a logging message to the client, if connected.
675
+ * Note: You only need to send the parameters object, not the entire JSON RPC message
676
+ * @see LoggingMessageNotification
677
+ * @param params
678
+ * @param sessionId optional for stateless and backward compatibility
679
+ */
680
+ async sendLoggingMessage(params, sessionId) {
681
+ if (this._capabilities.logging) {
682
+ if (!this.isMessageIgnored(params.level, sessionId)) {
683
+ return this.notification({ method: "notifications/message", params });
684
+ }
685
+ }
686
+ }
687
+ async sendResourceUpdated(params) {
688
+ return this.notification({
689
+ method: "notifications/resources/updated",
690
+ params
691
+ });
692
+ }
693
+ async sendResourceListChanged() {
694
+ return this.notification({
695
+ method: "notifications/resources/list_changed"
696
+ });
697
+ }
698
+ async sendToolListChanged() {
699
+ return this.notification({ method: "notifications/tools/list_changed" });
700
+ }
701
+ async sendPromptListChanged() {
702
+ return this.notification({ method: "notifications/prompts/list_changed" });
703
+ }
704
+ };
705
+
706
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js
707
+ init_esm_shims();
708
+ var COMPLETABLE_SYMBOL = /* @__PURE__ */ Symbol.for("mcp.completable");
709
+ function isCompletable(schema) {
710
+ return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema;
711
+ }
712
+ function getCompleter(schema) {
713
+ const meta = schema[COMPLETABLE_SYMBOL];
714
+ return meta?.complete;
715
+ }
716
+ var McpZodTypeKind;
717
+ (function(McpZodTypeKind2) {
718
+ McpZodTypeKind2["Completable"] = "McpCompletable";
719
+ })(McpZodTypeKind || (McpZodTypeKind = {}));
720
+
721
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/uriTemplate.js
722
+ init_esm_shims();
723
+
724
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.js
725
+ init_esm_shims();
726
+ var TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/;
727
+ function validateToolName(name) {
728
+ const warnings = [];
729
+ if (name.length === 0) {
730
+ return {
731
+ isValid: false,
732
+ warnings: ["Tool name cannot be empty"]
733
+ };
734
+ }
735
+ if (name.length > 128) {
736
+ return {
737
+ isValid: false,
738
+ warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]
739
+ };
740
+ }
741
+ if (name.includes(" ")) {
742
+ warnings.push("Tool name contains spaces, which may cause parsing issues");
743
+ }
744
+ if (name.includes(",")) {
745
+ warnings.push("Tool name contains commas, which may cause parsing issues");
746
+ }
747
+ if (name.startsWith("-") || name.endsWith("-")) {
748
+ warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");
749
+ }
750
+ if (name.startsWith(".") || name.endsWith(".")) {
751
+ warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");
752
+ }
753
+ if (!TOOL_NAME_REGEX.test(name)) {
754
+ const invalidChars = name.split("").filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index);
755
+ warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)");
756
+ return {
757
+ isValid: false,
758
+ warnings
759
+ };
760
+ }
761
+ return {
762
+ isValid: true,
763
+ warnings
764
+ };
765
+ }
766
+ function issueToolNameWarning(name, warnings) {
767
+ if (warnings.length > 0) {
768
+ console.warn(`Tool name validation warning for "${name}":`);
769
+ for (const warning of warnings) {
770
+ console.warn(` - ${warning}`);
771
+ }
772
+ console.warn("Tool registration will proceed, but this may cause compatibility issues.");
773
+ console.warn("Consider updating the tool name to conform to the MCP tool naming standard.");
774
+ console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.");
775
+ }
776
+ }
777
+ function validateAndWarnToolName(name) {
778
+ const result = validateToolName(name);
779
+ issueToolNameWarning(name, result.warnings);
780
+ return result.isValid;
781
+ }
782
+
783
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.js
784
+ init_esm_shims();
785
+ var ExperimentalMcpServerTasks = class {
786
+ constructor(_mcpServer) {
787
+ this._mcpServer = _mcpServer;
788
+ }
789
+ registerToolTask(name, config, handler) {
790
+ const execution = { taskSupport: "required", ...config.execution };
791
+ if (execution.taskSupport === "forbidden") {
792
+ throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`);
793
+ }
794
+ const mcpServerInternal = this._mcpServer;
795
+ return mcpServerInternal._createRegisteredTool(name, config.title, config.description, config.inputSchema, config.outputSchema, config.annotations, execution, config._meta, handler);
796
+ }
797
+ };
798
+
799
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js
800
+ var McpServer = class {
801
+ constructor(serverInfo, options) {
802
+ this._registeredResources = {};
803
+ this._registeredResourceTemplates = {};
804
+ this._registeredTools = {};
805
+ this._registeredPrompts = {};
806
+ this._toolHandlersInitialized = false;
807
+ this._completionHandlerInitialized = false;
808
+ this._resourceHandlersInitialized = false;
809
+ this._promptHandlersInitialized = false;
810
+ this.server = new Server(serverInfo, options);
811
+ }
812
+ /**
813
+ * Access experimental features.
814
+ *
815
+ * WARNING: These APIs are experimental and may change without notice.
816
+ *
817
+ * @experimental
818
+ */
819
+ get experimental() {
820
+ if (!this._experimental) {
821
+ this._experimental = {
822
+ tasks: new ExperimentalMcpServerTasks(this)
823
+ };
824
+ }
825
+ return this._experimental;
826
+ }
827
+ /**
828
+ * Attaches to the given transport, starts it, and starts listening for messages.
829
+ *
830
+ * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.
831
+ */
832
+ async connect(transport) {
833
+ return await this.server.connect(transport);
834
+ }
835
+ /**
836
+ * Closes the connection.
837
+ */
838
+ async close() {
839
+ await this.server.close();
840
+ }
841
+ setToolRequestHandlers() {
842
+ if (this._toolHandlersInitialized) {
843
+ return;
844
+ }
845
+ this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema));
846
+ this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema));
847
+ this.server.registerCapabilities({
848
+ tools: {
849
+ listChanged: true
850
+ }
851
+ });
852
+ this.server.setRequestHandler(ListToolsRequestSchema, () => ({
853
+ tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => {
854
+ const toolDefinition = {
855
+ name,
856
+ title: tool.title,
857
+ description: tool.description,
858
+ inputSchema: (() => {
859
+ const obj = normalizeObjectSchema(tool.inputSchema);
860
+ return obj ? toJsonSchemaCompat(obj, {
861
+ strictUnions: true,
862
+ pipeStrategy: "input"
863
+ }) : EMPTY_OBJECT_JSON_SCHEMA;
864
+ })(),
865
+ annotations: tool.annotations,
866
+ execution: tool.execution,
867
+ _meta: tool._meta
868
+ };
869
+ if (tool.outputSchema) {
870
+ const obj = normalizeObjectSchema(tool.outputSchema);
871
+ if (obj) {
872
+ toolDefinition.outputSchema = toJsonSchemaCompat(obj, {
873
+ strictUnions: true,
874
+ pipeStrategy: "output"
875
+ });
876
+ }
877
+ }
878
+ return toolDefinition;
879
+ })
880
+ }));
881
+ this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
882
+ try {
883
+ const tool = this._registeredTools[request.params.name];
884
+ if (!tool) {
885
+ throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`);
886
+ }
887
+ if (!tool.enabled) {
888
+ throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`);
889
+ }
890
+ const isTaskRequest = !!request.params.task;
891
+ const taskSupport = tool.execution?.taskSupport;
892
+ const isTaskHandler = "createTask" in tool.handler;
893
+ if ((taskSupport === "required" || taskSupport === "optional") && !isTaskHandler) {
894
+ throw new McpError(ErrorCode.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`);
895
+ }
896
+ if (taskSupport === "required" && !isTaskRequest) {
897
+ throw new McpError(ErrorCode.MethodNotFound, `Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`);
898
+ }
899
+ if (taskSupport === "optional" && !isTaskRequest && isTaskHandler) {
900
+ return await this.handleAutomaticTaskPolling(tool, request, extra);
901
+ }
902
+ const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);
903
+ const result = await this.executeToolHandler(tool, args, extra);
904
+ if (isTaskRequest) {
905
+ return result;
906
+ }
907
+ await this.validateToolOutput(tool, result, request.params.name);
908
+ return result;
909
+ } catch (error) {
910
+ if (error instanceof McpError) {
911
+ if (error.code === ErrorCode.UrlElicitationRequired) {
912
+ throw error;
913
+ }
914
+ }
915
+ return this.createToolError(error instanceof Error ? error.message : String(error));
916
+ }
917
+ });
918
+ this._toolHandlersInitialized = true;
919
+ }
920
+ /**
921
+ * Creates a tool error result.
922
+ *
923
+ * @param errorMessage - The error message.
924
+ * @returns The tool error result.
925
+ */
926
+ createToolError(errorMessage) {
927
+ return {
928
+ content: [
929
+ {
930
+ type: "text",
931
+ text: errorMessage
932
+ }
933
+ ],
934
+ isError: true
935
+ };
936
+ }
937
+ /**
938
+ * Validates tool input arguments against the tool's input schema.
939
+ */
940
+ async validateToolInput(tool, args, toolName) {
941
+ if (!tool.inputSchema) {
942
+ return void 0;
943
+ }
944
+ const inputObj = normalizeObjectSchema(tool.inputSchema);
945
+ const schemaToParse = inputObj ?? tool.inputSchema;
946
+ const parseResult = await safeParseAsync(schemaToParse, args);
947
+ if (!parseResult.success) {
948
+ const error = "error" in parseResult ? parseResult.error : "Unknown error";
949
+ const errorMessage = getParseErrorMessage(error);
950
+ throw new McpError(ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`);
951
+ }
952
+ return parseResult.data;
953
+ }
954
+ /**
955
+ * Validates tool output against the tool's output schema.
956
+ */
957
+ async validateToolOutput(tool, result, toolName) {
958
+ if (!tool.outputSchema) {
959
+ return;
960
+ }
961
+ if (!("content" in result)) {
962
+ return;
963
+ }
964
+ if (result.isError) {
965
+ return;
966
+ }
967
+ if (!result.structuredContent) {
968
+ throw new McpError(ErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);
969
+ }
970
+ const outputObj = normalizeObjectSchema(tool.outputSchema);
971
+ const parseResult = await safeParseAsync(outputObj, result.structuredContent);
972
+ if (!parseResult.success) {
973
+ const error = "error" in parseResult ? parseResult.error : "Unknown error";
974
+ const errorMessage = getParseErrorMessage(error);
975
+ throw new McpError(ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`);
976
+ }
977
+ }
978
+ /**
979
+ * Executes a tool handler (either regular or task-based).
980
+ */
981
+ async executeToolHandler(tool, args, extra) {
982
+ const handler = tool.handler;
983
+ const isTaskHandler = "createTask" in handler;
984
+ if (isTaskHandler) {
985
+ if (!extra.taskStore) {
986
+ throw new Error("No task store provided.");
987
+ }
988
+ const taskExtra = { ...extra, taskStore: extra.taskStore };
989
+ if (tool.inputSchema) {
990
+ const typedHandler = handler;
991
+ return await Promise.resolve(typedHandler.createTask(args, taskExtra));
992
+ } else {
993
+ const typedHandler = handler;
994
+ return await Promise.resolve(typedHandler.createTask(taskExtra));
995
+ }
996
+ }
997
+ if (tool.inputSchema) {
998
+ const typedHandler = handler;
999
+ return await Promise.resolve(typedHandler(args, extra));
1000
+ } else {
1001
+ const typedHandler = handler;
1002
+ return await Promise.resolve(typedHandler(extra));
1003
+ }
1004
+ }
1005
+ /**
1006
+ * Handles automatic task polling for tools with taskSupport 'optional'.
1007
+ */
1008
+ async handleAutomaticTaskPolling(tool, request, extra) {
1009
+ if (!extra.taskStore) {
1010
+ throw new Error("No task store provided for task-capable tool.");
1011
+ }
1012
+ const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);
1013
+ const handler = tool.handler;
1014
+ const taskExtra = { ...extra, taskStore: extra.taskStore };
1015
+ const createTaskResult = args ? await Promise.resolve(handler.createTask(args, taskExtra)) : (
1016
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1017
+ await Promise.resolve(handler.createTask(taskExtra))
1018
+ );
1019
+ const taskId = createTaskResult.task.taskId;
1020
+ let task = createTaskResult.task;
1021
+ const pollInterval = task.pollInterval ?? 5e3;
1022
+ while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") {
1023
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
1024
+ const updatedTask = await extra.taskStore.getTask(taskId);
1025
+ if (!updatedTask) {
1026
+ throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`);
1027
+ }
1028
+ task = updatedTask;
1029
+ }
1030
+ return await extra.taskStore.getTaskResult(taskId);
1031
+ }
1032
+ setCompletionRequestHandler() {
1033
+ if (this._completionHandlerInitialized) {
1034
+ return;
1035
+ }
1036
+ this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema));
1037
+ this.server.registerCapabilities({
1038
+ completions: {}
1039
+ });
1040
+ this.server.setRequestHandler(CompleteRequestSchema, async (request) => {
1041
+ switch (request.params.ref.type) {
1042
+ case "ref/prompt":
1043
+ assertCompleteRequestPrompt(request);
1044
+ return this.handlePromptCompletion(request, request.params.ref);
1045
+ case "ref/resource":
1046
+ assertCompleteRequestResourceTemplate(request);
1047
+ return this.handleResourceCompletion(request, request.params.ref);
1048
+ default:
1049
+ throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`);
1050
+ }
1051
+ });
1052
+ this._completionHandlerInitialized = true;
1053
+ }
1054
+ async handlePromptCompletion(request, ref) {
1055
+ const prompt = this._registeredPrompts[ref.name];
1056
+ if (!prompt) {
1057
+ throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`);
1058
+ }
1059
+ if (!prompt.enabled) {
1060
+ throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`);
1061
+ }
1062
+ if (!prompt.argsSchema) {
1063
+ return EMPTY_COMPLETION_RESULT;
1064
+ }
1065
+ const promptShape = getObjectShape(prompt.argsSchema);
1066
+ const field = promptShape?.[request.params.argument.name];
1067
+ if (!isCompletable(field)) {
1068
+ return EMPTY_COMPLETION_RESULT;
1069
+ }
1070
+ const completer = getCompleter(field);
1071
+ if (!completer) {
1072
+ return EMPTY_COMPLETION_RESULT;
1073
+ }
1074
+ const suggestions = await completer(request.params.argument.value, request.params.context);
1075
+ return createCompletionResult(suggestions);
1076
+ }
1077
+ async handleResourceCompletion(request, ref) {
1078
+ const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri);
1079
+ if (!template) {
1080
+ if (this._registeredResources[ref.uri]) {
1081
+ return EMPTY_COMPLETION_RESULT;
1082
+ }
1083
+ throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`);
1084
+ }
1085
+ const completer = template.resourceTemplate.completeCallback(request.params.argument.name);
1086
+ if (!completer) {
1087
+ return EMPTY_COMPLETION_RESULT;
1088
+ }
1089
+ const suggestions = await completer(request.params.argument.value, request.params.context);
1090
+ return createCompletionResult(suggestions);
1091
+ }
1092
+ setResourceRequestHandlers() {
1093
+ if (this._resourceHandlersInitialized) {
1094
+ return;
1095
+ }
1096
+ this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema));
1097
+ this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema));
1098
+ this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema));
1099
+ this.server.registerCapabilities({
1100
+ resources: {
1101
+ listChanged: true
1102
+ }
1103
+ });
1104
+ this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => {
1105
+ const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({
1106
+ uri,
1107
+ name: resource.name,
1108
+ ...resource.metadata
1109
+ }));
1110
+ const templateResources = [];
1111
+ for (const template of Object.values(this._registeredResourceTemplates)) {
1112
+ if (!template.resourceTemplate.listCallback) {
1113
+ continue;
1114
+ }
1115
+ const result = await template.resourceTemplate.listCallback(extra);
1116
+ for (const resource of result.resources) {
1117
+ templateResources.push({
1118
+ ...template.metadata,
1119
+ // the defined resource metadata should override the template metadata if present
1120
+ ...resource
1121
+ });
1122
+ }
1123
+ }
1124
+ return { resources: [...resources, ...templateResources] };
1125
+ });
1126
+ this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {
1127
+ const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({
1128
+ name,
1129
+ uriTemplate: template.resourceTemplate.uriTemplate.toString(),
1130
+ ...template.metadata
1131
+ }));
1132
+ return { resourceTemplates };
1133
+ });
1134
+ this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {
1135
+ const uri = new URL(request.params.uri);
1136
+ const resource = this._registeredResources[uri.toString()];
1137
+ if (resource) {
1138
+ if (!resource.enabled) {
1139
+ throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`);
1140
+ }
1141
+ return resource.readCallback(uri, extra);
1142
+ }
1143
+ for (const template of Object.values(this._registeredResourceTemplates)) {
1144
+ const variables = template.resourceTemplate.uriTemplate.match(uri.toString());
1145
+ if (variables) {
1146
+ return template.readCallback(uri, variables, extra);
1147
+ }
1148
+ }
1149
+ throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`);
1150
+ });
1151
+ this._resourceHandlersInitialized = true;
1152
+ }
1153
+ setPromptRequestHandlers() {
1154
+ if (this._promptHandlersInitialized) {
1155
+ return;
1156
+ }
1157
+ this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema));
1158
+ this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema));
1159
+ this.server.registerCapabilities({
1160
+ prompts: {
1161
+ listChanged: true
1162
+ }
1163
+ });
1164
+ this.server.setRequestHandler(ListPromptsRequestSchema, () => ({
1165
+ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => {
1166
+ return {
1167
+ name,
1168
+ title: prompt.title,
1169
+ description: prompt.description,
1170
+ arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : void 0
1171
+ };
1172
+ })
1173
+ }));
1174
+ this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => {
1175
+ const prompt = this._registeredPrompts[request.params.name];
1176
+ if (!prompt) {
1177
+ throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`);
1178
+ }
1179
+ if (!prompt.enabled) {
1180
+ throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`);
1181
+ }
1182
+ if (prompt.argsSchema) {
1183
+ const argsObj = normalizeObjectSchema(prompt.argsSchema);
1184
+ const parseResult = await safeParseAsync(argsObj, request.params.arguments);
1185
+ if (!parseResult.success) {
1186
+ const error = "error" in parseResult ? parseResult.error : "Unknown error";
1187
+ const errorMessage = getParseErrorMessage(error);
1188
+ throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${errorMessage}`);
1189
+ }
1190
+ const args = parseResult.data;
1191
+ const cb = prompt.callback;
1192
+ return await Promise.resolve(cb(args, extra));
1193
+ } else {
1194
+ const cb = prompt.callback;
1195
+ return await Promise.resolve(cb(extra));
1196
+ }
1197
+ });
1198
+ this._promptHandlersInitialized = true;
1199
+ }
1200
+ resource(name, uriOrTemplate, ...rest) {
1201
+ let metadata;
1202
+ if (typeof rest[0] === "object") {
1203
+ metadata = rest.shift();
1204
+ }
1205
+ const readCallback = rest[0];
1206
+ if (typeof uriOrTemplate === "string") {
1207
+ if (this._registeredResources[uriOrTemplate]) {
1208
+ throw new Error(`Resource ${uriOrTemplate} is already registered`);
1209
+ }
1210
+ const registeredResource = this._createRegisteredResource(name, void 0, uriOrTemplate, metadata, readCallback);
1211
+ this.setResourceRequestHandlers();
1212
+ this.sendResourceListChanged();
1213
+ return registeredResource;
1214
+ } else {
1215
+ if (this._registeredResourceTemplates[name]) {
1216
+ throw new Error(`Resource template ${name} is already registered`);
1217
+ }
1218
+ const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, void 0, uriOrTemplate, metadata, readCallback);
1219
+ this.setResourceRequestHandlers();
1220
+ this.sendResourceListChanged();
1221
+ return registeredResourceTemplate;
1222
+ }
1223
+ }
1224
+ registerResource(name, uriOrTemplate, config, readCallback) {
1225
+ if (typeof uriOrTemplate === "string") {
1226
+ if (this._registeredResources[uriOrTemplate]) {
1227
+ throw new Error(`Resource ${uriOrTemplate} is already registered`);
1228
+ }
1229
+ const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, config, readCallback);
1230
+ this.setResourceRequestHandlers();
1231
+ this.sendResourceListChanged();
1232
+ return registeredResource;
1233
+ } else {
1234
+ if (this._registeredResourceTemplates[name]) {
1235
+ throw new Error(`Resource template ${name} is already registered`);
1236
+ }
1237
+ const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, config, readCallback);
1238
+ this.setResourceRequestHandlers();
1239
+ this.sendResourceListChanged();
1240
+ return registeredResourceTemplate;
1241
+ }
1242
+ }
1243
+ _createRegisteredResource(name, title, uri, metadata, readCallback) {
1244
+ const registeredResource = {
1245
+ name,
1246
+ title,
1247
+ metadata,
1248
+ readCallback,
1249
+ enabled: true,
1250
+ disable: () => registeredResource.update({ enabled: false }),
1251
+ enable: () => registeredResource.update({ enabled: true }),
1252
+ remove: () => registeredResource.update({ uri: null }),
1253
+ update: (updates) => {
1254
+ if (typeof updates.uri !== "undefined" && updates.uri !== uri) {
1255
+ delete this._registeredResources[uri];
1256
+ if (updates.uri)
1257
+ this._registeredResources[updates.uri] = registeredResource;
1258
+ }
1259
+ if (typeof updates.name !== "undefined")
1260
+ registeredResource.name = updates.name;
1261
+ if (typeof updates.title !== "undefined")
1262
+ registeredResource.title = updates.title;
1263
+ if (typeof updates.metadata !== "undefined")
1264
+ registeredResource.metadata = updates.metadata;
1265
+ if (typeof updates.callback !== "undefined")
1266
+ registeredResource.readCallback = updates.callback;
1267
+ if (typeof updates.enabled !== "undefined")
1268
+ registeredResource.enabled = updates.enabled;
1269
+ this.sendResourceListChanged();
1270
+ }
1271
+ };
1272
+ this._registeredResources[uri] = registeredResource;
1273
+ return registeredResource;
1274
+ }
1275
+ _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) {
1276
+ const registeredResourceTemplate = {
1277
+ resourceTemplate: template,
1278
+ title,
1279
+ metadata,
1280
+ readCallback,
1281
+ enabled: true,
1282
+ disable: () => registeredResourceTemplate.update({ enabled: false }),
1283
+ enable: () => registeredResourceTemplate.update({ enabled: true }),
1284
+ remove: () => registeredResourceTemplate.update({ name: null }),
1285
+ update: (updates) => {
1286
+ if (typeof updates.name !== "undefined" && updates.name !== name) {
1287
+ delete this._registeredResourceTemplates[name];
1288
+ if (updates.name)
1289
+ this._registeredResourceTemplates[updates.name] = registeredResourceTemplate;
1290
+ }
1291
+ if (typeof updates.title !== "undefined")
1292
+ registeredResourceTemplate.title = updates.title;
1293
+ if (typeof updates.template !== "undefined")
1294
+ registeredResourceTemplate.resourceTemplate = updates.template;
1295
+ if (typeof updates.metadata !== "undefined")
1296
+ registeredResourceTemplate.metadata = updates.metadata;
1297
+ if (typeof updates.callback !== "undefined")
1298
+ registeredResourceTemplate.readCallback = updates.callback;
1299
+ if (typeof updates.enabled !== "undefined")
1300
+ registeredResourceTemplate.enabled = updates.enabled;
1301
+ this.sendResourceListChanged();
1302
+ }
1303
+ };
1304
+ this._registeredResourceTemplates[name] = registeredResourceTemplate;
1305
+ const variableNames = template.uriTemplate.variableNames;
1306
+ const hasCompleter = Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v));
1307
+ if (hasCompleter) {
1308
+ this.setCompletionRequestHandler();
1309
+ }
1310
+ return registeredResourceTemplate;
1311
+ }
1312
+ _createRegisteredPrompt(name, title, description, argsSchema, callback) {
1313
+ const registeredPrompt = {
1314
+ title,
1315
+ description,
1316
+ argsSchema: argsSchema === void 0 ? void 0 : objectFromShape(argsSchema),
1317
+ callback,
1318
+ enabled: true,
1319
+ disable: () => registeredPrompt.update({ enabled: false }),
1320
+ enable: () => registeredPrompt.update({ enabled: true }),
1321
+ remove: () => registeredPrompt.update({ name: null }),
1322
+ update: (updates) => {
1323
+ if (typeof updates.name !== "undefined" && updates.name !== name) {
1324
+ delete this._registeredPrompts[name];
1325
+ if (updates.name)
1326
+ this._registeredPrompts[updates.name] = registeredPrompt;
1327
+ }
1328
+ if (typeof updates.title !== "undefined")
1329
+ registeredPrompt.title = updates.title;
1330
+ if (typeof updates.description !== "undefined")
1331
+ registeredPrompt.description = updates.description;
1332
+ if (typeof updates.argsSchema !== "undefined")
1333
+ registeredPrompt.argsSchema = objectFromShape(updates.argsSchema);
1334
+ if (typeof updates.callback !== "undefined")
1335
+ registeredPrompt.callback = updates.callback;
1336
+ if (typeof updates.enabled !== "undefined")
1337
+ registeredPrompt.enabled = updates.enabled;
1338
+ this.sendPromptListChanged();
1339
+ }
1340
+ };
1341
+ this._registeredPrompts[name] = registeredPrompt;
1342
+ if (argsSchema) {
1343
+ const hasCompletable = Object.values(argsSchema).some((field) => {
1344
+ const inner = field instanceof ZodOptional ? field._def?.innerType : field;
1345
+ return isCompletable(inner);
1346
+ });
1347
+ if (hasCompletable) {
1348
+ this.setCompletionRequestHandler();
1349
+ }
1350
+ }
1351
+ return registeredPrompt;
1352
+ }
1353
+ _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, execution, _meta, handler) {
1354
+ validateAndWarnToolName(name);
1355
+ const registeredTool = {
1356
+ title,
1357
+ description,
1358
+ inputSchema: getZodSchemaObject(inputSchema),
1359
+ outputSchema: getZodSchemaObject(outputSchema),
1360
+ annotations,
1361
+ execution,
1362
+ _meta,
1363
+ handler,
1364
+ enabled: true,
1365
+ disable: () => registeredTool.update({ enabled: false }),
1366
+ enable: () => registeredTool.update({ enabled: true }),
1367
+ remove: () => registeredTool.update({ name: null }),
1368
+ update: (updates) => {
1369
+ if (typeof updates.name !== "undefined" && updates.name !== name) {
1370
+ if (typeof updates.name === "string") {
1371
+ validateAndWarnToolName(updates.name);
1372
+ }
1373
+ delete this._registeredTools[name];
1374
+ if (updates.name)
1375
+ this._registeredTools[updates.name] = registeredTool;
1376
+ }
1377
+ if (typeof updates.title !== "undefined")
1378
+ registeredTool.title = updates.title;
1379
+ if (typeof updates.description !== "undefined")
1380
+ registeredTool.description = updates.description;
1381
+ if (typeof updates.paramsSchema !== "undefined")
1382
+ registeredTool.inputSchema = objectFromShape(updates.paramsSchema);
1383
+ if (typeof updates.outputSchema !== "undefined")
1384
+ registeredTool.outputSchema = objectFromShape(updates.outputSchema);
1385
+ if (typeof updates.callback !== "undefined")
1386
+ registeredTool.handler = updates.callback;
1387
+ if (typeof updates.annotations !== "undefined")
1388
+ registeredTool.annotations = updates.annotations;
1389
+ if (typeof updates._meta !== "undefined")
1390
+ registeredTool._meta = updates._meta;
1391
+ if (typeof updates.enabled !== "undefined")
1392
+ registeredTool.enabled = updates.enabled;
1393
+ this.sendToolListChanged();
1394
+ }
1395
+ };
1396
+ this._registeredTools[name] = registeredTool;
1397
+ this.setToolRequestHandlers();
1398
+ this.sendToolListChanged();
1399
+ return registeredTool;
1400
+ }
1401
+ /**
1402
+ * tool() implementation. Parses arguments passed to overrides defined above.
1403
+ */
1404
+ tool(name, ...rest) {
1405
+ if (this._registeredTools[name]) {
1406
+ throw new Error(`Tool ${name} is already registered`);
1407
+ }
1408
+ let description;
1409
+ let inputSchema;
1410
+ let outputSchema;
1411
+ let annotations;
1412
+ if (typeof rest[0] === "string") {
1413
+ description = rest.shift();
1414
+ }
1415
+ if (rest.length > 1) {
1416
+ const firstArg = rest[0];
1417
+ if (isZodRawShapeCompat(firstArg)) {
1418
+ inputSchema = rest.shift();
1419
+ if (rest.length > 1 && typeof rest[0] === "object" && rest[0] !== null && !isZodRawShapeCompat(rest[0])) {
1420
+ annotations = rest.shift();
1421
+ }
1422
+ } else if (typeof firstArg === "object" && firstArg !== null) {
1423
+ if (Object.values(firstArg).some((v) => typeof v === "object" && v !== null)) {
1424
+ throw new Error(`Tool ${name} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);
1425
+ }
1426
+ annotations = rest.shift();
1427
+ }
1428
+ }
1429
+ const callback = rest[0];
1430
+ return this._createRegisteredTool(name, void 0, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, void 0, callback);
1431
+ }
1432
+ /**
1433
+ * Registers a tool with a config object and callback.
1434
+ */
1435
+ registerTool(name, config, cb) {
1436
+ if (this._registeredTools[name]) {
1437
+ throw new Error(`Tool ${name} is already registered`);
1438
+ }
1439
+ const { title, description, inputSchema, outputSchema, annotations, _meta } = config;
1440
+ return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, _meta, cb);
1441
+ }
1442
+ prompt(name, ...rest) {
1443
+ if (this._registeredPrompts[name]) {
1444
+ throw new Error(`Prompt ${name} is already registered`);
1445
+ }
1446
+ let description;
1447
+ if (typeof rest[0] === "string") {
1448
+ description = rest.shift();
1449
+ }
1450
+ let argsSchema;
1451
+ if (rest.length > 1) {
1452
+ argsSchema = rest.shift();
1453
+ }
1454
+ const cb = rest[0];
1455
+ const registeredPrompt = this._createRegisteredPrompt(name, void 0, description, argsSchema, cb);
1456
+ this.setPromptRequestHandlers();
1457
+ this.sendPromptListChanged();
1458
+ return registeredPrompt;
1459
+ }
1460
+ /**
1461
+ * Registers a prompt with a config object and callback.
1462
+ */
1463
+ registerPrompt(name, config, cb) {
1464
+ if (this._registeredPrompts[name]) {
1465
+ throw new Error(`Prompt ${name} is already registered`);
1466
+ }
1467
+ const { title, description, argsSchema } = config;
1468
+ const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb);
1469
+ this.setPromptRequestHandlers();
1470
+ this.sendPromptListChanged();
1471
+ return registeredPrompt;
1472
+ }
1473
+ /**
1474
+ * Checks if the server is connected to a transport.
1475
+ * @returns True if the server is connected
1476
+ */
1477
+ isConnected() {
1478
+ return this.server.transport !== void 0;
1479
+ }
1480
+ /**
1481
+ * Sends a logging message to the client, if connected.
1482
+ * Note: You only need to send the parameters object, not the entire JSON RPC message
1483
+ * @see LoggingMessageNotification
1484
+ * @param params
1485
+ * @param sessionId optional for stateless and backward compatibility
1486
+ */
1487
+ async sendLoggingMessage(params, sessionId) {
1488
+ return this.server.sendLoggingMessage(params, sessionId);
1489
+ }
1490
+ /**
1491
+ * Sends a resource list changed event to the client, if connected.
1492
+ */
1493
+ sendResourceListChanged() {
1494
+ if (this.isConnected()) {
1495
+ this.server.sendResourceListChanged();
1496
+ }
1497
+ }
1498
+ /**
1499
+ * Sends a tool list changed event to the client, if connected.
1500
+ */
1501
+ sendToolListChanged() {
1502
+ if (this.isConnected()) {
1503
+ this.server.sendToolListChanged();
1504
+ }
1505
+ }
1506
+ /**
1507
+ * Sends a prompt list changed event to the client, if connected.
1508
+ */
1509
+ sendPromptListChanged() {
1510
+ if (this.isConnected()) {
1511
+ this.server.sendPromptListChanged();
1512
+ }
1513
+ }
1514
+ };
1515
+ var EMPTY_OBJECT_JSON_SCHEMA = {
1516
+ type: "object",
1517
+ properties: {}
1518
+ };
1519
+ function isZodTypeLike(value) {
1520
+ return value !== null && typeof value === "object" && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
1521
+ }
1522
+ function isZodSchemaInstance(obj) {
1523
+ return "_def" in obj || "_zod" in obj || isZodTypeLike(obj);
1524
+ }
1525
+ function isZodRawShapeCompat(obj) {
1526
+ if (typeof obj !== "object" || obj === null) {
1527
+ return false;
1528
+ }
1529
+ if (isZodSchemaInstance(obj)) {
1530
+ return false;
1531
+ }
1532
+ if (Object.keys(obj).length === 0) {
1533
+ return true;
1534
+ }
1535
+ return Object.values(obj).some(isZodTypeLike);
1536
+ }
1537
+ function getZodSchemaObject(schema) {
1538
+ if (!schema) {
1539
+ return void 0;
1540
+ }
1541
+ if (isZodRawShapeCompat(schema)) {
1542
+ return objectFromShape(schema);
1543
+ }
1544
+ if (!isZodSchemaInstance(schema)) {
1545
+ throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");
1546
+ }
1547
+ return schema;
1548
+ }
1549
+ function promptArgumentsFromSchema(schema) {
1550
+ const shape = getObjectShape(schema);
1551
+ if (!shape)
1552
+ return [];
1553
+ return Object.entries(shape).map(([name, field]) => {
1554
+ const description = getSchemaDescription(field);
1555
+ const isOptional = isSchemaOptional(field);
1556
+ return {
1557
+ name,
1558
+ description,
1559
+ required: !isOptional
1560
+ };
1561
+ });
1562
+ }
1563
+ function getMethodValue(schema) {
1564
+ const shape = getObjectShape(schema);
1565
+ const methodSchema = shape?.method;
1566
+ if (!methodSchema) {
1567
+ throw new Error("Schema is missing a method literal");
1568
+ }
1569
+ const value = getLiteralValue(methodSchema);
1570
+ if (typeof value === "string") {
1571
+ return value;
1572
+ }
1573
+ throw new Error("Schema method literal must be a string");
1574
+ }
1575
+ function createCompletionResult(suggestions) {
1576
+ return {
1577
+ completion: {
1578
+ values: suggestions.slice(0, 100),
1579
+ total: suggestions.length,
1580
+ hasMore: suggestions.length > 100
1581
+ }
1582
+ };
1583
+ }
1584
+ var EMPTY_COMPLETION_RESULT = {
1585
+ completion: {
1586
+ values: [],
1587
+ hasMore: false
1588
+ }
1589
+ };
1590
+
1591
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
1592
+ init_esm_shims();
1593
+ import process2 from "process";
1594
+ var StdioServerTransport = class {
1595
+ constructor(_stdin = process2.stdin, _stdout = process2.stdout) {
1596
+ this._stdin = _stdin;
1597
+ this._stdout = _stdout;
1598
+ this._readBuffer = new ReadBuffer();
1599
+ this._started = false;
1600
+ this._ondata = (chunk) => {
1601
+ this._readBuffer.append(chunk);
1602
+ this.processReadBuffer();
1603
+ };
1604
+ this._onerror = (error) => {
1605
+ this.onerror?.(error);
1606
+ };
1607
+ }
1608
+ /**
1609
+ * Starts listening for messages on stdin.
1610
+ */
1611
+ async start() {
1612
+ if (this._started) {
1613
+ throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");
1614
+ }
1615
+ this._started = true;
1616
+ this._stdin.on("data", this._ondata);
1617
+ this._stdin.on("error", this._onerror);
1618
+ }
1619
+ processReadBuffer() {
1620
+ while (true) {
1621
+ try {
1622
+ const message = this._readBuffer.readMessage();
1623
+ if (message === null) {
1624
+ break;
1625
+ }
1626
+ this.onmessage?.(message);
1627
+ } catch (error) {
1628
+ this.onerror?.(error);
1629
+ }
1630
+ }
1631
+ }
1632
+ async close() {
1633
+ this._stdin.off("data", this._ondata);
1634
+ this._stdin.off("error", this._onerror);
1635
+ const remainingDataListeners = this._stdin.listenerCount("data");
1636
+ if (remainingDataListeners === 0) {
1637
+ this._stdin.pause();
1638
+ }
1639
+ this._readBuffer.clear();
1640
+ this.onclose?.();
1641
+ }
1642
+ send(message) {
1643
+ return new Promise((resolve) => {
1644
+ const json2 = serializeMessage(message);
1645
+ if (this._stdout.write(json2)) {
1646
+ resolve();
1647
+ } else {
1648
+ this._stdout.once("drain", resolve);
1649
+ }
1650
+ });
1651
+ }
1652
+ };
1653
+
1654
+ // src/mcp/server.ts
1655
+ var import_semver = __toESM(require_semver(), 1);
1656
+
1657
+ // src/mcp/metrics.ts
1658
+ init_esm_shims();
1659
+ var stats = /* @__PURE__ */ new Map();
1660
+ function recordToolCall(tool, ok, ms) {
1661
+ const s = stats.get(tool) ?? { calls: 0, errors: 0, totalMs: 0 };
1662
+ s.calls += 1;
1663
+ if (!ok) s.errors += 1;
1664
+ s.totalMs += ms;
1665
+ stats.set(tool, s);
1666
+ }
1667
+ async function timed(tool, fn) {
1668
+ const start = Date.now();
1669
+ let ok = false;
1670
+ try {
1671
+ const result = await fn();
1672
+ ok = true;
1673
+ return result;
1674
+ } finally {
1675
+ recordToolCall(tool, ok, Date.now() - start);
1676
+ }
1677
+ }
1678
+ function renderPrometheus() {
1679
+ const lines = [
1680
+ "# HELP lurq_tool_calls_total Total MCP tool invocations.",
1681
+ "# TYPE lurq_tool_calls_total counter",
1682
+ "# HELP lurq_tool_errors_total MCP tool invocations that threw.",
1683
+ "# TYPE lurq_tool_errors_total counter",
1684
+ "# HELP lurq_tool_duration_ms_total Cumulative tool handler time in ms.",
1685
+ "# TYPE lurq_tool_duration_ms_total counter"
1686
+ ];
1687
+ for (const [tool, s] of stats) {
1688
+ const label = `{tool="${tool}"}`;
1689
+ lines.push(`lurq_tool_calls_total${label} ${s.calls}`);
1690
+ lines.push(`lurq_tool_errors_total${label} ${s.errors}`);
1691
+ lines.push(`lurq_tool_duration_ms_total${label} ${s.totalMs}`);
1692
+ }
1693
+ return lines.join("\n") + "\n";
1694
+ }
1695
+
1696
+ // src/mcp/compact.ts
1697
+ init_esm_shims();
1698
+ function compact(value) {
1699
+ if (value instanceof Date) return value;
1700
+ if (Array.isArray(value)) {
1701
+ return value.filter((v) => v !== null && v !== void 0).map((v) => compact(v));
1702
+ }
1703
+ if (value !== null && typeof value === "object") {
1704
+ const out = {};
1705
+ for (const [key, raw] of Object.entries(value)) {
1706
+ if (raw === null || raw === void 0) continue;
1707
+ out[key] = compact(raw);
1708
+ }
1709
+ return out;
1710
+ }
1711
+ return value;
1712
+ }
1713
+
1714
+ // src/mcp/toolDescriptions.ts
1715
+ init_esm_shims();
1716
+ var VERIFY_DESCRIPTION = "Confirm an npm package is real, healthy, and not risky before installing: guards against hallucinated or typosquatted names, deprecations and known advisories, and returns a safety verdict with its reasons and what was not checked. Checks the live registry. The cheap gate to call before every install; use evaluate when you need the full scores.";
1717
+ var COMPAT_DESCRIPTION = "Check whether a set of packages forms a coherent stack. Resolves the whole set the way npm would and returns a definitive verdict: compatible, conflict (with the exact clashing constraints), or unknown. Checks peer-dependency and engine ranges from declared metadata, plus any recorded sandbox conflicts. Read-only: never installs or executes package code. Not always instant: a set checked before answers immediately, but a new set is resolved live from registry metadata, which can take up to ~25 seconds. Call once with the whole stack before committing to it.";
1718
+ var COMPAT_PACKAGES_DESCRIPTION = "The full candidate stack to check together, 2\u201330 npm package names \u2014 a whole package.json dependency list is the intended input. Pass every package in one call: conflicts routinely appear only across the whole set (a peer range three packages deep), so checking pairs separately misses them and costs a round trip each.";
1719
+ var COMPAT_VERSIONS_DESCRIPTION = 'Optional exact versions keyed by package name, e.g. {"react":"19.0.0"} (use when not checking latest). Must be exact semver versions, not ranges.';
1720
+ var COMPAT_NODE_DESCRIPTION = 'Optional target Node runtime (e.g. "20" or "20.20.2") for engines.node checks';
1721
+
1722
+ // src/db/usage.ts
1723
+ init_esm_shims();
1724
+ import { and, desc, eq, gte, sql } from "drizzle-orm";
1725
+ function windowStart(days) {
1726
+ return sql`CURRENT_DATE - (${days}::int - 1)`;
1727
+ }
1728
+ async function recordUsage(db, ownerId, tool) {
1729
+ if (!ownerId) return;
1730
+ try {
1731
+ await db.insert(ownerUsageDaily).values({ ownerId, date: sql`CURRENT_DATE`, tool, count: 1 }).onConflictDoUpdate({
1732
+ target: [ownerUsageDaily.ownerId, ownerUsageDaily.date, ownerUsageDaily.tool],
1733
+ set: { count: sql`${ownerUsageDaily.count} + 1` }
1734
+ });
1735
+ } catch {
1736
+ }
1737
+ }
1738
+ async function getUsageSummary(db, ownerId, days) {
1739
+ const rows = await db.execute(sql`
1740
+ select
1741
+ to_char(d, 'YYYY-MM-DD') as date,
1742
+ coalesce(sum(u.count), 0)::int as count
1743
+ from generate_series(${windowStart(days)}, CURRENT_DATE, interval '1 day') as d
1744
+ left join ${ownerUsageDaily} u
1745
+ on u.date = d::date and u.owner_id = ${ownerId}
1746
+ group by d
1747
+ order by d
1748
+ `);
1749
+ const series = rows.map((r) => ({ date: String(r.date), count: Number(r.count) }));
1750
+ const today = series.at(-1)?.count ?? 0;
1751
+ return { today, series };
1752
+ }
1753
+ async function getUsageByTool(db, ownerId, days) {
1754
+ const rows = await db.select({
1755
+ tool: ownerUsageDaily.tool,
1756
+ count: sql`sum(${ownerUsageDaily.count})::int`
1757
+ }).from(ownerUsageDaily).where(
1758
+ and(
1759
+ eq(ownerUsageDaily.ownerId, ownerId),
1760
+ gte(ownerUsageDaily.date, windowStart(days))
1761
+ )
1762
+ ).groupBy(ownerUsageDaily.tool).orderBy(desc(sql`sum(${ownerUsageDaily.count})`));
1763
+ return rows.map((r) => ({ tool: r.tool, count: Number(r.count) }));
1764
+ }
1765
+
1766
+ // src/core/analytics.ts
1767
+ init_esm_shims();
1768
+ var HOST = "https://us.i.posthog.com";
1769
+ var FLUSH_AT = 50;
1770
+ var FLUSH_MS = 1e4;
1771
+ var queue = [];
1772
+ var timer = null;
1773
+ function capture(distinctId, event, properties = {}) {
1774
+ if (!distinctId || !getConfig().LURQ_POSTHOG_KEY) return;
1775
+ queue.push({
1776
+ event,
1777
+ properties: { ...properties, distinct_id: distinctId },
1778
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1779
+ });
1780
+ if (queue.length >= FLUSH_AT) {
1781
+ void flush();
1782
+ } else if (!timer) {
1783
+ timer = setTimeout(() => void flush(), FLUSH_MS);
1784
+ timer.unref();
1785
+ }
1786
+ }
1787
+ async function flush() {
1788
+ if (timer) {
1789
+ clearTimeout(timer);
1790
+ timer = null;
1791
+ }
1792
+ const key = getConfig().LURQ_POSTHOG_KEY;
1793
+ if (!key || queue.length === 0) return;
1794
+ const batch = queue;
1795
+ queue = [];
1796
+ try {
1797
+ const res = await fetch(`${HOST}/batch/`, {
1798
+ method: "POST",
1799
+ headers: { "Content-Type": "application/json" },
1800
+ body: JSON.stringify({ api_key: key, batch }),
1801
+ signal: AbortSignal.timeout(5e3)
1802
+ });
1803
+ if (!res.ok) logger.warn(`posthog batch rejected (${res.status}), dropped ${batch.length} event(s)`);
1804
+ } catch (err) {
1805
+ logger.warn("posthog batch failed:", err instanceof Error ? err.message : String(err));
1806
+ }
1807
+ }
1808
+
1809
+ // src/mcp/server.ts
1810
+ var npmName = external_exports.string().trim().min(1).max(214).regex(/^(?:@[a-z0-9-][a-z0-9-._]*\/)?[a-z0-9-][a-z0-9-._]*$/i, "Invalid npm package name");
1811
+ var exactVersion = external_exports.string().trim().max(256).refine((v) => import_semver.default.valid(v) !== null, 'Must be an exact semver version, e.g. "19.0.0"');
1812
+ function json(obj) {
1813
+ return { content: [{ type: "text", text: JSON.stringify(compact(obj)) }] };
1814
+ }
1815
+ var SERVER_INSTRUCTIONS = [
1816
+ "lurq answers npm package questions from evidence instead of training data.",
1817
+ "Call verify before installing any package, compat before committing to a set of versions, and usage before writing code against a package API that may have moved.",
1818
+ "When choosing a library, bring the candidates you know and check them with compare or evaluate: lurq verifies choices, it does not search for them.",
1819
+ "If unsure which tool fits, call capabilities.",
1820
+ "When lurq flags a problem (a package that does not exist, a deprecation, an advisory, a version conflict), tell the user what it found and that it came from lurq, with the evidence it returned."
1821
+ ].join(" ");
1822
+ var READ_INDEX = { readOnlyHint: true, openWorldHint: false };
1823
+ var READ_LIVE = { readOnlyHint: true, openWorldHint: true };
1824
+ function buildMcpServer(db, ctx = {}) {
1825
+ const server = new McpServer(
1826
+ { name: SERVER_NAME, version: VERSION },
1827
+ { instructions: SERVER_INSTRUCTIONS }
1828
+ );
1829
+ const run = (tool, fn) => (async () => {
1830
+ let ok = false;
1831
+ try {
1832
+ const result = await timed(tool, fn);
1833
+ ok = true;
1834
+ return result;
1835
+ } finally {
1836
+ void recordUsage(db, ctx.ownerId ?? null, tool);
1837
+ capture(ctx.ownerId, "tool_called", { tool, ok });
1838
+ }
1839
+ })();
1840
+ const reply = (obj) => {
1841
+ const result = json(obj);
1842
+ if (ctx.notice) result.content.push({ type: "text", text: ctx.notice });
1843
+ return result;
1844
+ };
1845
+ server.registerTool(
1846
+ "evaluate",
1847
+ {
1848
+ title: "Evaluate a package",
1849
+ description: "Full evidence read for one npm package: health and quality scores and the signals behind them, advisories, the shared safety verdict, a summary and a usage guide. Use it when a choice needs more than verify's install gate. Enforces the account's dependency policy. A package lurq has never tracked is fetched and scored on demand, waiting up to ~4 seconds; if scoring takes longer the result is `tracked: false` with a note to retry in a few seconds, which is not an answer about the package.",
1850
+ annotations: READ_LIVE,
1851
+ inputSchema: {
1852
+ package: npmName.describe("npm package name")
1853
+ }
1854
+ },
1855
+ async (args) => reply(await run("evaluate", () => handleEvaluate(db, args, ctx.ownerId ?? null)))
1856
+ );
1857
+ server.registerTool(
1858
+ "policy",
1859
+ {
1860
+ title: "Read the dependency policy",
1861
+ description: "The rules this account's selection policy enforces on which packages you may add: denied packages (with the reason), license allowlist, confidence, advisory, adoption, staleness and bundle-size floors. Read it once before choosing dependencies so you pick an allowed package first; evaluate already enforces it. Read-only.",
1862
+ annotations: READ_INDEX,
1863
+ inputSchema: {}
1864
+ },
1865
+ async () => reply(await run("policy", () => handlePolicy(db, ctx.ownerId ?? null)))
1866
+ );
1867
+ server.registerTool(
1868
+ "compare",
1869
+ {
1870
+ title: "Compare packages",
1871
+ description: "Side-by-side comparison of 2\u20135 npm packages you are choosing between, ranked by health score. Untracked names are fetched on demand; one still being scored comes back under `pending` (retry shortly), and a name not on npm under `notFound`.",
1872
+ annotations: READ_LIVE,
1873
+ inputSchema: {
1874
+ packages: external_exports.array(npmName).min(2).max(5).describe("2\u20135 npm package names")
1875
+ }
1876
+ },
1877
+ async (args) => reply(await run("compare", () => handleCompare(db, args, ctx.ownerId ?? null)))
1878
+ );
1879
+ server.registerTool(
1880
+ "compat",
1881
+ {
1882
+ title: "Check package compatibility",
1883
+ description: COMPAT_DESCRIPTION,
1884
+ annotations: READ_LIVE,
1885
+ inputSchema: {
1886
+ packages: external_exports.array(npmName).min(2).max(30).describe(COMPAT_PACKAGES_DESCRIPTION),
1887
+ versions: external_exports.record(exactVersion).optional().describe(COMPAT_VERSIONS_DESCRIPTION),
1888
+ node: external_exports.string().optional().describe(COMPAT_NODE_DESCRIPTION)
1889
+ }
1890
+ },
1891
+ async (args) => reply(await run("compat", () => handleCompat(db, args)))
1892
+ );
1893
+ server.registerTool(
1894
+ "verify",
1895
+ {
1896
+ title: "Verify a package",
1897
+ description: VERIFY_DESCRIPTION,
1898
+ annotations: READ_LIVE,
1899
+ inputSchema: {
1900
+ package: npmName.describe("npm package name to verify")
1901
+ }
1902
+ },
1903
+ async (args) => reply(await run("verify", () => handleVerify(db, args, ctx.ownerId ?? null)))
1904
+ );
1905
+ server.registerTool(
1906
+ "usage",
1907
+ {
1908
+ title: "Version-exact API surface + drift",
1909
+ description: "A package version's TYPED API: exported symbols and their signatures from its shipped .d.ts (or DefinitelyTyped), exact to the version, none of it in the model's training data. Use before writing code against a package whose API may have moved. For whether a name exists at RUNTIME (what decides if an import throws) use resolve_surface; for is-it-safe-to-install use verify. Pass knownVersion (e.g. the version you were trained on) to get the precise delta: added, removed, renamed, changed. Also returns the version's declared engines (Node/runtime floor). Large surfaces are paged, 80 symbols per call: `totalSymbols` is the size, `query` filters by name, `offset` pages. `shallow: true` means the API lives on an interface's members that are not listed, and the note says where to read them. For framework file/convention changes (not exported symbols), consult the official migration guide / Context7 instead.",
1910
+ annotations: READ_LIVE,
1911
+ inputSchema: {
1912
+ package: npmName.describe("npm package name"),
1913
+ version: external_exports.string().optional().describe("Target version (defaults to latest)"),
1914
+ knownVersion: external_exports.string().optional().describe("A version you already know; returns the API delta from it to the target"),
1915
+ query: external_exports.string().max(100).optional().describe("Part of a symbol name (case-insensitive); returns only matching symbols"),
1916
+ offset: external_exports.number().int().min(0).optional().describe("Index of the first symbol to return, to page past the first 80")
1917
+ }
1918
+ },
1919
+ async (args) => reply(await run("usage", () => handleUsage(db, args)))
1920
+ );
1921
+ server.registerTool(
1922
+ "diagram",
1923
+ {
1924
+ title: "Reference architecture diagram",
1925
+ description: "Emit a reference-architecture Mermaid diagram for a stack you have already chosen (package names). A labeled starting point keyed by layer, not a validated architecture, and not an architecture designer.",
1926
+ annotations: READ_INDEX,
1927
+ inputSchema: {
1928
+ stack: external_exports.array(npmName).optional().describe("Package names that make up the stack; omit or empty to get usage guidance")
1929
+ }
1930
+ },
1931
+ async (args) => reply(await run("diagram", () => handleDiagram(db, args)))
1932
+ );
1933
+ server.registerTool(
1934
+ "resolve_surface",
1935
+ {
1936
+ title: "Version-exact runtime surface",
1937
+ description: "What a package version ACTUALLY exports at runtime, extracted from its shipped JavaScript rather than from documentation or the model's memory: names and arity, not type signatures (use usage for those). Call before writing code against a package whose API may have moved. Runtime existence is what decides whether an import throws; a removed type breaks tsc, a removed runtime symbol breaks the program. A miss returns UNKNOWN and queues extraction, UNKNOWN never means the symbol is absent.",
1938
+ annotations: READ_LIVE,
1939
+ inputSchema: {
1940
+ package: npmName.describe("npm package name"),
1941
+ version: external_exports.string().optional().describe("Exact version; omit for the latest extracted")
1942
+ }
1943
+ },
1944
+ async (args) => reply(await run("resolve_surface", () => handleResolveSurface(db, args)))
1945
+ );
1946
+ server.registerTool(
1947
+ "diff_surface",
1948
+ {
1949
+ title: "Surface diff between two versions",
1950
+ description: 'What changed in a package\'s runtime surface between two versions: symbols removed, added, and arity changes, plus renames the package itself proves (a removed name that shared one declaration with a name the new version still exports). Removals break `node`; type-only removals are returned separately because they break `tsc` instead. Answers "when did this stop working" from static comparison, with no install required. Use before an upgrade, and to explain a break after one.',
1951
+ annotations: READ_LIVE,
1952
+ inputSchema: {
1953
+ package: npmName.describe("npm package name"),
1954
+ fromVersion: external_exports.string().describe("Version you are on"),
1955
+ toVersion: external_exports.string().describe("Version you are moving to")
1956
+ }
1957
+ },
1958
+ async (args) => reply(await run("diff_surface", () => handleDiffSurface(db, args)))
1959
+ );
1960
+ server.registerTool(
1961
+ "mcp_stack",
1962
+ {
1963
+ title: "Do these MCP servers coexist?",
1964
+ description: "Check whether a set of MCP servers can be wired into one agent together. The npm question does not apply \u2014 servers are separate processes with nothing to resolve between them. They clash in the single flat TOOL NAMESPACE the agent assembles from all of them: two servers exposing the same tool name leave the agent unable to express which it means, and nothing errors, one simply shadows the other. Also reports the standing context cost, since every tool's schema rides in every request. Pass `tools` for a server when you already hold its tool list (any server: remote, PyPI, Docker, private) and it is analysed as-is; otherwise the npm server's probed surface is used, and one that has not been probed makes the answer UNKNOWN, never clean.",
1965
+ annotations: READ_INDEX,
1966
+ inputSchema: {
1967
+ servers: external_exports.array(
1968
+ external_exports.object({
1969
+ server: external_exports.string().trim().min(1).max(300).describe("npm package name of the MCP server, or any label when `tools` is given"),
1970
+ version: external_exports.string().max(100).nullable().optional(),
1971
+ tools: external_exports.array(
1972
+ external_exports.object({
1973
+ name: external_exports.string().min(1).max(256),
1974
+ annotations: external_exports.record(external_exports.unknown()).optional()
1975
+ })
1976
+ ).max(2e3).optional().describe("The tool list as the agent received it; names and annotations are enough")
1977
+ }).refine((s) => s.tools !== void 0 || npmName.safeParse(s.server).success, {
1978
+ message: "server must be an npm package name unless tools are given"
1979
+ })
1980
+ ).min(1).max(50).describe("The servers configured into one agent")
1981
+ }
1982
+ },
1983
+ async (args) => reply(
1984
+ await run("mcp_stack", async () => {
1985
+ const { checkMcpStack } = await import("./mcpStack-BYJCZNIV.js");
1986
+ return checkMcpStack(
1987
+ db,
1988
+ args.servers.map((s) => ({
1989
+ server: s.server,
1990
+ version: s.version ?? null,
1991
+ tools: s.tools
1992
+ }))
1993
+ );
1994
+ })
1995
+ )
1996
+ );
1997
+ server.registerTool(
1998
+ "mcp_surface",
1999
+ {
2000
+ title: "An MCP server's tool contract",
2001
+ description: "What an MCP server ACTUALLY exposes: every tool, its required and optional parameters, and its behaviour annotations, read from a live `tools/list` handshake in a sandbox rather than from a README or the model's memory. Call before wiring an agent to a server, or when a tool call is failing for reasons the error does not explain. Also returns `requires` \u2014 the API keys and settings the server declares it needs \u2014 and `configRequest`, a ready-made line to put in front of your user when something is missing, so 'it needs a token' never presents as 'it is broken'. A miss returns UNKNOWN and queues a probe; UNKNOWN never means the server has no tools.",
2002
+ annotations: READ_LIVE,
2003
+ inputSchema: {
2004
+ server: npmName.describe("npm package name of the MCP server"),
2005
+ version: external_exports.string().optional().describe("Exact version; omit for the latest probed")
2006
+ }
2007
+ },
2008
+ async (args) => reply(await run("mcp_surface", () => handleMcpSurface(db, args)))
2009
+ );
2010
+ server.registerTool(
2011
+ "mcp_drift",
2012
+ {
2013
+ title: "MCP tool-contract drift between two versions",
2014
+ description: "What moved in an MCP server's tool contract between two versions: tools removed, parameters that became required, types narrowed, and annotation flips. Two findings here have no npm equivalent and are why this exists. SILENT DRIFT is a schema that changed while its description stayed byte-identical, invisible to anyone reading a changelog. PRIVILEGE WIDENING is a tool that stopped being read-only or started being destructive, which does not break anything and is worse than a break. Use before upgrading a server an agent depends on.",
2015
+ annotations: READ_INDEX,
2016
+ inputSchema: {
2017
+ server: npmName.describe("npm package name of the MCP server"),
2018
+ fromVersion: external_exports.string().describe("Version you are on"),
2019
+ toVersion: external_exports.string().describe("Version you are moving to")
2020
+ }
2021
+ },
2022
+ async (args) => reply(await run("mcp_drift", () => handleMcpDrift(db, args)))
2023
+ );
2024
+ server.registerTool(
2025
+ "audit",
2026
+ {
2027
+ title: "Audit a whole project",
2028
+ description: "Assess an entire project's dependencies in ONE call: which packages are outdated, deprecated or carry advisories for the exact installed version, and which configured MCP servers have drifted, need credentials, or cannot be observed at all. Send the inventory you read locally (names and versions only \u2014 never source). Returns a per-item verdict plus an explicit coverage count: how many were answered, how many are queued because the index has not seen them, and how many were skipped and why. An item lurq could not assess is reported as unassessed, never as clean.",
2029
+ annotations: READ_LIVE,
2030
+ inputSchema: {
2031
+ packages: external_exports.array(
2032
+ external_exports.object({
2033
+ name: npmName,
2034
+ range: external_exports.string().optional().describe("Declared range, e.g. ^6.4.0"),
2035
+ installed: external_exports.string().nullable().optional().describe(
2036
+ "Resolved version from the lockfile or node_modules \u2014 what actually runs"
2037
+ )
2038
+ })
2039
+ ).max(600).optional().describe("npm dependencies read from package.json + lockfile"),
2040
+ mcpServers: external_exports.array(
2041
+ external_exports.object({
2042
+ alias: external_exports.string().max(200).optional(),
2043
+ kind: external_exports.enum(["npm-stdio", "remote", "local", "other-registry"]).optional().describe("How it launches; decides whether lurq can read its contract"),
2044
+ packageName: external_exports.string().max(300).nullable().optional(),
2045
+ version: external_exports.string().max(100).nullable().optional(),
2046
+ endpoint: external_exports.string().max(300).nullable().optional()
2047
+ })
2048
+ ).max(200).optional().describe("MCP servers read from .mcp.json / agent configs")
2049
+ }
2050
+ },
2051
+ async (args) => reply(await run("audit", () => handleAudit(db, args, ctx.ownerId ?? null)))
2052
+ );
2053
+ server.registerTool(
2054
+ "capabilities",
2055
+ {
2056
+ title: "What lurq can do",
2057
+ description: "Look up which lurq tool answers a situation, and what to run next. Call when you're unsure whether lurq covers something (an upgrade, a licence rule, a version's exact exports, publishing a package) instead of guessing or skipping it. Returns matching capabilities with the tool or command to use.",
2058
+ annotations: READ_INDEX,
2059
+ inputSchema: {
2060
+ query: external_exports.string().max(300).optional().describe("What you are trying to do, in plain words. Omit for the full menu.")
2061
+ }
2062
+ },
2063
+ async (args) => reply({ capabilities: searchCapabilities(args.query ?? "", 6) })
2064
+ );
2065
+ server.registerTool(
2066
+ "report_outcome",
2067
+ {
2068
+ title: "Report how a package worked out",
2069
+ description: "Opt-in feedback after you act on lurq's evidence about a package (verify, evaluate, compare, compat): whether you went with it and whether it built. No source code, only the coarse decision + a build signal. Helps lurq learn which packages agents actually succeed with; safe to skip.",
2070
+ // The one tool that writes: each call appends a row, so a repeat is a
2071
+ // second report, not a no-op.
2072
+ annotations: {
2073
+ readOnlyHint: false,
2074
+ destructiveHint: false,
2075
+ idempotentHint: false,
2076
+ openWorldHint: false
2077
+ },
2078
+ inputSchema: {
2079
+ package: npmName.describe("The package you decided on"),
2080
+ accepted: external_exports.boolean().describe("Did you go with this package?"),
2081
+ buildSignal: external_exports.enum(["installed", "compiled", "tests_passed", "failed"]).optional().describe("Coarse post-install result, if known"),
2082
+ need: external_exports.string().max(500).optional().describe("What you needed the package for, in plain words (no source code)")
2083
+ }
2084
+ },
2085
+ // ownerId comes from the authenticated key (ctx), NOT the tool arguments —
2086
+ // a caller must never be able to attribute an outcome to another org.
2087
+ async (args) => reply(await run("report_outcome", () => handleReportOutcome(db, args, ctx.ownerId ?? null)))
2088
+ );
2089
+ server.server.registerCapabilities({ resources: {}, prompts: {} });
2090
+ server.server.setRequestHandler(ListResourcesRequestSchema, () => ({ resources: [] }));
2091
+ server.server.setRequestHandler(ListResourceTemplatesRequestSchema, () => ({ resourceTemplates: [] }));
2092
+ server.server.setRequestHandler(ListPromptsRequestSchema, () => ({ prompts: [] }));
2093
+ return server;
2094
+ }
2095
+ var SERVE_NEEDS_DATABASE = "`lurq serve` answers from a local lurq index and needs DATABASE_URL, which is not set. To use lurq from an agent without running your own index, connect it to the hosted service instead: run `npx lurqrun` and it writes the MCP entry for your assistants. To self-host, set DATABASE_URL to a migrated lurq index.";
2096
+ async function startMcpServer() {
2097
+ if (!getConfig().DATABASE_URL) throw new Error(SERVE_NEEDS_DATABASE);
2098
+ const { db, close } = createDb();
2099
+ const server = buildMcpServer(db);
2100
+ const shutdown = async () => {
2101
+ try {
2102
+ await close();
2103
+ } finally {
2104
+ process.exit(0);
2105
+ }
2106
+ };
2107
+ process.on("SIGINT", shutdown);
2108
+ process.on("SIGTERM", shutdown);
2109
+ const transport = new StdioServerTransport();
2110
+ await server.connect(transport);
2111
+ logger.info(`${SERVER_NAME} MCP server v${VERSION} running on stdio.`);
2112
+ }
2113
+
2114
+ export {
2115
+ renderPrometheus,
2116
+ recordUsage,
2117
+ getUsageSummary,
2118
+ getUsageByTool,
2119
+ capture,
2120
+ flush,
2121
+ npmName,
2122
+ exactVersion,
2123
+ buildMcpServer,
2124
+ SERVE_NEEDS_DATABASE,
2125
+ startMcpServer
2126
+ };