@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.
- package/README.md +3 -3
- package/package.json +8 -19
- package/src/adapter/adapter.instance.js +5 -0
- package/src/adapter/adapter.instance.js.map +1 -1
- package/src/auth/authorization/authorization.class.d.ts +1 -4
- package/src/auth/authorization/authorization.class.js +6 -13
- package/src/auth/authorization/authorization.class.js.map +1 -1
- package/src/auth/flows/session.verify.flow.d.ts +1 -0
- package/src/auth/flows/session.verify.flow.js +11 -1
- package/src/auth/flows/session.verify.flow.js.map +1 -1
- package/src/auth/flows/well-known.jwks.flow.js +2 -2
- package/src/auth/flows/well-known.jwks.flow.js.map +1 -1
- package/src/auth/jwks/dev-key-persistence.d.ts +63 -0
- package/src/auth/jwks/dev-key-persistence.js +219 -0
- package/src/auth/jwks/dev-key-persistence.js.map +1 -0
- package/src/auth/jwks/index.d.ts +1 -0
- package/src/auth/jwks/index.js +1 -0
- package/src/auth/jwks/index.js.map +1 -1
- package/src/auth/jwks/jwks.service.d.ts +7 -4
- package/src/auth/jwks/jwks.service.js +81 -12
- package/src/auth/jwks/jwks.service.js.map +1 -1
- package/src/auth/jwks/jwks.types.d.ts +7 -0
- package/src/auth/jwks/jwks.types.js.map +1 -1
- package/src/auth/machine-id.d.ts +5 -0
- package/src/auth/machine-id.js +32 -0
- package/src/auth/machine-id.js.map +1 -0
- package/src/auth/session/index.d.ts +1 -0
- package/src/auth/session/index.js +3 -1
- package/src/auth/session/index.js.map +1 -1
- package/src/auth/session/record/session.base.js +5 -3
- package/src/auth/session/record/session.base.js.map +1 -1
- package/src/auth/session/record/session.stateless.d.ts +2 -2
- package/src/auth/session/record/session.stateless.js +5 -3
- package/src/auth/session/record/session.stateless.js.map +1 -1
- package/src/auth/session/redis-session.store.d.ts +64 -0
- package/src/auth/session/redis-session.store.js +204 -0
- package/src/auth/session/redis-session.store.js.map +1 -0
- package/src/auth/session/session.service.d.ts +0 -2
- package/src/auth/session/session.service.js +1 -7
- package/src/auth/session/session.service.js.map +1 -1
- package/src/auth/session/transport-session.manager.js +3 -5
- package/src/auth/session/transport-session.manager.js.map +1 -1
- package/src/auth/session/transport-session.types.d.ts +4 -0
- package/src/auth/session/transport-session.types.js +4 -3
- package/src/auth/session/transport-session.types.js.map +1 -1
- package/src/auth/session/utils/session-id.utils.d.ts +12 -1
- package/src/auth/session/utils/session-id.utils.js +48 -9
- package/src/auth/session/utils/session-id.utils.js.map +1 -1
- package/src/auth/ui/base-layout.d.ts +0 -8
- package/src/auth/ui/base-layout.js +1 -14
- package/src/auth/ui/base-layout.js.map +1 -1
- package/src/auth/ui/index.d.ts +3 -4
- package/src/auth/ui/index.js +10 -11
- package/src/auth/ui/index.js.map +1 -1
- package/src/auth/ui/{htmx-templates.d.ts → templates.d.ts} +5 -6
- package/src/auth/ui/{htmx-templates.js → templates.js} +8 -15
- package/src/auth/ui/templates.js.map +1 -0
- package/src/common/decorators/decorator-utils.js.map +1 -1
- package/src/common/decorators/front-mcp.decorator.js +28 -2
- package/src/common/decorators/front-mcp.decorator.js.map +1 -1
- package/src/common/index.d.ts +0 -1
- package/src/common/index.js +0 -1
- package/src/common/index.js.map +1 -1
- package/src/common/interfaces/adapter.interface.d.ts +6 -0
- package/src/common/interfaces/adapter.interface.js.map +1 -1
- package/src/common/interfaces/execution-context.interface.d.ts +52 -3
- package/src/common/interfaces/execution-context.interface.js +88 -3
- package/src/common/interfaces/execution-context.interface.js.map +1 -1
- package/src/common/interfaces/flow.interface.d.ts +13 -0
- package/src/common/interfaces/flow.interface.js +24 -0
- package/src/common/interfaces/flow.interface.js.map +1 -1
- package/src/common/interfaces/server.interface.d.ts +9 -0
- package/src/common/interfaces/server.interface.js.map +1 -1
- package/src/common/metadata/app.metadata.d.ts +108 -0
- package/src/common/metadata/front-mcp.metadata.d.ts +659 -2
- package/src/common/metadata/front-mcp.metadata.js +3 -1
- package/src/common/metadata/front-mcp.metadata.js.map +1 -1
- package/src/common/metadata/provider.metadata.d.ts +14 -0
- package/src/common/metadata/provider.metadata.js +18 -2
- package/src/common/metadata/provider.metadata.js.map +1 -1
- package/src/common/metadata/tool.metadata.d.ts +33 -1
- package/src/common/metadata/tool.metadata.js.map +1 -1
- package/src/common/migrate/auth-transport.migrate.d.ts +62 -0
- package/src/common/migrate/auth-transport.migrate.js +140 -0
- package/src/common/migrate/auth-transport.migrate.js.map +1 -0
- package/src/common/migrate/index.d.ts +1 -0
- package/src/common/migrate/index.js +6 -0
- package/src/common/migrate/index.js.map +1 -0
- package/src/common/schemas/http-output.schema.d.ts +10 -2
- package/src/common/schemas/index.d.ts +1 -0
- package/src/common/schemas/index.js +1 -0
- package/src/common/schemas/index.js.map +1 -1
- package/src/common/schemas/session-header.schema.d.ts +16 -0
- package/src/common/schemas/session-header.schema.js +42 -0
- package/src/common/schemas/session-header.schema.js.map +1 -0
- package/src/common/tokens/front-mcp.tokens.js +3 -1
- package/src/common/tokens/front-mcp.tokens.js.map +1 -1
- package/src/common/types/options/auth.options.d.ts +233 -3
- package/src/common/types/options/auth.options.js +29 -40
- package/src/common/types/options/auth.options.js.map +1 -1
- package/src/common/types/options/index.d.ts +2 -0
- package/src/common/types/options/index.js +2 -0
- package/src/common/types/options/index.js.map +1 -1
- package/src/common/types/options/redis.options.d.ts +22 -0
- package/src/common/types/options/redis.options.js +45 -0
- package/src/common/types/options/redis.options.js.map +1 -0
- package/src/common/types/options/transport.options.d.ts +84 -0
- package/src/common/types/options/transport.options.js +121 -0
- package/src/common/types/options/transport.options.js.map +1 -0
- package/src/completion/flows/complete.flow.d.ts +17 -2
- package/src/context/frontmcp-context-storage.d.ts +94 -0
- package/src/context/frontmcp-context-storage.js +183 -0
- package/src/context/frontmcp-context-storage.js.map +1 -0
- package/src/context/frontmcp-context.d.ts +269 -0
- package/src/context/frontmcp-context.js +360 -0
- package/src/context/frontmcp-context.js.map +1 -0
- package/src/context/frontmcp-context.provider.d.ts +43 -0
- package/src/context/frontmcp-context.provider.js +61 -0
- package/src/context/frontmcp-context.provider.js.map +1 -0
- package/src/context/index.d.ts +34 -0
- package/src/context/index.js +64 -0
- package/src/context/index.js.map +1 -0
- package/src/context/request-context-storage.d.ts +89 -0
- package/src/context/request-context-storage.js +183 -0
- package/src/context/request-context-storage.js.map +1 -0
- package/src/context/request-context.d.ts +184 -0
- package/src/context/request-context.js +209 -0
- package/src/context/request-context.js.map +1 -0
- package/src/context/request-context.provider.d.ts +37 -0
- package/src/context/request-context.provider.js +51 -0
- package/src/context/request-context.provider.js.map +1 -0
- package/src/context/session-key.provider.d.ts +45 -0
- package/src/context/session-key.provider.js +65 -0
- package/src/context/session-key.provider.js.map +1 -0
- package/src/context/trace-context.d.ts +43 -0
- package/src/context/trace-context.js +142 -0
- package/src/context/trace-context.js.map +1 -0
- package/src/errors/index.d.ts +1 -1
- package/src/errors/index.js +3 -1
- package/src/errors/index.js.map +1 -1
- package/src/errors/mcp.error.d.ts +7 -0
- package/src/errors/mcp.error.js +11 -1
- package/src/errors/mcp.error.js.map +1 -1
- package/src/flows/flow.instance.d.ts +16 -0
- package/src/flows/flow.instance.js +166 -80
- package/src/flows/flow.instance.js.map +1 -1
- package/src/flows/flow.registry.d.ts +5 -0
- package/src/flows/flow.registry.js +45 -3
- package/src/flows/flow.registry.js.map +1 -1
- package/src/front-mcp/front-mcp.d.ts +12 -0
- package/src/front-mcp/front-mcp.js +22 -3
- package/src/front-mcp/front-mcp.js.map +1 -1
- package/src/front-mcp/front-mcp.providers.d.ts +266 -1
- package/src/front-mcp/front-mcp.providers.js +2 -1
- package/src/front-mcp/front-mcp.providers.js.map +1 -1
- package/src/front-mcp/serverless-handler.d.ts +28 -0
- package/src/front-mcp/serverless-handler.js +61 -0
- package/src/front-mcp/serverless-handler.js.map +1 -0
- package/src/hooks/hooks.utils.d.ts +1 -1
- package/src/hooks/hooks.utils.js +10 -3
- package/src/hooks/hooks.utils.js.map +1 -1
- package/src/index.d.ts +8 -4
- package/src/index.js +20 -1
- package/src/index.js.map +1 -1
- package/src/logger/instances/instance.logger.js +0 -1
- package/src/logger/instances/instance.logger.js.map +1 -1
- package/src/logging/flows/set-level.flow.d.ts +17 -2
- package/src/notification/notification.service.js +5 -1
- package/src/notification/notification.service.js.map +1 -1
- package/src/prompt/flows/get-prompt.flow.d.ts +97 -2
- package/src/prompt/flows/prompts-list.flow.d.ts +12 -1
- package/src/provider/provider.registry.d.ts +97 -5
- package/src/provider/provider.registry.js +306 -9
- package/src/provider/provider.registry.js.map +1 -1
- package/src/provider/provider.types.d.ts +21 -3
- package/src/provider/provider.types.js.map +1 -1
- package/src/resource/flows/read-resource.flow.d.ts +22 -3
- package/src/resource/flows/resource-templates-list.flow.d.ts +20 -1
- package/src/resource/flows/resources-list.flow.d.ts +20 -1
- package/src/resource/flows/subscribe-resource.flow.d.ts +17 -2
- package/src/resource/flows/unsubscribe-resource.flow.d.ts +17 -2
- package/src/scope/flows/http.request.flow.js +43 -7
- package/src/scope/flows/http.request.flow.js.map +1 -1
- package/src/scope/scope.instance.js +12 -5
- package/src/scope/scope.instance.js.map +1 -1
- package/src/server/adapters/base.host.adapter.d.ts +9 -0
- package/src/server/adapters/base.host.adapter.js.map +1 -1
- package/src/server/adapters/express.host.adapter.d.ts +12 -0
- package/src/server/adapters/express.host.adapter.js +21 -1
- package/src/server/adapters/express.host.adapter.js.map +1 -1
- package/src/server/server.instance.d.ts +3 -0
- package/src/server/server.instance.js +14 -7
- package/src/server/server.instance.js.map +1 -1
- package/src/tool/flows/call-tool.flow.d.ts +118 -13
- package/src/tool/flows/call-tool.flow.js +240 -194
- package/src/tool/flows/call-tool.flow.js.map +1 -1
- package/src/tool/flows/tools-list.flow.d.ts +25 -11
- package/src/tool/flows/tools-list.flow.js +82 -31
- package/src/tool/flows/tools-list.flow.js.map +1 -1
- package/src/tool/tool.instance.d.ts +1 -4
- package/src/transport/adapters/transport.streamable-http.adapter.js +1 -0
- package/src/transport/adapters/transport.streamable-http.adapter.js.map +1 -1
- package/src/transport/flows/handle.sse.flow.js +9 -2
- package/src/transport/flows/handle.sse.flow.js.map +1 -1
- package/src/transport/flows/handle.streamable-http.flow.js +63 -6
- package/src/transport/flows/handle.streamable-http.flow.js.map +1 -1
- package/src/transport/mcp-handlers/complete-request.handler.d.ts +27 -1
- package/src/transport/mcp-handlers/get-prompt-request.handler.d.ts +52 -1
- package/src/transport/mcp-handlers/index.d.ts +413 -7
- package/src/transport/mcp-handlers/initialize-request.handler.js +12 -2
- package/src/transport/mcp-handlers/initialize-request.handler.js.map +1 -1
- package/src/transport/mcp-handlers/list-prompts-request.handler.d.ts +27 -1
- package/src/transport/mcp-handlers/list-resource-templates-request.handler.d.ts +32 -1
- package/src/transport/mcp-handlers/list-resources-request.handler.d.ts +32 -1
- package/src/transport/mcp-handlers/list-tools-request.handler.d.ts +30 -1
- package/src/transport/mcp-handlers/logging-set-level-request.handler.d.ts +20 -0
- package/src/transport/mcp-handlers/read-resource-request.handler.d.ts +27 -1
- package/src/transport/mcp-handlers/subscribe-request.handler.d.ts +20 -0
- package/src/transport/mcp-handlers/unsubscribe-request.handler.d.ts +20 -0
- package/src/transport/transport.registry.d.ts +68 -4
- package/src/transport/transport.registry.js +313 -11
- package/src/transport/transport.registry.js.map +1 -1
- package/src/auth/ui/htmx-templates.js.map +0 -1
- package/src/common/providers/session.provider.d.ts +0 -13
- package/src/common/providers/session.provider.js +0 -27
- package/src/common/providers/session.provider.js.map +0 -1
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RequestContextStorage - AsyncLocalStorage wrapper for request-scoped context
|
|
3
|
+
*
|
|
4
|
+
* Provides concurrent-safe request context propagation using Node.js AsyncLocalStorage.
|
|
5
|
+
* Access through DI only - never use static imports to access the storage directly.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* // In a flow or middleware
|
|
10
|
+
* const storage = this.get(RequestContextStorage);
|
|
11
|
+
* await storage.runFromHeaders(request.headers, {
|
|
12
|
+
* sessionId: sessionId,
|
|
13
|
+
* authInfo: authInfo,
|
|
14
|
+
* scopeId: scope.id,
|
|
15
|
+
* }, async () => {
|
|
16
|
+
* // All code here can access the context via DI
|
|
17
|
+
* const ctx = this.get(REQUEST_CONTEXT);
|
|
18
|
+
* });
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
import { RequestContext, RequestContextArgs } from './request-context';
|
|
22
|
+
/**
|
|
23
|
+
* RequestContextStorage provides request-scoped context via AsyncLocalStorage.
|
|
24
|
+
*
|
|
25
|
+
* This is a GLOBAL-scoped provider because it manages the storage itself,
|
|
26
|
+
* not the per-request data. The actual RequestContext is accessed via
|
|
27
|
+
* the REQUEST_CONTEXT token which is REQUEST-scoped.
|
|
28
|
+
*/
|
|
29
|
+
export declare class RequestContextStorage {
|
|
30
|
+
/**
|
|
31
|
+
* Run a callback with a new RequestContext.
|
|
32
|
+
*
|
|
33
|
+
* @param args - Arguments to create the context
|
|
34
|
+
* @param fn - Async function to run with the context
|
|
35
|
+
* @returns Result of the callback
|
|
36
|
+
*/
|
|
37
|
+
run<T>(args: RequestContextArgs, fn: () => T | Promise<T>): T | Promise<T>;
|
|
38
|
+
/**
|
|
39
|
+
* Run with context extracted from HTTP headers.
|
|
40
|
+
*
|
|
41
|
+
* Automatically parses trace context from headers using W3C Trace Context
|
|
42
|
+
* specification with fallback to x-frontmcp-trace-id.
|
|
43
|
+
*
|
|
44
|
+
* @param headers - HTTP headers
|
|
45
|
+
* @param args - Additional context args (sessionId, authInfo, scopeId)
|
|
46
|
+
* @param fn - Async function to run
|
|
47
|
+
* @returns Result of the callback
|
|
48
|
+
*/
|
|
49
|
+
runFromHeaders<T>(headers: Record<string, unknown>, args: Omit<RequestContextArgs, 'traceContext' | 'metadata'>, fn: () => T | Promise<T>): T | Promise<T>;
|
|
50
|
+
/**
|
|
51
|
+
* Run with an existing RequestContext.
|
|
52
|
+
*
|
|
53
|
+
* Useful when you need to propagate an existing context to a new async scope.
|
|
54
|
+
*
|
|
55
|
+
* @param context - Existing RequestContext
|
|
56
|
+
* @param fn - Async function to run
|
|
57
|
+
* @returns Result of the callback
|
|
58
|
+
*/
|
|
59
|
+
runWithContext<T>(context: RequestContext, fn: () => T | Promise<T>): T | Promise<T>;
|
|
60
|
+
/**
|
|
61
|
+
* Get the current RequestContext.
|
|
62
|
+
*
|
|
63
|
+
* @returns Current context or undefined if not in a request scope
|
|
64
|
+
*/
|
|
65
|
+
getStore(): RequestContext | undefined;
|
|
66
|
+
/**
|
|
67
|
+
* Get the current RequestContext, throwing if not available.
|
|
68
|
+
*
|
|
69
|
+
* @throws Error if not in a request scope
|
|
70
|
+
*/
|
|
71
|
+
getStoreOrThrow(): RequestContext;
|
|
72
|
+
/**
|
|
73
|
+
* Check if currently running within a request context.
|
|
74
|
+
*
|
|
75
|
+
* @returns True if a RequestContext is available
|
|
76
|
+
*/
|
|
77
|
+
hasContext(): boolean;
|
|
78
|
+
/**
|
|
79
|
+
* Update the authInfo in the current context.
|
|
80
|
+
*
|
|
81
|
+
* This mutates the existing context in place to preserve internal state
|
|
82
|
+
* (marks, store, sessionMetadata) while updating auth info.
|
|
83
|
+
*
|
|
84
|
+
* @param authInfo - Auth info fields to set/update (merged with existing)
|
|
85
|
+
* @param fn - Function to run after update
|
|
86
|
+
* @returns Result of the callback
|
|
87
|
+
*/
|
|
88
|
+
updateAuthInfo<T>(authInfo: RequestContextArgs['authInfo'], fn: () => T | Promise<T>): T | Promise<T>;
|
|
89
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* RequestContextStorage - AsyncLocalStorage wrapper for request-scoped context
|
|
4
|
+
*
|
|
5
|
+
* Provides concurrent-safe request 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(RequestContextStorage);
|
|
12
|
+
* await storage.runFromHeaders(request.headers, {
|
|
13
|
+
* sessionId: sessionId,
|
|
14
|
+
* authInfo: authInfo,
|
|
15
|
+
* scopeId: scope.id,
|
|
16
|
+
* }, async () => {
|
|
17
|
+
* // All code here can access the context via DI
|
|
18
|
+
* const ctx = this.get(REQUEST_CONTEXT);
|
|
19
|
+
* });
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
23
|
+
exports.RequestContextStorage = void 0;
|
|
24
|
+
const tslib_1 = require("tslib");
|
|
25
|
+
const node_async_hooks_1 = require("node:async_hooks");
|
|
26
|
+
const decorators_1 = require("../common/decorators");
|
|
27
|
+
const metadata_1 = require("../common/metadata");
|
|
28
|
+
const request_context_1 = require("./request-context");
|
|
29
|
+
const trace_context_1 = require("./trace-context");
|
|
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 requestContextStorage = new node_async_hooks_1.AsyncLocalStorage();
|
|
37
|
+
/**
|
|
38
|
+
* RequestContextStorage provides request-scoped context via AsyncLocalStorage.
|
|
39
|
+
*
|
|
40
|
+
* This is a GLOBAL-scoped provider because it manages the storage itself,
|
|
41
|
+
* not the per-request data. The actual RequestContext is accessed via
|
|
42
|
+
* the REQUEST_CONTEXT token which is REQUEST-scoped.
|
|
43
|
+
*/
|
|
44
|
+
let RequestContextStorage = class RequestContextStorage {
|
|
45
|
+
/**
|
|
46
|
+
* Run a callback with a new RequestContext.
|
|
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 request_context_1.RequestContext(args);
|
|
54
|
+
return requestContextStorage.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, authInfo, 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 request_context_1.RequestContext({
|
|
71
|
+
...args,
|
|
72
|
+
traceContext,
|
|
73
|
+
metadata,
|
|
74
|
+
});
|
|
75
|
+
return requestContextStorage.run(context, fn);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Run with an existing RequestContext.
|
|
79
|
+
*
|
|
80
|
+
* Useful when you need to propagate an existing context to a new async scope.
|
|
81
|
+
*
|
|
82
|
+
* @param context - Existing RequestContext
|
|
83
|
+
* @param fn - Async function to run
|
|
84
|
+
* @returns Result of the callback
|
|
85
|
+
*/
|
|
86
|
+
runWithContext(context, fn) {
|
|
87
|
+
return requestContextStorage.run(context, fn);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Get the current RequestContext.
|
|
91
|
+
*
|
|
92
|
+
* @returns Current context or undefined if not in a request scope
|
|
93
|
+
*/
|
|
94
|
+
getStore() {
|
|
95
|
+
return requestContextStorage.getStore();
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Get the current RequestContext, throwing if not available.
|
|
99
|
+
*
|
|
100
|
+
* @throws Error if not in a request scope
|
|
101
|
+
*/
|
|
102
|
+
getStoreOrThrow() {
|
|
103
|
+
const ctx = this.getStore();
|
|
104
|
+
if (!ctx) {
|
|
105
|
+
throw new Error('RequestContext not available. Ensure operation runs within request scope.');
|
|
106
|
+
}
|
|
107
|
+
return ctx;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Check if currently running within a request context.
|
|
111
|
+
*
|
|
112
|
+
* @returns True if a RequestContext is available
|
|
113
|
+
*/
|
|
114
|
+
hasContext() {
|
|
115
|
+
return requestContextStorage.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
|
+
// Mutate in place to preserve marks, store, and sessionMetadata
|
|
130
|
+
current.updateAuthInfo(authInfo);
|
|
131
|
+
return fn();
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
exports.RequestContextStorage = RequestContextStorage;
|
|
135
|
+
exports.RequestContextStorage = RequestContextStorage = tslib_1.__decorate([
|
|
136
|
+
(0, decorators_1.Provider)({
|
|
137
|
+
name: 'RequestContextStorage',
|
|
138
|
+
description: 'Manages request-scoped context via AsyncLocalStorage',
|
|
139
|
+
scope: metadata_1.ProviderScope.GLOBAL,
|
|
140
|
+
})
|
|
141
|
+
], RequestContextStorage);
|
|
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=request-context-storage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request-context-storage.js","sourceRoot":"","sources":["../../../src/context/request-context-storage.ts"],"names":[],"mappings":"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","sourcesContent":["/**\n * RequestContextStorage - AsyncLocalStorage wrapper for request-scoped context\n *\n * Provides concurrent-safe request 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(RequestContextStorage);\n * await storage.runFromHeaders(request.headers, {\n * sessionId: sessionId,\n * authInfo: authInfo,\n * scopeId: scope.id,\n * }, async () => {\n * // All code here can access the context via DI\n * const ctx = this.get(REQUEST_CONTEXT);\n * });\n * ```\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { Provider } from '../common/decorators';\nimport { ProviderScope } from '../common/metadata';\nimport { RequestContext, RequestContextArgs, RequestMetadata } from './request-context';\nimport { parseTraceContext } from './trace-context';\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 requestContextStorage = new AsyncLocalStorage<RequestContext>();\n\n/**\n * RequestContextStorage provides request-scoped context via AsyncLocalStorage.\n *\n * This is a GLOBAL-scoped provider because it manages the storage itself,\n * not the per-request data. The actual RequestContext is accessed via\n * the REQUEST_CONTEXT token which is REQUEST-scoped.\n */\n@Provider({\n name: 'RequestContextStorage',\n description: 'Manages request-scoped context via AsyncLocalStorage',\n scope: ProviderScope.GLOBAL,\n})\nexport class RequestContextStorage {\n /**\n * Run a callback with a new RequestContext.\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: RequestContextArgs, fn: () => T | Promise<T>): T | Promise<T> {\n const context = new RequestContext(args);\n return requestContextStorage.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, authInfo, 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<RequestContextArgs, '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 RequestContext({\n ...args,\n traceContext,\n metadata,\n });\n return requestContextStorage.run(context, fn);\n }\n\n /**\n * Run with an existing RequestContext.\n *\n * Useful when you need to propagate an existing context to a new async scope.\n *\n * @param context - Existing RequestContext\n * @param fn - Async function to run\n * @returns Result of the callback\n */\n runWithContext<T>(context: RequestContext, fn: () => T | Promise<T>): T | Promise<T> {\n return requestContextStorage.run(context, fn);\n }\n\n /**\n * Get the current RequestContext.\n *\n * @returns Current context or undefined if not in a request scope\n */\n getStore(): RequestContext | undefined {\n return requestContextStorage.getStore();\n }\n\n /**\n * Get the current RequestContext, throwing if not available.\n *\n * @throws Error if not in a request scope\n */\n getStoreOrThrow(): RequestContext {\n const ctx = this.getStore();\n if (!ctx) {\n throw new Error('RequestContext not available. Ensure operation runs within request scope.');\n }\n return ctx;\n }\n\n /**\n * Check if currently running within a request context.\n *\n * @returns True if a RequestContext is available\n */\n hasContext(): boolean {\n return requestContextStorage.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: RequestContextArgs['authInfo'], fn: () => T | Promise<T>): T | Promise<T> {\n const current = this.getStoreOrThrow();\n // Mutate in place to preserve marks, store, and sessionMetadata\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"]}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RequestContext - Production-ready request context for FrontMCP
|
|
3
|
+
*
|
|
4
|
+
* Provides request-scoped state that flows through the entire async execution
|
|
5
|
+
* chain via AsyncLocalStorage. Access via DI only using the REQUEST_CONTEXT token.
|
|
6
|
+
*/
|
|
7
|
+
import { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';
|
|
8
|
+
import { FrontMcpLogger } from '../common/interfaces/logger.interface';
|
|
9
|
+
import { TraceContext } from './trace-context';
|
|
10
|
+
import type { SessionIdPayload } from '../common/types';
|
|
11
|
+
/**
|
|
12
|
+
* Request metadata extracted from HTTP headers.
|
|
13
|
+
*/
|
|
14
|
+
export interface RequestMetadata {
|
|
15
|
+
/** User-Agent header */
|
|
16
|
+
userAgent?: string;
|
|
17
|
+
/** Content-Type header */
|
|
18
|
+
contentType?: string;
|
|
19
|
+
/** Accept header */
|
|
20
|
+
accept?: string;
|
|
21
|
+
/** Client IP address (from x-forwarded-for or socket) */
|
|
22
|
+
clientIp?: string;
|
|
23
|
+
/** Custom headers matching x-frontmcp-* pattern */
|
|
24
|
+
customHeaders: Record<string, string>;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Arguments for creating a RequestContext.
|
|
28
|
+
*/
|
|
29
|
+
export interface RequestContextArgs {
|
|
30
|
+
/** Optional request ID (generated if not provided) */
|
|
31
|
+
requestId?: string;
|
|
32
|
+
/** Optional trace context (generated if not provided) */
|
|
33
|
+
traceContext?: TraceContext;
|
|
34
|
+
/** Session identifier (required) */
|
|
35
|
+
sessionId: string;
|
|
36
|
+
/** Authentication information (can be partial, progressively populated) */
|
|
37
|
+
authInfo: Partial<AuthInfo>;
|
|
38
|
+
/** Scope identifier (required) */
|
|
39
|
+
scopeId: string;
|
|
40
|
+
/** Optional timestamp (defaults to Date.now()) */
|
|
41
|
+
timestamp?: number;
|
|
42
|
+
/** Optional request metadata */
|
|
43
|
+
metadata?: RequestMetadata;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* RequestContext provides per-request state that flows through
|
|
47
|
+
* the entire async execution chain via AsyncLocalStorage.
|
|
48
|
+
*
|
|
49
|
+
* Access via DI only using the REQUEST_CONTEXT token:
|
|
50
|
+
* ```typescript
|
|
51
|
+
* const ctx = this.get(REQUEST_CONTEXT);
|
|
52
|
+
* console.log(ctx.requestId, ctx.traceContext.traceId);
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
export declare class RequestContext {
|
|
56
|
+
/** Unique request identifier (UUID v4) */
|
|
57
|
+
readonly requestId: string;
|
|
58
|
+
/** W3C Trace Context or generated trace ID */
|
|
59
|
+
readonly traceContext: TraceContext;
|
|
60
|
+
/** Session identifier (from mcp-session-id header or authorization) */
|
|
61
|
+
readonly sessionId: string;
|
|
62
|
+
/**
|
|
63
|
+
* Authentication information.
|
|
64
|
+
* Note: This is mutable to allow updating after authorization is verified.
|
|
65
|
+
* It's Partial<AuthInfo> because auth info is progressively populated
|
|
66
|
+
* throughout the request lifecycle (some fields like transport are only
|
|
67
|
+
* available after the transport is established).
|
|
68
|
+
*/
|
|
69
|
+
private _authInfo;
|
|
70
|
+
/** Scope identifier */
|
|
71
|
+
readonly scopeId: string;
|
|
72
|
+
/** Request start timestamp */
|
|
73
|
+
readonly timestamp: number;
|
|
74
|
+
/** Request metadata (headers, user-agent, etc.) */
|
|
75
|
+
readonly metadata: RequestMetadata;
|
|
76
|
+
/** Timing marks for performance tracking */
|
|
77
|
+
private readonly marks;
|
|
78
|
+
/** Request-scoped data store */
|
|
79
|
+
private readonly store;
|
|
80
|
+
constructor(args: RequestContextArgs);
|
|
81
|
+
/**
|
|
82
|
+
* Get authentication information.
|
|
83
|
+
* Returns Partial<AuthInfo> because auth info is progressively populated.
|
|
84
|
+
*/
|
|
85
|
+
get authInfo(): Partial<AuthInfo>;
|
|
86
|
+
/**
|
|
87
|
+
* Update auth info after authorization is verified.
|
|
88
|
+
* Called by checkAuthorization stage after session verification.
|
|
89
|
+
* Can be called multiple times to progressively add fields.
|
|
90
|
+
*
|
|
91
|
+
* @param authInfo - The auth info fields to set/update
|
|
92
|
+
* @internal
|
|
93
|
+
*/
|
|
94
|
+
updateAuthInfo(authInfo: Partial<AuthInfo>): void;
|
|
95
|
+
/**
|
|
96
|
+
* Session metadata including protocol, platform type, and node info.
|
|
97
|
+
* Only available after session verification in authenticated flows.
|
|
98
|
+
*/
|
|
99
|
+
private _sessionMetadata?;
|
|
100
|
+
/**
|
|
101
|
+
* Get session metadata.
|
|
102
|
+
*
|
|
103
|
+
* Contains protocol type, platform type, nodeId, and authSignature.
|
|
104
|
+
* Only available after session verification completes.
|
|
105
|
+
*
|
|
106
|
+
* @returns Session metadata or undefined if not yet verified
|
|
107
|
+
*/
|
|
108
|
+
get sessionMetadata(): SessionIdPayload | undefined;
|
|
109
|
+
/**
|
|
110
|
+
* Update session metadata after session verification.
|
|
111
|
+
* Called by checkAuthorization stage after session verification.
|
|
112
|
+
*
|
|
113
|
+
* @param metadata - Session metadata from verified session
|
|
114
|
+
* @internal
|
|
115
|
+
*/
|
|
116
|
+
updateSessionMetadata(metadata: SessionIdPayload): void;
|
|
117
|
+
/**
|
|
118
|
+
* Get a child logger with request context attached.
|
|
119
|
+
*
|
|
120
|
+
* Creates a child logger with a prefix containing the request ID and trace ID
|
|
121
|
+
* for easy request tracing in logs.
|
|
122
|
+
*
|
|
123
|
+
* @param parentLogger - The parent logger to create a child from
|
|
124
|
+
* @returns A logger with requestId and traceId in the prefix
|
|
125
|
+
*/
|
|
126
|
+
getLogger(parentLogger: FrontMcpLogger): FrontMcpLogger;
|
|
127
|
+
/**
|
|
128
|
+
* Mark a timing point for performance tracking.
|
|
129
|
+
*
|
|
130
|
+
* @param name - Name of the timing mark
|
|
131
|
+
*/
|
|
132
|
+
mark(name: string): void;
|
|
133
|
+
/**
|
|
134
|
+
* Get elapsed time in milliseconds between two marks.
|
|
135
|
+
*
|
|
136
|
+
* @param from - Start mark name (defaults to 'init')
|
|
137
|
+
* @param to - End mark name (defaults to current time)
|
|
138
|
+
* @returns Elapsed time in milliseconds
|
|
139
|
+
*/
|
|
140
|
+
elapsed(from?: string, to?: string): number;
|
|
141
|
+
/**
|
|
142
|
+
* Get all timing marks.
|
|
143
|
+
*
|
|
144
|
+
* @returns Read-only map of mark names to timestamps
|
|
145
|
+
*/
|
|
146
|
+
getMarks(): ReadonlyMap<string, number>;
|
|
147
|
+
/**
|
|
148
|
+
* Store request-scoped data.
|
|
149
|
+
*
|
|
150
|
+
* @param key - Storage key
|
|
151
|
+
* @param value - Value to store
|
|
152
|
+
*/
|
|
153
|
+
set<T>(key: string | symbol, value: T): void;
|
|
154
|
+
/**
|
|
155
|
+
* Retrieve request-scoped data.
|
|
156
|
+
*
|
|
157
|
+
* @param key - Storage key
|
|
158
|
+
* @returns Stored value or undefined
|
|
159
|
+
*/
|
|
160
|
+
get<T>(key: string | symbol): T | undefined;
|
|
161
|
+
/**
|
|
162
|
+
* Check if a key exists in the request-scoped store.
|
|
163
|
+
*
|
|
164
|
+
* @param key - Storage key
|
|
165
|
+
* @returns True if key exists
|
|
166
|
+
*/
|
|
167
|
+
has(key: string | symbol): boolean;
|
|
168
|
+
/**
|
|
169
|
+
* Delete a key from the request-scoped store.
|
|
170
|
+
*
|
|
171
|
+
* @param key - Storage key
|
|
172
|
+
* @returns True if key was deleted
|
|
173
|
+
*/
|
|
174
|
+
delete(key: string | symbol): boolean;
|
|
175
|
+
/**
|
|
176
|
+
* Get a summary of the context for logging.
|
|
177
|
+
*
|
|
178
|
+
* Note: sessionId is hashed to prevent accidental exposure of user-identifying
|
|
179
|
+
* session identifiers in logs while still allowing correlation.
|
|
180
|
+
*
|
|
181
|
+
* @returns Object with key context fields
|
|
182
|
+
*/
|
|
183
|
+
toLogContext(): Record<string, unknown>;
|
|
184
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* RequestContext - Production-ready request context for FrontMCP
|
|
4
|
+
*
|
|
5
|
+
* Provides request-scoped state that flows through the entire async execution
|
|
6
|
+
* chain via AsyncLocalStorage. Access via DI only using the REQUEST_CONTEXT token.
|
|
7
|
+
*/
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.RequestContext = void 0;
|
|
10
|
+
const node_crypto_1 = require("node:crypto");
|
|
11
|
+
const trace_context_1 = require("./trace-context");
|
|
12
|
+
/**
|
|
13
|
+
* RequestContext provides per-request state that flows through
|
|
14
|
+
* the entire async execution chain via AsyncLocalStorage.
|
|
15
|
+
*
|
|
16
|
+
* Access via DI only using the REQUEST_CONTEXT token:
|
|
17
|
+
* ```typescript
|
|
18
|
+
* const ctx = this.get(REQUEST_CONTEXT);
|
|
19
|
+
* console.log(ctx.requestId, ctx.traceContext.traceId);
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
class RequestContext {
|
|
23
|
+
/** Unique request identifier (UUID v4) */
|
|
24
|
+
requestId;
|
|
25
|
+
/** W3C Trace Context or generated trace ID */
|
|
26
|
+
traceContext;
|
|
27
|
+
/** Session identifier (from mcp-session-id header or authorization) */
|
|
28
|
+
sessionId;
|
|
29
|
+
/**
|
|
30
|
+
* Authentication information.
|
|
31
|
+
* Note: This is mutable to allow updating after authorization is verified.
|
|
32
|
+
* It's Partial<AuthInfo> because auth info is progressively populated
|
|
33
|
+
* throughout the request lifecycle (some fields like transport are only
|
|
34
|
+
* available after the transport is established).
|
|
35
|
+
*/
|
|
36
|
+
_authInfo;
|
|
37
|
+
/** Scope identifier */
|
|
38
|
+
scopeId;
|
|
39
|
+
/** Request start timestamp */
|
|
40
|
+
timestamp;
|
|
41
|
+
/** Request metadata (headers, user-agent, etc.) */
|
|
42
|
+
metadata;
|
|
43
|
+
/** Timing marks for performance tracking */
|
|
44
|
+
marks = new Map();
|
|
45
|
+
/** Request-scoped data store */
|
|
46
|
+
store = new Map();
|
|
47
|
+
constructor(args) {
|
|
48
|
+
this.requestId = args.requestId ?? (0, node_crypto_1.randomUUID)();
|
|
49
|
+
this.traceContext = args.traceContext ?? (0, trace_context_1.generateTraceContext)();
|
|
50
|
+
this.sessionId = args.sessionId;
|
|
51
|
+
this._authInfo = args.authInfo;
|
|
52
|
+
this.scopeId = args.scopeId;
|
|
53
|
+
this.timestamp = args.timestamp ?? Date.now();
|
|
54
|
+
// Defensive normalization: ensure customHeaders is always an object
|
|
55
|
+
// even if args.metadata is partially defined at runtime (TS can't enforce this)
|
|
56
|
+
const metadata = args.metadata;
|
|
57
|
+
this.metadata = {
|
|
58
|
+
...metadata,
|
|
59
|
+
customHeaders: metadata?.customHeaders ?? {},
|
|
60
|
+
};
|
|
61
|
+
// Initial mark
|
|
62
|
+
this.marks.set('init', this.timestamp);
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Get authentication information.
|
|
66
|
+
* Returns Partial<AuthInfo> because auth info is progressively populated.
|
|
67
|
+
*/
|
|
68
|
+
get authInfo() {
|
|
69
|
+
return this._authInfo;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Update auth info after authorization is verified.
|
|
73
|
+
* Called by checkAuthorization stage after session verification.
|
|
74
|
+
* Can be called multiple times to progressively add fields.
|
|
75
|
+
*
|
|
76
|
+
* @param authInfo - The auth info fields to set/update
|
|
77
|
+
* @internal
|
|
78
|
+
*/
|
|
79
|
+
updateAuthInfo(authInfo) {
|
|
80
|
+
// Merge with existing auth info to support progressive updates
|
|
81
|
+
this._authInfo = { ...this._authInfo, ...authInfo };
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Session metadata including protocol, platform type, and node info.
|
|
85
|
+
* Only available after session verification in authenticated flows.
|
|
86
|
+
*/
|
|
87
|
+
_sessionMetadata;
|
|
88
|
+
/**
|
|
89
|
+
* Get session metadata.
|
|
90
|
+
*
|
|
91
|
+
* Contains protocol type, platform type, nodeId, and authSignature.
|
|
92
|
+
* Only available after session verification completes.
|
|
93
|
+
*
|
|
94
|
+
* @returns Session metadata or undefined if not yet verified
|
|
95
|
+
*/
|
|
96
|
+
get sessionMetadata() {
|
|
97
|
+
return this._sessionMetadata;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Update session metadata after session verification.
|
|
101
|
+
* Called by checkAuthorization stage after session verification.
|
|
102
|
+
*
|
|
103
|
+
* @param metadata - Session metadata from verified session
|
|
104
|
+
* @internal
|
|
105
|
+
*/
|
|
106
|
+
updateSessionMetadata(metadata) {
|
|
107
|
+
this._sessionMetadata = metadata;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Get a child logger with request context attached.
|
|
111
|
+
*
|
|
112
|
+
* Creates a child logger with a prefix containing the request ID and trace ID
|
|
113
|
+
* for easy request tracing in logs.
|
|
114
|
+
*
|
|
115
|
+
* @param parentLogger - The parent logger to create a child from
|
|
116
|
+
* @returns A logger with requestId and traceId in the prefix
|
|
117
|
+
*/
|
|
118
|
+
getLogger(parentLogger) {
|
|
119
|
+
// FrontMcpLogger.child() takes a string prefix
|
|
120
|
+
const prefix = `[${this.requestId.slice(0, 8)}:${this.traceContext.traceId.slice(0, 8)}]`;
|
|
121
|
+
return parentLogger.child(prefix);
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Mark a timing point for performance tracking.
|
|
125
|
+
*
|
|
126
|
+
* @param name - Name of the timing mark
|
|
127
|
+
*/
|
|
128
|
+
mark(name) {
|
|
129
|
+
this.marks.set(name, Date.now());
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Get elapsed time in milliseconds between two marks.
|
|
133
|
+
*
|
|
134
|
+
* @param from - Start mark name (defaults to 'init')
|
|
135
|
+
* @param to - End mark name (defaults to current time)
|
|
136
|
+
* @returns Elapsed time in milliseconds
|
|
137
|
+
*/
|
|
138
|
+
elapsed(from, to) {
|
|
139
|
+
const fromTime = this.marks.get(from ?? 'init') ?? this.timestamp;
|
|
140
|
+
const toTime = to ? this.marks.get(to) ?? Date.now() : Date.now();
|
|
141
|
+
return toTime - fromTime;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Get all timing marks.
|
|
145
|
+
*
|
|
146
|
+
* @returns Read-only map of mark names to timestamps
|
|
147
|
+
*/
|
|
148
|
+
getMarks() {
|
|
149
|
+
return this.marks;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Store request-scoped data.
|
|
153
|
+
*
|
|
154
|
+
* @param key - Storage key
|
|
155
|
+
* @param value - Value to store
|
|
156
|
+
*/
|
|
157
|
+
set(key, value) {
|
|
158
|
+
this.store.set(key, value);
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Retrieve request-scoped data.
|
|
162
|
+
*
|
|
163
|
+
* @param key - Storage key
|
|
164
|
+
* @returns Stored value or undefined
|
|
165
|
+
*/
|
|
166
|
+
get(key) {
|
|
167
|
+
return this.store.get(key);
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Check if a key exists in the request-scoped store.
|
|
171
|
+
*
|
|
172
|
+
* @param key - Storage key
|
|
173
|
+
* @returns True if key exists
|
|
174
|
+
*/
|
|
175
|
+
has(key) {
|
|
176
|
+
return this.store.has(key);
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Delete a key from the request-scoped store.
|
|
180
|
+
*
|
|
181
|
+
* @param key - Storage key
|
|
182
|
+
* @returns True if key was deleted
|
|
183
|
+
*/
|
|
184
|
+
delete(key) {
|
|
185
|
+
return this.store.delete(key);
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Get a summary of the context for logging.
|
|
189
|
+
*
|
|
190
|
+
* Note: sessionId is hashed to prevent accidental exposure of user-identifying
|
|
191
|
+
* session identifiers in logs while still allowing correlation.
|
|
192
|
+
*
|
|
193
|
+
* @returns Object with key context fields
|
|
194
|
+
*/
|
|
195
|
+
toLogContext() {
|
|
196
|
+
return {
|
|
197
|
+
requestId: this.requestId,
|
|
198
|
+
traceId: this.traceContext.traceId,
|
|
199
|
+
parentId: this.traceContext.parentId,
|
|
200
|
+
// Hash sessionId to prevent logging user-identifying information
|
|
201
|
+
// while preserving ability to correlate logs for the same session
|
|
202
|
+
sessionIdHash: (0, node_crypto_1.createHash)('sha256').update(this.sessionId).digest('hex').slice(0, 12),
|
|
203
|
+
scopeId: this.scopeId,
|
|
204
|
+
elapsed: this.elapsed(),
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
exports.RequestContext = RequestContext;
|
|
209
|
+
//# sourceMappingURL=request-context.js.map
|