@frontmcp/sdk 0.5.0 → 0.6.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 (226) hide show
  1. package/README.md +3 -3
  2. package/package.json +8 -19
  3. package/src/adapter/adapter.instance.js +5 -0
  4. package/src/adapter/adapter.instance.js.map +1 -1
  5. package/src/auth/authorization/authorization.class.d.ts +1 -4
  6. package/src/auth/authorization/authorization.class.js +6 -13
  7. package/src/auth/authorization/authorization.class.js.map +1 -1
  8. package/src/auth/flows/session.verify.flow.d.ts +1 -0
  9. package/src/auth/flows/session.verify.flow.js +11 -1
  10. package/src/auth/flows/session.verify.flow.js.map +1 -1
  11. package/src/auth/flows/well-known.jwks.flow.js +2 -2
  12. package/src/auth/flows/well-known.jwks.flow.js.map +1 -1
  13. package/src/auth/jwks/dev-key-persistence.d.ts +63 -0
  14. package/src/auth/jwks/dev-key-persistence.js +219 -0
  15. package/src/auth/jwks/dev-key-persistence.js.map +1 -0
  16. package/src/auth/jwks/index.d.ts +1 -0
  17. package/src/auth/jwks/index.js +1 -0
  18. package/src/auth/jwks/index.js.map +1 -1
  19. package/src/auth/jwks/jwks.service.d.ts +7 -4
  20. package/src/auth/jwks/jwks.service.js +81 -12
  21. package/src/auth/jwks/jwks.service.js.map +1 -1
  22. package/src/auth/jwks/jwks.types.d.ts +7 -0
  23. package/src/auth/jwks/jwks.types.js.map +1 -1
  24. package/src/auth/machine-id.d.ts +5 -0
  25. package/src/auth/machine-id.js +32 -0
  26. package/src/auth/machine-id.js.map +1 -0
  27. package/src/auth/session/index.d.ts +1 -0
  28. package/src/auth/session/index.js +3 -1
  29. package/src/auth/session/index.js.map +1 -1
  30. package/src/auth/session/record/session.base.js +5 -3
  31. package/src/auth/session/record/session.base.js.map +1 -1
  32. package/src/auth/session/record/session.stateless.d.ts +2 -2
  33. package/src/auth/session/record/session.stateless.js +5 -3
  34. package/src/auth/session/record/session.stateless.js.map +1 -1
  35. package/src/auth/session/redis-session.store.d.ts +64 -0
  36. package/src/auth/session/redis-session.store.js +204 -0
  37. package/src/auth/session/redis-session.store.js.map +1 -0
  38. package/src/auth/session/session.service.d.ts +0 -2
  39. package/src/auth/session/session.service.js +1 -7
  40. package/src/auth/session/session.service.js.map +1 -1
  41. package/src/auth/session/transport-session.manager.js +3 -5
  42. package/src/auth/session/transport-session.manager.js.map +1 -1
  43. package/src/auth/session/transport-session.types.d.ts +4 -0
  44. package/src/auth/session/transport-session.types.js +4 -3
  45. package/src/auth/session/transport-session.types.js.map +1 -1
  46. package/src/auth/session/utils/session-id.utils.d.ts +12 -1
  47. package/src/auth/session/utils/session-id.utils.js +48 -9
  48. package/src/auth/session/utils/session-id.utils.js.map +1 -1
  49. package/src/auth/ui/base-layout.d.ts +0 -8
  50. package/src/auth/ui/base-layout.js +1 -14
  51. package/src/auth/ui/base-layout.js.map +1 -1
  52. package/src/auth/ui/index.d.ts +3 -4
  53. package/src/auth/ui/index.js +10 -11
  54. package/src/auth/ui/index.js.map +1 -1
  55. package/src/auth/ui/{htmx-templates.d.ts → templates.d.ts} +5 -6
  56. package/src/auth/ui/{htmx-templates.js → templates.js} +8 -15
  57. package/src/auth/ui/templates.js.map +1 -0
  58. package/src/common/decorators/decorator-utils.js.map +1 -1
  59. package/src/common/decorators/front-mcp.decorator.js +28 -2
  60. package/src/common/decorators/front-mcp.decorator.js.map +1 -1
  61. package/src/common/index.d.ts +0 -1
  62. package/src/common/index.js +0 -1
  63. package/src/common/index.js.map +1 -1
  64. package/src/common/interfaces/adapter.interface.d.ts +6 -0
  65. package/src/common/interfaces/adapter.interface.js.map +1 -1
  66. package/src/common/interfaces/execution-context.interface.d.ts +52 -3
  67. package/src/common/interfaces/execution-context.interface.js +88 -3
  68. package/src/common/interfaces/execution-context.interface.js.map +1 -1
  69. package/src/common/interfaces/flow.interface.d.ts +13 -0
  70. package/src/common/interfaces/flow.interface.js +24 -0
  71. package/src/common/interfaces/flow.interface.js.map +1 -1
  72. package/src/common/interfaces/server.interface.d.ts +9 -0
  73. package/src/common/interfaces/server.interface.js.map +1 -1
  74. package/src/common/metadata/app.metadata.d.ts +108 -0
  75. package/src/common/metadata/front-mcp.metadata.d.ts +659 -2
  76. package/src/common/metadata/front-mcp.metadata.js +3 -1
  77. package/src/common/metadata/front-mcp.metadata.js.map +1 -1
  78. package/src/common/metadata/provider.metadata.d.ts +14 -0
  79. package/src/common/metadata/provider.metadata.js +18 -2
  80. package/src/common/metadata/provider.metadata.js.map +1 -1
  81. package/src/common/metadata/tool.metadata.d.ts +33 -1
  82. package/src/common/metadata/tool.metadata.js.map +1 -1
  83. package/src/common/migrate/auth-transport.migrate.d.ts +62 -0
  84. package/src/common/migrate/auth-transport.migrate.js +140 -0
  85. package/src/common/migrate/auth-transport.migrate.js.map +1 -0
  86. package/src/common/migrate/index.d.ts +1 -0
  87. package/src/common/migrate/index.js +6 -0
  88. package/src/common/migrate/index.js.map +1 -0
  89. package/src/common/schemas/http-output.schema.d.ts +10 -2
  90. package/src/common/schemas/index.d.ts +1 -0
  91. package/src/common/schemas/index.js +1 -0
  92. package/src/common/schemas/index.js.map +1 -1
  93. package/src/common/schemas/session-header.schema.d.ts +16 -0
  94. package/src/common/schemas/session-header.schema.js +42 -0
  95. package/src/common/schemas/session-header.schema.js.map +1 -0
  96. package/src/common/tokens/front-mcp.tokens.js +3 -1
  97. package/src/common/tokens/front-mcp.tokens.js.map +1 -1
  98. package/src/common/types/options/auth.options.d.ts +233 -3
  99. package/src/common/types/options/auth.options.js +29 -40
  100. package/src/common/types/options/auth.options.js.map +1 -1
  101. package/src/common/types/options/index.d.ts +2 -0
  102. package/src/common/types/options/index.js +2 -0
  103. package/src/common/types/options/index.js.map +1 -1
  104. package/src/common/types/options/redis.options.d.ts +22 -0
  105. package/src/common/types/options/redis.options.js +45 -0
  106. package/src/common/types/options/redis.options.js.map +1 -0
  107. package/src/common/types/options/transport.options.d.ts +84 -0
  108. package/src/common/types/options/transport.options.js +121 -0
  109. package/src/common/types/options/transport.options.js.map +1 -0
  110. package/src/completion/flows/complete.flow.d.ts +17 -2
  111. package/src/context/frontmcp-context-storage.d.ts +94 -0
  112. package/src/context/frontmcp-context-storage.js +183 -0
  113. package/src/context/frontmcp-context-storage.js.map +1 -0
  114. package/src/context/frontmcp-context.d.ts +269 -0
  115. package/src/context/frontmcp-context.js +360 -0
  116. package/src/context/frontmcp-context.js.map +1 -0
  117. package/src/context/frontmcp-context.provider.d.ts +43 -0
  118. package/src/context/frontmcp-context.provider.js +61 -0
  119. package/src/context/frontmcp-context.provider.js.map +1 -0
  120. package/src/context/index.d.ts +34 -0
  121. package/src/context/index.js +64 -0
  122. package/src/context/index.js.map +1 -0
  123. package/src/context/request-context-storage.d.ts +89 -0
  124. package/src/context/request-context-storage.js +183 -0
  125. package/src/context/request-context-storage.js.map +1 -0
  126. package/src/context/request-context.d.ts +184 -0
  127. package/src/context/request-context.js +209 -0
  128. package/src/context/request-context.js.map +1 -0
  129. package/src/context/request-context.provider.d.ts +37 -0
  130. package/src/context/request-context.provider.js +51 -0
  131. package/src/context/request-context.provider.js.map +1 -0
  132. package/src/context/session-key.provider.d.ts +45 -0
  133. package/src/context/session-key.provider.js +65 -0
  134. package/src/context/session-key.provider.js.map +1 -0
  135. package/src/context/trace-context.d.ts +43 -0
  136. package/src/context/trace-context.js +142 -0
  137. package/src/context/trace-context.js.map +1 -0
  138. package/src/errors/index.d.ts +1 -1
  139. package/src/errors/index.js +3 -1
  140. package/src/errors/index.js.map +1 -1
  141. package/src/errors/mcp.error.d.ts +7 -0
  142. package/src/errors/mcp.error.js +11 -1
  143. package/src/errors/mcp.error.js.map +1 -1
  144. package/src/flows/flow.instance.d.ts +16 -0
  145. package/src/flows/flow.instance.js +166 -80
  146. package/src/flows/flow.instance.js.map +1 -1
  147. package/src/flows/flow.registry.d.ts +5 -0
  148. package/src/flows/flow.registry.js +45 -3
  149. package/src/flows/flow.registry.js.map +1 -1
  150. package/src/front-mcp/front-mcp.d.ts +12 -0
  151. package/src/front-mcp/front-mcp.js +22 -3
  152. package/src/front-mcp/front-mcp.js.map +1 -1
  153. package/src/front-mcp/front-mcp.providers.d.ts +266 -1
  154. package/src/front-mcp/front-mcp.providers.js +2 -1
  155. package/src/front-mcp/front-mcp.providers.js.map +1 -1
  156. package/src/front-mcp/serverless-handler.d.ts +28 -0
  157. package/src/front-mcp/serverless-handler.js +61 -0
  158. package/src/front-mcp/serverless-handler.js.map +1 -0
  159. package/src/hooks/hooks.utils.d.ts +1 -1
  160. package/src/hooks/hooks.utils.js +10 -3
  161. package/src/hooks/hooks.utils.js.map +1 -1
  162. package/src/index.d.ts +8 -4
  163. package/src/index.js +20 -1
  164. package/src/index.js.map +1 -1
  165. package/src/logger/instances/instance.logger.js +0 -1
  166. package/src/logger/instances/instance.logger.js.map +1 -1
  167. package/src/logging/flows/set-level.flow.d.ts +17 -2
  168. package/src/notification/notification.service.js +5 -1
  169. package/src/notification/notification.service.js.map +1 -1
  170. package/src/prompt/flows/get-prompt.flow.d.ts +97 -2
  171. package/src/prompt/flows/prompts-list.flow.d.ts +12 -1
  172. package/src/provider/provider.registry.d.ts +97 -5
  173. package/src/provider/provider.registry.js +306 -9
  174. package/src/provider/provider.registry.js.map +1 -1
  175. package/src/provider/provider.types.d.ts +21 -3
  176. package/src/provider/provider.types.js.map +1 -1
  177. package/src/resource/flows/read-resource.flow.d.ts +22 -3
  178. package/src/resource/flows/resource-templates-list.flow.d.ts +20 -1
  179. package/src/resource/flows/resources-list.flow.d.ts +20 -1
  180. package/src/resource/flows/subscribe-resource.flow.d.ts +17 -2
  181. package/src/resource/flows/unsubscribe-resource.flow.d.ts +17 -2
  182. package/src/scope/flows/http.request.flow.js +43 -7
  183. package/src/scope/flows/http.request.flow.js.map +1 -1
  184. package/src/scope/scope.instance.js +12 -5
  185. package/src/scope/scope.instance.js.map +1 -1
  186. package/src/server/adapters/base.host.adapter.d.ts +9 -0
  187. package/src/server/adapters/base.host.adapter.js.map +1 -1
  188. package/src/server/adapters/express.host.adapter.d.ts +12 -0
  189. package/src/server/adapters/express.host.adapter.js +21 -1
  190. package/src/server/adapters/express.host.adapter.js.map +1 -1
  191. package/src/server/server.instance.d.ts +3 -0
  192. package/src/server/server.instance.js +14 -7
  193. package/src/server/server.instance.js.map +1 -1
  194. package/src/tool/flows/call-tool.flow.d.ts +118 -13
  195. package/src/tool/flows/call-tool.flow.js +240 -194
  196. package/src/tool/flows/call-tool.flow.js.map +1 -1
  197. package/src/tool/flows/tools-list.flow.d.ts +25 -11
  198. package/src/tool/flows/tools-list.flow.js +82 -31
  199. package/src/tool/flows/tools-list.flow.js.map +1 -1
  200. package/src/tool/tool.instance.d.ts +1 -4
  201. package/src/transport/adapters/transport.streamable-http.adapter.js +1 -0
  202. package/src/transport/adapters/transport.streamable-http.adapter.js.map +1 -1
  203. package/src/transport/flows/handle.sse.flow.js +9 -2
  204. package/src/transport/flows/handle.sse.flow.js.map +1 -1
  205. package/src/transport/flows/handle.streamable-http.flow.js +63 -6
  206. package/src/transport/flows/handle.streamable-http.flow.js.map +1 -1
  207. package/src/transport/mcp-handlers/complete-request.handler.d.ts +27 -1
  208. package/src/transport/mcp-handlers/get-prompt-request.handler.d.ts +52 -1
  209. package/src/transport/mcp-handlers/index.d.ts +413 -7
  210. package/src/transport/mcp-handlers/initialize-request.handler.js +12 -2
  211. package/src/transport/mcp-handlers/initialize-request.handler.js.map +1 -1
  212. package/src/transport/mcp-handlers/list-prompts-request.handler.d.ts +27 -1
  213. package/src/transport/mcp-handlers/list-resource-templates-request.handler.d.ts +32 -1
  214. package/src/transport/mcp-handlers/list-resources-request.handler.d.ts +32 -1
  215. package/src/transport/mcp-handlers/list-tools-request.handler.d.ts +30 -1
  216. package/src/transport/mcp-handlers/logging-set-level-request.handler.d.ts +20 -0
  217. package/src/transport/mcp-handlers/read-resource-request.handler.d.ts +27 -1
  218. package/src/transport/mcp-handlers/subscribe-request.handler.d.ts +20 -0
  219. package/src/transport/mcp-handlers/unsubscribe-request.handler.d.ts +20 -0
  220. package/src/transport/transport.registry.d.ts +68 -4
  221. package/src/transport/transport.registry.js +313 -11
  222. package/src/transport/transport.registry.js.map +1 -1
  223. package/src/auth/ui/htmx-templates.js.map +0 -1
  224. package/src/common/providers/session.provider.d.ts +0 -13
  225. package/src/common/providers/session.provider.js +0 -27
  226. package/src/common/providers/session.provider.js.map +0 -1
@@ -0,0 +1,183 @@
1
+ "use strict";
2
+ /**
3
+ * FrontMcpContextStorage - AsyncLocalStorage wrapper for unified context
4
+ *
5
+ * Provides concurrent-safe context propagation using Node.js AsyncLocalStorage.
6
+ * Access through DI only - never use static imports to access the storage directly.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * // In a flow or middleware
11
+ * const storage = this.get(FrontMcpContextStorage);
12
+ * await storage.runFromHeaders(request.headers, {
13
+ * sessionId: sessionId,
14
+ * scopeId: scope.id,
15
+ * }, async () => {
16
+ * // All code here can access the context via DI
17
+ * const ctx = this.get(FRONTMCP_CONTEXT);
18
+ * });
19
+ * ```
20
+ */
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.ContextStorage = exports.FrontMcpContextStorage = void 0;
23
+ const tslib_1 = require("tslib");
24
+ const node_async_hooks_1 = require("node:async_hooks");
25
+ const decorators_1 = require("../common/decorators");
26
+ const metadata_1 = require("../common/metadata");
27
+ const frontmcp_context_1 = require("./frontmcp-context");
28
+ const trace_context_1 = require("./trace-context");
29
+ const mcp_error_1 = require("../errors/mcp.error");
30
+ /**
31
+ * Module-level AsyncLocalStorage instance.
32
+ *
33
+ * This is the ONLY place where the storage is created.
34
+ * Access should be through DI, not through static imports.
35
+ */
36
+ const frontmcpContextStorage = new node_async_hooks_1.AsyncLocalStorage();
37
+ /**
38
+ * FrontMcpContextStorage provides unified context via AsyncLocalStorage.
39
+ *
40
+ * This is a GLOBAL-scoped provider because it manages the storage itself,
41
+ * not the per-context data. The actual FrontMcpContext is accessed via
42
+ * the FRONTMCP_CONTEXT token which is CONTEXT-scoped.
43
+ */
44
+ let FrontMcpContextStorage = class FrontMcpContextStorage {
45
+ /**
46
+ * Run a callback with a new FrontMcpContext.
47
+ *
48
+ * @param args - Arguments to create the context
49
+ * @param fn - Async function to run with the context
50
+ * @returns Result of the callback
51
+ */
52
+ run(args, fn) {
53
+ const context = new frontmcp_context_1.FrontMcpContext(args);
54
+ return frontmcpContextStorage.run(context, fn);
55
+ }
56
+ /**
57
+ * Run with context extracted from HTTP headers.
58
+ *
59
+ * Automatically parses trace context from headers using W3C Trace Context
60
+ * specification with fallback to x-frontmcp-trace-id.
61
+ *
62
+ * @param headers - HTTP headers
63
+ * @param args - Additional context args (sessionId, scopeId)
64
+ * @param fn - Async function to run
65
+ * @returns Result of the callback
66
+ */
67
+ runFromHeaders(headers, args, fn) {
68
+ const traceContext = (0, trace_context_1.parseTraceContext)(headers);
69
+ const metadata = extractMetadata(headers);
70
+ const context = new frontmcp_context_1.FrontMcpContext({
71
+ ...args,
72
+ traceContext,
73
+ metadata,
74
+ });
75
+ return frontmcpContextStorage.run(context, fn);
76
+ }
77
+ /**
78
+ * Run with an existing FrontMcpContext.
79
+ *
80
+ * Useful when you need to propagate an existing context to a new async scope.
81
+ *
82
+ * @param context - Existing FrontMcpContext
83
+ * @param fn - Async function to run
84
+ * @returns Result of the callback
85
+ */
86
+ runWithContext(context, fn) {
87
+ return frontmcpContextStorage.run(context, fn);
88
+ }
89
+ /**
90
+ * Get the current FrontMcpContext.
91
+ *
92
+ * @returns Current context or undefined if not in a context scope
93
+ */
94
+ getStore() {
95
+ return frontmcpContextStorage.getStore();
96
+ }
97
+ /**
98
+ * Get the current FrontMcpContext, throwing if not available.
99
+ *
100
+ * @throws Error if not in a context scope
101
+ */
102
+ getStoreOrThrow() {
103
+ const ctx = this.getStore();
104
+ if (!ctx) {
105
+ throw new mcp_error_1.RequestContextNotAvailableError('FrontMcpContext not available. Ensure operation runs within context scope.');
106
+ }
107
+ return ctx;
108
+ }
109
+ /**
110
+ * Check if currently running within a context.
111
+ *
112
+ * @returns True if a FrontMcpContext is available
113
+ */
114
+ hasContext() {
115
+ return frontmcpContextStorage.getStore() !== undefined;
116
+ }
117
+ /**
118
+ * Update the authInfo in the current context.
119
+ *
120
+ * This mutates the existing context in place to preserve internal state
121
+ * (marks, store, sessionMetadata) while updating auth info.
122
+ *
123
+ * @param authInfo - Auth info fields to set/update (merged with existing)
124
+ * @param fn - Function to run after update
125
+ * @returns Result of the callback
126
+ */
127
+ updateAuthInfo(authInfo, fn) {
128
+ const current = this.getStoreOrThrow();
129
+ current.updateAuthInfo(authInfo);
130
+ return fn();
131
+ }
132
+ };
133
+ exports.FrontMcpContextStorage = FrontMcpContextStorage;
134
+ exports.ContextStorage = FrontMcpContextStorage;
135
+ exports.ContextStorage = exports.FrontMcpContextStorage = FrontMcpContextStorage = tslib_1.__decorate([
136
+ (0, decorators_1.Provider)({
137
+ name: 'FrontMcpContextStorage',
138
+ description: 'Manages unified context via AsyncLocalStorage',
139
+ scope: metadata_1.ProviderScope.GLOBAL,
140
+ })
141
+ ], FrontMcpContextStorage);
142
+ /**
143
+ * Extract request metadata from headers.
144
+ */
145
+ function extractMetadata(headers) {
146
+ const customHeaders = {};
147
+ for (const [key, value] of Object.entries(headers)) {
148
+ if (key.toLowerCase().startsWith('x-frontmcp-') && typeof value === 'string') {
149
+ customHeaders[key.toLowerCase()] = value;
150
+ }
151
+ }
152
+ return {
153
+ userAgent: typeof headers['user-agent'] === 'string' ? headers['user-agent'] : undefined,
154
+ contentType: typeof headers['content-type'] === 'string' ? headers['content-type'] : undefined,
155
+ accept: typeof headers['accept'] === 'string' ? headers['accept'] : undefined,
156
+ clientIp: extractClientIp(headers),
157
+ customHeaders,
158
+ };
159
+ }
160
+ /**
161
+ * Extract client IP from headers.
162
+ * Handles both string and array header values (some adapters pass arrays).
163
+ */
164
+ function extractClientIp(headers) {
165
+ // x-forwarded-for can be comma-separated list; first is client IP
166
+ const xff = headers['x-forwarded-for'];
167
+ if (typeof xff === 'string') {
168
+ return xff.split(',')[0]?.trim();
169
+ }
170
+ // Some adapters pass arrays for multi-value headers
171
+ if (Array.isArray(xff) && typeof xff[0] === 'string') {
172
+ return xff[0].split(',')[0]?.trim();
173
+ }
174
+ const realIp = headers['x-real-ip'];
175
+ if (typeof realIp === 'string') {
176
+ return realIp;
177
+ }
178
+ if (Array.isArray(realIp) && typeof realIp[0] === 'string') {
179
+ return realIp[0];
180
+ }
181
+ return undefined;
182
+ }
183
+ //# sourceMappingURL=frontmcp-context-storage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"frontmcp-context-storage.js","sourceRoot":"","sources":["../../../src/context/frontmcp-context-storage.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;GAkBG;;;;AAEH,uDAAqD;AACrD,qDAAgD;AAChD,iDAAmD;AACnD,yDAA2F;AAC3F,mDAAoD;AAEpD,mDAAsE;AAEtE;;;;;GAKG;AACH,MAAM,sBAAsB,GAAG,IAAI,oCAAiB,EAAmB,CAAC;AAExE;;;;;;GAMG;AAMI,IAAM,sBAAsB,GAA5B,MAAM,sBAAsB;IACjC;;;;;;OAMG;IACH,GAAG,CAAI,IAAyB,EAAE,EAAwB;QACxD,MAAM,OAAO,GAAG,IAAI,kCAAe,CAAC,IAAI,CAAC,CAAC;QAC1C,OAAO,sBAAsB,CAAC,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;IACjD,CAAC;IAED;;;;;;;;;;OAUG;IACH,cAAc,CACZ,OAAgC,EAChC,IAA4D,EAC5D,EAAwB;QAExB,MAAM,YAAY,GAAG,IAAA,iCAAiB,EAAC,OAAO,CAAC,CAAC;QAChD,MAAM,QAAQ,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;QAC1C,MAAM,OAAO,GAAG,IAAI,kCAAe,CAAC;YAClC,GAAG,IAAI;YACP,YAAY;YACZ,QAAQ;SACT,CAAC,CAAC;QACH,OAAO,sBAAsB,CAAC,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC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CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,OAAO,MAAM,CAAC,CAAC,CAAC,KAAK,QAAQ,EAAE,CAAC;QAC3D,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC;IACnB,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["/**\n * FrontMcpContextStorage - AsyncLocalStorage wrapper for unified context\n *\n * Provides concurrent-safe context propagation using Node.js AsyncLocalStorage.\n * Access through DI only - never use static imports to access the storage directly.\n *\n * @example\n * ```typescript\n * // In a flow or middleware\n * const storage = this.get(FrontMcpContextStorage);\n * await storage.runFromHeaders(request.headers, {\n * sessionId: sessionId,\n * scopeId: scope.id,\n * }, async () => {\n * // All code here can access the context via DI\n * const ctx = this.get(FRONTMCP_CONTEXT);\n * });\n * ```\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { Provider } from '../common/decorators';\nimport { ProviderScope } from '../common/metadata';\nimport { FrontMcpContext, FrontMcpContextArgs, RequestMetadata } from './frontmcp-context';\nimport { parseTraceContext } from './trace-context';\nimport { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';\nimport { RequestContextNotAvailableError } from '../errors/mcp.error';\n\n/**\n * Module-level AsyncLocalStorage instance.\n *\n * This is the ONLY place where the storage is created.\n * Access should be through DI, not through static imports.\n */\nconst frontmcpContextStorage = new AsyncLocalStorage<FrontMcpContext>();\n\n/**\n * FrontMcpContextStorage provides unified context via AsyncLocalStorage.\n *\n * This is a GLOBAL-scoped provider because it manages the storage itself,\n * not the per-context data. The actual FrontMcpContext is accessed via\n * the FRONTMCP_CONTEXT token which is CONTEXT-scoped.\n */\n@Provider({\n name: 'FrontMcpContextStorage',\n description: 'Manages unified context via AsyncLocalStorage',\n scope: ProviderScope.GLOBAL,\n})\nexport class FrontMcpContextStorage {\n /**\n * Run a callback with a new FrontMcpContext.\n *\n * @param args - Arguments to create the context\n * @param fn - Async function to run with the context\n * @returns Result of the callback\n */\n run<T>(args: FrontMcpContextArgs, fn: () => T | Promise<T>): T | Promise<T> {\n const context = new FrontMcpContext(args);\n return frontmcpContextStorage.run(context, fn);\n }\n\n /**\n * Run with context extracted from HTTP headers.\n *\n * Automatically parses trace context from headers using W3C Trace Context\n * specification with fallback to x-frontmcp-trace-id.\n *\n * @param headers - HTTP headers\n * @param args - Additional context args (sessionId, scopeId)\n * @param fn - Async function to run\n * @returns Result of the callback\n */\n runFromHeaders<T>(\n headers: Record<string, unknown>,\n args: Omit<FrontMcpContextArgs, 'traceContext' | 'metadata'>,\n fn: () => T | Promise<T>,\n ): T | Promise<T> {\n const traceContext = parseTraceContext(headers);\n const metadata = extractMetadata(headers);\n const context = new FrontMcpContext({\n ...args,\n traceContext,\n metadata,\n });\n return frontmcpContextStorage.run(context, fn);\n }\n\n /**\n * Run with an existing FrontMcpContext.\n *\n * Useful when you need to propagate an existing context to a new async scope.\n *\n * @param context - Existing FrontMcpContext\n * @param fn - Async function to run\n * @returns Result of the callback\n */\n runWithContext<T>(context: FrontMcpContext, fn: () => T | Promise<T>): T | Promise<T> {\n return frontmcpContextStorage.run(context, fn);\n }\n\n /**\n * Get the current FrontMcpContext.\n *\n * @returns Current context or undefined if not in a context scope\n */\n getStore(): FrontMcpContext | undefined {\n return frontmcpContextStorage.getStore();\n }\n\n /**\n * Get the current FrontMcpContext, throwing if not available.\n *\n * @throws Error if not in a context scope\n */\n getStoreOrThrow(): FrontMcpContext {\n const ctx = this.getStore();\n if (!ctx) {\n throw new RequestContextNotAvailableError(\n 'FrontMcpContext not available. Ensure operation runs within context scope.',\n );\n }\n return ctx;\n }\n\n /**\n * Check if currently running within a context.\n *\n * @returns True if a FrontMcpContext is available\n */\n hasContext(): boolean {\n return frontmcpContextStorage.getStore() !== undefined;\n }\n\n /**\n * Update the authInfo in the current context.\n *\n * This mutates the existing context in place to preserve internal state\n * (marks, store, sessionMetadata) while updating auth info.\n *\n * @param authInfo - Auth info fields to set/update (merged with existing)\n * @param fn - Function to run after update\n * @returns Result of the callback\n */\n updateAuthInfo<T>(authInfo: Partial<AuthInfo>, fn: () => T | Promise<T>): T | Promise<T> {\n const current = this.getStoreOrThrow();\n current.updateAuthInfo(authInfo);\n return fn();\n }\n}\n\n/**\n * Extract request metadata from headers.\n */\nfunction extractMetadata(headers: Record<string, unknown>): RequestMetadata {\n const customHeaders: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase().startsWith('x-frontmcp-') && typeof value === 'string') {\n customHeaders[key.toLowerCase()] = value;\n }\n }\n\n return {\n userAgent: typeof headers['user-agent'] === 'string' ? headers['user-agent'] : undefined,\n contentType: typeof headers['content-type'] === 'string' ? headers['content-type'] : undefined,\n accept: typeof headers['accept'] === 'string' ? headers['accept'] : undefined,\n clientIp: extractClientIp(headers),\n customHeaders,\n };\n}\n\n/**\n * Extract client IP from headers.\n * Handles both string and array header values (some adapters pass arrays).\n */\nfunction extractClientIp(headers: Record<string, unknown>): string | undefined {\n // x-forwarded-for can be comma-separated list; first is client IP\n const xff = headers['x-forwarded-for'];\n if (typeof xff === 'string') {\n return xff.split(',')[0]?.trim();\n }\n // Some adapters pass arrays for multi-value headers\n if (Array.isArray(xff) && typeof xff[0] === 'string') {\n return xff[0].split(',')[0]?.trim();\n }\n\n const realIp = headers['x-real-ip'];\n if (typeof realIp === 'string') {\n return realIp;\n }\n if (Array.isArray(realIp) && typeof realIp[0] === 'string') {\n return realIp[0];\n }\n\n return undefined;\n}\n\n/**\n * Alias for backward compatibility.\n * @deprecated Use FrontMcpContextStorage instead\n */\nexport { FrontMcpContextStorage as ContextStorage };\n"]}
@@ -0,0 +1,269 @@
1
+ /**
2
+ * FrontMcpContext - Unified context for FrontMCP
3
+ *
4
+ * Single point of truth for all request-related data, combining session and request state.
5
+ * Flows through the entire async execution chain via AsyncLocalStorage.
6
+ *
7
+ * Access via DI using the FRONTMCP_CONTEXT token:
8
+ * ```typescript
9
+ * const ctx = this.get(FRONTMCP_CONTEXT);
10
+ * console.log(ctx.requestId, ctx.sessionId, ctx.authInfo);
11
+ * ```
12
+ */
13
+ import { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';
14
+ import { FrontMcpLogger } from '../common/interfaces/logger.interface';
15
+ import { TraceContext } from './trace-context';
16
+ import type { SessionIdPayload } from '../common/types';
17
+ /**
18
+ * Request metadata extracted from HTTP headers.
19
+ */
20
+ export interface RequestMetadata {
21
+ /** User-Agent header */
22
+ userAgent?: string;
23
+ /** Content-Type header */
24
+ contentType?: string;
25
+ /** Accept header */
26
+ accept?: string;
27
+ /** Client IP address (from x-forwarded-for or socket) */
28
+ clientIp?: string;
29
+ /** Custom headers matching x-frontmcp-* pattern */
30
+ customHeaders: Record<string, string>;
31
+ }
32
+ /**
33
+ * Configuration for the context.
34
+ */
35
+ export interface FrontMcpContextConfig {
36
+ /** Auto-inject auth headers in fetch requests (default: true) */
37
+ autoInjectAuthHeaders?: boolean;
38
+ /** Auto-inject tracing headers in fetch requests (default: true) */
39
+ autoInjectTracingHeaders?: boolean;
40
+ /** Default fetch request timeout in milliseconds (default: 30000) */
41
+ requestTimeout?: number;
42
+ }
43
+ /**
44
+ * Arguments for creating a FrontMcpContext.
45
+ */
46
+ export interface FrontMcpContextArgs {
47
+ /** Optional request ID (generated if not provided) */
48
+ requestId?: string;
49
+ /** Optional trace context (generated if not provided) */
50
+ traceContext?: TraceContext;
51
+ /** Session identifier (required) */
52
+ sessionId: string;
53
+ /** Authentication information (can be partial, progressively populated) */
54
+ authInfo?: Partial<AuthInfo>;
55
+ /** Scope identifier (required) */
56
+ scopeId: string;
57
+ /** Optional timestamp (defaults to Date.now()) */
58
+ timestamp?: number;
59
+ /** Optional request metadata */
60
+ metadata?: RequestMetadata;
61
+ /** Optional configuration */
62
+ config?: FrontMcpContextConfig;
63
+ }
64
+ /**
65
+ * Interface for transport access (elicit support).
66
+ * Provides clean API for accessing transport capabilities.
67
+ */
68
+ export interface TransportAccessor {
69
+ /**
70
+ * Check if transport supports elicit requests.
71
+ */
72
+ readonly supportsElicit: boolean;
73
+ /**
74
+ * Send an elicit request to the client for interactive input.
75
+ *
76
+ * @param message - Message to display to the user
77
+ * @param requestedSchema - Zod schema for validating the response
78
+ * @returns Typed elicit result with action and validated content
79
+ */
80
+ elicit<T>(message: string, requestedSchema: T): Promise<{
81
+ action: string;
82
+ content: unknown;
83
+ }>;
84
+ }
85
+ type FlowBaseRef = {
86
+ readonly name: string;
87
+ };
88
+ type ScopeRef = {
89
+ readonly id: string;
90
+ readonly logger: FrontMcpLogger;
91
+ };
92
+ type TransportRef = {
93
+ sendElicitRequest: TransportAccessor['elicit'];
94
+ readonly type: string;
95
+ };
96
+ /**
97
+ * FrontMcpContext - Unified context for FrontMCP
98
+ *
99
+ * Provides a single point of truth for all request-related data:
100
+ * - Identity: requestId, sessionId, scopeId
101
+ * - Tracing: W3C trace context
102
+ * - Auth: authentication information (progressively populated)
103
+ * - References: transport, flow, scope (pointers, not copies)
104
+ * - Store: key/value storage for context-scoped data
105
+ * - Fetch: context-aware fetch with auto-injection
106
+ */
107
+ export declare class FrontMcpContext {
108
+ /** Unique request identifier (UUID v4) */
109
+ readonly requestId: string;
110
+ /** Session identifier (validated) */
111
+ readonly sessionId: string;
112
+ /** Scope identifier */
113
+ readonly scopeId: string;
114
+ /** W3C Trace Context or generated trace ID */
115
+ readonly traceContext: TraceContext;
116
+ /** Request start timestamp */
117
+ readonly timestamp: number;
118
+ /** Context configuration */
119
+ readonly config: FrontMcpContextConfig;
120
+ /** Request metadata (headers, user-agent, etc.) */
121
+ readonly metadata: RequestMetadata;
122
+ private _authInfo;
123
+ private _sessionMetadata?;
124
+ private _transport?;
125
+ private _flow?;
126
+ private _scope?;
127
+ private readonly marks;
128
+ private readonly store;
129
+ constructor(args: FrontMcpContextArgs);
130
+ /**
131
+ * Get authentication information.
132
+ * Returns Partial<AuthInfo> because auth info is progressively populated.
133
+ */
134
+ get authInfo(): Partial<AuthInfo>;
135
+ /**
136
+ * Update auth info after authorization is verified.
137
+ * Can be called multiple times to progressively add fields.
138
+ *
139
+ * @param authInfo - The auth info fields to set/update
140
+ * @internal
141
+ */
142
+ updateAuthInfo(authInfo: Partial<AuthInfo>): void;
143
+ /**
144
+ * Get session metadata (protocol, platform type, node info).
145
+ * Only available after session verification.
146
+ */
147
+ get sessionMetadata(): SessionIdPayload | undefined;
148
+ /**
149
+ * Update session metadata after session verification.
150
+ *
151
+ * @param metadata - Session metadata from verified session
152
+ * @internal
153
+ */
154
+ updateSessionMetadata(metadata: SessionIdPayload): void;
155
+ /**
156
+ * Get transport accessor for elicit support.
157
+ * Returns undefined if no transport is registered.
158
+ */
159
+ get transport(): TransportAccessor | undefined;
160
+ /**
161
+ * Set transport reference (internal use).
162
+ * @internal
163
+ */
164
+ setTransport(transport: TransportRef): void;
165
+ /**
166
+ * Get current flow reference.
167
+ */
168
+ get flow(): FlowBaseRef | undefined;
169
+ /**
170
+ * Set flow reference (internal use).
171
+ * @internal
172
+ */
173
+ setFlow(flow: FlowBaseRef): void;
174
+ /**
175
+ * Get scope reference.
176
+ */
177
+ get scope(): ScopeRef | undefined;
178
+ /**
179
+ * Set scope reference (internal use).
180
+ * @internal
181
+ */
182
+ setScope(scope: ScopeRef): void;
183
+ /**
184
+ * Store context-scoped data.
185
+ *
186
+ * @param key - Storage key
187
+ * @param value - Value to store
188
+ */
189
+ set<T>(key: string | symbol, value: T): void;
190
+ /**
191
+ * Retrieve context-scoped data.
192
+ *
193
+ * @param key - Storage key
194
+ * @returns Stored value or undefined
195
+ */
196
+ get<T>(key: string | symbol): T | undefined;
197
+ /**
198
+ * Check if a key exists in the context store.
199
+ *
200
+ * @param key - Storage key
201
+ * @returns True if key exists
202
+ */
203
+ has(key: string | symbol): boolean;
204
+ /**
205
+ * Delete a key from the context store.
206
+ *
207
+ * @param key - Storage key
208
+ * @returns True if key was deleted
209
+ */
210
+ delete(key: string | symbol): boolean;
211
+ /**
212
+ * Mark a timing point for performance tracking.
213
+ *
214
+ * @param name - Name of the timing mark
215
+ */
216
+ mark(name: string): void;
217
+ /**
218
+ * Get elapsed time in milliseconds between two marks.
219
+ *
220
+ * @param from - Start mark name (defaults to 'init')
221
+ * @param to - End mark name (defaults to current time)
222
+ * @returns Elapsed time in milliseconds
223
+ */
224
+ elapsed(from?: string, to?: string): number;
225
+ /**
226
+ * Get all timing marks.
227
+ *
228
+ * @returns Read-only map of mark names to timestamps
229
+ */
230
+ getMarks(): ReadonlyMap<string, number>;
231
+ /**
232
+ * Get a child logger with context attached.
233
+ *
234
+ * Creates a child logger with a prefix containing the request ID and trace ID
235
+ * for easy request tracing in logs.
236
+ *
237
+ * @param parentLogger - The parent logger to create a child from
238
+ * @returns A logger with requestId and traceId in the prefix
239
+ */
240
+ getLogger(parentLogger: FrontMcpLogger): FrontMcpLogger;
241
+ /**
242
+ * Get a summary of the context for logging.
243
+ *
244
+ * Note: sessionId is hashed to prevent accidental exposure of user-identifying
245
+ * session identifiers in logs while still allowing correlation.
246
+ *
247
+ * @returns Object with key context fields
248
+ */
249
+ toLogContext(): Record<string, unknown>;
250
+ /**
251
+ * Perform a fetch request with automatic header injection.
252
+ *
253
+ * Injects:
254
+ * - Authorization header (if authInfo.token is available and autoInjectAuthHeaders is true)
255
+ * - W3C traceparent header (if autoInjectTracingHeaders is true)
256
+ * - x-request-id header
257
+ * - Custom headers from request metadata
258
+ *
259
+ * @param input - Request URL or Request object
260
+ * @param init - Request options
261
+ * @returns Fetch response
262
+ */
263
+ fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
264
+ }
265
+ /**
266
+ * Alias for FrontMcpContext.
267
+ * Use when you want a shorter name.
268
+ */
269
+ export { FrontMcpContext as Context };