@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
@@ -1,336 +0,0 @@
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
- /**
11
- * Histogram bucket
12
- */
13
- interface HistogramBucket {
14
- le: number;
15
- count: number;
16
- }
17
-
18
- /**
19
- * Latency histogram with cumulative buckets
20
- */
21
- interface Histogram {
22
- buckets: HistogramBucket[];
23
- sum: number;
24
- count: number;
25
- }
26
-
27
- /**
28
- * Default histogram buckets (milliseconds)
29
- */
30
- const DEFAULT_BUCKETS = [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000];
31
-
32
- function createHistogram(buckets: number[] = DEFAULT_BUCKETS): Histogram {
33
- return {
34
- buckets: buckets.map((le) => ({ le, count: 0 })),
35
- sum: 0,
36
- count: 0,
37
- };
38
- }
39
-
40
- function observeHistogram(histogram: Histogram, value: number): void {
41
- histogram.sum += value;
42
- histogram.count++;
43
- for (const bucket of histogram.buckets) {
44
- if (value <= bucket.le) {
45
- bucket.count++;
46
- }
47
- }
48
- }
49
-
50
- /**
51
- * Metrics snapshot returned by getMetrics()
52
- */
53
- export interface ServerMetricsSnapshot {
54
- counters: {
55
- tool_calls_total: number;
56
- tool_calls_success: number;
57
- tool_calls_failed: number;
58
- requests_rate_limited: number;
59
- requests_rejected_backpressure: number;
60
- auth_success: number;
61
- auth_failed: number;
62
- auth_cache_hits: number;
63
- };
64
- histograms: {
65
- tool_call_duration_ms: Histogram;
66
- };
67
- gauges: {
68
- active_requests: number;
69
- queued_requests: number;
70
- rate_limiter_keys: number;
71
- };
72
- collected_at: number;
73
- uptime_seconds: number;
74
- }
75
-
76
- /**
77
- * Tool call metrics by tool name
78
- */
79
- interface PerToolMetrics {
80
- calls: number;
81
- success: number;
82
- failed: number;
83
- totalDurationMs: number;
84
- }
85
-
86
- /**
87
- * Server metrics collector.
88
- *
89
- * @example
90
- * ```typescript
91
- * const metrics = new ServerMetrics();
92
- * metrics.recordToolCall("my_tool", true, 42);
93
- * console.log(metrics.toPrometheusFormat());
94
- * ```
95
- */
96
- export class ServerMetrics {
97
- private startTime = Date.now();
98
-
99
- // Counters
100
- private toolCallsTotal = 0;
101
- private toolCallsSuccess = 0;
102
- private toolCallsFailed = 0;
103
- private requestsRateLimited = 0;
104
- private requestsRejectedBackpressure = 0;
105
- private authSuccess = 0;
106
- private authFailed = 0;
107
- private authCacheHits = 0;
108
-
109
- // Histogram
110
- private toolCallDuration = createHistogram();
111
-
112
- // Per-tool breakdown
113
- private perTool = new Map<string, PerToolMetrics>();
114
-
115
- // Gauges (set externally via setGauge)
116
- private activeRequests = 0;
117
- private queuedRequests = 0;
118
- private rateLimiterKeys = 0;
119
-
120
- /**
121
- * Record a completed tool call
122
- */
123
- recordToolCall(toolName: string, success: boolean, durationMs: number): void {
124
- this.toolCallsTotal++;
125
- if (success) {
126
- this.toolCallsSuccess++;
127
- } else {
128
- this.toolCallsFailed++;
129
- }
130
- observeHistogram(this.toolCallDuration, durationMs);
131
-
132
- // Per-tool
133
- let pt = this.perTool.get(toolName);
134
- if (!pt) {
135
- pt = { calls: 0, success: 0, failed: 0, totalDurationMs: 0 };
136
- this.perTool.set(toolName, pt);
137
- }
138
- pt.calls++;
139
- if (success) pt.success++;
140
- else pt.failed++;
141
- pt.totalDurationMs += durationMs;
142
- }
143
-
144
- recordRateLimited(): void {
145
- this.requestsRateLimited++;
146
- }
147
-
148
- recordBackpressureRejected(): void {
149
- this.requestsRejectedBackpressure++;
150
- }
151
-
152
- recordAuth(success: boolean): void {
153
- if (success) this.authSuccess++;
154
- else this.authFailed++;
155
- }
156
-
157
- recordAuthCacheHit(): void {
158
- this.authCacheHits++;
159
- }
160
-
161
- /**
162
- * Update gauge values (called periodically or on-demand)
163
- */
164
- setGauges(gauges: {
165
- activeRequests?: number;
166
- queuedRequests?: number;
167
- rateLimiterKeys?: number;
168
- }): void {
169
- if (gauges.activeRequests !== undefined) {
170
- this.activeRequests = gauges.activeRequests;
171
- }
172
- if (gauges.queuedRequests !== undefined) {
173
- this.queuedRequests = gauges.queuedRequests;
174
- }
175
- if (gauges.rateLimiterKeys !== undefined) {
176
- this.rateLimiterKeys = gauges.rateLimiterKeys;
177
- }
178
- }
179
-
180
- /**
181
- * Get current metrics snapshot
182
- */
183
- getSnapshot(): ServerMetricsSnapshot {
184
- return {
185
- counters: {
186
- tool_calls_total: this.toolCallsTotal,
187
- tool_calls_success: this.toolCallsSuccess,
188
- tool_calls_failed: this.toolCallsFailed,
189
- requests_rate_limited: this.requestsRateLimited,
190
- requests_rejected_backpressure: this.requestsRejectedBackpressure,
191
- auth_success: this.authSuccess,
192
- auth_failed: this.authFailed,
193
- auth_cache_hits: this.authCacheHits,
194
- },
195
- histograms: {
196
- tool_call_duration_ms: { ...this.toolCallDuration },
197
- },
198
- gauges: {
199
- active_requests: this.activeRequests,
200
- queued_requests: this.queuedRequests,
201
- rate_limiter_keys: this.rateLimiterKeys,
202
- },
203
- collected_at: Date.now(),
204
- uptime_seconds: Math.floor((Date.now() - this.startTime) / 1000),
205
- };
206
- }
207
-
208
- /**
209
- * Prometheus text format export
210
- */
211
- toPrometheusFormat(prefix = "mcp_server"): string {
212
- const m = this.getSnapshot();
213
- const lines: string[] = [];
214
-
215
- // --- Counters ---
216
- const counter = (name: string, help: string, value: number) => {
217
- lines.push(`# HELP ${prefix}_${name} ${help}`);
218
- lines.push(`# TYPE ${prefix}_${name} counter`);
219
- lines.push(`${prefix}_${name} ${value}`);
220
- };
221
-
222
- counter(
223
- "tool_calls_total",
224
- "Total tool calls",
225
- m.counters.tool_calls_total,
226
- );
227
- counter(
228
- "tool_calls_success_total",
229
- "Successful tool calls",
230
- m.counters.tool_calls_success,
231
- );
232
- counter(
233
- "tool_calls_failed_total",
234
- "Failed tool calls",
235
- m.counters.tool_calls_failed,
236
- );
237
- counter(
238
- "requests_rate_limited_total",
239
- "Requests rejected by rate limiter",
240
- m.counters.requests_rate_limited,
241
- );
242
- counter(
243
- "requests_backpressure_total",
244
- "Requests rejected by backpressure",
245
- m.counters.requests_rejected_backpressure,
246
- );
247
- counter(
248
- "auth_success_total",
249
- "Successful auth verifications",
250
- m.counters.auth_success,
251
- );
252
- counter(
253
- "auth_failed_total",
254
- "Failed auth verifications",
255
- m.counters.auth_failed,
256
- );
257
- counter(
258
- "auth_cache_hits_total",
259
- "Auth token cache hits",
260
- m.counters.auth_cache_hits,
261
- );
262
-
263
- // --- Per-tool counters ---
264
- lines.push(`# HELP ${prefix}_tool_calls_by_name Tool calls by tool name`);
265
- lines.push(`# TYPE ${prefix}_tool_calls_by_name counter`);
266
- for (const [name, pt] of this.perTool) {
267
- lines.push(
268
- `${prefix}_tool_calls_by_name{tool="${name}",status="success"} ${pt.success}`,
269
- );
270
- lines.push(
271
- `${prefix}_tool_calls_by_name{tool="${name}",status="failed"} ${pt.failed}`,
272
- );
273
- }
274
-
275
- // --- Histogram ---
276
- const h = m.histograms.tool_call_duration_ms;
277
- lines.push(
278
- `# HELP ${prefix}_tool_call_duration_ms Tool call duration in milliseconds`,
279
- );
280
- lines.push(`# TYPE ${prefix}_tool_call_duration_ms histogram`);
281
- for (const bucket of h.buckets) {
282
- lines.push(
283
- `${prefix}_tool_call_duration_ms_bucket{le="${bucket.le}"} ${bucket.count}`,
284
- );
285
- }
286
- lines.push(`${prefix}_tool_call_duration_ms_bucket{le="+Inf"} ${h.count}`);
287
- lines.push(`${prefix}_tool_call_duration_ms_sum ${h.sum}`);
288
- lines.push(`${prefix}_tool_call_duration_ms_count ${h.count}`);
289
-
290
- // --- Gauges ---
291
- const gauge = (name: string, help: string, value: number) => {
292
- lines.push(`# HELP ${prefix}_${name} ${help}`);
293
- lines.push(`# TYPE ${prefix}_${name} gauge`);
294
- lines.push(`${prefix}_${name} ${value}`);
295
- };
296
-
297
- gauge(
298
- "active_requests",
299
- "Currently executing requests",
300
- m.gauges.active_requests,
301
- );
302
- gauge(
303
- "queued_requests",
304
- "Requests waiting in queue",
305
- m.gauges.queued_requests,
306
- );
307
- gauge(
308
- "rate_limiter_keys",
309
- "Tracked rate limiter keys",
310
- m.gauges.rate_limiter_keys,
311
- );
312
- gauge("uptime_seconds", "Server uptime in seconds", m.uptime_seconds);
313
-
314
- return lines.join("\n") + "\n";
315
- }
316
-
317
- /**
318
- * Reset all metrics
319
- */
320
- reset(): void {
321
- this.toolCallsTotal = 0;
322
- this.toolCallsSuccess = 0;
323
- this.toolCallsFailed = 0;
324
- this.requestsRateLimited = 0;
325
- this.requestsRejectedBackpressure = 0;
326
- this.authSuccess = 0;
327
- this.authFailed = 0;
328
- this.authCacheHits = 0;
329
- this.toolCallDuration = createHistogram();
330
- this.perTool.clear();
331
- this.activeRequests = 0;
332
- this.queuedRequests = 0;
333
- this.rateLimiterKeys = 0;
334
- this.startTime = Date.now();
335
- }
336
- }
@@ -1,330 +0,0 @@
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
-
13
- import {
14
- type Context,
15
- context as otelContext,
16
- type Span,
17
- type SpanContext,
18
- SpanStatusCode,
19
- trace,
20
- TraceFlags,
21
- type Tracer,
22
- type TraceState,
23
- } from "@opentelemetry/api";
24
- import { env } from "../runtime/runtime.js";
25
-
26
- let serverTracer: Tracer | null = null;
27
-
28
- /**
29
- * W3C `traceparent`: `<2 hex version>-<32 hex trace-id>-<16 hex parent-id>-<2 hex flags>`.
30
- *
31
- * Matches the 55-character prefix only — the trailing-content rule depends on
32
- * the version and is applied separately, see {@link parseTraceParent}.
33
- *
34
- * Case-sensitive on purpose. The spec mandates lowercase hex, and accepting
35
- * uppercase produces a trace id that will not match the same trace elsewhere in
36
- * the pipeline: a silently broken join is worse than a dropped header.
37
- */
38
- const TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})/;
39
-
40
- /** `00-` + 32 + `-` + 16 + `-` + 2 = 55. */
41
- const TRACEPARENT_PREFIX_LENGTH = 55;
42
-
43
- /** All-zero ids are explicitly invalid in the W3C spec. */
44
- const INVALID_TRACE_ID = "0".repeat(32);
45
- const INVALID_SPAN_ID = "0".repeat(16);
46
-
47
- /** W3C caps `tracestate` at 32 list members; the rest are dropped. */
48
- const TRACESTATE_MAX_MEMBERS = 32;
49
-
50
- /**
51
- * W3C `tracestate` key, both forms of the ABNF:
52
- * - simple: `lcalpha 0*255(lcalpha / DIGIT / "_" / "-" / "*" / "/")`
53
- * - multi-tenant: `tenant-id "@" system-id`
54
- */
55
- const TRACESTATE_KEY =
56
- /^(?:[a-z][a-z0-9_\-*/]{0,255}|[a-z0-9][a-z0-9_\-*/]{0,240}@[a-z][a-z0-9_\-*/]{0,13})$/;
57
-
58
- /**
59
- * W3C `tracestate` value — the ABNF is `0*255(chr) nblk-chr`:
60
- *
61
- * - `chr` is printable ASCII except comma and equals. `=` inside a value is
62
- * forbidden, so a member carrying one is malformed, not a value to preserve.
63
- * - the final character is `nblk-chr`, which additionally excludes SP. That
64
- * makes the value **non-empty** and forbids a trailing space, so `vendor=`
65
- * is not a valid member.
66
- */
67
- const TRACESTATE_VALUE =
68
- /^[\x20-\x2B\x2D-\x3C\x3E-\x7E]{0,255}[\x21-\x2B\x2D-\x3C\x3E-\x7E]$/;
69
-
70
- /**
71
- * The grammar's optional whitespace around a list member is SP and HTAB only.
72
- * `String.trim()` also eats CR, LF, FF, VT and Unicode spaces — none of which
73
- * are legal separators here, so trimming with it would silently accept a
74
- * malformed list.
75
- */
76
- function trimOws(member: string): string {
77
- return member.replace(/^[ \t]+/, "").replace(/[ \t]+$/, "");
78
- }
79
-
80
- /**
81
- * `tracestate` carried to the next hop.
82
- *
83
- * `@opentelemetry/api` declares the interface but ships no implementation —
84
- * that lives in `@opentelemetry/core`. Pulling in the SDK package for one
85
- * key/value list would put a second OTel dependency in the public API, so this
86
- * is the minimum that satisfies the interface.
87
- *
88
- * Members are validated against the W3C ABNF rather than passed through: the
89
- * spec permits discarding invalid entries, and this list is re-serialised onto
90
- * the next hop — accepting a malformed member here means emitting a malformed
91
- * `tracestate` downstream, turning one peer's bug into ours.
92
- */
93
- class ListTraceState implements TraceState {
94
- readonly #entries: ReadonlyArray<readonly [string, string]>;
95
-
96
- constructor(entries: ReadonlyArray<readonly [string, string]>) {
97
- this.#entries = entries;
98
- }
99
-
100
- static #isValid(key: string, value: string): boolean {
101
- return TRACESTATE_KEY.test(key) && TRACESTATE_VALUE.test(value);
102
- }
103
-
104
- static parse(raw: string): ListTraceState | undefined {
105
- const seen = new Set<string>();
106
- const entries: Array<readonly [string, string]> = [];
107
-
108
- for (const member of raw.split(",")) {
109
- // Optional whitespace around a list member is part of the grammar; the
110
- // key and value themselves are matched exactly.
111
- const trimmed = trimOws(member);
112
- if (trimmed.length === 0) continue;
113
-
114
- const at = trimmed.indexOf("=");
115
- if (at <= 0) continue;
116
-
117
- const key = trimmed.slice(0, at);
118
- const value = trimmed.slice(at + 1);
119
- // Duplicate keys are invalid; the first occurrence is the live one.
120
- if (seen.has(key)) continue;
121
- if (!ListTraceState.#isValid(key, value)) continue;
122
-
123
- seen.add(key);
124
- entries.push([key, value]);
125
- if (entries.length === TRACESTATE_MAX_MEMBERS) break;
126
- }
127
-
128
- return entries.length > 0 ? new ListTraceState(entries) : undefined;
129
- }
130
-
131
- get(key: string): string | undefined {
132
- return this.#entries.find(([k]) => k === key)?.[1];
133
- }
134
-
135
- set(key: string, value: string): TraceState {
136
- // Returns the state unchanged rather than throwing. The OpenTelemetry
137
- // specification is explicit that "API methods MUST NOT throw unhandled
138
- // exceptions when used incorrectly by end users" — telemetry is not worth
139
- // taking an application down for. Rejecting the mutation still keeps the
140
- // invalid member off the wire, which is the property that matters.
141
- if (!ListTraceState.#isValid(key, value)) return this;
142
- // W3C: a mutated key moves to the front of the list.
143
- return new ListTraceState([
144
- [key, value] as const,
145
- ...this.#entries.filter(([k]) => k !== key),
146
- ].slice(0, TRACESTATE_MAX_MEMBERS));
147
- }
148
-
149
- unset(key: string): TraceState {
150
- return new ListTraceState(this.#entries.filter(([k]) => k !== key));
151
- }
152
-
153
- serialize(): string {
154
- return this.#entries.map(([k, v]) => `${k}=${v}`).join(",");
155
- }
156
- }
157
-
158
- /**
159
- * Parse a W3C trace context into an OTel `SpanContext` (spec 2026-07-28).
160
- *
161
- * The revision documents `traceparent` / `tracestate` / `baggage` as `_meta`
162
- * keys so a tool call joins the caller's trace instead of starting a detached
163
- * one. Returns `undefined` for anything malformed — a bad header leaves the span
164
- * unparented, it never fails the call.
165
- *
166
- * Version handling follows the W3C forward-compatibility rule, which is not
167
- * "reject anything unfamiliar":
168
- *
169
- * - `ff` is forbidden outright.
170
- * - `00` is a fixed 55-character format; anything longer is malformed.
171
- * - a higher version MAY carry fields this implementation does not know. The
172
- * receiver parses the first 55 characters and ignores the rest, provided the
173
- * next character is a `-`. Rejecting those would make this server drop trace
174
- * context the day a new version ships — the exact breakage the rule exists to
175
- * prevent.
176
- */
177
- export function parseTraceParent(
178
- traceparent: unknown,
179
- tracestate?: unknown,
180
- ): SpanContext | undefined {
181
- if (typeof traceparent !== "string") return undefined;
182
- if (traceparent.length < TRACEPARENT_PREFIX_LENGTH) return undefined;
183
-
184
- const match = TRACEPARENT.exec(traceparent);
185
- if (!match) return undefined;
186
-
187
- const [, version, traceId, spanId, flags] = match;
188
- if (version === "ff") return undefined;
189
-
190
- if (version === "00") {
191
- if (traceparent.length !== TRACEPARENT_PREFIX_LENGTH) return undefined;
192
- } else if (
193
- traceparent.length > TRACEPARENT_PREFIX_LENGTH &&
194
- traceparent[TRACEPARENT_PREFIX_LENGTH] !== "-"
195
- ) {
196
- // Longer, but not a well-formed continuation: the extra characters are not
197
- // a new field, so the whole header is suspect.
198
- return undefined;
199
- }
200
-
201
- if (traceId === INVALID_TRACE_ID || spanId === INVALID_SPAN_ID) {
202
- return undefined;
203
- }
204
-
205
- const traceState = typeof tracestate === "string"
206
- ? ListTraceState.parse(tracestate)
207
- : undefined;
208
-
209
- return {
210
- traceId,
211
- spanId,
212
- // Only the sampled bit is defined; the rest of the byte is reserved.
213
- traceFlags: (parseInt(flags, 16) & TraceFlags.SAMPLED) as TraceFlags,
214
- isRemote: true,
215
- ...(traceState ? { traceState } : {}),
216
- };
217
- }
218
-
219
- /**
220
- * The OTel context a remote `SpanContext` should parent, or the active one.
221
- *
222
- * Note the fallback is the *active* context, not `ROOT_CONTEXT`: with no
223
- * caller-supplied trace context the span attaches to whatever span is active in
224
- * this process, and only becomes a root when there is none. That is the right
225
- * default — it preserves in-process nesting — but it means "no traceparent" and
226
- * "root span" are not synonyms.
227
- */
228
- function parentContext(remote?: SpanContext): Context {
229
- const active = otelContext.active();
230
- return remote ? trace.setSpanContext(active, remote) : active;
231
- }
232
-
233
- /**
234
- * Get or create the MCP server tracer
235
- */
236
- export function getServerTracer(): Tracer {
237
- if (!serverTracer) {
238
- serverTracer = trace.getTracer("mcp.server", "0.8.0");
239
- }
240
- return serverTracer;
241
- }
242
-
243
- /**
244
- * Span attributes for MCP tool calls
245
- */
246
- export interface ToolCallSpanAttributes {
247
- "mcp.tool.name": string;
248
- "mcp.server.name"?: string;
249
- "mcp.transport"?: string;
250
- "mcp.session.id"?: string;
251
- "mcp.auth.subject"?: string;
252
- "mcp.auth.client_id"?: string;
253
- [key: string]: string | number | boolean | undefined;
254
- }
255
-
256
- /**
257
- * Start a span for a tool call.
258
- * Caller MUST call span.end() when done.
259
- *
260
- * `remoteParent` is the caller's trace context, read from the request's `_meta`
261
- * (spec 2026-07-28). With it the span joins the caller's trace; without it the
262
- * span falls back to the active context, which is what every call produced
263
- * before the `_meta` keys were wired in — a server-side trace nobody could
264
- * correlate to the client that caused it.
265
- */
266
- export function startToolCallSpan(
267
- toolName: string,
268
- attributes: ToolCallSpanAttributes,
269
- remoteParent?: SpanContext,
270
- ): Span {
271
- const tracer = getServerTracer();
272
- return tracer.startSpan(
273
- `mcp.tool.call ${toolName}`,
274
- { attributes },
275
- parentContext(remoteParent),
276
- );
277
- }
278
-
279
- /**
280
- * Record a tool call result on a span and end it.
281
- */
282
- export function endToolCallSpan(
283
- span: Span,
284
- success: boolean,
285
- durationMs: number,
286
- error?: string,
287
- ): void {
288
- span.setAttribute("mcp.tool.duration_ms", durationMs);
289
- span.setAttribute("mcp.tool.success", success);
290
-
291
- if (error) {
292
- span.setAttribute("mcp.tool.error", error);
293
- span.recordException(new Error(error));
294
- }
295
-
296
- span.setStatus({
297
- code: success ? SpanStatusCode.OK : SpanStatusCode.ERROR,
298
- message: error,
299
- });
300
- span.end();
301
- }
302
-
303
- /**
304
- * Record an auth event as a fire-and-forget span.
305
- */
306
- export function recordAuthEvent(
307
- event: "verify" | "reject" | "cache_hit",
308
- attributes: Record<string, string | number | boolean | undefined>,
309
- ): void {
310
- const tracer = getServerTracer();
311
- tracer.startActiveSpan(`mcp.auth.${event}`, { attributes }, (span) => {
312
- span.setStatus({
313
- code: event === "reject" ? SpanStatusCode.ERROR : SpanStatusCode.OK,
314
- });
315
- span.end();
316
- });
317
- }
318
-
319
- /**
320
- * Check if OTEL is enabled.
321
- * Deno: OTEL_DENO=true | Node.js: OTEL_ENABLED=true
322
- */
323
- export function isOtelEnabled(): boolean {
324
- try {
325
- return env("OTEL_DENO") === "true" || env("OTEL_ENABLED") === "true";
326
- } catch {
327
- // Deno without --allow-env throws NotCapable
328
- return false;
329
- }
330
- }