@casys/mcp-server 0.26.0 → 0.27.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 (299) hide show
  1. package/CHANGELOG.md +1779 -0
  2. package/LICENSE +21 -0
  3. package/README.md +19 -5
  4. package/esm/_dnt.polyfills.d.ts +12 -0
  5. package/esm/_dnt.polyfills.d.ts.map +1 -0
  6. package/esm/_dnt.polyfills.js +15 -0
  7. package/esm/_dnt.shims.d.ts +2 -0
  8. package/esm/_dnt.shims.d.ts.map +1 -0
  9. package/esm/_dnt.shims.js +57 -0
  10. package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.d.ts +33 -0
  11. package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.d.ts.map +1 -0
  12. package/esm/deps/jsr.io/@std/yaml/1.2.0/_chars.js +48 -0
  13. package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.d.ts +106 -0
  14. package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.d.ts.map +1 -0
  15. package/esm/deps/jsr.io/@std/yaml/1.2.0/_dumper_state.js +636 -0
  16. package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.d.ts +67 -0
  17. package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.d.ts.map +1 -0
  18. package/esm/deps/jsr.io/@std/yaml/1.2.0/_loader_state.js +1393 -0
  19. package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.d.ts +44 -0
  20. package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.d.ts.map +1 -0
  21. package/esm/deps/jsr.io/@std/yaml/1.2.0/_schema.js +117 -0
  22. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.d.ts +3 -0
  23. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.d.ts.map +1 -0
  24. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/binary.js +103 -0
  25. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.d.ts +3 -0
  26. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.d.ts.map +1 -0
  27. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/bool.js +32 -0
  28. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.d.ts +3 -0
  29. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.d.ts.map +1 -0
  30. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/float.js +96 -0
  31. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.d.ts +3 -0
  32. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.d.ts.map +1 -0
  33. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/int.js +159 -0
  34. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.d.ts +3 -0
  35. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.d.ts.map +1 -0
  36. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/map.js +14 -0
  37. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.d.ts +3 -0
  38. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.d.ts.map +1 -0
  39. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/merge.js +10 -0
  40. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.d.ts +3 -0
  41. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.d.ts.map +1 -0
  42. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/nil.js +22 -0
  43. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.d.ts +3 -0
  44. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.d.ts.map +1 -0
  45. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/omap.js +29 -0
  46. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.d.ts +3 -0
  47. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.d.ts.map +1 -0
  48. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/pairs.js +19 -0
  49. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.d.ts +3 -0
  50. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.d.ts.map +1 -0
  51. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/regexp.js +30 -0
  52. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.d.ts +3 -0
  53. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.d.ts.map +1 -0
  54. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/seq.js +10 -0
  55. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.d.ts +3 -0
  56. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.d.ts.map +1 -0
  57. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/set.js +14 -0
  58. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.d.ts +3 -0
  59. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.d.ts.map +1 -0
  60. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/str.js +9 -0
  61. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.d.ts +3 -0
  62. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.d.ts.map +1 -0
  63. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/timestamp.js +81 -0
  64. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.d.ts +3 -0
  65. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.d.ts.map +1 -0
  66. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type/undefined.js +20 -0
  67. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.d.ts +32 -0
  68. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.d.ts.map +1 -0
  69. package/esm/deps/jsr.io/@std/yaml/1.2.0/_type.js +6 -0
  70. package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.d.ts +4 -0
  71. package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.d.ts.map +1 -0
  72. package/esm/deps/jsr.io/@std/yaml/1.2.0/_utils.js +13 -0
  73. package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.d.ts +51 -0
  74. package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.d.ts.map +1 -0
  75. package/esm/deps/jsr.io/@std/yaml/1.2.0/mod.js +53 -0
  76. package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.d.ts +79 -0
  77. package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.d.ts.map +1 -0
  78. package/esm/deps/jsr.io/@std/yaml/1.2.0/parse.js +91 -0
  79. package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.d.ts +100 -0
  80. package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.d.ts.map +1 -0
  81. package/esm/deps/jsr.io/@std/yaml/1.2.0/stringify.js +33 -0
  82. package/esm/deps/jsr.io/@std/yaml/1.2.0/types.d.ts +111 -0
  83. package/esm/deps/jsr.io/@std/yaml/1.2.0/types.d.ts.map +1 -0
  84. package/esm/deps/jsr.io/@std/yaml/1.2.0/types.js +104 -0
  85. package/esm/mod.d.ts +102 -0
  86. package/esm/mod.d.ts.map +1 -0
  87. package/esm/mod.js +103 -0
  88. package/esm/package.json +3 -0
  89. package/esm/src/auth/as-metadata-proxy.d.ts +112 -0
  90. package/esm/src/auth/as-metadata-proxy.d.ts.map +1 -0
  91. package/esm/src/auth/as-metadata-proxy.js +171 -0
  92. package/esm/src/auth/config.d.ts +117 -0
  93. package/esm/src/auth/config.d.ts.map +1 -0
  94. package/esm/src/auth/config.js +219 -0
  95. package/esm/src/auth/jwt-provider.d.ts +157 -0
  96. package/esm/src/auth/jwt-provider.d.ts.map +1 -0
  97. package/esm/src/auth/jwt-provider.js +187 -0
  98. package/esm/src/auth/middleware.d.ts +61 -0
  99. package/esm/src/auth/middleware.d.ts.map +1 -0
  100. package/esm/src/auth/middleware.js +209 -0
  101. package/esm/src/auth/mod.d.ts +23 -0
  102. package/esm/src/auth/mod.d.ts.map +1 -0
  103. package/esm/src/auth/mod.js +27 -0
  104. package/esm/src/auth/multi-tenant-middleware.d.ts +131 -0
  105. package/esm/src/auth/multi-tenant-middleware.d.ts.map +1 -0
  106. package/esm/src/auth/multi-tenant-middleware.js +128 -0
  107. package/esm/src/auth/presets.d.ts +231 -0
  108. package/esm/src/auth/presets.d.ts.map +1 -0
  109. package/esm/src/auth/presets.js +223 -0
  110. package/{src/auth/provider.ts → esm/src/auth/provider.d.ts} +13 -15
  111. package/esm/src/auth/provider.d.ts.map +1 -0
  112. package/esm/src/auth/provider.js +34 -0
  113. package/esm/src/auth/scope-middleware.d.ts +30 -0
  114. package/esm/src/auth/scope-middleware.d.ts.map +1 -0
  115. package/esm/src/auth/scope-middleware.js +48 -0
  116. package/esm/src/auth/static-token-provider.d.ts +155 -0
  117. package/esm/src/auth/static-token-provider.d.ts.map +1 -0
  118. package/esm/src/auth/static-token-provider.js +256 -0
  119. package/esm/src/auth/types.d.ts +151 -0
  120. package/esm/src/auth/types.d.ts.map +1 -0
  121. package/esm/src/auth/types.js +64 -0
  122. package/esm/src/client-auth/callback-server.d.ts +34 -0
  123. package/esm/src/client-auth/callback-server.d.ts.map +1 -0
  124. package/esm/src/client-auth/callback-server.js +141 -0
  125. package/esm/src/client-auth/client-id-metadata.d.ts +29 -0
  126. package/esm/src/client-auth/client-id-metadata.d.ts.map +1 -0
  127. package/esm/src/client-auth/client-id-metadata.js +149 -0
  128. package/esm/src/client-auth/connect.d.ts +32 -0
  129. package/esm/src/client-auth/connect.d.ts.map +1 -0
  130. package/esm/src/client-auth/connect.js +47 -0
  131. package/esm/src/client-auth/mod.d.ts +19 -0
  132. package/esm/src/client-auth/mod.d.ts.map +1 -0
  133. package/{src/client-auth/mod.ts → esm/src/client-auth/mod.js} +1 -26
  134. package/esm/src/client-auth/provider.d.ts +78 -0
  135. package/esm/src/client-auth/provider.d.ts.map +1 -0
  136. package/esm/src/client-auth/provider.js +246 -0
  137. package/esm/src/client-auth/token-store/file-store.d.ts +20 -0
  138. package/esm/src/client-auth/token-store/file-store.d.ts.map +1 -0
  139. package/esm/src/client-auth/token-store/file-store.js +62 -0
  140. package/esm/src/client-auth/token-store/memory-store.d.ts +14 -0
  141. package/esm/src/client-auth/token-store/memory-store.d.ts.map +1 -0
  142. package/esm/src/client-auth/token-store/memory-store.js +25 -0
  143. package/esm/src/client-auth/types.d.ts +89 -0
  144. package/esm/src/client-auth/types.d.ts.map +1 -0
  145. package/esm/src/client-auth/types.js +10 -0
  146. package/esm/src/concurrency/rate-limiter.d.ts +87 -0
  147. package/esm/src/concurrency/rate-limiter.d.ts.map +1 -0
  148. package/esm/src/concurrency/rate-limiter.js +165 -0
  149. package/esm/src/concurrency/request-queue.d.ts +71 -0
  150. package/esm/src/concurrency/request-queue.d.ts.map +1 -0
  151. package/esm/src/concurrency/request-queue.js +128 -0
  152. package/esm/src/http/body.d.ts +20 -0
  153. package/esm/src/http/body.d.ts.map +1 -0
  154. package/esm/src/http/body.js +63 -0
  155. package/esm/src/http/request-guards.d.ts +54 -0
  156. package/esm/src/http/request-guards.d.ts.map +1 -0
  157. package/esm/src/http/request-guards.js +114 -0
  158. package/esm/src/http/wire.d.ts +26 -0
  159. package/esm/src/http/wire.d.ts.map +1 -0
  160. package/{src/http/wire.ts → esm/src/http/wire.js} +13 -19
  161. package/esm/src/inspector/launcher.d.ts +48 -0
  162. package/esm/src/inspector/launcher.d.ts.map +1 -0
  163. package/esm/src/inspector/launcher.js +100 -0
  164. package/esm/src/mcp-app.d.ts +728 -0
  165. package/esm/src/mcp-app.d.ts.map +1 -0
  166. package/esm/src/mcp-app.js +3530 -0
  167. package/{src/middleware/backpressure.ts → esm/src/middleware/backpressure.d.ts} +2 -14
  168. package/esm/src/middleware/backpressure.d.ts.map +1 -0
  169. package/esm/src/middleware/backpressure.js +31 -0
  170. package/esm/src/middleware/mod.d.ts +11 -0
  171. package/esm/src/middleware/mod.d.ts.map +1 -0
  172. package/{src/middleware/mod.ts → esm/src/middleware/mod.js} +0 -10
  173. package/{src/middleware/rate-limit.ts → esm/src/middleware/rate-limit.d.ts} +2 -25
  174. package/esm/src/middleware/rate-limit.d.ts.map +1 -0
  175. package/esm/src/middleware/rate-limit.js +33 -0
  176. package/esm/src/middleware/runner.d.ts +32 -0
  177. package/esm/src/middleware/runner.d.ts.map +1 -0
  178. package/esm/src/middleware/runner.js +49 -0
  179. package/esm/src/middleware/types.d.ts +76 -0
  180. package/esm/src/middleware/types.d.ts.map +1 -0
  181. package/esm/src/middleware/types.js +9 -0
  182. package/esm/src/middleware/validation.d.ts +24 -0
  183. package/esm/src/middleware/validation.d.ts.map +1 -0
  184. package/esm/src/middleware/validation.js +30 -0
  185. package/esm/src/mrtr/capability-check.d.ts +75 -0
  186. package/esm/src/mrtr/capability-check.d.ts.map +1 -0
  187. package/esm/src/mrtr/capability-check.js +233 -0
  188. package/esm/src/mrtr/mod.d.ts +18 -0
  189. package/esm/src/mrtr/mod.d.ts.map +1 -0
  190. package/esm/src/mrtr/mod.js +12 -0
  191. package/esm/src/mrtr/replay-store.d.ts +50 -0
  192. package/esm/src/mrtr/replay-store.d.ts.map +1 -0
  193. package/esm/src/mrtr/replay-store.js +61 -0
  194. package/esm/src/mrtr/request-state.d.ts +181 -0
  195. package/esm/src/mrtr/request-state.d.ts.map +1 -0
  196. package/esm/src/mrtr/request-state.js +313 -0
  197. package/esm/src/mrtr/retry-guard.d.ts +61 -0
  198. package/esm/src/mrtr/retry-guard.d.ts.map +1 -0
  199. package/esm/src/mrtr/retry-guard.js +53 -0
  200. package/esm/src/mrtr/types.d.ts +99 -0
  201. package/esm/src/mrtr/types.d.ts.map +1 -0
  202. package/esm/src/mrtr/types.js +14 -0
  203. package/esm/src/observability/metrics.d.ts +104 -0
  204. package/esm/src/observability/metrics.d.ts.map +1 -0
  205. package/esm/src/observability/metrics.js +207 -0
  206. package/{src/observability/mod.ts → esm/src/observability/mod.d.ts} +2 -11
  207. package/esm/src/observability/mod.d.ts.map +1 -0
  208. package/esm/src/observability/mod.js +11 -0
  209. package/esm/src/observability/otel.d.ts +73 -0
  210. package/esm/src/observability/otel.d.ts.map +1 -0
  211. package/esm/src/observability/otel.js +260 -0
  212. package/esm/src/runtime/runtime.d.ts +10 -0
  213. package/esm/src/runtime/runtime.d.ts.map +1 -0
  214. package/esm/src/runtime/runtime.deno.d.ts +50 -0
  215. package/esm/src/runtime/runtime.deno.d.ts.map +1 -0
  216. package/esm/src/runtime/runtime.deno.js +120 -0
  217. package/{src/runtime/runtime.ts → esm/src/runtime/runtime.js} +5 -14
  218. package/esm/src/runtime/runtime.node.d.ts +51 -0
  219. package/esm/src/runtime/runtime.node.d.ts.map +1 -0
  220. package/esm/src/runtime/runtime.node.js +268 -0
  221. package/{src/runtime/types.ts → esm/src/runtime/types.d.ts} +28 -51
  222. package/esm/src/runtime/types.d.ts.map +1 -0
  223. package/esm/src/runtime/types.js +12 -0
  224. package/esm/src/security/channel-hmac.d.ts +43 -0
  225. package/esm/src/security/channel-hmac.d.ts.map +1 -0
  226. package/{src/security/channel-hmac.ts → esm/src/security/channel-hmac.js} +12 -17
  227. package/esm/src/security/csp.d.ts +50 -0
  228. package/esm/src/security/csp.d.ts.map +1 -0
  229. package/esm/src/security/csp.js +63 -0
  230. package/esm/src/security/message-signer.d.ts +88 -0
  231. package/esm/src/security/message-signer.d.ts.map +1 -0
  232. package/esm/src/security/message-signer.js +166 -0
  233. package/esm/src/subscriptions/subscription-registry.d.ts +256 -0
  234. package/esm/src/subscriptions/subscription-registry.d.ts.map +1 -0
  235. package/esm/src/subscriptions/subscription-registry.js +406 -0
  236. package/{src/tasks/mod.ts → esm/src/tasks/mod.d.ts} +3 -23
  237. package/esm/src/tasks/mod.d.ts.map +1 -0
  238. package/esm/src/tasks/mod.js +11 -0
  239. package/esm/src/tasks/task-store.d.ts +342 -0
  240. package/esm/src/tasks/task-store.d.ts.map +1 -0
  241. package/esm/src/tasks/task-store.js +649 -0
  242. package/esm/src/transport/request-headers.d.ts +145 -0
  243. package/esm/src/transport/request-headers.d.ts.map +1 -0
  244. package/esm/src/transport/request-headers.js +525 -0
  245. package/esm/src/types.d.ts +776 -0
  246. package/esm/src/types.d.ts.map +1 -0
  247. package/esm/src/types.js +92 -0
  248. package/esm/src/ui/viewer-utils.d.ts +45 -0
  249. package/esm/src/ui/viewer-utils.d.ts.map +1 -0
  250. package/esm/src/ui/viewer-utils.js +97 -0
  251. package/esm/src/validation/schema-validator.d.ts +115 -0
  252. package/esm/src/validation/schema-validator.d.ts.map +1 -0
  253. package/esm/src/validation/schema-validator.js +249 -0
  254. package/package.json +35 -23
  255. package/mod.ts +0 -302
  256. package/src/auth/as-metadata-proxy.ts +0 -288
  257. package/src/auth/config.ts +0 -368
  258. package/src/auth/jwt-provider.ts +0 -327
  259. package/src/auth/middleware.ts +0 -257
  260. package/src/auth/mod.ts +0 -89
  261. package/src/auth/multi-tenant-middleware.ts +0 -236
  262. package/src/auth/presets.ts +0 -351
  263. package/src/auth/scope-middleware.ts +0 -59
  264. package/src/auth/static-token-provider.ts +0 -197
  265. package/src/auth/types.ts +0 -207
  266. package/src/client-auth/callback-server.ts +0 -166
  267. package/src/client-auth/client-id-metadata.ts +0 -260
  268. package/src/client-auth/connect.ts +0 -72
  269. package/src/client-auth/provider.ts +0 -300
  270. package/src/client-auth/token-store/file-store.ts +0 -73
  271. package/src/client-auth/token-store/memory-store.ts +0 -32
  272. package/src/client-auth/types.ts +0 -95
  273. package/src/concurrency/rate-limiter.ts +0 -190
  274. package/src/concurrency/request-queue.ts +0 -140
  275. package/src/http/body.ts +0 -72
  276. package/src/http/request-guards.ts +0 -137
  277. package/src/inspector/launcher.ts +0 -131
  278. package/src/mcp-app.ts +0 -4426
  279. package/src/middleware/runner.ts +0 -63
  280. package/src/middleware/types.ts +0 -104
  281. package/src/middleware/validation.ts +0 -28
  282. package/src/mrtr/capability-check.ts +0 -303
  283. package/src/mrtr/mod.ts +0 -46
  284. package/src/mrtr/replay-store.ts +0 -103
  285. package/src/mrtr/request-state.ts +0 -435
  286. package/src/mrtr/types.ts +0 -107
  287. package/src/observability/metrics.ts +0 -336
  288. package/src/observability/otel.ts +0 -330
  289. package/src/runtime/runtime.deno.ts +0 -149
  290. package/src/runtime/runtime.node.ts +0 -324
  291. package/src/security/csp.ts +0 -89
  292. package/src/security/message-signer.ts +0 -223
  293. package/src/subscriptions/subscription-registry.ts +0 -558
  294. package/src/tasks/task-store.ts +0 -1014
  295. package/src/testdata/stdio-e2e-server.ts +0 -110
  296. package/src/transport/request-headers.ts +0 -661
  297. package/src/types.ts +0 -907
  298. package/src/ui/viewer-utils.ts +0 -117
  299. package/src/validation/schema-validator.ts +0 -307
@@ -0,0 +1,207 @@
1
+ /**
2
+ * Server Metrics Collector for @casys/mcp-server
3
+ *
4
+ * In-memory counters, histograms, and gauges with Prometheus text format export.
5
+ * Designed to be embedded in McpApp — no external dependencies.
6
+ *
7
+ * @module lib/server/observability/metrics
8
+ */
9
+ /**
10
+ * Default histogram buckets (milliseconds)
11
+ */
12
+ const DEFAULT_BUCKETS = [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000];
13
+ function createHistogram(buckets = DEFAULT_BUCKETS) {
14
+ return {
15
+ buckets: buckets.map((le) => ({ le, count: 0 })),
16
+ sum: 0,
17
+ count: 0,
18
+ };
19
+ }
20
+ function observeHistogram(histogram, value) {
21
+ histogram.sum += value;
22
+ histogram.count++;
23
+ for (const bucket of histogram.buckets) {
24
+ if (value <= bucket.le) {
25
+ bucket.count++;
26
+ }
27
+ }
28
+ }
29
+ /**
30
+ * Server metrics collector.
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * const metrics = new ServerMetrics();
35
+ * metrics.recordToolCall("my_tool", true, 42);
36
+ * console.log(metrics.toPrometheusFormat());
37
+ * ```
38
+ */
39
+ export class ServerMetrics {
40
+ startTime = Date.now();
41
+ // Counters
42
+ toolCallsTotal = 0;
43
+ toolCallsSuccess = 0;
44
+ toolCallsFailed = 0;
45
+ requestsRateLimited = 0;
46
+ requestsRejectedBackpressure = 0;
47
+ authSuccess = 0;
48
+ authFailed = 0;
49
+ authCacheHits = 0;
50
+ // Histogram
51
+ toolCallDuration = createHistogram();
52
+ // Per-tool breakdown
53
+ perTool = new Map();
54
+ // Gauges (set externally via setGauge)
55
+ activeRequests = 0;
56
+ queuedRequests = 0;
57
+ rateLimiterKeys = 0;
58
+ /**
59
+ * Record a completed tool call
60
+ */
61
+ recordToolCall(toolName, success, durationMs) {
62
+ this.toolCallsTotal++;
63
+ if (success) {
64
+ this.toolCallsSuccess++;
65
+ }
66
+ else {
67
+ this.toolCallsFailed++;
68
+ }
69
+ observeHistogram(this.toolCallDuration, durationMs);
70
+ // Per-tool
71
+ let pt = this.perTool.get(toolName);
72
+ if (!pt) {
73
+ pt = { calls: 0, success: 0, failed: 0, totalDurationMs: 0 };
74
+ this.perTool.set(toolName, pt);
75
+ }
76
+ pt.calls++;
77
+ if (success)
78
+ pt.success++;
79
+ else
80
+ pt.failed++;
81
+ pt.totalDurationMs += durationMs;
82
+ }
83
+ recordRateLimited() {
84
+ this.requestsRateLimited++;
85
+ }
86
+ recordBackpressureRejected() {
87
+ this.requestsRejectedBackpressure++;
88
+ }
89
+ recordAuth(success) {
90
+ if (success)
91
+ this.authSuccess++;
92
+ else
93
+ this.authFailed++;
94
+ }
95
+ recordAuthCacheHit() {
96
+ this.authCacheHits++;
97
+ }
98
+ /**
99
+ * Update gauge values (called periodically or on-demand)
100
+ */
101
+ setGauges(gauges) {
102
+ if (gauges.activeRequests !== undefined) {
103
+ this.activeRequests = gauges.activeRequests;
104
+ }
105
+ if (gauges.queuedRequests !== undefined) {
106
+ this.queuedRequests = gauges.queuedRequests;
107
+ }
108
+ if (gauges.rateLimiterKeys !== undefined) {
109
+ this.rateLimiterKeys = gauges.rateLimiterKeys;
110
+ }
111
+ }
112
+ /**
113
+ * Get current metrics snapshot
114
+ */
115
+ getSnapshot() {
116
+ return {
117
+ counters: {
118
+ tool_calls_total: this.toolCallsTotal,
119
+ tool_calls_success: this.toolCallsSuccess,
120
+ tool_calls_failed: this.toolCallsFailed,
121
+ requests_rate_limited: this.requestsRateLimited,
122
+ requests_rejected_backpressure: this.requestsRejectedBackpressure,
123
+ auth_success: this.authSuccess,
124
+ auth_failed: this.authFailed,
125
+ auth_cache_hits: this.authCacheHits,
126
+ },
127
+ histograms: {
128
+ tool_call_duration_ms: { ...this.toolCallDuration },
129
+ },
130
+ gauges: {
131
+ active_requests: this.activeRequests,
132
+ queued_requests: this.queuedRequests,
133
+ rate_limiter_keys: this.rateLimiterKeys,
134
+ },
135
+ collected_at: Date.now(),
136
+ uptime_seconds: Math.floor((Date.now() - this.startTime) / 1000),
137
+ };
138
+ }
139
+ /**
140
+ * Prometheus text format export
141
+ */
142
+ toPrometheusFormat(prefix = "mcp_server") {
143
+ const m = this.getSnapshot();
144
+ const lines = [];
145
+ // --- Counters ---
146
+ const counter = (name, help, value) => {
147
+ lines.push(`# HELP ${prefix}_${name} ${help}`);
148
+ lines.push(`# TYPE ${prefix}_${name} counter`);
149
+ lines.push(`${prefix}_${name} ${value}`);
150
+ };
151
+ counter("tool_calls_total", "Total tool calls", m.counters.tool_calls_total);
152
+ counter("tool_calls_success_total", "Successful tool calls", m.counters.tool_calls_success);
153
+ counter("tool_calls_failed_total", "Failed tool calls", m.counters.tool_calls_failed);
154
+ counter("requests_rate_limited_total", "Requests rejected by rate limiter", m.counters.requests_rate_limited);
155
+ counter("requests_backpressure_total", "Requests rejected by backpressure", m.counters.requests_rejected_backpressure);
156
+ counter("auth_success_total", "Successful auth verifications", m.counters.auth_success);
157
+ counter("auth_failed_total", "Failed auth verifications", m.counters.auth_failed);
158
+ counter("auth_cache_hits_total", "Auth token cache hits", m.counters.auth_cache_hits);
159
+ // --- Per-tool counters ---
160
+ lines.push(`# HELP ${prefix}_tool_calls_by_name Tool calls by tool name`);
161
+ lines.push(`# TYPE ${prefix}_tool_calls_by_name counter`);
162
+ for (const [name, pt] of this.perTool) {
163
+ lines.push(`${prefix}_tool_calls_by_name{tool="${name}",status="success"} ${pt.success}`);
164
+ lines.push(`${prefix}_tool_calls_by_name{tool="${name}",status="failed"} ${pt.failed}`);
165
+ }
166
+ // --- Histogram ---
167
+ const h = m.histograms.tool_call_duration_ms;
168
+ lines.push(`# HELP ${prefix}_tool_call_duration_ms Tool call duration in milliseconds`);
169
+ lines.push(`# TYPE ${prefix}_tool_call_duration_ms histogram`);
170
+ for (const bucket of h.buckets) {
171
+ lines.push(`${prefix}_tool_call_duration_ms_bucket{le="${bucket.le}"} ${bucket.count}`);
172
+ }
173
+ lines.push(`${prefix}_tool_call_duration_ms_bucket{le="+Inf"} ${h.count}`);
174
+ lines.push(`${prefix}_tool_call_duration_ms_sum ${h.sum}`);
175
+ lines.push(`${prefix}_tool_call_duration_ms_count ${h.count}`);
176
+ // --- Gauges ---
177
+ const gauge = (name, help, value) => {
178
+ lines.push(`# HELP ${prefix}_${name} ${help}`);
179
+ lines.push(`# TYPE ${prefix}_${name} gauge`);
180
+ lines.push(`${prefix}_${name} ${value}`);
181
+ };
182
+ gauge("active_requests", "Currently executing requests", m.gauges.active_requests);
183
+ gauge("queued_requests", "Requests waiting in queue", m.gauges.queued_requests);
184
+ gauge("rate_limiter_keys", "Tracked rate limiter keys", m.gauges.rate_limiter_keys);
185
+ gauge("uptime_seconds", "Server uptime in seconds", m.uptime_seconds);
186
+ return lines.join("\n") + "\n";
187
+ }
188
+ /**
189
+ * Reset all metrics
190
+ */
191
+ reset() {
192
+ this.toolCallsTotal = 0;
193
+ this.toolCallsSuccess = 0;
194
+ this.toolCallsFailed = 0;
195
+ this.requestsRateLimited = 0;
196
+ this.requestsRejectedBackpressure = 0;
197
+ this.authSuccess = 0;
198
+ this.authFailed = 0;
199
+ this.authCacheHits = 0;
200
+ this.toolCallDuration = createHistogram();
201
+ this.perTool.clear();
202
+ this.activeRequests = 0;
203
+ this.queuedRequests = 0;
204
+ this.rateLimiterKeys = 0;
205
+ this.startTime = Date.now();
206
+ }
207
+ }
@@ -7,15 +7,6 @@
7
7
  *
8
8
  * @module lib/server/observability
9
9
  */
10
-
11
- export {
12
- endToolCallSpan,
13
- getServerTracer,
14
- isOtelEnabled,
15
- parseTraceParent,
16
- recordAuthEvent,
17
- startToolCallSpan,
18
- type ToolCallSpanAttributes,
19
- } from "./otel.js";
20
-
10
+ export { endToolCallSpan, getServerTracer, isOtelEnabled, parseTraceParent, recordAuthEvent, startToolCallSpan, type ToolCallSpanAttributes, } from "./otel.js";
21
11
  export { ServerMetrics, type ServerMetricsSnapshot } from "./metrics.js";
12
+ //# sourceMappingURL=mod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.ts","sourceRoot":"","sources":["../../../src/src/observability/mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EACL,eAAe,EACf,eAAe,EACf,aAAa,EACb,gBAAgB,EAChB,eAAe,EACf,iBAAiB,EACjB,KAAK,sBAAsB,GAC5B,MAAM,WAAW,CAAC;AAEnB,OAAO,EAAE,aAAa,EAAE,KAAK,qBAAqB,EAAE,MAAM,cAAc,CAAC"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Observability module for @casys/mcp-server
3
+ *
4
+ * - OTel tracing (spans on tool calls, auth events)
5
+ * - Metrics collection (counters, histograms, gauges)
6
+ * - Prometheus text format export
7
+ *
8
+ * @module lib/server/observability
9
+ */
10
+ export { endToolCallSpan, getServerTracer, isOtelEnabled, parseTraceParent, recordAuthEvent, startToolCallSpan, } from "./otel.js";
11
+ export { ServerMetrics } from "./metrics.js";
@@ -0,0 +1,73 @@
1
+ /**
2
+ * OpenTelemetry Integration for @casys/mcp-server
3
+ *
4
+ * Provides tracing for tool calls, auth, and middleware pipeline.
5
+ *
6
+ * Enable with:
7
+ * - Deno: OTEL_DENO=true deno run --unstable-otel ...
8
+ * - Node.js: OTEL_ENABLED=true node ...
9
+ *
10
+ * @module lib/server/observability/otel
11
+ */
12
+ import { type Span, type SpanContext, type Tracer } from "@opentelemetry/api";
13
+ /**
14
+ * Parse a W3C trace context into an OTel `SpanContext` (spec 2026-07-28).
15
+ *
16
+ * The revision documents `traceparent` / `tracestate` / `baggage` as `_meta`
17
+ * keys so a tool call joins the caller's trace instead of starting a detached
18
+ * one. Returns `undefined` for anything malformed — a bad header leaves the span
19
+ * unparented, it never fails the call.
20
+ *
21
+ * Version handling follows the W3C forward-compatibility rule, which is not
22
+ * "reject anything unfamiliar":
23
+ *
24
+ * - `ff` is forbidden outright.
25
+ * - `00` is a fixed 55-character format; anything longer is malformed.
26
+ * - a higher version MAY carry fields this implementation does not know. The
27
+ * receiver parses the first 55 characters and ignores the rest, provided the
28
+ * next character is a `-`. Rejecting those would make this server drop trace
29
+ * context the day a new version ships — the exact breakage the rule exists to
30
+ * prevent.
31
+ */
32
+ export declare function parseTraceParent(traceparent: unknown, tracestate?: unknown): SpanContext | undefined;
33
+ /**
34
+ * Get or create the MCP server tracer
35
+ */
36
+ export declare function getServerTracer(): Tracer;
37
+ /**
38
+ * Span attributes for MCP tool calls
39
+ */
40
+ export interface ToolCallSpanAttributes {
41
+ "mcp.tool.name": string;
42
+ "mcp.server.name"?: string;
43
+ "mcp.transport"?: string;
44
+ "mcp.session.id"?: string;
45
+ "mcp.auth.subject"?: string;
46
+ "mcp.auth.client_id"?: string;
47
+ [key: string]: string | number | boolean | undefined;
48
+ }
49
+ /**
50
+ * Start a span for a tool call.
51
+ * Caller MUST call span.end() when done.
52
+ *
53
+ * `remoteParent` is the caller's trace context, read from the request's `_meta`
54
+ * (spec 2026-07-28). With it the span joins the caller's trace; without it the
55
+ * span falls back to the active context, which is what every call produced
56
+ * before the `_meta` keys were wired in — a server-side trace nobody could
57
+ * correlate to the client that caused it.
58
+ */
59
+ export declare function startToolCallSpan(toolName: string, attributes: ToolCallSpanAttributes, remoteParent?: SpanContext): Span;
60
+ /**
61
+ * Record a tool call result on a span and end it.
62
+ */
63
+ export declare function endToolCallSpan(span: Span, success: boolean, durationMs: number, error?: string): void;
64
+ /**
65
+ * Record an auth event as a fire-and-forget span.
66
+ */
67
+ export declare function recordAuthEvent(event: "verify" | "reject" | "cache_hit", attributes: Record<string, string | number | boolean | undefined>): void;
68
+ /**
69
+ * Check if OTEL is enabled.
70
+ * Deno: OTEL_DENO=true | Node.js: OTEL_ENABLED=true
71
+ */
72
+ export declare function isOtelEnabled(): boolean;
73
+ //# sourceMappingURL=otel.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"otel.d.ts","sourceRoot":"","sources":["../../../src/src/observability/otel.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAGL,KAAK,IAAI,EACT,KAAK,WAAW,EAIhB,KAAK,MAAM,EAEZ,MAAM,oBAAoB,CAAC;AAwI5B;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,gBAAgB,CAC9B,WAAW,EAAE,OAAO,EACpB,UAAU,CAAC,EAAE,OAAO,GACnB,WAAW,GAAG,SAAS,CAqCzB;AAgBD;;GAEG;AACH,wBAAgB,eAAe,IAAI,MAAM,CAKxC;AAED;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACrC,eAAe,EAAE,MAAM,CAAC;IACxB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,SAAS,CAAC;CACtD;AAED;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,sBAAsB,EAClC,YAAY,CAAC,EAAE,WAAW,GACzB,IAAI,CAON;AAED;;GAEG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,OAAO,EAChB,UAAU,EAAE,MAAM,EAClB,KAAK,CAAC,EAAE,MAAM,GACb,IAAI,CAcN;AAED;;GAEG;AACH,wBAAgB,eAAe,CAC7B,KAAK,EAAE,QAAQ,GAAG,QAAQ,GAAG,WAAW,EACxC,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,SAAS,CAAC,GAChE,IAAI,CAQN;AAED;;;GAGG;AACH,wBAAgB,aAAa,IAAI,OAAO,CAOvC"}
@@ -0,0 +1,260 @@
1
+ /**
2
+ * OpenTelemetry Integration for @casys/mcp-server
3
+ *
4
+ * Provides tracing for tool calls, auth, and middleware pipeline.
5
+ *
6
+ * Enable with:
7
+ * - Deno: OTEL_DENO=true deno run --unstable-otel ...
8
+ * - Node.js: OTEL_ENABLED=true node ...
9
+ *
10
+ * @module lib/server/observability/otel
11
+ */
12
+ import { context as otelContext, SpanStatusCode, trace, TraceFlags, } from "@opentelemetry/api";
13
+ import { env } from "../runtime/runtime.js";
14
+ let serverTracer = null;
15
+ /**
16
+ * W3C `traceparent`: `<2 hex version>-<32 hex trace-id>-<16 hex parent-id>-<2 hex flags>`.
17
+ *
18
+ * Matches the 55-character prefix only — the trailing-content rule depends on
19
+ * the version and is applied separately, see {@link parseTraceParent}.
20
+ *
21
+ * Case-sensitive on purpose. The spec mandates lowercase hex, and accepting
22
+ * uppercase produces a trace id that will not match the same trace elsewhere in
23
+ * the pipeline: a silently broken join is worse than a dropped header.
24
+ */
25
+ const TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})/;
26
+ /** `00-` + 32 + `-` + 16 + `-` + 2 = 55. */
27
+ const TRACEPARENT_PREFIX_LENGTH = 55;
28
+ /** All-zero ids are explicitly invalid in the W3C spec. */
29
+ const INVALID_TRACE_ID = "0".repeat(32);
30
+ const INVALID_SPAN_ID = "0".repeat(16);
31
+ /** W3C caps `tracestate` at 32 list members; the rest are dropped. */
32
+ const TRACESTATE_MAX_MEMBERS = 32;
33
+ /**
34
+ * W3C `tracestate` key, both forms of the ABNF:
35
+ * - simple: `lcalpha 0*255(lcalpha / DIGIT / "_" / "-" / "*" / "/")`
36
+ * - multi-tenant: `tenant-id "@" system-id`
37
+ */
38
+ const TRACESTATE_KEY = /^(?:[a-z][a-z0-9_\-*/]{0,255}|[a-z0-9][a-z0-9_\-*/]{0,240}@[a-z][a-z0-9_\-*/]{0,13})$/;
39
+ /**
40
+ * W3C `tracestate` value — the ABNF is `0*255(chr) nblk-chr`:
41
+ *
42
+ * - `chr` is printable ASCII except comma and equals. `=` inside a value is
43
+ * forbidden, so a member carrying one is malformed, not a value to preserve.
44
+ * - the final character is `nblk-chr`, which additionally excludes SP. That
45
+ * makes the value **non-empty** and forbids a trailing space, so `vendor=`
46
+ * is not a valid member.
47
+ */
48
+ const TRACESTATE_VALUE = /^[\x20-\x2B\x2D-\x3C\x3E-\x7E]{0,255}[\x21-\x2B\x2D-\x3C\x3E-\x7E]$/;
49
+ /**
50
+ * The grammar's optional whitespace around a list member is SP and HTAB only.
51
+ * `String.trim()` also eats CR, LF, FF, VT and Unicode spaces — none of which
52
+ * are legal separators here, so trimming with it would silently accept a
53
+ * malformed list.
54
+ */
55
+ function trimOws(member) {
56
+ return member.replace(/^[ \t]+/, "").replace(/[ \t]+$/, "");
57
+ }
58
+ /**
59
+ * `tracestate` carried to the next hop.
60
+ *
61
+ * `@opentelemetry/api` declares the interface but ships no implementation —
62
+ * that lives in `@opentelemetry/core`. Pulling in the SDK package for one
63
+ * key/value list would put a second OTel dependency in the public API, so this
64
+ * is the minimum that satisfies the interface.
65
+ *
66
+ * Members are validated against the W3C ABNF rather than passed through: the
67
+ * spec permits discarding invalid entries, and this list is re-serialised onto
68
+ * the next hop — accepting a malformed member here means emitting a malformed
69
+ * `tracestate` downstream, turning one peer's bug into ours.
70
+ */
71
+ class ListTraceState {
72
+ #entries;
73
+ constructor(entries) {
74
+ this.#entries = entries;
75
+ }
76
+ static #isValid(key, value) {
77
+ return TRACESTATE_KEY.test(key) && TRACESTATE_VALUE.test(value);
78
+ }
79
+ static parse(raw) {
80
+ const seen = new Set();
81
+ const entries = [];
82
+ for (const member of raw.split(",")) {
83
+ // Optional whitespace around a list member is part of the grammar; the
84
+ // key and value themselves are matched exactly.
85
+ const trimmed = trimOws(member);
86
+ if (trimmed.length === 0)
87
+ continue;
88
+ const at = trimmed.indexOf("=");
89
+ if (at <= 0)
90
+ continue;
91
+ const key = trimmed.slice(0, at);
92
+ const value = trimmed.slice(at + 1);
93
+ // Duplicate keys are invalid; the first occurrence is the live one.
94
+ if (seen.has(key))
95
+ continue;
96
+ if (!ListTraceState.#isValid(key, value))
97
+ continue;
98
+ seen.add(key);
99
+ entries.push([key, value]);
100
+ if (entries.length === TRACESTATE_MAX_MEMBERS)
101
+ break;
102
+ }
103
+ return entries.length > 0 ? new ListTraceState(entries) : undefined;
104
+ }
105
+ get(key) {
106
+ return this.#entries.find(([k]) => k === key)?.[1];
107
+ }
108
+ set(key, value) {
109
+ // Returns the state unchanged rather than throwing. The OpenTelemetry
110
+ // specification is explicit that "API methods MUST NOT throw unhandled
111
+ // exceptions when used incorrectly by end users" — telemetry is not worth
112
+ // taking an application down for. Rejecting the mutation still keeps the
113
+ // invalid member off the wire, which is the property that matters.
114
+ if (!ListTraceState.#isValid(key, value))
115
+ return this;
116
+ // W3C: a mutated key moves to the front of the list.
117
+ return new ListTraceState([
118
+ [key, value],
119
+ ...this.#entries.filter(([k]) => k !== key),
120
+ ].slice(0, TRACESTATE_MAX_MEMBERS));
121
+ }
122
+ unset(key) {
123
+ return new ListTraceState(this.#entries.filter(([k]) => k !== key));
124
+ }
125
+ serialize() {
126
+ return this.#entries.map(([k, v]) => `${k}=${v}`).join(",");
127
+ }
128
+ }
129
+ /**
130
+ * Parse a W3C trace context into an OTel `SpanContext` (spec 2026-07-28).
131
+ *
132
+ * The revision documents `traceparent` / `tracestate` / `baggage` as `_meta`
133
+ * keys so a tool call joins the caller's trace instead of starting a detached
134
+ * one. Returns `undefined` for anything malformed — a bad header leaves the span
135
+ * unparented, it never fails the call.
136
+ *
137
+ * Version handling follows the W3C forward-compatibility rule, which is not
138
+ * "reject anything unfamiliar":
139
+ *
140
+ * - `ff` is forbidden outright.
141
+ * - `00` is a fixed 55-character format; anything longer is malformed.
142
+ * - a higher version MAY carry fields this implementation does not know. The
143
+ * receiver parses the first 55 characters and ignores the rest, provided the
144
+ * next character is a `-`. Rejecting those would make this server drop trace
145
+ * context the day a new version ships — the exact breakage the rule exists to
146
+ * prevent.
147
+ */
148
+ export function parseTraceParent(traceparent, tracestate) {
149
+ if (typeof traceparent !== "string")
150
+ return undefined;
151
+ if (traceparent.length < TRACEPARENT_PREFIX_LENGTH)
152
+ return undefined;
153
+ const match = TRACEPARENT.exec(traceparent);
154
+ if (!match)
155
+ return undefined;
156
+ const [, version, traceId, spanId, flags] = match;
157
+ if (version === "ff")
158
+ return undefined;
159
+ if (version === "00") {
160
+ if (traceparent.length !== TRACEPARENT_PREFIX_LENGTH)
161
+ return undefined;
162
+ }
163
+ else if (traceparent.length > TRACEPARENT_PREFIX_LENGTH &&
164
+ traceparent[TRACEPARENT_PREFIX_LENGTH] !== "-") {
165
+ // Longer, but not a well-formed continuation: the extra characters are not
166
+ // a new field, so the whole header is suspect.
167
+ return undefined;
168
+ }
169
+ if (traceId === INVALID_TRACE_ID || spanId === INVALID_SPAN_ID) {
170
+ return undefined;
171
+ }
172
+ const traceState = typeof tracestate === "string"
173
+ ? ListTraceState.parse(tracestate)
174
+ : undefined;
175
+ return {
176
+ traceId,
177
+ spanId,
178
+ // Only the sampled bit is defined; the rest of the byte is reserved.
179
+ traceFlags: (parseInt(flags, 16) & TraceFlags.SAMPLED),
180
+ isRemote: true,
181
+ ...(traceState ? { traceState } : {}),
182
+ };
183
+ }
184
+ /**
185
+ * The OTel context a remote `SpanContext` should parent, or the active one.
186
+ *
187
+ * Note the fallback is the *active* context, not `ROOT_CONTEXT`: with no
188
+ * caller-supplied trace context the span attaches to whatever span is active in
189
+ * this process, and only becomes a root when there is none. That is the right
190
+ * default — it preserves in-process nesting — but it means "no traceparent" and
191
+ * "root span" are not synonyms.
192
+ */
193
+ function parentContext(remote) {
194
+ const active = otelContext.active();
195
+ return remote ? trace.setSpanContext(active, remote) : active;
196
+ }
197
+ /**
198
+ * Get or create the MCP server tracer
199
+ */
200
+ export function getServerTracer() {
201
+ if (!serverTracer) {
202
+ serverTracer = trace.getTracer("mcp.server", "0.8.0");
203
+ }
204
+ return serverTracer;
205
+ }
206
+ /**
207
+ * Start a span for a tool call.
208
+ * Caller MUST call span.end() when done.
209
+ *
210
+ * `remoteParent` is the caller's trace context, read from the request's `_meta`
211
+ * (spec 2026-07-28). With it the span joins the caller's trace; without it the
212
+ * span falls back to the active context, which is what every call produced
213
+ * before the `_meta` keys were wired in — a server-side trace nobody could
214
+ * correlate to the client that caused it.
215
+ */
216
+ export function startToolCallSpan(toolName, attributes, remoteParent) {
217
+ const tracer = getServerTracer();
218
+ return tracer.startSpan(`mcp.tool.call ${toolName}`, { attributes }, parentContext(remoteParent));
219
+ }
220
+ /**
221
+ * Record a tool call result on a span and end it.
222
+ */
223
+ export function endToolCallSpan(span, success, durationMs, error) {
224
+ span.setAttribute("mcp.tool.duration_ms", durationMs);
225
+ span.setAttribute("mcp.tool.success", success);
226
+ if (error) {
227
+ span.setAttribute("mcp.tool.error", error);
228
+ span.recordException(new Error(error));
229
+ }
230
+ span.setStatus({
231
+ code: success ? SpanStatusCode.OK : SpanStatusCode.ERROR,
232
+ message: error,
233
+ });
234
+ span.end();
235
+ }
236
+ /**
237
+ * Record an auth event as a fire-and-forget span.
238
+ */
239
+ export function recordAuthEvent(event, attributes) {
240
+ const tracer = getServerTracer();
241
+ tracer.startActiveSpan(`mcp.auth.${event}`, { attributes }, (span) => {
242
+ span.setStatus({
243
+ code: event === "reject" ? SpanStatusCode.ERROR : SpanStatusCode.OK,
244
+ });
245
+ span.end();
246
+ });
247
+ }
248
+ /**
249
+ * Check if OTEL is enabled.
250
+ * Deno: OTEL_DENO=true | Node.js: OTEL_ENABLED=true
251
+ */
252
+ export function isOtelEnabled() {
253
+ try {
254
+ return env("OTEL_DENO") === "true" || env("OTEL_ENABLED") === "true";
255
+ }
256
+ catch {
257
+ // Deno without --allow-env throws NotCapable
258
+ return false;
259
+ }
260
+ }
@@ -0,0 +1,10 @@
1
+ export type { FetchHandler, ServeHandle, ServeOptions } from "./types.js";
2
+ export declare const env: import("./types.js").EnvFn;
3
+ export declare const readTextFile: import("./types.js").ReadTextFileFn;
4
+ export declare const writeTextFile: import("./types.js").WriteTextFileFn;
5
+ export declare const mkdir: import("./types.js").MkdirFn;
6
+ export declare const remove: import("./types.js").RemoveFn;
7
+ export declare const readDir: import("./types.js").ReadDirFn;
8
+ export declare const serve: import("./types.js").ServeFn;
9
+ export declare const unrefTimer: import("./types.js").UnrefTimerFn;
10
+ //# sourceMappingURL=runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../../src/src/runtime/runtime.ts"],"names":[],"mappings":"AA+BA,YAAY,EAAE,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAa1E,eAAO,MAAM,GAAG,4BAAW,CAAC;AAC5B,eAAO,MAAM,YAAY,qCAAoB,CAAC;AAC9C,eAAO,MAAM,aAAa,sCAAqB,CAAC;AAChD,eAAO,MAAM,KAAK,8BAAa,CAAC;AAChC,eAAO,MAAM,MAAM,+BAAc,CAAC;AAClC,eAAO,MAAM,OAAO,gCAAe,CAAC;AACpC,eAAO,MAAM,KAAK,8BAAa,CAAC;AAChC,eAAO,MAAM,UAAU,mCAAkB,CAAC"}
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Runtime adapter — Deno implementation
3
+ *
4
+ * Implements the RuntimePort contract for Deno.
5
+ * Selected automatically by runtime.ts (the selector) when running under Deno.
6
+ *
7
+ * @see types.ts for the port contract
8
+ * @module lib/server/runtime.deno
9
+ */
10
+ import type { FetchHandler, ServeHandle, ServeOptions } from "./types.js";
11
+ export type { FetchHandler, ServeHandle, ServeOptions } from "./types.js";
12
+ /**
13
+ * Get an environment variable.
14
+ */
15
+ export declare function env(key: string): string | undefined;
16
+ /**
17
+ * Read a UTF-8 text file.
18
+ * Returns null if the file does not exist.
19
+ */
20
+ export declare function readTextFile(path: string): Promise<string | null>;
21
+ /**
22
+ * Write a UTF-8 text file.
23
+ */
24
+ export declare function writeTextFile(path: string, content: string, opts?: {
25
+ mode?: number;
26
+ }): Promise<void>;
27
+ /**
28
+ * Create a directory.
29
+ */
30
+ export declare function mkdir(path: string, opts?: {
31
+ recursive?: boolean;
32
+ mode?: number;
33
+ }): Promise<void>;
34
+ /**
35
+ * Remove a file or empty directory. No-op if absent.
36
+ */
37
+ export declare function remove(path: string): Promise<void>;
38
+ /**
39
+ * Read directory entry names. Returns [] if absent.
40
+ */
41
+ export declare function readDir(path: string): Promise<string[]>;
42
+ /**
43
+ * Start an HTTP server with a fetch-style handler.
44
+ */
45
+ export declare function serve(options: ServeOptions, handler: FetchHandler): ServeHandle;
46
+ /**
47
+ * Unref a timer so it doesn't block process exit.
48
+ */
49
+ export declare function unrefTimer(id: number): void;
50
+ //# sourceMappingURL=runtime.deno.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.deno.d.ts","sourceRoot":"","sources":["../../../src/src/runtime/runtime.deno.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EACV,YAAY,EAEZ,WAAW,EACX,YAAY,EACb,MAAM,YAAY,CAAC;AAGpB,YAAY,EAAE,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE1E;;GAEG;AACH,wBAAgB,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAEnD;AAED;;;GAGG;AACH,wBAAsB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CASvE;AAED;;GAEG;AACH,wBAAsB,aAAa,CACjC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,IAAI,CAAC,EAAE;IAAE,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,GACvB,OAAO,CAAC,IAAI,CAAC,CAEf;AAED;;GAEG;AACH,wBAAsB,KAAK,CACzB,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE;IAAE,SAAS,CAAC,EAAE,OAAO,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,GAC5C,OAAO,CAAC,IAAI,CAAC,CAEf;AAED;;GAEG;AACH,wBAAsB,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CASxD;AAED;;GAEG;AACH,wBAAsB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAa7D;AAED;;GAEG;AACH,wBAAgB,KAAK,CACnB,OAAO,EAAE,YAAY,EACrB,OAAO,EAAE,YAAY,GACpB,WAAW,CAwBb;AAED;;GAEG;AACH,wBAAgB,UAAU,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAE3C"}