convex 1.45.0-alpha.0 → 1.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (333) hide show
  1. package/CHANGELOG.md +55 -6
  2. package/dist/browser.bundle.js +1 -1
  3. package/dist/browser.bundle.js.map +2 -2
  4. package/dist/cjs/browser/http_client.js.map +2 -2
  5. package/dist/cjs/browser/query_options.js.map +2 -2
  6. package/dist/cjs/browser/simple_client.js.map +2 -2
  7. package/dist/cjs/browser/sync/optimistic_updates.js.map +1 -1
  8. package/dist/cjs/browser/sync/optimistic_updates_impl.js.map +2 -2
  9. package/dist/cjs/cli/codegen.js +2 -0
  10. package/dist/cjs/cli/codegen.js.map +2 -2
  11. package/dist/cjs/cli/deploy.js +1 -0
  12. package/dist/cjs/cli/deploy.js.map +2 -2
  13. package/dist/cjs/cli/docs.js +3 -36
  14. package/dist/cjs/cli/docs.js.map +2 -2
  15. package/dist/cjs/cli/lib/checkForLargeIndexDeletion.js +101 -60
  16. package/dist/cjs/cli/lib/checkForLargeIndexDeletion.js.map +2 -2
  17. package/dist/cjs/cli/lib/checkForSlowSchemaValidation.js +107 -0
  18. package/dist/cjs/cli/lib/checkForSlowSchemaValidation.js.map +7 -0
  19. package/dist/cjs/cli/lib/codegen.js.map +2 -2
  20. package/dist/cjs/cli/lib/components.js +12 -0
  21. package/dist/cjs/cli/lib/components.js.map +2 -2
  22. package/dist/cjs/cli/lib/deploy2.js +29 -2
  23. package/dist/cjs/cli/lib/deploy2.js.map +2 -2
  24. package/dist/cjs/cli/lib/deployApi/evaluateSchema.js +73 -0
  25. package/dist/cjs/cli/lib/deployApi/evaluateSchema.js.map +7 -0
  26. package/dist/cjs/cli/lib/deployApi/finishPush.js +1 -0
  27. package/dist/cjs/cli/lib/deployApi/finishPush.js.map +2 -2
  28. package/dist/cjs/cli/lib/deployApi/startPush.js +1 -1
  29. package/dist/cjs/cli/lib/deployApi/startPush.js.map +2 -2
  30. package/dist/cjs/cli/lib/dev.js +1 -0
  31. package/dist/cjs/cli/lib/dev.js.map +2 -2
  32. package/dist/cjs/cli/lib/generatedFunctionLogsApi.js.map +1 -1
  33. package/dist/cjs/cli/lib/indexes.js +1 -1
  34. package/dist/cjs/cli/lib/indexes.js.map +1 -1
  35. package/dist/cjs/cli/lib/localDeployment/run.js +30 -1
  36. package/dist/cjs/cli/lib/localDeployment/run.js.map +2 -2
  37. package/dist/cjs/cli/lib/localDeployment/upgrade.js +6 -5
  38. package/dist/cjs/cli/lib/localDeployment/upgrade.js.map +2 -2
  39. package/dist/cjs/cli/lib/localDeployment/utils.js +5 -1
  40. package/dist/cjs/cli/lib/localDeployment/utils.js.map +2 -2
  41. package/dist/cjs/cli/lib/run.js +1 -0
  42. package/dist/cjs/cli/lib/run.js.map +2 -2
  43. package/dist/cjs/cli/lib/utils/utils.js +36 -29
  44. package/dist/cjs/cli/lib/utils/utils.js.map +2 -2
  45. package/dist/cjs/cli/mcp.js +16 -6
  46. package/dist/cjs/cli/mcp.js.map +2 -2
  47. package/dist/cjs/index.js +1 -1
  48. package/dist/cjs/index.js.map +1 -1
  49. package/dist/cjs/nextjs/index.js.map +2 -2
  50. package/dist/cjs/react/client.js.map +2 -2
  51. package/dist/cjs/react/hydration.js.map +2 -2
  52. package/dist/cjs/react/queries_observer.js.map +2 -2
  53. package/dist/cjs/react/use_paginated_query2.js.map +2 -2
  54. package/dist/cjs/react/use_queries.js.map +2 -2
  55. package/dist/cjs/server/api.js.map +2 -2
  56. package/dist/cjs/server/components/index.js.map +2 -2
  57. package/dist/cjs/server/cron.js +10 -10
  58. package/dist/cjs/server/cron.js.map +2 -2
  59. package/dist/cjs/server/impl/actions_impl.js.map +2 -2
  60. package/dist/cjs/server/impl/meta_impl.js +8 -2
  61. package/dist/cjs/server/impl/meta_impl.js.map +2 -2
  62. package/dist/cjs/server/impl/scheduler_impl.js.map +2 -2
  63. package/dist/cjs/server/index.js.map +2 -2
  64. package/dist/cjs/server/meta.js.map +1 -1
  65. package/dist/cjs/server/registration.js.map +1 -1
  66. package/dist/cjs/server/scheduler.js.map +1 -1
  67. package/dist/cjs/server/schema.js +50 -3
  68. package/dist/cjs/server/schema.js.map +2 -2
  69. package/dist/cjs/values/validator.js +1 -1
  70. package/dist/cjs/values/validator.js.map +2 -2
  71. package/dist/cjs/values/validators.js +81 -25
  72. package/dist/cjs/values/validators.js.map +2 -2
  73. package/dist/cjs-types/browser/http_client.d.ts +5 -5
  74. package/dist/cjs-types/browser/http_client.d.ts.map +1 -1
  75. package/dist/cjs-types/browser/query_options.d.ts +2 -2
  76. package/dist/cjs-types/browser/query_options.d.ts.map +1 -1
  77. package/dist/cjs-types/browser/simple_client.d.ts +6 -6
  78. package/dist/cjs-types/browser/simple_client.d.ts.map +1 -1
  79. package/dist/cjs-types/browser/sync/optimistic_updates.d.ts +4 -4
  80. package/dist/cjs-types/browser/sync/optimistic_updates.d.ts.map +1 -1
  81. package/dist/cjs-types/browser/sync/optimistic_updates_impl.d.ts.map +1 -1
  82. package/dist/cjs-types/cli/codegen.d.ts.map +1 -1
  83. package/dist/cjs-types/cli/docs.d.ts.map +1 -1
  84. package/dist/cjs-types/cli/lib/checkForLargeIndexDeletion.d.ts +26 -5
  85. package/dist/cjs-types/cli/lib/checkForLargeIndexDeletion.d.ts.map +1 -1
  86. package/dist/cjs-types/cli/lib/checkForSlowSchemaValidation.d.ts +14 -0
  87. package/dist/cjs-types/cli/lib/checkForSlowSchemaValidation.d.ts.map +1 -0
  88. package/dist/cjs-types/cli/lib/codegen.d.ts +1 -0
  89. package/dist/cjs-types/cli/lib/codegen.d.ts.map +1 -1
  90. package/dist/cjs-types/cli/lib/components.d.ts +1 -0
  91. package/dist/cjs-types/cli/lib/components.d.ts.map +1 -1
  92. package/dist/cjs-types/cli/lib/deploy2.d.ts +6 -0
  93. package/dist/cjs-types/cli/lib/deploy2.d.ts.map +1 -1
  94. package/dist/cjs-types/cli/lib/deployApi/evaluateSchema.d.ts +453 -0
  95. package/dist/cjs-types/cli/lib/deployApi/evaluateSchema.d.ts.map +1 -0
  96. package/dist/cjs-types/cli/lib/deployApi/finishPush.d.ts +1 -2
  97. package/dist/cjs-types/cli/lib/deployApi/finishPush.d.ts.map +1 -1
  98. package/dist/cjs-types/cli/lib/dev.d.ts.map +1 -1
  99. package/dist/cjs-types/cli/lib/generatedFunctionLogsApi.d.ts +2 -0
  100. package/dist/cjs-types/cli/lib/generatedFunctionLogsApi.d.ts.map +1 -1
  101. package/dist/cjs-types/cli/lib/localDeployment/run.d.ts +2 -0
  102. package/dist/cjs-types/cli/lib/localDeployment/run.d.ts.map +1 -1
  103. package/dist/cjs-types/cli/lib/localDeployment/upgrade.d.ts.map +1 -1
  104. package/dist/cjs-types/cli/lib/localDeployment/utils.d.ts +1 -0
  105. package/dist/cjs-types/cli/lib/localDeployment/utils.d.ts.map +1 -1
  106. package/dist/cjs-types/cli/lib/run.d.ts.map +1 -1
  107. package/dist/cjs-types/cli/lib/utils/utils.d.ts +5 -5
  108. package/dist/cjs-types/cli/lib/utils/utils.d.ts.map +1 -1
  109. package/dist/cjs-types/cli/mcp.d.ts.map +1 -1
  110. package/dist/cjs-types/index.d.ts +1 -1
  111. package/dist/cjs-types/index.d.ts.map +1 -1
  112. package/dist/cjs-types/nextjs/index.d.ts +6 -6
  113. package/dist/cjs-types/nextjs/index.d.ts.map +1 -1
  114. package/dist/cjs-types/react/client.d.ts +15 -15
  115. package/dist/cjs-types/react/client.d.ts.map +1 -1
  116. package/dist/cjs-types/react/hydration.d.ts +3 -3
  117. package/dist/cjs-types/react/hydration.d.ts.map +1 -1
  118. package/dist/cjs-types/react/queries_observer.d.ts +9 -9
  119. package/dist/cjs-types/react/queries_observer.d.ts.map +1 -1
  120. package/dist/cjs-types/react/use_paginated_query2.d.ts.map +1 -1
  121. package/dist/cjs-types/react/use_queries.d.ts +14 -6
  122. package/dist/cjs-types/react/use_queries.d.ts.map +1 -1
  123. package/dist/cjs-types/server/api.d.ts +157 -7
  124. package/dist/cjs-types/server/api.d.ts.map +1 -1
  125. package/dist/cjs-types/server/components/index.d.ts +2 -2
  126. package/dist/cjs-types/server/components/index.d.ts.map +1 -1
  127. package/dist/cjs-types/server/cron.d.ts +21 -20
  128. package/dist/cjs-types/server/cron.d.ts.map +1 -1
  129. package/dist/cjs-types/server/impl/actions_impl.d.ts +18 -4
  130. package/dist/cjs-types/server/impl/actions_impl.d.ts.map +1 -1
  131. package/dist/cjs-types/server/impl/meta_impl.d.ts.map +1 -1
  132. package/dist/cjs-types/server/impl/scheduler_impl.d.ts.map +1 -1
  133. package/dist/cjs-types/server/index.d.ts +2 -1
  134. package/dist/cjs-types/server/index.d.ts.map +1 -1
  135. package/dist/cjs-types/server/meta.d.ts.map +1 -1
  136. package/dist/cjs-types/server/registration.d.ts +7 -7
  137. package/dist/cjs-types/server/registration.d.ts.map +1 -1
  138. package/dist/cjs-types/server/scheduler.d.ts +9 -7
  139. package/dist/cjs-types/server/scheduler.d.ts.map +1 -1
  140. package/dist/cjs-types/server/schema.d.ts +1 -0
  141. package/dist/cjs-types/server/schema.d.ts.map +1 -1
  142. package/dist/cjs-types/values/validator.d.ts.map +1 -1
  143. package/dist/cjs-types/values/validators.d.ts +30 -0
  144. package/dist/cjs-types/values/validators.d.ts.map +1 -1
  145. package/dist/cli.bundle.cjs +1753 -140
  146. package/dist/cli.bundle.cjs.map +4 -4
  147. package/dist/esm/browser/http_client.js.map +2 -2
  148. package/dist/esm/browser/query_options.js.map +2 -2
  149. package/dist/esm/browser/simple_client.js.map +2 -2
  150. package/dist/esm/browser/sync/optimistic_updates_impl.js.map +2 -2
  151. package/dist/esm/cli/codegen.js +2 -0
  152. package/dist/esm/cli/codegen.js.map +2 -2
  153. package/dist/esm/cli/deploy.js +1 -0
  154. package/dist/esm/cli/deploy.js.map +2 -2
  155. package/dist/esm/cli/docs.js +3 -43
  156. package/dist/esm/cli/docs.js.map +2 -2
  157. package/dist/esm/cli/lib/checkForLargeIndexDeletion.js +100 -60
  158. package/dist/esm/cli/lib/checkForLargeIndexDeletion.js.map +2 -2
  159. package/dist/esm/cli/lib/checkForSlowSchemaValidation.js +85 -0
  160. package/dist/esm/cli/lib/checkForSlowSchemaValidation.js.map +7 -0
  161. package/dist/esm/cli/lib/codegen.js.map +2 -2
  162. package/dist/esm/cli/lib/components.js +12 -0
  163. package/dist/esm/cli/lib/components.js.map +2 -2
  164. package/dist/esm/cli/lib/deploy2.js +30 -2
  165. package/dist/esm/cli/lib/deploy2.js.map +2 -2
  166. package/dist/esm/cli/lib/deployApi/evaluateSchema.js +46 -0
  167. package/dist/esm/cli/lib/deployApi/evaluateSchema.js.map +7 -0
  168. package/dist/esm/cli/lib/deployApi/finishPush.js +1 -1
  169. package/dist/esm/cli/lib/deployApi/finishPush.js.map +2 -2
  170. package/dist/esm/cli/lib/deployApi/startPush.js +1 -1
  171. package/dist/esm/cli/lib/deployApi/startPush.js.map +2 -2
  172. package/dist/esm/cli/lib/dev.js +1 -0
  173. package/dist/esm/cli/lib/dev.js.map +2 -2
  174. package/dist/esm/cli/lib/indexes.js +1 -1
  175. package/dist/esm/cli/lib/indexes.js.map +1 -1
  176. package/dist/esm/cli/lib/localDeployment/run.js +30 -2
  177. package/dist/esm/cli/lib/localDeployment/run.js.map +2 -2
  178. package/dist/esm/cli/lib/localDeployment/upgrade.js +4 -3
  179. package/dist/esm/cli/lib/localDeployment/upgrade.js.map +2 -2
  180. package/dist/esm/cli/lib/localDeployment/utils.js +3 -0
  181. package/dist/esm/cli/lib/localDeployment/utils.js.map +2 -2
  182. package/dist/esm/cli/lib/run.js +1 -0
  183. package/dist/esm/cli/lib/run.js.map +2 -2
  184. package/dist/esm/cli/lib/utils/utils.js +36 -30
  185. package/dist/esm/cli/lib/utils/utils.js.map +2 -2
  186. package/dist/esm/cli/mcp.js +17 -7
  187. package/dist/esm/cli/mcp.js.map +2 -2
  188. package/dist/esm/index.js +1 -1
  189. package/dist/esm/index.js.map +1 -1
  190. package/dist/esm/nextjs/index.js.map +2 -2
  191. package/dist/esm/react/client.js.map +2 -2
  192. package/dist/esm/react/hydration.js +3 -1
  193. package/dist/esm/react/hydration.js.map +2 -2
  194. package/dist/esm/react/queries_observer.js +3 -1
  195. package/dist/esm/react/queries_observer.js.map +2 -2
  196. package/dist/esm/react/use_paginated_query2.js +3 -1
  197. package/dist/esm/react/use_paginated_query2.js.map +2 -2
  198. package/dist/esm/react/use_queries.js.map +2 -2
  199. package/dist/esm/server/api.js.map +2 -2
  200. package/dist/esm/server/components/index.js.map +2 -2
  201. package/dist/esm/server/cron.js +13 -11
  202. package/dist/esm/server/cron.js.map +2 -2
  203. package/dist/esm/server/impl/actions_impl.js.map +2 -2
  204. package/dist/esm/server/impl/meta_impl.js +9 -3
  205. package/dist/esm/server/impl/meta_impl.js.map +2 -2
  206. package/dist/esm/server/impl/scheduler_impl.js.map +2 -2
  207. package/dist/esm/server/index.js.map +2 -2
  208. package/dist/esm/server/schema.js +50 -3
  209. package/dist/esm/server/schema.js.map +2 -2
  210. package/dist/esm/values/validator.js +1 -1
  211. package/dist/esm/values/validator.js.map +2 -2
  212. package/dist/esm/values/validators.js +81 -25
  213. package/dist/esm/values/validators.js.map +2 -2
  214. package/dist/esm-types/browser/http_client.d.ts +5 -5
  215. package/dist/esm-types/browser/http_client.d.ts.map +1 -1
  216. package/dist/esm-types/browser/query_options.d.ts +2 -2
  217. package/dist/esm-types/browser/query_options.d.ts.map +1 -1
  218. package/dist/esm-types/browser/simple_client.d.ts +6 -6
  219. package/dist/esm-types/browser/simple_client.d.ts.map +1 -1
  220. package/dist/esm-types/browser/sync/optimistic_updates.d.ts +4 -4
  221. package/dist/esm-types/browser/sync/optimistic_updates.d.ts.map +1 -1
  222. package/dist/esm-types/browser/sync/optimistic_updates_impl.d.ts.map +1 -1
  223. package/dist/esm-types/cli/codegen.d.ts.map +1 -1
  224. package/dist/esm-types/cli/docs.d.ts.map +1 -1
  225. package/dist/esm-types/cli/lib/checkForLargeIndexDeletion.d.ts +26 -5
  226. package/dist/esm-types/cli/lib/checkForLargeIndexDeletion.d.ts.map +1 -1
  227. package/dist/esm-types/cli/lib/checkForSlowSchemaValidation.d.ts +14 -0
  228. package/dist/esm-types/cli/lib/checkForSlowSchemaValidation.d.ts.map +1 -0
  229. package/dist/esm-types/cli/lib/codegen.d.ts +1 -0
  230. package/dist/esm-types/cli/lib/codegen.d.ts.map +1 -1
  231. package/dist/esm-types/cli/lib/components.d.ts +1 -0
  232. package/dist/esm-types/cli/lib/components.d.ts.map +1 -1
  233. package/dist/esm-types/cli/lib/deploy2.d.ts +6 -0
  234. package/dist/esm-types/cli/lib/deploy2.d.ts.map +1 -1
  235. package/dist/esm-types/cli/lib/deployApi/evaluateSchema.d.ts +453 -0
  236. package/dist/esm-types/cli/lib/deployApi/evaluateSchema.d.ts.map +1 -0
  237. package/dist/esm-types/cli/lib/deployApi/finishPush.d.ts +1 -2
  238. package/dist/esm-types/cli/lib/deployApi/finishPush.d.ts.map +1 -1
  239. package/dist/esm-types/cli/lib/dev.d.ts.map +1 -1
  240. package/dist/esm-types/cli/lib/generatedFunctionLogsApi.d.ts +2 -0
  241. package/dist/esm-types/cli/lib/generatedFunctionLogsApi.d.ts.map +1 -1
  242. package/dist/esm-types/cli/lib/localDeployment/run.d.ts +2 -0
  243. package/dist/esm-types/cli/lib/localDeployment/run.d.ts.map +1 -1
  244. package/dist/esm-types/cli/lib/localDeployment/upgrade.d.ts.map +1 -1
  245. package/dist/esm-types/cli/lib/localDeployment/utils.d.ts +1 -0
  246. package/dist/esm-types/cli/lib/localDeployment/utils.d.ts.map +1 -1
  247. package/dist/esm-types/cli/lib/run.d.ts.map +1 -1
  248. package/dist/esm-types/cli/lib/utils/utils.d.ts +5 -5
  249. package/dist/esm-types/cli/lib/utils/utils.d.ts.map +1 -1
  250. package/dist/esm-types/cli/mcp.d.ts.map +1 -1
  251. package/dist/esm-types/index.d.ts +1 -1
  252. package/dist/esm-types/index.d.ts.map +1 -1
  253. package/dist/esm-types/nextjs/index.d.ts +6 -6
  254. package/dist/esm-types/nextjs/index.d.ts.map +1 -1
  255. package/dist/esm-types/react/client.d.ts +15 -15
  256. package/dist/esm-types/react/client.d.ts.map +1 -1
  257. package/dist/esm-types/react/hydration.d.ts +3 -3
  258. package/dist/esm-types/react/hydration.d.ts.map +1 -1
  259. package/dist/esm-types/react/queries_observer.d.ts +9 -9
  260. package/dist/esm-types/react/queries_observer.d.ts.map +1 -1
  261. package/dist/esm-types/react/use_paginated_query2.d.ts.map +1 -1
  262. package/dist/esm-types/react/use_queries.d.ts +14 -6
  263. package/dist/esm-types/react/use_queries.d.ts.map +1 -1
  264. package/dist/esm-types/server/api.d.ts +157 -7
  265. package/dist/esm-types/server/api.d.ts.map +1 -1
  266. package/dist/esm-types/server/components/index.d.ts +2 -2
  267. package/dist/esm-types/server/components/index.d.ts.map +1 -1
  268. package/dist/esm-types/server/cron.d.ts +21 -20
  269. package/dist/esm-types/server/cron.d.ts.map +1 -1
  270. package/dist/esm-types/server/impl/actions_impl.d.ts +18 -4
  271. package/dist/esm-types/server/impl/actions_impl.d.ts.map +1 -1
  272. package/dist/esm-types/server/impl/meta_impl.d.ts.map +1 -1
  273. package/dist/esm-types/server/impl/scheduler_impl.d.ts.map +1 -1
  274. package/dist/esm-types/server/index.d.ts +2 -1
  275. package/dist/esm-types/server/index.d.ts.map +1 -1
  276. package/dist/esm-types/server/meta.d.ts.map +1 -1
  277. package/dist/esm-types/server/registration.d.ts +7 -7
  278. package/dist/esm-types/server/registration.d.ts.map +1 -1
  279. package/dist/esm-types/server/scheduler.d.ts +9 -7
  280. package/dist/esm-types/server/scheduler.d.ts.map +1 -1
  281. package/dist/esm-types/server/schema.d.ts +1 -0
  282. package/dist/esm-types/server/schema.d.ts.map +1 -1
  283. package/dist/esm-types/values/validator.d.ts.map +1 -1
  284. package/dist/esm-types/values/validators.d.ts +30 -0
  285. package/dist/esm-types/values/validators.d.ts.map +1 -1
  286. package/dist/react.bundle.js +1 -1
  287. package/dist/react.bundle.js.map +2 -2
  288. package/package.json +5 -5
  289. package/src/browser/http_client.ts +43 -10
  290. package/src/browser/query_options.ts +11 -5
  291. package/src/browser/simple_client.ts +35 -14
  292. package/src/browser/sync/optimistic_updates.ts +17 -4
  293. package/src/browser/sync/optimistic_updates_impl.ts +17 -4
  294. package/src/cli/codegen.ts +1 -0
  295. package/src/cli/deploy.ts +1 -0
  296. package/src/cli/docs.ts +3 -44
  297. package/src/cli/lib/checkForLargeIndexDeletion.ts +154 -82
  298. package/src/cli/lib/checkForSlowSchemaValidation.ts +130 -0
  299. package/src/cli/lib/codegen.ts +1 -0
  300. package/src/cli/lib/components.ts +17 -0
  301. package/src/cli/lib/deploy2.ts +56 -1
  302. package/src/cli/lib/deployApi/evaluateSchema.ts +62 -0
  303. package/src/cli/lib/deployApi/finishPush.ts +1 -1
  304. package/src/cli/lib/deployApi/startPush.ts +1 -1
  305. package/src/cli/lib/dev.ts +1 -0
  306. package/src/cli/lib/generatedFunctionLogsApi.ts +2 -0
  307. package/src/cli/lib/indexes.ts +1 -1
  308. package/src/cli/lib/localDeployment/run.ts +44 -2
  309. package/src/cli/lib/localDeployment/upgrade.ts +4 -6
  310. package/src/cli/lib/localDeployment/utils.ts +6 -0
  311. package/src/cli/lib/run.ts +1 -0
  312. package/src/cli/lib/utils/utils.ts +63 -35
  313. package/src/cli/mcp.ts +29 -7
  314. package/src/index.ts +1 -1
  315. package/src/nextjs/index.ts +19 -8
  316. package/src/react/client.ts +73 -30
  317. package/src/react/hydration.tsx +14 -6
  318. package/src/react/queries_observer.ts +19 -16
  319. package/src/react/use_paginated_query2.ts +10 -6
  320. package/src/react/use_queries.ts +23 -7
  321. package/src/server/api.ts +220 -14
  322. package/src/server/components/index.ts +4 -6
  323. package/src/server/cron.ts +34 -24
  324. package/src/server/impl/actions_impl.ts +16 -5
  325. package/src/server/impl/meta_impl.ts +8 -1
  326. package/src/server/impl/scheduler_impl.ts +13 -6
  327. package/src/server/index.ts +1 -3
  328. package/src/server/meta.ts +25 -0
  329. package/src/server/registration.ts +28 -7
  330. package/src/server/scheduler.ts +22 -7
  331. package/src/server/schema.ts +55 -0
  332. package/src/values/validator.ts +3 -1
  333. package/src/values/validators.ts +84 -26
@@ -15222,7 +15222,7 @@ var require_context = __commonJS({
15222
15222
  };
15223
15223
  });
15224
15224
  var nodeContextIntegration = core.defineIntegration(_nodeContextIntegration);
15225
- var Context12 = core.convertIntegrationFnToClass(INTEGRATION_NAME, nodeContextIntegration);
15225
+ var Context11 = core.convertIntegrationFnToClass(INTEGRATION_NAME, nodeContextIntegration);
15226
15226
  function _updateContext(contexts) {
15227
15227
  if (_optionalChain([contexts, "optionalAccess", (_11) => _11.app, "optionalAccess", (_12) => _12.app_memory])) {
15228
15228
  contexts.app.app_memory = process.memoryUsage().rss;
@@ -15432,7 +15432,7 @@ var require_context = __commonJS({
15432
15432
  return void 0;
15433
15433
  }
15434
15434
  }
15435
- exports2.Context = Context12;
15435
+ exports2.Context = Context11;
15436
15436
  exports2.getDeviceContext = getDeviceContext;
15437
15437
  exports2.nodeContextIntegration = nodeContextIntegration;
15438
15438
  exports2.readDirAsync = readDirAsync;
@@ -47456,7 +47456,7 @@ var version;
47456
47456
  var init_index = __esm({
47457
47457
  "src/index.ts"() {
47458
47458
  "use strict";
47459
- version = "1.45.0-alpha.0";
47459
+ version = "1.46.0";
47460
47460
  }
47461
47461
  });
47462
47462
 
@@ -50783,6 +50783,9 @@ function printLocalDeploymentWelcomeMessage() {
50783
50783
  )
50784
50784
  );
50785
50785
  }
50786
+ function releaseDate(version4) {
50787
+ return /^precompiled-(\d{4}-\d{2}-\d{2})-/.exec(version4)?.[1] ?? null;
50788
+ }
50786
50789
  var LOCAL_BACKEND_INSTANCE_SECRET;
50787
50790
  var init_utils2 = __esm({
50788
50791
  "src/cli/lib/localDeployment/utils.ts"() {
@@ -53834,6 +53837,16 @@ var init_download = __esm({
53834
53837
  });
53835
53838
 
53836
53839
  // src/cli/lib/localDeployment/run.ts
53840
+ function _backendSupportsControlPlaneAuth(version4) {
53841
+ if (version4 === FIRST_CONTROL_PLANE_AUTH_BACKEND_VERSION) {
53842
+ return true;
53843
+ }
53844
+ const backendDate = releaseDate(version4);
53845
+ const firstSupportedDate = releaseDate(
53846
+ FIRST_CONTROL_PLANE_AUTH_BACKEND_VERSION
53847
+ );
53848
+ return backendDate !== null && firstSupportedDate !== null && backendDate > firstSupportedDate;
53849
+ }
53837
53850
  async function parseStartupTimeoutSecs(ctx) {
53838
53851
  const raw = process.env.CONVEX_LOCAL_BACKEND_STARTUP_TIMEOUT_SECS;
53839
53852
  if (raw === void 0) {
@@ -53921,7 +53934,22 @@ async function runLocalBackend(ctx, args) {
53921
53934
  errForSentry: new LocalDeploymentError(message)
53922
53935
  });
53923
53936
  }
53924
- const commandStr = `${args.binaryPath} ${commandArgs.join(" ")}`;
53937
+ const supportsControlPlane = _backendSupportsControlPlaneAuth(
53938
+ args.backendVersion
53939
+ );
53940
+ if (supportsControlPlane && provisionHost !== productionProvisionHost) {
53941
+ commandArgs.push("--control-plane-url", provisionHost);
53942
+ }
53943
+ const auth2 = ctx.bigBrainAuth();
53944
+ if (supportsControlPlane && args.deploymentKind === "local" && auth2?.kind === "accessToken") {
53945
+ commandArgs.push("--control-plane-access-token", auth2.accessToken);
53946
+ }
53947
+ const displayArgs = commandArgs.map(
53948
+ (arg, index) => index > 0 && ["--instance-secret", "--control-plane-access-token"].includes(
53949
+ commandArgs[index - 1]
53950
+ ) ? "[REDACTED]" : arg
53951
+ );
53952
+ const commandStr = `${args.binaryPath} ${displayArgs.join(" ")}`;
53925
53953
  logVerbose(`Starting local backend: \`${commandStr}\``);
53926
53954
  const p = import_child_process2.default.spawn(args.binaryPath, commandArgs, {
53927
53955
  stdio: "ignore",
@@ -54125,6 +54153,7 @@ Run \`npx convex dev\` first.`
54125
54153
  const instanceSecret = config3.instanceSecret ?? LOCAL_BACKEND_INSTANCE_SECRET;
54126
54154
  const { cleanupHandle } = await runLocalBackend(ctx, {
54127
54155
  binaryPath,
54156
+ backendVersion: config3.backendVersion,
54128
54157
  ports: config3.ports,
54129
54158
  deploymentKind,
54130
54159
  deploymentName: args.deploymentName,
@@ -54140,7 +54169,7 @@ Run \`npx convex dev\` first.`
54140
54169
  }
54141
54170
  };
54142
54171
  }
54143
- var import_path6, import_child_process2, import_crypto3, DEFAULT_STARTUP_TIMEOUT_SECS;
54172
+ var import_path6, import_child_process2, import_crypto3, DEFAULT_STARTUP_TIMEOUT_SECS, FIRST_CONTROL_PLANE_AUTH_BACKEND_VERSION;
54144
54173
  var init_run = __esm({
54145
54174
  "src/cli/lib/localDeployment/run.ts"() {
54146
54175
  "use strict";
@@ -54154,7 +54183,9 @@ var init_run = __esm({
54154
54183
  import_crypto3 = require("crypto");
54155
54184
  init_errors3();
54156
54185
  init_utils2();
54186
+ init_config();
54157
54187
  DEFAULT_STARTUP_TIMEOUT_SECS = 30;
54188
+ FIRST_CONTROL_PLANE_AUTH_BACKEND_VERSION = "precompiled-2026-09-15-4e9b83a";
54158
54189
  }
54159
54190
  });
54160
54191
 
@@ -64238,23 +64269,19 @@ function waitUntilCalled() {
64238
64269
  return [waitPromise, () => onCalled(null)];
64239
64270
  }
64240
64271
  function formatSize(n) {
64241
- if (n === 0) {
64242
- return "0 bytes";
64272
+ let value = n;
64273
+ let unitIndex = 0;
64274
+ while (value >= 1024 && unitIndex < BYTE_UNITS.length - 1) {
64275
+ value /= 1024;
64276
+ unitIndex++;
64243
64277
  }
64244
- for (const [unitSize, unitName] of BYTE_UNITS) {
64245
- if (n < unitSize) {
64246
- continue;
64247
- }
64248
- if (n % unitSize === 0) {
64249
- return `${n / unitSize} ${unitName}`;
64250
- }
64251
- if (n * 10 % unitSize === 0) {
64252
- const whole = Math.floor(n / unitSize);
64253
- const frac = Math.floor(n * 10 / unitSize) % 10;
64254
- return `${whole}.${frac} ${unitName}`;
64255
- }
64278
+ const roundedValue = Number(value.toFixed(1));
64279
+ if (roundedValue >= 1024 && unitIndex < BYTE_UNITS.length - 1) {
64280
+ value /= 1024;
64281
+ unitIndex++;
64256
64282
  }
64257
- return `${n} bytes`;
64283
+ const formatted = value.toFixed(1).replace(/\.0$/, "");
64284
+ return `${formatted} ${BYTE_UNITS[unitIndex]}`;
64258
64285
  }
64259
64286
  function formatDuration(ms) {
64260
64287
  const twoDigits = (n, unit) => `${n.toLocaleString("en-US", { maximumFractionDigits: 2 })}${unit}`;
@@ -64371,8 +64398,8 @@ function retryDelay(attempt, _error, _response) {
64371
64398
  const randomSum = delay * 0.2 * Math.random();
64372
64399
  return delay + randomSum;
64373
64400
  }
64374
- function deploymentFetchRetryOn(onError, method) {
64375
- const shouldRetry = function(_attempt, error3, response) {
64401
+ function deploymentFetchRetryOn(onError, method, maxRetries = MAX_RETRIES, shouldRetryOverride) {
64402
+ const defaultShouldRetry = function(_attempt, error3, response) {
64376
64403
  if (error3 !== null) {
64377
64404
  return { kind: "retry", error: error3 };
64378
64405
  }
@@ -64418,12 +64445,18 @@ function deploymentFetchRetryOn(onError, method) {
64418
64445
  }
64419
64446
  return { kind: "stop" };
64420
64447
  };
64448
+ const shouldRetry = shouldRetryOverride ? function(_attempt, error3, response) {
64449
+ return shouldRetryOverride(error3, response) ? {
64450
+ kind: "retry",
64451
+ error: error3 ?? `Received response with status ${response?.status}`
64452
+ } : { kind: "stop" };
64453
+ } : defaultShouldRetry;
64421
64454
  return function(attempt, error3, response) {
64422
64455
  const result = shouldRetry(attempt, error3, response);
64423
64456
  if (result.kind === "retry") {
64424
64457
  onError?.(result.error, attempt);
64425
64458
  }
64426
- if (attempt >= MAX_RETRIES) {
64459
+ if (attempt >= maxRetries) {
64427
64460
  return false;
64428
64461
  }
64429
64462
  return result.kind === "retry";
@@ -64452,13 +64485,19 @@ function bareDeploymentFetch(_ctx, options) {
64452
64485
  };
64453
64486
  }
64454
64487
  function deploymentFetch(_ctx, options) {
64455
- const { deploymentUrl, adminKey, onError } = options;
64488
+ const {
64489
+ deploymentUrl,
64490
+ adminKey,
64491
+ onError,
64492
+ maxRetries = MAX_RETRIES,
64493
+ shouldRetry
64494
+ } = options;
64456
64495
  const onErrorWithAttempt = (err, attempt) => {
64457
64496
  onError?.(err);
64458
64497
  if (attempt >= RETRY_LOG_THRESHOLD) {
64459
64498
  logMessage(
64460
64499
  chalkStderr.gray(
64461
- `Retrying request (attempt ${attempt}/${MAX_RETRIES})...`
64500
+ `Retrying request (attempt ${attempt}/${maxRetries})...`
64462
64501
  )
64463
64502
  );
64464
64503
  }
@@ -64477,7 +64516,12 @@ function deploymentFetch(_ctx, options) {
64477
64516
  }
64478
64517
  const func = throwingFetch(url2, {
64479
64518
  retryDelay,
64480
- retryOn: deploymentFetchRetryOn(onErrorWithAttempt, options2?.method),
64519
+ retryOn: deploymentFetchRetryOn(
64520
+ onErrorWithAttempt,
64521
+ options2?.method,
64522
+ maxRetries,
64523
+ shouldRetry
64524
+ ),
64481
64525
  ...options2,
64482
64526
  headers
64483
64527
  });
@@ -64611,14 +64655,7 @@ ${advice}`;
64611
64655
  PLATFORM_MANAGEMENT_API_URL,
64612
64656
  bigBrainFetch
64613
64657
  );
64614
- BYTE_UNITS = [
64615
- [1 << 30, "GiB"],
64616
- [1e9, "GB"],
64617
- [1 << 20, "MiB"],
64618
- [1e6, "MB"],
64619
- [1 << 10, "KiB"],
64620
- [1e3, "KB"]
64621
- ];
64658
+ BYTE_UNITS = ["bytes", "KiB", "MiB", "GiB", "TiB", "PiB"];
64622
64659
  IDEMPOTENT_METHODS = ["GET", "HEAD", "PUT", "DELETE", "OPTIONS", "TRACE"];
64623
64660
  }
64624
64661
  });
@@ -110146,6 +110183,7 @@ init_run();
110146
110183
  init_log();
110147
110184
  init_filePaths();
110148
110185
  init_run();
110186
+ init_utils2();
110149
110187
  init_prompts();
110150
110188
  init_download();
110151
110189
 
@@ -110236,6 +110274,7 @@ async function handlePotentialUpgradeAndStart(ctx, args) {
110236
110274
  );
110237
110275
  const { cleanupHandle: cleanupHandle2 } = await runLocalBackend(ctx, {
110238
110276
  binaryPath: args.newBinaryPath,
110277
+ backendVersion: args.newVersion,
110239
110278
  deploymentKind: args.deploymentKind,
110240
110279
  deploymentName: args.deploymentName,
110241
110280
  ports: args.ports,
@@ -110265,6 +110304,7 @@ async function handlePotentialUpgradeAndStart(ctx, args) {
110265
110304
  });
110266
110305
  const { cleanupHandle: cleanupHandle2 } = await runLocalBackend(ctx, {
110267
110306
  binaryPath: oldBinaryPath,
110307
+ backendVersion: args.oldVersion,
110268
110308
  ports: args.ports,
110269
110309
  deploymentKind: args.deploymentKind,
110270
110310
  deploymentName: args.deploymentName,
@@ -110296,6 +110336,7 @@ async function handleUpgrade(ctx, args) {
110296
110336
  logVerbose(`Running backend on new version ${args.newVersion}`);
110297
110337
  const { cleanupHandle } = await runLocalBackend(ctx, {
110298
110338
  binaryPath: args.newBinaryPath,
110339
+ backendVersion: args.newVersion,
110299
110340
  ports: args.ports,
110300
110341
  deploymentKind: args.deploymentKind,
110301
110342
  deploymentName: args.deploymentName,
@@ -110319,9 +110360,6 @@ function _isDowngrade(oldVersion, newVersion) {
110319
110360
  const newDate = releaseDate(newVersion);
110320
110361
  return oldDate !== null && newDate !== null && newDate < oldDate;
110321
110362
  }
110322
- function releaseDate(version4) {
110323
- return /^precompiled-(\d{4}-\d{2}-\d{2})-/.exec(version4)?.[1] ?? null;
110324
- }
110325
110363
 
110326
110364
  // src/cli/lib/localDeployment/localDeployment.ts
110327
110365
  init_errors3();
@@ -114593,7 +114631,7 @@ var startPushRequest = looseObject({
114593
114631
  var schemaChange = looseObject({
114594
114632
  allocatedComponentIds: external_exports.any(),
114595
114633
  schemaIds: external_exports.any(),
114596
- indexDiffs: external_exports.record(componentDefinitionPath, indexDiff).optional()
114634
+ indexDiffs: external_exports.record(componentPath, indexDiff).optional()
114597
114635
  });
114598
114636
  var startPushResponse = looseObject({
114599
114637
  environmentVariables: external_exports.record(external_exports.string(), external_exports.string()),
@@ -114631,6 +114669,49 @@ var schemaStatus = external_exports.union([
114631
114669
  })
114632
114670
  ]);
114633
114671
 
114672
+ // src/cli/lib/deployApi/evaluateSchema.ts
114673
+ init_zod();
114674
+ var tableValidationOutcome = external_exports.enum([
114675
+ "notValidated",
114676
+ "supersetOfEnforced",
114677
+ "supersetOfShape",
114678
+ "mustWalk"
114679
+ ]);
114680
+ var indexChangePrediction = external_exports.enum([
114681
+ "added",
114682
+ "identical",
114683
+ "enabled",
114684
+ "disabled",
114685
+ "dropped"
114686
+ ]);
114687
+ var tablePrediction = looseObject({
114688
+ name: external_exports.string(),
114689
+ outcome: tableValidationOutcome,
114690
+ numDocs: external_exports.number(),
114691
+ sizeBytes: external_exports.number()
114692
+ });
114693
+ var indexPrediction = external_exports.intersection(
114694
+ developerIndexConfig,
114695
+ looseObject({
114696
+ change: indexChangePrediction,
114697
+ needsBackfill: external_exports.boolean(),
114698
+ numDocs: external_exports.number()
114699
+ })
114700
+ );
114701
+ var componentSchemaPrediction = looseObject({
114702
+ definitionPath: external_exports.string(),
114703
+ schemaValidation: external_exports.boolean(),
114704
+ tables: external_exports.array(tablePrediction),
114705
+ indexes: external_exports.array(indexPrediction)
114706
+ });
114707
+ var evaluateSchemaResponse = looseObject({
114708
+ componentSchemaEvaluations: external_exports.record(
114709
+ componentPath,
114710
+ componentSchemaPrediction
114711
+ ),
114712
+ newComponentDefinitions: external_exports.array(componentDefinitionPath)
114713
+ });
114714
+
114634
114715
  // src/cli/lib/deploy2.ts
114635
114716
  init_source();
114636
114717
  var import_node_util9 = require("node:util");
@@ -114645,7 +114726,7 @@ function addProgressLinkIfSlow(msg, deploymentName, start) {
114645
114726
  if (Date.now() - start > 1e4) {
114646
114727
  const dashboardUrl2 = deploymentDashboardUrlPage(
114647
114728
  deploymentName,
114648
- `/data?showSchema=true`
114729
+ `/schema?showSchema=true`
114649
114730
  );
114650
114731
  msg = msg.concat(`
114651
114732
  See progress here: ${dashboardUrl2}`);
@@ -115710,7 +115791,19 @@ async function evaluatePush(ctx, span, request, options) {
115710
115791
  );
115711
115792
  return evaluatePushResponse.parse(response);
115712
115793
  }
115713
- async function pushCode(ctx, span, request, options, endpoint) {
115794
+ async function evaluateSchema(ctx, span, request, options, bestEffort) {
115795
+ const response = await pushCode(
115796
+ ctx,
115797
+ span,
115798
+ request,
115799
+ options,
115800
+ "/api/deploy2/evaluate_schema",
115801
+ bestEffort
115802
+ );
115803
+ return evaluateSchemaResponse.parse(response);
115804
+ }
115805
+ var BEST_EFFORT_RETRIES = 5;
115806
+ async function pushCode(ctx, span, request, options, endpoint, bestEffort) {
115714
115807
  const unchangedModuleCount = request.appDefinition?.unchangedModuleHashes?.length ?? 0;
115715
115808
  const changedModuleCount = request.appDefinition?.changedModules?.length ?? 0;
115716
115809
  const requestSummary = {
@@ -115730,7 +115823,16 @@ async function pushCode(ctx, span, request, options, endpoint) {
115730
115823
  const fetch2 = deploymentFetch(ctx, {
115731
115824
  deploymentUrl: options.url,
115732
115825
  adminKey: request.adminKey,
115733
- onError
115826
+ onError,
115827
+ // Best-effort callers tolerate failure, so retry only plausibly
115828
+ // transient conditions — network errors and 5xx responses (e.g. table
115829
+ // summaries still bootstrapping) — and fail fast on everything else,
115830
+ // like a 404 from a deployment whose backend doesn't yet expose the
115831
+ // endpoint.
115832
+ ...bestEffort ? {
115833
+ maxRetries: BEST_EFFORT_RETRIES,
115834
+ shouldRetry: (error3, response) => error3 !== null || response !== null && response.status >= 500
115835
+ } : {}
115734
115836
  });
115735
115837
  try {
115736
115838
  const response = await fetch2(endpoint, {
@@ -115744,6 +115846,9 @@ async function pushCode(ctx, span, request, options, endpoint) {
115744
115846
  });
115745
115847
  return await response.json();
115746
115848
  } catch (error3) {
115849
+ if (bestEffort) {
115850
+ throw error3;
115851
+ }
115747
115852
  return await handlePushConfigError(
115748
115853
  ctx,
115749
115854
  error3,
@@ -115956,6 +116061,7 @@ async function deployToDeployment(ctx, credentials, options) {
115956
116061
  liveComponentSources: !!options.liveComponentSources,
115957
116062
  pushAllModules: !!options.pushAllModules,
115958
116063
  largeIndexDeletionCheck: options.allowDeletingLargeIndexes ? "has confirmation" : "ask for confirmation",
116064
+ warnOnSlowSchemaValidation: true,
115959
116065
  message: options.message
115960
116066
  };
115961
116067
  showSpinner(`Deploying to ${url2}...${options.dryRun ? " [dry run]" : ""}`);
@@ -119641,71 +119747,28 @@ async function checkForLargeIndexDeletion({
119641
119747
  askForConfirmation
119642
119748
  }) {
119643
119749
  changeSpinner("Verifying that the push isn\u2019t deleting large indexes...");
119644
- const { schemaChange: schemaChange2 } = await evaluatePush(ctx, span, request, options);
119645
- const indexDiffs = schemaChange2.indexDiffs ?? {};
119646
- const deletedIndexes = Object.entries(indexDiffs).flatMap(
119647
- ([componentDefinitionPath2, indexDiff2]) => indexDiff2.removed_indexes.map((index) => ({
119648
- componentDefinitionPath: componentDefinitionPath2,
119649
- index
119650
- }))
119651
- );
119750
+ const deletedIndexes = await deletedIndexesFromSchemaEvaluation({
119751
+ ctx,
119752
+ span,
119753
+ request,
119754
+ options
119755
+ }) ?? await deletedIndexesFromTableSizes({ ctx, span, request, options });
119652
119756
  if (deletedIndexes.length === 0) {
119653
119757
  logFinishedStep("No indexes are deleted by this push");
119654
119758
  return;
119655
119759
  }
119656
- const tablesWithDeletedIndexes = [
119657
- ...new Set(
119658
- deletedIndexes.map(
119659
- ({ componentDefinitionPath: componentDefinitionPath2, index }) => `${componentDefinitionPath2}:${getTableName(index)}`
119660
- )
119661
- )
119662
- ].map((str) => {
119663
- const [componentDefinitionPath2, table] = str.split(":");
119664
- return { componentDefinitionPath: componentDefinitionPath2, table };
119665
- });
119666
- changeSpinner("Checking whether the deleted indexes are on large tables...");
119667
- const documentCounts = await Promise.all(
119668
- tablesWithDeletedIndexes.map(
119669
- async ({ componentDefinitionPath: componentDefinitionPath2, table }) => ({
119670
- componentDefinitionPath: componentDefinitionPath2,
119671
- table,
119672
- count: await runSystemQuery(ctx, {
119673
- deploymentUrl: options.url,
119674
- adminKey: options.adminKey,
119675
- functionName: "_system/cli/tableSize:default",
119676
- componentPath: componentDefinitionPath2,
119677
- args: { tableName: table }
119678
- })
119679
- })
119680
- )
119681
- );
119682
- const deletedIndexesWithDocumentsCount = deletedIndexes.map(
119683
- ({ componentDefinitionPath: componentDefinitionPath2, index }) => ({
119684
- componentDefinitionPath: componentDefinitionPath2,
119685
- index,
119686
- count: documentCounts.find(
119687
- (count) => count.table === getTableName(index) && count.componentDefinitionPath === componentDefinitionPath2
119688
- ).count
119689
- })
119690
- );
119691
119760
  const minDocumentsForWarning = minDocumentsForIndexDeleteWarning();
119692
- if (!deletedIndexesWithDocumentsCount.some(
119693
- ({ count }) => count >= minDocumentsForWarning
119761
+ if (!deletedIndexes.some(
119762
+ ({ documentsCount }) => documentsCount >= minDocumentsForWarning
119694
119763
  )) {
119695
119764
  logFinishedStep("No large indexes are deleted by this push");
119696
119765
  return;
119697
119766
  }
119698
- logMessage(`\u26A0\uFE0F This code push will ${chalkStderr.bold("delete")} the following ${deletedIndexesWithDocumentsCount.length === 1 ? "index" : "indexes"}
119767
+ logMessage(`\u26A0\uFE0F This code push will ${chalkStderr.bold("delete")} the following ${deletedIndexes.length === 1 ? "index" : "indexes"}
119699
119768
  from your production deployment (${options.url}):
119700
119769
 
119701
- ${deletedIndexesWithDocumentsCount.map(
119702
- ({ componentDefinitionPath: componentDefinitionPath2, index, count }) => formatDeletedIndex({
119703
- componentDefinitionPath: componentDefinitionPath2,
119704
- index,
119705
- indexDiff: indexDiffs[componentDefinitionPath2],
119706
- documentsCount: count,
119707
- minDocumentsForWarning
119708
- })
119770
+ ${deletedIndexes.map(
119771
+ (deletedIndex) => formatDeletedIndex({ ...deletedIndex, minDocumentsForWarning })
119709
119772
  ).join("\n")}
119710
119773
 
119711
119774
  The documents that are in the index won\u2019t be deleted, but the index will need
@@ -119728,7 +119791,7 @@ to be backfilled again if you want to restore it later.
119728
119791
  }
119729
119792
  stopSpinner();
119730
119793
  if (!await promptYesNo(ctx, {
119731
- message: `Delete ${deletedIndexesWithDocumentsCount.length === 1 ? "this index" : "these indexes"}?`,
119794
+ message: `Delete ${deletedIndexes.length === 1 ? "this index" : "these indexes"}?`,
119732
119795
  default: false
119733
119796
  })) {
119734
119797
  return ctx.crash({
@@ -119739,16 +119802,98 @@ to be backfilled again if you want to restore it later.
119739
119802
  }
119740
119803
  logFinishedStep("Proceeding with push.");
119741
119804
  }
119805
+ async function deletedIndexesFromSchemaEvaluation({
119806
+ ctx,
119807
+ span,
119808
+ request,
119809
+ options
119810
+ }) {
119811
+ try {
119812
+ const response = await evaluateSchema(
119813
+ ctx,
119814
+ span,
119815
+ request,
119816
+ options,
119817
+ /* bestEffort */
119818
+ true
119819
+ );
119820
+ return Object.entries(response.componentSchemaEvaluations).flatMap(
119821
+ ([componentPath2, prediction]) => prediction.indexes.filter((index) => index.change === "dropped").map((index) => ({
119822
+ componentPath: componentPath2,
119823
+ index,
119824
+ documentsCount: index.numDocs,
119825
+ replacedBy: prediction.indexes.find(
119826
+ (other) => other.change === "added" && other.name === index.name
119827
+ ) ?? null
119828
+ }))
119829
+ );
119830
+ } catch (error3) {
119831
+ logVerbose(
119832
+ `Schema evaluation unavailable, sizing deleted indexes per table: ${error3 instanceof Error ? error3.message : String(error3)}`
119833
+ );
119834
+ return null;
119835
+ }
119836
+ }
119837
+ async function deletedIndexesFromTableSizes({
119838
+ ctx,
119839
+ span,
119840
+ request,
119841
+ options
119842
+ }) {
119843
+ const { schemaChange: schemaChange2 } = await evaluatePush(ctx, span, request, options);
119844
+ const indexDiffs = schemaChange2.indexDiffs ?? {};
119845
+ const deletedIndexes = Object.entries(indexDiffs).flatMap(
119846
+ ([componentPath2, indexDiff2]) => indexDiff2.removed_indexes.map((index) => ({
119847
+ componentPath: componentPath2,
119848
+ index,
119849
+ replacedBy: indexDiff2.added_indexes.find((other) => other.name === index.name) ?? null
119850
+ }))
119851
+ );
119852
+ if (deletedIndexes.length === 0) {
119853
+ return [];
119854
+ }
119855
+ const tablesWithDeletedIndexes = [
119856
+ ...new Set(
119857
+ deletedIndexes.map(
119858
+ ({ componentPath: componentPath2, index }) => `${componentPath2}:${getTableName(index)}`
119859
+ )
119860
+ )
119861
+ ].map((str) => {
119862
+ const [componentPath2, table] = str.split(":");
119863
+ return { componentPath: componentPath2, table };
119864
+ });
119865
+ changeSpinner("Checking whether the deleted indexes are on large tables...");
119866
+ const documentCounts = await Promise.all(
119867
+ tablesWithDeletedIndexes.map(async ({ componentPath: componentPath2, table }) => ({
119868
+ componentPath: componentPath2,
119869
+ table,
119870
+ count: await runSystemQuery(ctx, {
119871
+ deploymentUrl: options.url,
119872
+ adminKey: options.adminKey,
119873
+ functionName: "_system/cli/tableSize:default",
119874
+ componentPath: componentPath2,
119875
+ args: { tableName: table }
119876
+ })
119877
+ }))
119878
+ );
119879
+ return deletedIndexes.map(({ componentPath: componentPath2, index, replacedBy }) => ({
119880
+ componentPath: componentPath2,
119881
+ index,
119882
+ replacedBy,
119883
+ documentsCount: documentCounts.find(
119884
+ (count) => count.table === getTableName(index) && count.componentPath === componentPath2
119885
+ ).count
119886
+ }));
119887
+ }
119742
119888
  function formatDeletedIndex({
119743
- componentDefinitionPath: componentDefinitionPath2,
119889
+ componentPath: componentPath2,
119744
119890
  index,
119745
- indexDiff: indexDiff2,
119746
119891
  documentsCount,
119892
+ replacedBy,
119747
119893
  minDocumentsForWarning
119748
119894
  }) {
119749
- const componentNameFormatted = componentDefinitionPath2 !== "" ? `${chalkStderr.gray(componentDefinitionPath2)}:` : "";
119895
+ const componentNameFormatted = componentPath2 !== "" ? `${chalkStderr.gray(componentPath2)}:` : "";
119750
119896
  const documentsCountFormatted = documentsCount >= minDocumentsForWarning ? ` ${chalkStderr.yellowBright(`\u26A0\uFE0F ${documentsCount.toLocaleString()} documents`)}` : ` ${documentsCount.toLocaleString()} ${documentsCount === 1 ? "document" : "documents"}`;
119751
- const replacedBy = indexDiff2.added_indexes.find((i) => i.name === index.name);
119752
119897
  const replacedByFormatted = replacedBy ? `
119753
119898
  ${chalkStderr.green("\u2192 replaced by:")} ${formatIndex(replacedBy)}` : "";
119754
119899
  return "\u26D4 " + componentNameFormatted + formatIndex(index) + documentsCountFormatted + replacedByFormatted;
@@ -119768,6 +119913,90 @@ function minDocumentsForIndexDeleteWarning() {
119768
119913
  return MIN_DOCUMENTS_FOR_INDEX_DELETE_WARNING;
119769
119914
  }
119770
119915
 
119916
+ // src/cli/lib/checkForSlowSchemaValidation.ts
119917
+ init_source();
119918
+ init_log();
119919
+ init_utils3();
119920
+ var MIN_BYTES_FOR_SCHEMA_WALK_WARNING = 1 << 27;
119921
+ async function checkForSlowSchemaValidation({
119922
+ ctx,
119923
+ span,
119924
+ request,
119925
+ options
119926
+ }) {
119927
+ const response = await evaluateSchemaBestEffort({
119928
+ ctx,
119929
+ span,
119930
+ request,
119931
+ options
119932
+ });
119933
+ if (response === null) {
119934
+ return;
119935
+ }
119936
+ const walkedTables = Object.entries(
119937
+ response.componentSchemaEvaluations
119938
+ ).flatMap(
119939
+ ([componentPath2, prediction]) => prediction.tables.filter((table) => table.outcome === "mustWalk").map((table) => ({ componentPath: componentPath2, table }))
119940
+ );
119941
+ if (walkedTables.length === 0) {
119942
+ return;
119943
+ }
119944
+ const totalBytes = walkedTables.reduce(
119945
+ (sum, { table }) => sum + table.sizeBytes,
119946
+ 0
119947
+ );
119948
+ if (totalBytes < minBytesForSchemaWalkWarning()) {
119949
+ return;
119950
+ }
119951
+ logMessage(`\u26A0\uFE0F This schema change requires checking every document in the following ${walkedTables.length === 1 ? "table" : "tables"} against your new schema, totaling ${chalkStderr.yellowBright(formatSize(totalBytes))}. This deploy may take a while:
119952
+
119953
+ ${walkedTables.map(
119954
+ ({ componentPath: componentPath2, table }) => formatWalkedTable({ componentPath: componentPath2, table })
119955
+ ).join("\n")}
119956
+ `);
119957
+ }
119958
+ async function evaluateSchemaBestEffort({
119959
+ ctx,
119960
+ span,
119961
+ request,
119962
+ options
119963
+ }) {
119964
+ try {
119965
+ return await evaluateSchema(
119966
+ ctx,
119967
+ span,
119968
+ request,
119969
+ options,
119970
+ /* bestEffort */
119971
+ true
119972
+ );
119973
+ } catch (error3) {
119974
+ logVerbose(
119975
+ `Skipping slow schema validation check: ${error3 instanceof Error ? error3.message : String(error3)}`
119976
+ );
119977
+ return null;
119978
+ }
119979
+ }
119980
+ function formatWalkedTable({
119981
+ componentPath: componentPath2,
119982
+ table
119983
+ }) {
119984
+ const componentPrefix = componentPath2 !== "" ? `${chalkStderr.gray(componentPath2)}: ` : "";
119985
+ const docsFormatted = `${table.numDocs.toLocaleString()} documents, `;
119986
+ const sizeFormatted = formatSize(table.sizeBytes);
119987
+ return ` ${componentPrefix}${table.name} (${docsFormatted}${sizeFormatted})`;
119988
+ }
119989
+ function minBytesForSchemaWalkWarning() {
119990
+ const envValue = process.env.CONVEX_MIN_BYTES_FOR_SCHEMA_WALK_WARNING;
119991
+ if (envValue !== void 0) {
119992
+ const parsed = parseInt(envValue, 10);
119993
+ if (!isNaN(parsed)) {
119994
+ return parsed;
119995
+ }
119996
+ }
119997
+ return MIN_BYTES_FOR_SCHEMA_WALK_WARNING;
119998
+ }
119999
+
119771
120000
  // src/cli/lib/components.ts
119772
120001
  var import_crypto6 = require("crypto");
119773
120002
  async function runCodegen(ctx, credentials, options) {
@@ -120041,6 +120270,17 @@ async function startComponentsPushAndCodegen(ctx, parentSpan, projectConfig, con
120041
120270
  })
120042
120271
  );
120043
120272
  }
120273
+ if (options.dryRun && options.warnOnSlowSchemaValidation) {
120274
+ await parentSpan.enterAsync(
120275
+ "checkForSlowSchemaValidation",
120276
+ (span) => checkForSlowSchemaValidation({
120277
+ ctx,
120278
+ span,
120279
+ request: startPushRequest2,
120280
+ options
120281
+ })
120282
+ );
120283
+ }
120044
120284
  changeSpinner("Uploading functions to Convex...");
120045
120285
  const startPushResponse2 = await parentSpan.enterAsync(
120046
120286
  "startPush",
@@ -120569,6 +120809,7 @@ async function devAgainstDeployment(ctx, credentials, devOptions) {
120569
120809
  // Pass logManager to control logs during deploy
120570
120810
  largeIndexDeletionCheck: "no verification",
120571
120811
  // `convex dev` can’t push to prod
120812
+ warnOnSlowSchemaValidation: true,
120572
120813
  message: null
120573
120814
  },
120574
120815
  devOptions
@@ -121311,6 +121552,7 @@ async function pushToDeployment(ctx, args) {
121311
121552
  pushAllModules: false,
121312
121553
  largeIndexDeletionCheck: "no verification",
121313
121554
  // `convex run` can’t push to prod
121555
+ warnOnSlowSchemaValidation: true,
121314
121556
  message: null
121315
121557
  },
121316
121558
  {
@@ -124991,6 +125233,8 @@ var codegen = new Command2("codegen").summary("Generate backend type definitions
124991
125233
  systemUdfs: !!options.systemUdfs,
124992
125234
  largeIndexDeletionCheck: "no verification",
124993
125235
  // `codegen` is a read-only operation
125236
+ warnOnSlowSchemaValidation: false,
125237
+ // ditto: a codegen dry run never deploys
124994
125238
  codegenOnlyThisComponent: options.componentDir
124995
125239
  };
124996
125240
  if (options.systemUdfs) {
@@ -127385,6 +127629,7 @@ async function deployToNewPreviewDeployment(ctx, deploymentSelection, options) {
127385
127629
  pushAllModules: !!options.pushAllModules,
127386
127630
  largeIndexDeletionCheck: "no verification",
127387
127631
  // fine for preview deployments
127632
+ warnOnSlowSchemaValidation: true,
127388
127633
  message: options.message
127389
127634
  };
127390
127635
  showSpinner(`Deploying to ${previewUrl}...`);
@@ -130679,42 +130924,11 @@ var dev = new Command2("dev").summary("Develop against a dev deployment, watchin
130679
130924
  // src/cli/docs.ts
130680
130925
  init_source();
130681
130926
  init_log();
130682
- init_utils3();
130683
130927
  var docs = new Command2("docs").description("Open the docs in the browser").allowExcessArguments(false).option("--no-open", "Print docs URL instead of opening it in your browser").action(async (options) => {
130684
- const ctx = await oneoffContext({
130685
- url: void 0,
130686
- adminKey: void 0,
130687
- envFile: void 0
130688
- });
130689
- const deploymentSelection = await getDeploymentSelection(ctx, {
130690
- url: void 0,
130691
- adminKey: void 0,
130692
- envFile: void 0
130693
- });
130694
- const configuredDeployment = deploymentNameFromSelection(deploymentSelection);
130695
- if (configuredDeployment === null) {
130696
- await openDocs(ctx, options.open);
130697
- return;
130698
- }
130699
- const getCookieUrl = new URL(
130700
- `get_cookie/${configuredDeployment}`,
130701
- BIG_BRAIN_URL
130702
- );
130703
- const fetch2 = bigBrainFetch(ctx);
130704
- try {
130705
- const res = await fetch2(getCookieUrl);
130706
- deprecationCheckWarning(ctx, res);
130707
- const { cookie } = await res.json();
130708
- await openDocs(ctx, options.open, cookie);
130709
- } catch {
130710
- await openDocs(ctx, options.open);
130711
- }
130928
+ await openDocs(options.open);
130712
130929
  });
130713
- async function openDocs(ctx, toOpen, cookie) {
130714
- let docsUrl = "https://docs.convex.dev";
130715
- if (cookie !== void 0) {
130716
- docsUrl += "/?t=" + cookie;
130717
- }
130930
+ async function openDocs(toOpen) {
130931
+ const docsUrl = "https://docs.convex.dev/?utm_source=convex-cli";
130718
130932
  if (toOpen) {
130719
130933
  await open_default(docsUrl);
130720
130934
  logMessage(chalkStderr.green("Docs have launched! Check your browser."));
@@ -131886,6 +132100,9 @@ var logs = new Command2("logs").summary("Watch logs from your deployment").descr
131886
132100
  });
131887
132101
  });
131888
132102
 
132103
+ // src/cli/mcp.ts
132104
+ init_log();
132105
+
131889
132106
  // ../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs
131890
132107
  var __create2 = Object.create;
131891
132108
  var __defProp2 = Object.defineProperty;
@@ -138681,6 +138898,7 @@ function missingClientCapabilities(required2, declared) {
138681
138898
  return Object.keys(missing).length > 0 ? missing : void 0;
138682
138899
  }
138683
138900
  var FIRST_MODERN_PROTOCOL_VERSION = "2026-07-28";
138901
+ var SUPPORTED_MODERN_PROTOCOL_VERSIONS = [FIRST_MODERN_PROTOCOL_VERSION];
138684
138902
  function isModernProtocolVersion(version4) {
138685
138903
  return version4 >= FIRST_MODERN_PROTOCOL_VERSION;
138686
138904
  }
@@ -141239,6 +141457,25 @@ function isSpecNotificationMethod(method) {
141239
141457
  return ALL_CODECS.some((codec) => codec.hasNotificationMethod(method));
141240
141458
  }
141241
141459
  var ALL_CODECS = [rev2025Codec, rev2026Codec];
141460
+ function isPlainObject$3(value) {
141461
+ return value !== null && typeof value === "object" && !Array.isArray(value);
141462
+ }
141463
+ function requestMetaOf(params) {
141464
+ if (!isPlainObject$3(params)) return void 0;
141465
+ const meta2 = params["_meta"];
141466
+ return isPlainObject$3(meta2) ? meta2 : void 0;
141467
+ }
141468
+ function hasEnvelopeClaim(params) {
141469
+ const meta2 = requestMetaOf(params);
141470
+ return meta2 !== void 0 && PROTOCOL_VERSION_META_KEY in meta2;
141471
+ }
141472
+ function envelopeClaimVersion(params) {
141473
+ const value = requestMetaOf(params)?.[PROTOCOL_VERSION_META_KEY];
141474
+ return typeof value === "string" ? value : void 0;
141475
+ }
141476
+ function validateEnvelopeMeta(meta2) {
141477
+ return codecForVersion(MODERN_WIRE_REVISION).validateEnvelopeMeta(meta2);
141478
+ }
141242
141479
  var schemas_exports2 = /* @__PURE__ */ __exportAll({
141243
141480
  AnnotationsSchema: () => AnnotationsSchema,
141244
141481
  AudioContentSchema: () => AudioContentSchema,
@@ -141412,6 +141649,96 @@ var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value
141412
141649
  var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;
141413
141650
  var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;
141414
141651
  var isInputRequiredResult = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.resultType === "input_required";
141652
+ function assertCompleteRequestPrompt(request) {
141653
+ if (request.params.ref.type !== "ref/prompt") throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);
141654
+ }
141655
+ function assertCompleteRequestResourceTemplate(request) {
141656
+ if (request.params.ref.type !== "ref/resource") throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);
141657
+ }
141658
+ var X_MCP_HEADER_KEY = "x-mcp-header";
141659
+ var RFC9110_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
141660
+ var PERMITTED_X_MCP_HEADER_TYPES = /* @__PURE__ */ new Set([
141661
+ "string",
141662
+ "integer",
141663
+ "boolean",
141664
+ "number"
141665
+ ]);
141666
+ function scanXMcpHeaderDeclarations(inputSchema9) {
141667
+ const declarations = [];
141668
+ const seenLower = /* @__PURE__ */ new Map();
141669
+ const visit = (node, path38, reachable) => {
141670
+ if (node === null || typeof node !== "object") return void 0;
141671
+ const schema2 = node;
141672
+ if (X_MCP_HEADER_KEY in schema2) {
141673
+ if (!reachable || path38.length === 0) return `${pathName(path38)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;
141674
+ const raw = schema2[X_MCP_HEADER_KEY];
141675
+ if (typeof raw !== "string" || raw.length === 0) return `${pathName(path38)}: x-mcp-header MUST be a non-empty string`;
141676
+ if (!RFC9110_TOKEN.test(raw)) return `${pathName(path38)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;
141677
+ const type = typeof schema2.type === "string" ? schema2.type : void 0;
141678
+ if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path38)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? "<none>"}`;
141679
+ const lower = raw.toLowerCase();
141680
+ const prior = seenLower.get(lower);
141681
+ if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`;
141682
+ seenLower.set(lower, raw);
141683
+ declarations.push({
141684
+ path: path38,
141685
+ headerName: raw,
141686
+ type
141687
+ });
141688
+ }
141689
+ const properties = schema2.properties;
141690
+ if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) {
141691
+ const fault$1 = visit(child, [...path38, key], reachable);
141692
+ if (fault$1 !== void 0) return fault$1;
141693
+ }
141694
+ for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) {
141695
+ const sub = schema2[k];
141696
+ if (sub === void 0) continue;
141697
+ const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub];
141698
+ for (const branch of branches) {
141699
+ const fault$1 = visit(branch, [...path38, `<${k}>`], false);
141700
+ if (fault$1 !== void 0) return fault$1;
141701
+ }
141702
+ }
141703
+ };
141704
+ const fault = visit(inputSchema9, [], true);
141705
+ return fault === void 0 ? {
141706
+ valid: true,
141707
+ declarations
141708
+ } : {
141709
+ valid: false,
141710
+ reason: fault
141711
+ };
141712
+ }
141713
+ var NON_REACHABLE_SUBSCHEMA_KEYWORDS = [
141714
+ "items",
141715
+ "prefixItems",
141716
+ "contains",
141717
+ "additionalProperties",
141718
+ "unevaluatedProperties",
141719
+ "unevaluatedItems",
141720
+ "propertyNames",
141721
+ "patternProperties",
141722
+ "dependentSchemas",
141723
+ "oneOf",
141724
+ "anyOf",
141725
+ "allOf",
141726
+ "not",
141727
+ "if",
141728
+ "then",
141729
+ "else",
141730
+ "$defs",
141731
+ "definitions"
141732
+ ];
141733
+ var OBJECT_VALUED_SUBSCHEMA_KEYWORDS = /* @__PURE__ */ new Set([
141734
+ "patternProperties",
141735
+ "dependentSchemas",
141736
+ "$defs",
141737
+ "definitions"
141738
+ ]);
141739
+ function pathName(path38) {
141740
+ return path38.length === 0 ? "<root>" : path38.join(".");
141741
+ }
141415
141742
  var HEADER_MISMATCH_ERROR_CODE = -32020;
141416
141743
  var INBOUND_VALIDATION_LADDER = [
141417
141744
  {
@@ -141499,6 +141826,45 @@ var LADDER_ERROR_HTTP_STATUS = {
141499
141826
  [ProtocolErrorCode.MissingRequiredClientCapability]: 400,
141500
141827
  [HEADER_MISMATCH_ERROR_CODE]: 400
141501
141828
  };
141829
+ function rejection(rung, cell, httpStatus, error3, settled) {
141830
+ return {
141831
+ kind: "reject",
141832
+ rung,
141833
+ cell,
141834
+ httpStatus,
141835
+ code: error3.code,
141836
+ message: error3.message,
141837
+ ...error3.data !== void 0 && { data: error3.data },
141838
+ settled
141839
+ };
141840
+ }
141841
+ function carriesValidModernEnvelopeClaim(params) {
141842
+ if (!hasEnvelopeClaim(params)) return false;
141843
+ const claimedVersion = envelopeClaimVersion(params);
141844
+ if (claimedVersion === void 0 || !isModernProtocolVersion(claimedVersion)) return false;
141845
+ const meta2 = requestMetaOf(params);
141846
+ return meta2 !== void 0 && validateEnvelopeMeta(meta2).length === 0;
141847
+ }
141848
+ function modernOnlyStrictRejection(route, supportedVersions) {
141849
+ switch (route.reason) {
141850
+ case "http-method":
141851
+ return rejection("http-method", "modern-only-method-not-allowed", 405, new ProtocolError(-32e3, "Method not allowed."), true);
141852
+ case "batch":
141853
+ return rejection("jsonrpc-shape", "modern-only-batch-not-supported", 400, new ProtocolError(ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches are not supported by this endpoint"), true);
141854
+ case "response":
141855
+ return rejection("jsonrpc-shape", "modern-only-response-post", 400, new ProtocolError(ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC responses cannot be posted to this endpoint"), true);
141856
+ case "notification":
141857
+ return;
141858
+ case "initialize":
141859
+ case "no-claim": {
141860
+ const requested = route.requestedVersion;
141861
+ return rejection("era-classification", "modern-only-missing-envelope", 400, requested === void 0 ? new ProtocolError(ProtocolErrorCode.UnsupportedProtocolVersion, "Unsupported protocol version: the request did not name a protocol version", { supported: [...supportedVersions] }) : new UnsupportedProtocolVersionError({
141862
+ supported: [...supportedVersions],
141863
+ requested
141864
+ }), true);
141865
+ }
141866
+ }
141867
+ }
141502
141868
  function parseSchema(schema2, data2) {
141503
141869
  return safeParse2(schema2, data2);
141504
141870
  }
@@ -141613,6 +141979,16 @@ function isLibraryFormatPattern(format5, pattern, vendor) {
141613
141979
  if (vendor !== "zod") return true;
141614
141980
  return referencePatternsForFormat(format5, pattern).has(pattern);
141615
141981
  }
141982
+ function promptArgumentsFromStandardSchema(schema2) {
141983
+ const jsonSchema = standardSchemaToJsonSchema(schema2, "input");
141984
+ const properties = jsonSchema.properties || {};
141985
+ const required2 = jsonSchema.required || [];
141986
+ return Object.entries(properties).map(([name, prop]) => ({
141987
+ name,
141988
+ description: prop?.description,
141989
+ required: required2.includes(name)
141990
+ }));
141991
+ }
141616
141992
  function isJsonObject(value) {
141617
141993
  return typeof value === "object" && value !== null && !Array.isArray(value);
141618
141994
  }
@@ -142050,6 +142426,9 @@ function withRequestStateValue(ctx, value) {
142050
142426
  };
142051
142427
  }
142052
142428
  var writeNegotiatedProtocolVersion;
142429
+ function setNegotiatedProtocolVersion(instance, version4) {
142430
+ writeNegotiatedProtocolVersion(instance, version4);
142431
+ }
142053
142432
  var Protocol = class {
142054
142433
  _transport;
142055
142434
  _requestMessageId = 0;
@@ -142908,6 +143287,68 @@ function deserializeMessage(line) {
142908
143287
  function serializeMessage(message) {
142909
143288
  return JSON.stringify(message) + "\n";
142910
143289
  }
143290
+ var TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/;
143291
+ function validateToolName(name) {
143292
+ const warnings = [];
143293
+ if (name.length === 0) return {
143294
+ isValid: false,
143295
+ warnings: ["Tool name cannot be empty"]
143296
+ };
143297
+ if (name.length > 128) return {
143298
+ isValid: false,
143299
+ warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]
143300
+ };
143301
+ if (name.includes(" ")) warnings.push("Tool name contains spaces, which may cause parsing issues");
143302
+ if (name.includes(",")) warnings.push("Tool name contains commas, which may cause parsing issues");
143303
+ if (name.startsWith("-") || name.endsWith("-")) warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");
143304
+ if (name.startsWith(".") || name.endsWith(".")) warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");
143305
+ if (!TOOL_NAME_REGEX.test(name)) {
143306
+ const invalidChars = [...name].filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index);
143307
+ 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 (.)");
143308
+ return {
143309
+ isValid: false,
143310
+ warnings
143311
+ };
143312
+ }
143313
+ return {
143314
+ isValid: true,
143315
+ warnings
143316
+ };
143317
+ }
143318
+ function issueToolNameWarning(name, warnings) {
143319
+ if (warnings.length > 0) {
143320
+ console.warn(`Tool name validation warning for "${name}":`);
143321
+ for (const warning2 of warnings) console.warn(` - ${warning2}`);
143322
+ console.warn("Tool registration will proceed, but this may cause compatibility issues.");
143323
+ console.warn("Consider updating the tool name to conform to the MCP tool naming standard.");
143324
+ console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.");
143325
+ }
143326
+ }
143327
+ function validateAndWarnToolName(name) {
143328
+ const result = validateToolName(name);
143329
+ issueToolNameWarning(name, result.warnings);
143330
+ return result.isValid;
143331
+ }
143332
+ function isZodV4Schema(v) {
143333
+ return typeof v === "object" && v !== null && "_zod" in v;
143334
+ }
143335
+ function looksLikeZodV3(v) {
143336
+ return typeof v === "object" && v !== null && !("_zod" in v) && "_def" in v && typeof v._def?.typeName === "string";
143337
+ }
143338
+ function isZodRawShape(obj) {
143339
+ if (typeof obj !== "object" || obj === null) return false;
143340
+ if (isStandardSchema(obj)) return false;
143341
+ const proto2 = Object.getPrototypeOf(obj);
143342
+ if (proto2 !== Object.prototype && proto2 !== null) return false;
143343
+ return Object.values(obj).every((v) => isZodV4Schema(v));
143344
+ }
143345
+ function normalizeRawShapeSchema(schema2) {
143346
+ if (schema2 === void 0) return void 0;
143347
+ if (isZodRawShape(schema2)) return object(schema2);
143348
+ if (typeof schema2 === "object" && schema2 !== null && !isStandardSchema(schema2) && Object.values(schema2).some((v) => looksLikeZodV3(v))) throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");
143349
+ if (!isStandardSchema(schema2)) throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");
143350
+ return schema2;
143351
+ }
142911
143352
 
142912
143353
  // ../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/ajvProvider-CEoC__sr.mjs
142913
143354
  var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports2) => {
@@ -149924,7 +150365,197 @@ var import_node_process16 = __toESM(require("node:process"), 1);
149924
150365
 
149925
150366
  // ../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/mcp-DXXb3Vv3.mjs
149926
150367
  var COMPLETABLE_SYMBOL = Symbol.for("mcp.completable");
150368
+ function isCompletable(schema2) {
150369
+ return !!schema2 && typeof schema2 === "object" && COMPLETABLE_SYMBOL in schema2;
150370
+ }
150371
+ function getCompleter(schema2) {
150372
+ return schema2[COMPLETABLE_SYMBOL]?.complete;
150373
+ }
149927
150374
  var MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
150375
+ function listenFilterAccepts(filter, event) {
150376
+ switch (event.kind) {
150377
+ case "tools_list_changed":
150378
+ return filter.toolsListChanged === true;
150379
+ case "prompts_list_changed":
150380
+ return filter.promptsListChanged === true;
150381
+ case "resources_list_changed":
150382
+ return filter.resourcesListChanged === true;
150383
+ case "resource_updated":
150384
+ return filter.resourceSubscriptions !== void 0 && filter.resourceSubscriptions.includes(event.uri);
150385
+ }
150386
+ }
150387
+ function honoredSubset(requested, capabilities) {
150388
+ const honored = {};
150389
+ const allow = (bit) => capabilities === void 0 || bit === true;
150390
+ if (requested.toolsListChanged === true && allow(capabilities?.tools?.listChanged)) honored.toolsListChanged = true;
150391
+ if (requested.promptsListChanged === true && allow(capabilities?.prompts?.listChanged)) honored.promptsListChanged = true;
150392
+ if (requested.resourcesListChanged === true && allow(capabilities?.resources?.listChanged)) honored.resourcesListChanged = true;
150393
+ if (requested.resourceSubscriptions !== void 0 && requested.resourceSubscriptions.length > 0 && allow(capabilities?.resources?.subscribe)) honored.resourceSubscriptions = [...requested.resourceSubscriptions];
150394
+ return honored;
150395
+ }
150396
+ var DEFAULT_MAX_SUBSCRIPTIONS = 1024;
150397
+ function stampSubscriptionId(notification, subscriptionId) {
150398
+ return {
150399
+ method: notification.method,
150400
+ params: {
150401
+ ...notification.params,
150402
+ _meta: {
150403
+ ...notification.params?._meta,
150404
+ [SUBSCRIPTION_ID_META_KEY]: subscriptionId
150405
+ }
150406
+ }
150407
+ };
150408
+ }
150409
+ function parseListenFilter(message) {
150410
+ const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen", message);
150411
+ return outcome.ok ? outcome.value.params?.notifications : void 0;
150412
+ }
150413
+ var CHANGE_NOTIFICATION_METHODS = /* @__PURE__ */ new Set([
150414
+ "notifications/tools/list_changed",
150415
+ "notifications/prompts/list_changed",
150416
+ "notifications/resources/list_changed",
150417
+ "notifications/resources/updated"
150418
+ ]);
150419
+ var StdioListenRouter = class {
150420
+ /** Active subscriptions, keyed by the listen request's JSON-RPC id verbatim. */
150421
+ _subs = /* @__PURE__ */ new Map();
150422
+ /**
150423
+ * The serving instance's declared capabilities. Filled in by the entry
150424
+ * once the modern instance is constructed (the router is created before
150425
+ * the instance exists), so the acknowledged filter is narrowed against
150426
+ * what the server can actually deliver.
150427
+ */
150428
+ _serverCapabilities;
150429
+ /**
150430
+ * The serving instance's identity, stamped onto the graceful-close
150431
+ * results' `_meta` (the spec's `SubscriptionsListenResultMeta` extends
150432
+ * `ResultMetaObject`). Handed over together with the capabilities.
150433
+ */
150434
+ _serverInfo;
150435
+ constructor(_maxSubscriptions = DEFAULT_MAX_SUBSCRIPTIONS, serverCapabilities, serverInfo) {
150436
+ this._maxSubscriptions = _maxSubscriptions;
150437
+ this._serverCapabilities = serverCapabilities;
150438
+ this._serverInfo = serverInfo;
150439
+ }
150440
+ /**
150441
+ * Record the serving instance's declared capabilities and identity once
150442
+ * it has been constructed. Called by `serveStdio`'s connect path;
150443
+ * subsequent `serve()` calls narrow the honored filter against the
150444
+ * capabilities, and `teardownAll()` stamps the identity.
150445
+ */
150446
+ setServerCapabilities(capabilities, serverInfo) {
150447
+ this._serverCapabilities = capabilities;
150448
+ if (serverInfo !== void 0) this._serverInfo = serverInfo;
150449
+ }
150450
+ /** Whether `id` is an active listen subscription on this connection. */
150451
+ has(id) {
150452
+ return this._subs.has(id);
150453
+ }
150454
+ /**
150455
+ * Serve one inbound `subscriptions/listen` request: registers the
150456
+ * subscription and returns the stamped acknowledged notification (or, on
150457
+ * capacity / params rejection, the in-band JSON-RPC error response).
150458
+ *
150459
+ * @throws when called before {@linkcode setServerCapabilities} (or the
150460
+ * constructor) has supplied the serving instance's capabilities. Honoring a
150461
+ * filter without knowing the server's advertised capabilities would fail
150462
+ * open (deliver unadvertised types); the entry guarantees capabilities are
150463
+ * set before any listen request is routed here.
150464
+ */
150465
+ serve(message) {
150466
+ if (this._serverCapabilities === void 0) throw new Error("StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities");
150467
+ if (this._subs.size >= this._maxSubscriptions) return {
150468
+ jsonrpc: "2.0",
150469
+ id: message.id,
150470
+ error: {
150471
+ code: -32603,
150472
+ message: "Subscription limit reached"
150473
+ }
150474
+ };
150475
+ const filter = parseListenFilter(message);
150476
+ if (filter === void 0) return {
150477
+ jsonrpc: "2.0",
150478
+ id: message.id,
150479
+ error: {
150480
+ code: -32602,
150481
+ message: "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter"
150482
+ }
150483
+ };
150484
+ const honored = honoredSubset(filter, this._serverCapabilities);
150485
+ this._subs.set(message.id, honored);
150486
+ return stampSubscriptionId({
150487
+ method: "notifications/subscriptions/acknowledged",
150488
+ params: { notifications: honored }
150489
+ }, message.id);
150490
+ }
150491
+ /**
150492
+ * Tear down one subscription (inbound `notifications/cancelled`). Returns
150493
+ * `true` when a subscription was removed. After this call NOTHING further
150494
+ * is delivered for that subscription id (the post-cancel hardening).
150495
+ */
150496
+ cancel(id) {
150497
+ return this._subs.delete(id);
150498
+ }
150499
+ /**
150500
+ * Route an outbound notification through the active subscriptions.
150501
+ *
150502
+ * - For a subscription-gated change notification, returns one stamped copy
150503
+ * per subscription that opted in to it (an empty array means it is
150504
+ * dropped — the modern era never delivers an un-requested change type).
150505
+ * - For any other outbound message, returns `'passthrough'` (the entry
150506
+ * forwards it as-is).
150507
+ */
150508
+ routeOutbound(message) {
150509
+ if (!CHANGE_NOTIFICATION_METHODS.has(message.method)) return "passthrough";
150510
+ const uriParam = message.params?.["uri"];
150511
+ const uri = typeof uriParam === "string" ? uriParam : void 0;
150512
+ const event = notificationToServerEvent(message.method, uri);
150513
+ const out = [];
150514
+ for (const [subscriptionId, filter] of this._subs) if (listenFilterAccepts(filter, event)) out.push(stampSubscriptionId({
150515
+ method: message.method,
150516
+ params: message.params ?? {}
150517
+ }, subscriptionId));
150518
+ return out;
150519
+ }
150520
+ /**
150521
+ * Server-side graceful teardown of every active subscription: returns the
150522
+ * empty `subscriptions/listen` JSON-RPC result for each subscription id —
150523
+ * the spec's graceful-close signal, `_meta` carrying the subscription id
150524
+ * and the serving instance's identity — for the entry to emit before
150525
+ * closing the wire. Clears the set so nothing further is delivered.
150526
+ */
150527
+ teardownAll() {
150528
+ const out = [];
150529
+ for (const id of this._subs.keys()) out.push({
150530
+ jsonrpc: "2.0",
150531
+ id,
150532
+ result: {
150533
+ resultType: "complete",
150534
+ _meta: {
150535
+ [SUBSCRIPTION_ID_META_KEY]: id,
150536
+ ...this._serverInfo !== void 0 && { [SERVER_INFO_META_KEY]: this._serverInfo }
150537
+ }
150538
+ }
150539
+ });
150540
+ this._subs.clear();
150541
+ return out;
150542
+ }
150543
+ };
150544
+ function notificationToServerEvent(method, uri) {
150545
+ switch (method) {
150546
+ case "notifications/tools/list_changed":
150547
+ return { kind: "tools_list_changed" };
150548
+ case "notifications/prompts/list_changed":
150549
+ return { kind: "prompts_list_changed" };
150550
+ case "notifications/resources/list_changed":
150551
+ return { kind: "resources_list_changed" };
150552
+ default:
150553
+ return {
150554
+ kind: "resource_updated",
150555
+ uri: uri ?? ""
150556
+ };
150557
+ }
150558
+ }
149928
150559
  var DEFAULT_LEGACY_SHIM_MAX_ROUNDS = 8;
149929
150560
  var DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS = 6e5;
149930
150561
  function resolveLegacyShimOptions(options) {
@@ -150062,6 +150693,12 @@ var INPUT_REQUIRED_CAPABLE_METHODS = /* @__PURE__ */ new Set([
150062
150693
  var writeClientIdentity;
150063
150694
  var installDiscoverHandler;
150064
150695
  var readServerIdentity;
150696
+ function installModernOnlyHandlers(server, servedModernVersions) {
150697
+ installDiscoverHandler(server, servedModernVersions);
150698
+ }
150699
+ function serverIdentityOf(server) {
150700
+ return readServerIdentity(server);
150701
+ }
150065
150702
  var Server = class extends Protocol {
150066
150703
  _clientCapabilities;
150067
150704
  _clientVersion;
@@ -150673,6 +151310,579 @@ var Server = class extends Protocol {
150673
151310
  function discoverAdvertisedCapabilities(capabilities) {
150674
151311
  return { ...capabilities };
150675
151312
  }
151313
+ var McpServer = class {
151314
+ /**
151315
+ * The underlying {@linkcode Server} instance, useful for advanced operations like sending notifications.
151316
+ */
151317
+ server;
151318
+ _registeredResources = {};
151319
+ _registeredResourceTemplates = {};
151320
+ _registeredTools = {};
151321
+ _registeredPrompts = {};
151322
+ /**
151323
+ * Per-tool JSON-converted `inputSchema`, memoized so the SEP-2243
151324
+ * registration-time scan and the pre-dispatch validation step share one
151325
+ * conversion instead of paying it twice per request under the
151326
+ * per-request-factory `createMcpHandler` model.
151327
+ */
151328
+ _toolInputSchemaJson = {};
151329
+ /**
151330
+ * The JSON-serialized `inputSchema` of a registered tool, or `undefined`
151331
+ * when no such tool is registered. Used by the HTTP entry's pre-dispatch
151332
+ * SEP-2243 `Mcp-Param-*` validation step (which needs the same JSON Schema
151333
+ * `tools/list` would emit, before dispatch reaches the handler).
151334
+ *
151335
+ * @internal
151336
+ */
151337
+ toolInputSchemaJson(name) {
151338
+ const tool = this._registeredTools[name];
151339
+ if (tool === void 0 || !tool.enabled) return void 0;
151340
+ if (Object.hasOwn(this._toolInputSchemaJson, name)) return this._toolInputSchemaJson[name];
151341
+ if (tool.inputSchema === void 0) return EMPTY_OBJECT_JSON_SCHEMA;
151342
+ try {
151343
+ const json = standardSchemaToJsonSchema(tool.inputSchema, "input");
151344
+ this._toolInputSchemaJson[name] = json;
151345
+ return json;
151346
+ } catch {
151347
+ return;
151348
+ }
151349
+ }
151350
+ constructor(serverInfo, options) {
151351
+ this.server = new Server(serverInfo, options);
151352
+ if (options?.capabilities?.tools) this.setToolRequestHandlers();
151353
+ if (options?.capabilities?.resources) this.setResourceRequestHandlers();
151354
+ if (options?.capabilities?.prompts) this.setPromptRequestHandlers();
151355
+ }
151356
+ /**
151357
+ * Attaches to the given transport, starts it, and starts listening for messages.
151358
+ *
151359
+ * The `server` object assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward.
151360
+ *
151361
+ * @example
151362
+ * ```ts source="./mcp.examples.ts#McpServer_connect_stdio"
151363
+ * const server = new McpServer({ name: 'my-server', version: '1.0.0' });
151364
+ * const transport = new StdioServerTransport();
151365
+ * await server.connect(transport);
151366
+ * ```
151367
+ */
151368
+ async connect(transport) {
151369
+ return await this.server.connect(transport);
151370
+ }
151371
+ /**
151372
+ * Closes the connection.
151373
+ */
151374
+ async close() {
151375
+ await this.server.close();
151376
+ }
151377
+ _toolHandlersInitialized = false;
151378
+ setToolRequestHandlers() {
151379
+ if (this._toolHandlersInitialized) return;
151380
+ this.server.assertCanSetRequestHandler("tools/list");
151381
+ this.server.assertCanSetRequestHandler("tools/call");
151382
+ this.server.registerCapabilities({ tools: { listChanged: this.server.getCapabilities().tools?.listChanged ?? true } });
151383
+ this.server.setRequestHandler("tools/list", () => ({ tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => {
151384
+ const toolDefinition = {
151385
+ name,
151386
+ title: tool.title,
151387
+ description: tool.description,
151388
+ inputSchema: tool.inputSchema ? standardSchemaToJsonSchema(tool.inputSchema, "input") : EMPTY_OBJECT_JSON_SCHEMA,
151389
+ annotations: tool.annotations,
151390
+ icons: tool.icons,
151391
+ execution: tool.execution,
151392
+ _meta: tool._meta
151393
+ };
151394
+ if (tool.outputSchema) toolDefinition.outputSchema = standardSchemaToJsonSchema(tool.outputSchema, "output");
151395
+ return toolDefinition;
151396
+ }) }));
151397
+ this.server.setRequestHandler("tools/call", async (request, ctx) => {
151398
+ const tool = this._registeredTools[request.params.name];
151399
+ if (!tool) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} not found`);
151400
+ if (!tool.enabled) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} disabled`);
151401
+ try {
151402
+ const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);
151403
+ const result = await this.executeToolHandler(tool, args, ctx);
151404
+ await this.validateToolOutput(tool, result, request.params.name);
151405
+ if (isInputRequiredResult(result)) return result;
151406
+ return this.server.projectCallToolResult(result, tool.outputSchemaJson);
151407
+ } catch (error3) {
151408
+ if (error3 instanceof ProtocolError && error3.code === ProtocolErrorCode.UrlElicitationRequired) throw error3;
151409
+ return this.createToolError(error3 instanceof Error ? error3.message : String(error3));
151410
+ }
151411
+ });
151412
+ this._toolHandlersInitialized = true;
151413
+ }
151414
+ /**
151415
+ * Creates a tool error result.
151416
+ *
151417
+ * @param errorMessage - The error message.
151418
+ * @returns The tool error result.
151419
+ */
151420
+ createToolError(errorMessage) {
151421
+ return {
151422
+ content: [{
151423
+ type: "text",
151424
+ text: errorMessage
151425
+ }],
151426
+ isError: true
151427
+ };
151428
+ }
151429
+ /**
151430
+ * Validates tool input arguments against the tool's input schema.
151431
+ */
151432
+ async validateToolInput(tool, args, toolName) {
151433
+ if (!tool.inputSchema) return;
151434
+ const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {});
151435
+ if (!parseResult.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`);
151436
+ return parseResult.data;
151437
+ }
151438
+ /**
151439
+ * Validates tool output against the tool's output schema.
151440
+ */
151441
+ async validateToolOutput(tool, result, toolName) {
151442
+ if (!tool.outputSchema) return;
151443
+ if (isInputRequiredResult(result)) return;
151444
+ if (result.isError) return;
151445
+ if (result.structuredContent === void 0) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);
151446
+ const parseResult = await validateStandardSchema(tool.outputSchema, result.structuredContent);
151447
+ if (!parseResult.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`);
151448
+ }
151449
+ /**
151450
+ * Executes a tool handler.
151451
+ */
151452
+ async executeToolHandler(tool, args, ctx) {
151453
+ return tool.executor(args, ctx);
151454
+ }
151455
+ _completionHandlerInitialized = false;
151456
+ setCompletionRequestHandler() {
151457
+ if (this._completionHandlerInitialized) return;
151458
+ this.server.assertCanSetRequestHandler("completion/complete");
151459
+ this.server.registerCapabilities({ completions: {} });
151460
+ this.server.setRequestHandler("completion/complete", async (request) => {
151461
+ switch (request.params.ref.type) {
151462
+ case "ref/prompt":
151463
+ assertCompleteRequestPrompt(request);
151464
+ return this.handlePromptCompletion(request, request.params.ref);
151465
+ case "ref/resource":
151466
+ assertCompleteRequestResourceTemplate(request);
151467
+ return this.handleResourceCompletion(request, request.params.ref);
151468
+ default:
151469
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`);
151470
+ }
151471
+ });
151472
+ this._completionHandlerInitialized = true;
151473
+ }
151474
+ async handlePromptCompletion(request, ref) {
151475
+ const prompt = this._registeredPrompts[ref.name];
151476
+ if (!prompt) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} not found`);
151477
+ if (!prompt.enabled) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} disabled`);
151478
+ if (!prompt.argsSchema) return EMPTY_COMPLETION_RESULT;
151479
+ const field = unwrapOptionalSchema(getSchemaShape(prompt.argsSchema)?.[request.params.argument.name]);
151480
+ if (!isCompletable(field)) return EMPTY_COMPLETION_RESULT;
151481
+ const completer = getCompleter(field);
151482
+ if (!completer) return EMPTY_COMPLETION_RESULT;
151483
+ return createCompletionResult(await completer(request.params.argument.value, request.params.context));
151484
+ }
151485
+ async handleResourceCompletion(request, ref) {
151486
+ const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri);
151487
+ if (!template) {
151488
+ if (this._registeredResources[ref.uri]) return EMPTY_COMPLETION_RESULT;
151489
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`);
151490
+ }
151491
+ const completer = template.resourceTemplate.completeCallback(request.params.argument.name);
151492
+ if (!completer) return EMPTY_COMPLETION_RESULT;
151493
+ return createCompletionResult(await completer(request.params.argument.value, request.params.context));
151494
+ }
151495
+ _resourceHandlersInitialized = false;
151496
+ setResourceRequestHandlers() {
151497
+ if (this._resourceHandlersInitialized) return;
151498
+ this.server.assertCanSetRequestHandler("resources/list");
151499
+ this.server.assertCanSetRequestHandler("resources/templates/list");
151500
+ this.server.assertCanSetRequestHandler("resources/read");
151501
+ this.server.registerCapabilities({ resources: { listChanged: this.server.getCapabilities().resources?.listChanged ?? true } });
151502
+ this.server.setRequestHandler("resources/list", async (_request, ctx) => {
151503
+ const resources = Object.entries(this._registeredResources).filter(([_, resource2]) => resource2.enabled).map(([uri, resource2]) => ({
151504
+ uri,
151505
+ name: resource2.name,
151506
+ ...resource2.metadata
151507
+ }));
151508
+ const templateResources = [];
151509
+ for (const template of Object.values(this._registeredResourceTemplates)) {
151510
+ if (!template.resourceTemplate.listCallback) continue;
151511
+ const result = await template.resourceTemplate.listCallback(ctx);
151512
+ for (const resource2 of result.resources) templateResources.push({
151513
+ ...template.metadata,
151514
+ ...resource2
151515
+ });
151516
+ }
151517
+ return { resources: [...resources, ...templateResources] };
151518
+ });
151519
+ this.server.setRequestHandler("resources/templates/list", async () => {
151520
+ return { resourceTemplates: Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({
151521
+ name,
151522
+ uriTemplate: template.resourceTemplate.uriTemplate.toString(),
151523
+ ...template.metadata
151524
+ })) };
151525
+ });
151526
+ this.server.setRequestHandler("resources/read", async (request, ctx) => {
151527
+ let uri;
151528
+ try {
151529
+ uri = new URL(request.params.uri);
151530
+ } catch {
151531
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Resource URI ${request.params.uri} is invalid`, {
151532
+ uri: request.params.uri,
151533
+ reason: "invalid_uri"
151534
+ });
151535
+ }
151536
+ const resource2 = this._registeredResources[uri.toString()];
151537
+ if (resource2) {
151538
+ if (!resource2.enabled) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Resource ${uri} disabled`);
151539
+ return attachCacheHintFallback(await resource2.readCallback(uri, ctx), resource2.cacheHint);
151540
+ }
151541
+ for (const template of Object.values(this._registeredResourceTemplates)) {
151542
+ const variables = template.resourceTemplate.uriTemplate.match(uri.toString());
151543
+ if (variables) return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint);
151544
+ }
151545
+ throw new ResourceNotFoundError(request.params.uri);
151546
+ });
151547
+ this._resourceHandlersInitialized = true;
151548
+ }
151549
+ _promptHandlersInitialized = false;
151550
+ setPromptRequestHandlers() {
151551
+ if (this._promptHandlersInitialized) return;
151552
+ this.server.assertCanSetRequestHandler("prompts/list");
151553
+ this.server.assertCanSetRequestHandler("prompts/get");
151554
+ this.server.registerCapabilities({ prompts: { listChanged: this.server.getCapabilities().prompts?.listChanged ?? true } });
151555
+ this.server.setRequestHandler("prompts/list", () => ({ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => {
151556
+ return {
151557
+ name,
151558
+ title: prompt.title,
151559
+ description: prompt.description,
151560
+ arguments: prompt.argsSchema ? promptArgumentsFromStandardSchema(prompt.argsSchema) : void 0,
151561
+ icons: prompt.icons,
151562
+ _meta: prompt._meta
151563
+ };
151564
+ }) }));
151565
+ this.server.setRequestHandler("prompts/get", async (request, ctx) => {
151566
+ const prompt = this._registeredPrompts[request.params.name];
151567
+ if (!prompt) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} not found`);
151568
+ if (!prompt.enabled) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`);
151569
+ return prompt.handler(request.params.arguments, ctx);
151570
+ });
151571
+ this._promptHandlersInitialized = true;
151572
+ }
151573
+ registerResource(name, uriOrTemplate, config3, readCallback) {
151574
+ const cacheHint = config3.cacheHint;
151575
+ let metadata = config3;
151576
+ if (cacheHint !== void 0) {
151577
+ assertValidCacheHint(cacheHint, `resource ${name}`);
151578
+ const rest = { ...config3 };
151579
+ delete rest.cacheHint;
151580
+ metadata = rest;
151581
+ }
151582
+ if (typeof uriOrTemplate === "string") {
151583
+ if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`);
151584
+ const registeredResource = this._createRegisteredResource(name, config3.title, uriOrTemplate, metadata, readCallback);
151585
+ if (cacheHint !== void 0) registeredResource.cacheHint = cacheHint;
151586
+ this.setResourceRequestHandlers();
151587
+ this.sendResourceListChanged();
151588
+ return registeredResource;
151589
+ } else {
151590
+ if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`);
151591
+ const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config3.title, uriOrTemplate, metadata, readCallback);
151592
+ if (cacheHint !== void 0) registeredResourceTemplate.cacheHint = cacheHint;
151593
+ this.setResourceRequestHandlers();
151594
+ this.sendResourceListChanged();
151595
+ return registeredResourceTemplate;
151596
+ }
151597
+ }
151598
+ _createRegisteredResource(name, title, uri, metadata, readCallback) {
151599
+ const registeredResource = {
151600
+ name,
151601
+ title,
151602
+ metadata,
151603
+ readCallback,
151604
+ enabled: true,
151605
+ disable: () => registeredResource.update({ enabled: false }),
151606
+ enable: () => registeredResource.update({ enabled: true }),
151607
+ remove: () => registeredResource.update({ uri: null }),
151608
+ update: (updates) => {
151609
+ if (updates.uri !== void 0 && updates.uri !== uri) {
151610
+ delete this._registeredResources[uri];
151611
+ if (updates.uri) this._registeredResources[updates.uri] = registeredResource;
151612
+ }
151613
+ if (updates.name !== void 0) registeredResource.name = updates.name;
151614
+ if (updates.title !== void 0) registeredResource.title = updates.title;
151615
+ if (updates.metadata !== void 0) registeredResource.metadata = updates.metadata;
151616
+ if (updates.callback !== void 0) registeredResource.readCallback = updates.callback;
151617
+ if (updates.enabled !== void 0) registeredResource.enabled = updates.enabled;
151618
+ this.sendResourceListChanged();
151619
+ }
151620
+ };
151621
+ this._registeredResources[uri] = registeredResource;
151622
+ return registeredResource;
151623
+ }
151624
+ _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) {
151625
+ const registeredResourceTemplate = {
151626
+ resourceTemplate: template,
151627
+ title,
151628
+ metadata,
151629
+ readCallback,
151630
+ enabled: true,
151631
+ disable: () => registeredResourceTemplate.update({ enabled: false }),
151632
+ enable: () => registeredResourceTemplate.update({ enabled: true }),
151633
+ remove: () => registeredResourceTemplate.update({ name: null }),
151634
+ update: (updates) => {
151635
+ if (updates.name !== void 0 && updates.name !== name) {
151636
+ delete this._registeredResourceTemplates[name];
151637
+ if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate;
151638
+ }
151639
+ if (updates.title !== void 0) registeredResourceTemplate.title = updates.title;
151640
+ if (updates.template !== void 0) registeredResourceTemplate.resourceTemplate = updates.template;
151641
+ if (updates.metadata !== void 0) registeredResourceTemplate.metadata = updates.metadata;
151642
+ if (updates.callback !== void 0) registeredResourceTemplate.readCallback = updates.callback;
151643
+ if (updates.enabled !== void 0) registeredResourceTemplate.enabled = updates.enabled;
151644
+ this.sendResourceListChanged();
151645
+ }
151646
+ };
151647
+ this._registeredResourceTemplates[name] = registeredResourceTemplate;
151648
+ const variableNames = template.uriTemplate.variableNames;
151649
+ if (Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v))) this.setCompletionRequestHandler();
151650
+ return registeredResourceTemplate;
151651
+ }
151652
+ _createRegisteredPrompt(name, title, description8, argsSchema, callback, icons, _meta) {
151653
+ let currentArgsSchema = argsSchema;
151654
+ let currentCallback = callback;
151655
+ const registeredPrompt = {
151656
+ title,
151657
+ description: description8,
151658
+ argsSchema,
151659
+ icons,
151660
+ _meta,
151661
+ handler: createPromptHandler(name, argsSchema, callback),
151662
+ enabled: true,
151663
+ disable: () => registeredPrompt.update({ enabled: false }),
151664
+ enable: () => registeredPrompt.update({ enabled: true }),
151665
+ remove: () => registeredPrompt.update({ name: null }),
151666
+ update: (updates) => {
151667
+ if (updates.name !== void 0 && updates.name !== name) {
151668
+ delete this._registeredPrompts[name];
151669
+ if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt;
151670
+ }
151671
+ if (updates.title !== void 0) registeredPrompt.title = updates.title;
151672
+ if (updates.description !== void 0) registeredPrompt.description = updates.description;
151673
+ if (updates.icons !== void 0) registeredPrompt.icons = updates.icons;
151674
+ if (updates._meta !== void 0) registeredPrompt._meta = updates._meta;
151675
+ let needsHandlerRegen = false;
151676
+ if (updates.argsSchema !== void 0) {
151677
+ registeredPrompt.argsSchema = updates.argsSchema;
151678
+ currentArgsSchema = updates.argsSchema;
151679
+ needsHandlerRegen = true;
151680
+ }
151681
+ if (updates.callback !== void 0) {
151682
+ currentCallback = updates.callback;
151683
+ needsHandlerRegen = true;
151684
+ }
151685
+ if (needsHandlerRegen) registeredPrompt.handler = createPromptHandler(name, currentArgsSchema, currentCallback);
151686
+ if (updates.enabled !== void 0) registeredPrompt.enabled = updates.enabled;
151687
+ this.sendPromptListChanged();
151688
+ }
151689
+ };
151690
+ this._registeredPrompts[name] = registeredPrompt;
151691
+ if (argsSchema) {
151692
+ const shape = getSchemaShape(argsSchema);
151693
+ if (shape) {
151694
+ if (Object.values(shape).some((field) => {
151695
+ return isCompletable(unwrapOptionalSchema(field));
151696
+ })) this.setCompletionRequestHandler();
151697
+ }
151698
+ }
151699
+ return registeredPrompt;
151700
+ }
151701
+ _createRegisteredTool(name, title, description8, inputSchema9, outputSchema9, annotations, icons, execution, _meta, handler) {
151702
+ validateAndWarnToolName(name);
151703
+ if (inputSchema9 !== void 0) try {
151704
+ const json = standardSchemaToJsonSchema(inputSchema9, "input");
151705
+ this._toolInputSchemaJson[name] = json;
151706
+ const scan = scanXMcpHeaderDeclarations(json);
151707
+ if (!scan.valid) console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`);
151708
+ } catch {
151709
+ }
151710
+ let currentHandler = handler;
151711
+ const registeredTool = {
151712
+ title,
151713
+ description: description8,
151714
+ inputSchema: inputSchema9,
151715
+ outputSchema: outputSchema9,
151716
+ outputSchemaJson: convertOutputSchemaJson(outputSchema9),
151717
+ annotations,
151718
+ icons,
151719
+ execution,
151720
+ _meta,
151721
+ handler,
151722
+ executor: createToolExecutor(inputSchema9, handler),
151723
+ enabled: true,
151724
+ disable: () => registeredTool.update({ enabled: false }),
151725
+ enable: () => registeredTool.update({ enabled: true }),
151726
+ remove: () => registeredTool.update({ name: null }),
151727
+ update: (updates) => {
151728
+ if (updates.name !== void 0 && updates.name !== name) {
151729
+ if (typeof updates.name === "string") validateAndWarnToolName(updates.name);
151730
+ delete this._registeredTools[name];
151731
+ delete this._toolInputSchemaJson[name];
151732
+ if (updates.name) {
151733
+ delete this._toolInputSchemaJson[updates.name];
151734
+ this._registeredTools[updates.name] = registeredTool;
151735
+ name = updates.name;
151736
+ }
151737
+ }
151738
+ if (updates.title !== void 0) registeredTool.title = updates.title;
151739
+ if (updates.description !== void 0) registeredTool.description = updates.description;
151740
+ let needsExecutorRegen = false;
151741
+ if (updates.paramsSchema !== void 0) {
151742
+ registeredTool.inputSchema = updates.paramsSchema;
151743
+ delete this._toolInputSchemaJson[name];
151744
+ needsExecutorRegen = true;
151745
+ }
151746
+ if (updates.callback !== void 0) {
151747
+ registeredTool.handler = updates.callback;
151748
+ currentHandler = updates.callback;
151749
+ needsExecutorRegen = true;
151750
+ }
151751
+ if (needsExecutorRegen) registeredTool.executor = createToolExecutor(registeredTool.inputSchema, currentHandler);
151752
+ if (updates.outputSchema !== void 0) {
151753
+ registeredTool.outputSchema = updates.outputSchema;
151754
+ registeredTool.outputSchemaJson = convertOutputSchemaJson(updates.outputSchema);
151755
+ }
151756
+ if (updates.annotations !== void 0) registeredTool.annotations = updates.annotations;
151757
+ if (updates.icons !== void 0) registeredTool.icons = updates.icons;
151758
+ if (updates._meta !== void 0) registeredTool._meta = updates._meta;
151759
+ if (updates.enabled !== void 0) registeredTool.enabled = updates.enabled;
151760
+ this.sendToolListChanged();
151761
+ }
151762
+ };
151763
+ this._registeredTools[name] = registeredTool;
151764
+ this.setToolRequestHandlers();
151765
+ this.sendToolListChanged();
151766
+ return registeredTool;
151767
+ }
151768
+ registerTool(name, config3, cb) {
151769
+ if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`);
151770
+ const { title, description: description8, inputSchema: inputSchema9, outputSchema: outputSchema9, annotations, icons, _meta } = config3;
151771
+ return this._createRegisteredTool(name, title, description8, normalizeRawShapeSchema(inputSchema9), normalizeRawShapeSchema(outputSchema9), annotations, icons, void 0, _meta, cb);
151772
+ }
151773
+ registerPrompt(name, config3, cb) {
151774
+ if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`);
151775
+ const { title, description: description8, argsSchema, icons, _meta } = config3;
151776
+ const registeredPrompt = this._createRegisteredPrompt(name, title, description8, normalizeRawShapeSchema(argsSchema), cb, icons, _meta);
151777
+ this.setPromptRequestHandlers();
151778
+ this.sendPromptListChanged();
151779
+ return registeredPrompt;
151780
+ }
151781
+ /**
151782
+ * Checks if the server is connected to a transport.
151783
+ * @returns `true` if the server is connected
151784
+ */
151785
+ isConnected() {
151786
+ return this.server.transport !== void 0;
151787
+ }
151788
+ /**
151789
+ * Sends a logging message to the client, if connected.
151790
+ * Note: You only need to send the parameters object, not the entire JSON-RPC message.
151791
+ * @see {@linkcode LoggingMessageNotification}
151792
+ * @param params
151793
+ * @param sessionId Optional for stateless transports and backward compatibility.
151794
+ *
151795
+ * @example
151796
+ * ```ts source="./mcp.examples.ts#McpServer_sendLoggingMessage_basic"
151797
+ * await server.sendLoggingMessage({
151798
+ * level: 'info',
151799
+ * data: 'Processing complete'
151800
+ * });
151801
+ * ```
151802
+ *
151803
+ * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).
151804
+ * Remains functional during the deprecation window (at least twelve months).
151805
+ * Migrate to stderr logging (STDIO servers) or OpenTelemetry.
151806
+ */
151807
+ async sendLoggingMessage(params, sessionId) {
151808
+ return this.server.sendLoggingMessage(params, sessionId);
151809
+ }
151810
+ /**
151811
+ * Sends a resource list changed event to the client, if connected.
151812
+ */
151813
+ sendResourceListChanged() {
151814
+ if (this.isConnected()) this.server.sendResourceListChanged();
151815
+ }
151816
+ /**
151817
+ * Sends a tool list changed event to the client, if connected.
151818
+ */
151819
+ sendToolListChanged() {
151820
+ if (this.isConnected()) this.server.sendToolListChanged();
151821
+ }
151822
+ /**
151823
+ * Sends a prompt list changed event to the client, if connected.
151824
+ */
151825
+ sendPromptListChanged() {
151826
+ if (this.isConnected()) this.server.sendPromptListChanged();
151827
+ }
151828
+ };
151829
+ function createToolExecutor(inputSchema9, handler) {
151830
+ if (inputSchema9) {
151831
+ const callback$1 = handler;
151832
+ return async (args, ctx) => callback$1(args, ctx);
151833
+ }
151834
+ const callback = handler;
151835
+ return async (_args, ctx) => callback(ctx);
151836
+ }
151837
+ var EMPTY_OBJECT_JSON_SCHEMA = {
151838
+ type: "object",
151839
+ properties: {}
151840
+ };
151841
+ function convertOutputSchemaJson(outputSchema9) {
151842
+ if (outputSchema9 === void 0) return void 0;
151843
+ try {
151844
+ return standardSchemaToJsonSchema(outputSchema9, "output");
151845
+ } catch {
151846
+ return;
151847
+ }
151848
+ }
151849
+ function createPromptHandler(name, argsSchema, callback) {
151850
+ if (argsSchema) {
151851
+ const typedCallback = callback;
151852
+ return async (args, ctx) => {
151853
+ const parseResult = await validateStandardSchema(argsSchema, args);
151854
+ if (!parseResult.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid arguments for prompt ${name}: ${parseResult.error}`);
151855
+ return typedCallback(parseResult.data, ctx);
151856
+ };
151857
+ } else {
151858
+ const typedCallback = callback;
151859
+ return async (_args, ctx) => {
151860
+ return typedCallback(ctx);
151861
+ };
151862
+ }
151863
+ }
151864
+ function createCompletionResult(suggestions) {
151865
+ return { completion: {
151866
+ values: suggestions.map(String).slice(0, 100),
151867
+ total: suggestions.length,
151868
+ hasMore: suggestions.length > 100
151869
+ } };
151870
+ }
151871
+ var EMPTY_COMPLETION_RESULT = { completion: {
151872
+ values: [],
151873
+ hasMore: false
151874
+ } };
151875
+ function getSchemaShape(schema2) {
151876
+ const candidate = schema2;
151877
+ if (candidate.shape && typeof candidate.shape === "object") return candidate.shape;
151878
+ }
151879
+ function isOptionalSchema(schema2) {
151880
+ return schema2?.type === "optional";
151881
+ }
151882
+ function unwrapOptionalSchema(schema2) {
151883
+ if (!isOptionalSchema(schema2)) return schema2;
151884
+ return schema2.def?.innerType ?? schema2;
151885
+ }
150676
151886
 
150677
151887
  // ../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/stdio.mjs
150678
151888
  var StdioServerTransport = class {
@@ -150763,6 +151973,400 @@ var StdioServerTransport = class {
150763
151973
  });
150764
151974
  }
150765
151975
  };
151976
+ var DISCARD_ANSWER_TIMEOUT_MS = 3e3;
151977
+ var StdioConnectionChannel = class {
151978
+ onclose;
151979
+ onerror;
151980
+ onmessage;
151981
+ _closed = false;
151982
+ /** Request ids the entry delivered to the instance that the instance has not yet answered. */
151983
+ _pendingRequests = /* @__PURE__ */ new Set();
151984
+ _drainWaiters = [];
151985
+ constructor(_wire, _onInstanceClose, _outboundIntercept) {
151986
+ this._wire = _wire;
151987
+ this._onInstanceClose = _onInstanceClose;
151988
+ this._outboundIntercept = _outboundIntercept;
151989
+ }
151990
+ async start() {
151991
+ }
151992
+ async send(message, options) {
151993
+ if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
151994
+ const { id } = message;
151995
+ if (id !== void 0) this._settle(id);
151996
+ }
151997
+ if (this._closed) return;
151998
+ if (this._outboundIntercept?.(message) === "handled") return;
151999
+ return this._wire.send(message, options);
152000
+ }
152001
+ setProtocolVersion = (version4) => {
152002
+ this._wire.setProtocolVersion?.(version4);
152003
+ };
152004
+ /** Forwards one inbound message to the connected instance. */
152005
+ deliver(message, extra) {
152006
+ if (this._closed) return;
152007
+ if (isJSONRPCRequest(message)) this._pendingRequests.add(message.id);
152008
+ else if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") {
152009
+ const cancelledId = message.params?.requestId;
152010
+ if (cancelledId !== void 0) this._settle(cancelledId);
152011
+ }
152012
+ this.onmessage?.(message, extra);
152013
+ }
152014
+ /**
152015
+ * Resolves once every request delivered to the instance has been answered
152016
+ * through {@linkcode send}, settled by a delivered cancellation, or the
152017
+ * channel has been closed and nothing further can be answered. The wait is
152018
+ * bounded by `timeoutMs` as a backstop so no edge can hold the caller
152019
+ * indefinitely; resolves `false` only when the bound elapsed with requests
152020
+ * still unanswered. Used by the probe-discard path so a probe request the
152021
+ * entry accepted is never silently dropped.
152022
+ */
152023
+ async whenRequestsAnswered(timeoutMs) {
152024
+ if (this._closed || this._pendingRequests.size === 0) return true;
152025
+ return await new Promise((resolve2) => {
152026
+ const waiter = () => {
152027
+ clearTimeout(timer);
152028
+ resolve2(true);
152029
+ };
152030
+ const timer = setTimeout(() => {
152031
+ this._drainWaiters = this._drainWaiters.filter((pending) => pending !== waiter);
152032
+ resolve2(false);
152033
+ }, timeoutMs);
152034
+ this._drainWaiters.push(waiter);
152035
+ });
152036
+ }
152037
+ async close() {
152038
+ if (this._closed) return;
152039
+ this._closed = true;
152040
+ this._pendingRequests.clear();
152041
+ this._releaseDrainWaiters();
152042
+ try {
152043
+ this._onInstanceClose();
152044
+ } finally {
152045
+ this.onclose?.();
152046
+ }
152047
+ }
152048
+ _settle(id) {
152049
+ this._pendingRequests.delete(id);
152050
+ if (this._pendingRequests.size === 0) this._releaseDrainWaiters();
152051
+ }
152052
+ _releaseDrainWaiters() {
152053
+ const waiters = this._drainWaiters;
152054
+ this._drainWaiters = [];
152055
+ for (const waiter of waiters) waiter();
152056
+ }
152057
+ };
152058
+ function classifyOpeningMessage(message) {
152059
+ const params = message.params;
152060
+ if (message.method === "initialize" && !carriesValidModernEnvelopeClaim(params)) {
152061
+ const requestedVersion = params !== null && typeof params === "object" && typeof params.protocolVersion === "string" ? params.protocolVersion : void 0;
152062
+ return {
152063
+ kind: "legacy",
152064
+ reason: "initialize",
152065
+ ...requestedVersion !== void 0 && { requestedVersion }
152066
+ };
152067
+ }
152068
+ if (!hasEnvelopeClaim(params)) return {
152069
+ kind: "legacy",
152070
+ reason: "no-claim"
152071
+ };
152072
+ const meta2 = requestMetaOf(params);
152073
+ const firstIssue = (meta2 === void 0 ? [] : validateEnvelopeMeta(meta2))[0];
152074
+ if (firstIssue !== void 0) return {
152075
+ kind: "invalid-envelope",
152076
+ issue: firstIssue
152077
+ };
152078
+ const claimedVersion = envelopeClaimVersion(params);
152079
+ if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) return {
152080
+ kind: "unsupported-revision",
152081
+ requested: claimedVersion ?? "unknown"
152082
+ };
152083
+ return {
152084
+ kind: "modern",
152085
+ revision: claimedVersion,
152086
+ classification: {
152087
+ era: "modern",
152088
+ revision: claimedVersion
152089
+ }
152090
+ };
152091
+ }
152092
+ function serveStdio(factory, options = {}) {
152093
+ const legacyMode = options.legacy ?? "serve";
152094
+ const wire = options.transport ?? new StdioServerTransport();
152095
+ let state = { phase: "opening" };
152096
+ let discarding;
152097
+ let closing = false;
152098
+ const isTornDown = () => closing || state.phase === "closed";
152099
+ const reportError = (error3) => {
152100
+ try {
152101
+ options.onerror?.(error3);
152102
+ } catch {
152103
+ }
152104
+ };
152105
+ const writeErrorResponse = (id, code2, message, data2) => wire.send({
152106
+ jsonrpc: "2.0",
152107
+ id,
152108
+ error: {
152109
+ code: code2,
152110
+ message,
152111
+ ...data2 !== void 0 && { data: data2 }
152112
+ }
152113
+ }).catch((error3) => reportError(toError(error3)));
152114
+ const listenRouter = new StdioListenRouter(options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS);
152115
+ const modernOutboundIntercept = (message) => {
152116
+ if (!isJSONRPCNotification(message)) return void 0;
152117
+ const routed = listenRouter.routeOutbound(message);
152118
+ if (routed === "passthrough") return void 0;
152119
+ for (const stamped of routed) wire.send({
152120
+ jsonrpc: "2.0",
152121
+ ...stamped
152122
+ }).catch((error3) => reportError(toError(error3)));
152123
+ return "handled";
152124
+ };
152125
+ const tryServeListen = async (message) => {
152126
+ if (isJSONRPCRequest(message) && message.method === "subscriptions/listen") {
152127
+ const meta2 = requestMetaOf(message.params);
152128
+ const issue2 = hasEnvelopeClaim(message.params) ? (meta2 === void 0 ? [] : validateEnvelopeMeta(meta2))[0] : {
152129
+ key: "_meta",
152130
+ problem: "the per-request envelope is required on protocol revision 2026-07-28"
152131
+ };
152132
+ const claimedVersion = envelopeClaimVersion(message.params);
152133
+ let reply;
152134
+ if (issue2 !== void 0) reply = {
152135
+ jsonrpc: "2.0",
152136
+ id: message.id,
152137
+ error: {
152138
+ code: -32602,
152139
+ message: `Invalid _meta envelope: ${issue2.key}: ${issue2.problem}`
152140
+ }
152141
+ };
152142
+ else if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) {
152143
+ const error3 = new UnsupportedProtocolVersionError({
152144
+ supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS],
152145
+ requested: claimedVersion ?? "unknown"
152146
+ });
152147
+ reply = {
152148
+ jsonrpc: "2.0",
152149
+ id: message.id,
152150
+ error: {
152151
+ code: error3.code,
152152
+ message: error3.message,
152153
+ data: error3.data
152154
+ }
152155
+ };
152156
+ } else reply = listenRouter.serve(message);
152157
+ await wire.send("error" in reply ? reply : {
152158
+ jsonrpc: "2.0",
152159
+ method: reply.method,
152160
+ params: reply.params
152161
+ }).catch((error3) => reportError(toError(error3)));
152162
+ return true;
152163
+ }
152164
+ if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") {
152165
+ const cancelledId = message.params?.requestId;
152166
+ if (cancelledId !== void 0 && listenRouter.cancel(cancelledId)) return true;
152167
+ }
152168
+ return false;
152169
+ };
152170
+ const answerLegacyRejection = (request, reason, requestedVersion) => {
152171
+ const rejection2 = modernOnlyStrictRejection({
152172
+ kind: "legacy",
152173
+ reason,
152174
+ ...requestedVersion !== void 0 && { requestedVersion }
152175
+ }, SUPPORTED_MODERN_PROTOCOL_VERSIONS);
152176
+ if (rejection2 === void 0) return Promise.resolve();
152177
+ reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only stdio connection (${rejection2.cell}): ${rejection2.message}`));
152178
+ return writeErrorResponse(request.id, rejection2.code, rejection2.message, rejection2.data);
152179
+ };
152180
+ const onInstanceClosed = (channel) => {
152181
+ if (closing || channel === discarding) return;
152182
+ closeAll();
152183
+ };
152184
+ const connectInstance = async (era, revision) => {
152185
+ const product = await factory({ era });
152186
+ const server = product instanceof McpServer ? product.server : product;
152187
+ if (era === "modern") {
152188
+ setNegotiatedProtocolVersion(server, revision);
152189
+ installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS);
152190
+ listenRouter.setServerCapabilities(server.getCapabilities(), serverIdentityOf(server));
152191
+ }
152192
+ const channel = new StdioConnectionChannel(wire, () => onInstanceClosed(channel), era === "modern" ? modernOutboundIntercept : void 0);
152193
+ await product.connect(channel);
152194
+ return {
152195
+ product,
152196
+ channel
152197
+ };
152198
+ };
152199
+ const disposeLateInstance = (instance) => instance.product.close().catch((error3) => reportError(toError(error3)));
152200
+ const discardProbeInstance = async (instance) => {
152201
+ discarding = instance.channel;
152202
+ try {
152203
+ if (!await instance.channel.whenRequestsAnswered(DISCARD_ANSWER_TIMEOUT_MS)) reportError(/* @__PURE__ */ new Error(`Discarded the probe instance with requests still unanswered after ${DISCARD_ANSWER_TIMEOUT_MS}ms; continuing with the fallback`));
152204
+ await instance.product.close();
152205
+ } catch (error3) {
152206
+ reportError(toError(error3));
152207
+ } finally {
152208
+ discarding = void 0;
152209
+ }
152210
+ };
152211
+ const processMessage = async (message) => {
152212
+ if (state.phase === "closed") return;
152213
+ if (state.phase === "pinned") {
152214
+ if (state.era === "modern" && isJSONRPCRequest(message) && message.method === "initialize" && !carriesValidModernEnvelopeClaim(message.params)) {
152215
+ await answerLegacyRejection(message, "initialize", message.params !== null && typeof message.params === "object" && typeof message.params.protocolVersion === "string" ? message.params.protocolVersion : void 0);
152216
+ return;
152217
+ }
152218
+ if (state.era === "modern" && await tryServeListen(message)) return;
152219
+ state.instance.channel.deliver(message);
152220
+ return;
152221
+ }
152222
+ if (!isJSONRPCRequest(message) && !isJSONRPCNotification(message)) {
152223
+ reportError(/* @__PURE__ */ new Error("Discarded a JSON-RPC response received before the connection negotiated an era"));
152224
+ return;
152225
+ }
152226
+ const opening = classifyOpeningMessage(message);
152227
+ switch (opening.kind) {
152228
+ case "invalid-envelope": {
152229
+ const detail = `Invalid _meta envelope for protocol revision 2026-07-28: ${opening.issue.key}: ${opening.issue.problem}`;
152230
+ if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InvalidParams, detail, { envelope: opening.issue });
152231
+ else reportError(/* @__PURE__ */ new Error(`Discarded a notification with a malformed envelope: ${detail}`));
152232
+ return;
152233
+ }
152234
+ case "unsupported-revision":
152235
+ if (isJSONRPCRequest(message)) {
152236
+ const error3 = new UnsupportedProtocolVersionError({
152237
+ supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS],
152238
+ requested: opening.requested
152239
+ });
152240
+ reportError(error3);
152241
+ await writeErrorResponse(message.id, error3.code, error3.message, error3.data);
152242
+ } else reportError(/* @__PURE__ */ new Error(`Discarded a notification claiming unsupported protocol revision ${opening.requested}`));
152243
+ return;
152244
+ case "modern":
152245
+ if (isJSONRPCRequest(message) && message.method === "server/discover") {
152246
+ if (state.phase === "probe") {
152247
+ state.instance.channel.deliver(message, { classification: opening.classification });
152248
+ return;
152249
+ }
152250
+ const instance = await connectInstance("modern", opening.revision);
152251
+ if (isTornDown()) {
152252
+ await disposeLateInstance(instance);
152253
+ return;
152254
+ }
152255
+ state = {
152256
+ phase: "probe",
152257
+ instance
152258
+ };
152259
+ instance.channel.deliver(message, { classification: opening.classification });
152260
+ return;
152261
+ }
152262
+ if (state.phase === "probe") {
152263
+ if (isJSONRPCNotification(message)) {
152264
+ state.instance.channel.deliver(message, { classification: opening.classification });
152265
+ return;
152266
+ }
152267
+ state = {
152268
+ phase: "pinned",
152269
+ era: "modern",
152270
+ instance: state.instance
152271
+ };
152272
+ } else {
152273
+ const instance = await connectInstance("modern", opening.revision);
152274
+ if (isTornDown()) {
152275
+ await disposeLateInstance(instance);
152276
+ return;
152277
+ }
152278
+ state = {
152279
+ phase: "pinned",
152280
+ era: "modern",
152281
+ instance
152282
+ };
152283
+ }
152284
+ if (await tryServeListen(message)) return;
152285
+ state.instance.channel.deliver(message, { classification: opening.classification });
152286
+ return;
152287
+ case "legacy": {
152288
+ if (legacyMode === "reject") {
152289
+ if (isJSONRPCRequest(message)) await answerLegacyRejection(message, opening.reason, opening.requestedVersion);
152290
+ return;
152291
+ }
152292
+ if (state.phase === "probe") {
152293
+ await discardProbeInstance(state.instance);
152294
+ if (isTornDown()) return;
152295
+ state = { phase: "opening" };
152296
+ }
152297
+ const instance = await connectInstance("legacy");
152298
+ if (isTornDown()) {
152299
+ await disposeLateInstance(instance);
152300
+ return;
152301
+ }
152302
+ state = {
152303
+ phase: "pinned",
152304
+ era: "legacy",
152305
+ instance
152306
+ };
152307
+ state.instance.channel.deliver(message);
152308
+ return;
152309
+ }
152310
+ }
152311
+ };
152312
+ const queue = [];
152313
+ let pumping = false;
152314
+ const pump = async () => {
152315
+ if (pumping) return;
152316
+ pumping = true;
152317
+ try {
152318
+ while (queue.length > 0) {
152319
+ const message = queue.shift();
152320
+ try {
152321
+ await processMessage(message);
152322
+ } catch (error3) {
152323
+ if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InternalError, "Internal server error");
152324
+ reportError(toError(error3));
152325
+ }
152326
+ }
152327
+ } finally {
152328
+ pumping = false;
152329
+ }
152330
+ };
152331
+ const closeAll = async () => {
152332
+ if (closing || state.phase === "closed") return;
152333
+ closing = true;
152334
+ const current = state;
152335
+ state = { phase: "closed" };
152336
+ for (const result of listenRouter.teardownAll()) await wire.send(result).catch((error3) => reportError(toError(error3)));
152337
+ if (current.phase === "probe" || current.phase === "pinned") await current.instance.product.close().catch((error3) => reportError(toError(error3)));
152338
+ await wire.close().catch((error3) => reportError(toError(error3)));
152339
+ };
152340
+ wire.onmessage = (message) => {
152341
+ queue.push(message);
152342
+ pump();
152343
+ };
152344
+ wire.onerror = (error3) => {
152345
+ reportError(error3);
152346
+ if (state.phase === "probe" || state.phase === "pinned") state.instance.channel.onerror?.(error3);
152347
+ };
152348
+ wire.onclose = () => {
152349
+ if (closing || state.phase === "closed") return;
152350
+ closing = true;
152351
+ const current = state;
152352
+ state = { phase: "closed" };
152353
+ if (current.phase === "probe" || current.phase === "pinned") current.instance.product.close().catch((error3) => reportError(toError(error3)));
152354
+ };
152355
+ const started = wire.start().catch((error3) => {
152356
+ reportError(toError(error3));
152357
+ throw error3;
152358
+ });
152359
+ started.catch(() => {
152360
+ });
152361
+ return { close: async () => {
152362
+ await started.catch(() => {
152363
+ });
152364
+ await closeAll();
152365
+ } };
152366
+ }
152367
+ function toError(value) {
152368
+ return value instanceof Error ? value : new Error(String(value));
152369
+ }
150766
152370
 
150767
152371
  // src/cli/lib/mcp/requestContext.ts
150768
152372
  init_fs();
@@ -153159,11 +154763,7 @@ mcp.command("start").summary("Start the MCP server").description(
153159
154763
  ).addDeploymentSelectionOptions(actionDescription("Run the MCP server on")).action(async (options) => {
153160
154764
  const ctx = await oneoffContext(options);
153161
154765
  try {
153162
- const server = makeServer(options);
153163
- const transport = new StdioServerTransport();
153164
- await server.connect(transport);
153165
- await new Promise(() => {
153166
- });
154766
+ enabledTools(options);
153167
154767
  } catch (error3) {
153168
154768
  await ctx.crash({
153169
154769
  exitCode: 1,
@@ -153172,8 +154772,17 @@ mcp.command("start").summary("Start the MCP server").description(
153172
154772
  printedMessage: `Failed to start MCP server: ${error3}`
153173
154773
  });
153174
154774
  }
154775
+ serveStdio(() => makeServer(options), {
154776
+ legacy: "serve",
154777
+ // The only channel for out-of-band failures (transport errors, dropped
154778
+ // malformed notifications). stdout carries the protocol, so they go to
154779
+ // stderr.
154780
+ onerror: (error3) => logError(`MCP server error: ${error3.message}`)
154781
+ });
154782
+ await new Promise(() => {
154783
+ });
153175
154784
  });
153176
- function makeServer(options) {
154785
+ function enabledTools(options) {
153177
154786
  const disabledToolNames = /* @__PURE__ */ new Set();
153178
154787
  for (const toolName of options.disableTools?.split(",") ?? []) {
153179
154788
  const name = toolName.trim();
@@ -153190,6 +154799,10 @@ function makeServer(options) {
153190
154799
  enabledToolsByName[tool.name] = tool;
153191
154800
  }
153192
154801
  }
154802
+ return enabledToolsByName;
154803
+ }
154804
+ function makeServer(options) {
154805
+ const enabledToolsByName = enabledTools(options);
153193
154806
  const mutex = new Mutex();
153194
154807
  const server = new Server(
153195
154808
  {