@frontmcp/sdk 0.5.1 → 0.6.1
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 +1 -0
- package/package.json +12 -16
- 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 +2 -0
- package/src/auth/session/index.js +5 -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/session/vercel-kv-session.store.d.ts +96 -0
- package/src/auth/session/vercel-kv-session.store.js +216 -0
- package/src/auth/session/vercel-kv-session.store.js.map +1 -0
- 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 +26 -3
- 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 +1341 -2
- package/src/common/metadata/front-mcp.metadata.js +4 -1
- package/src/common/metadata/front-mcp.metadata.js.map +1 -1
- package/src/common/metadata/prompt.metadata.d.ts +4 -0
- 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/resource.metadata.d.ts +8 -0
- package/src/common/metadata/tool-ui.metadata.d.ts +2 -2
- package/src/common/metadata/tool-ui.metadata.js +1 -1
- package/src/common/metadata/tool-ui.metadata.js.map +1 -1
- package/src/common/metadata/tool.metadata.d.ts +5 -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 +24 -6
- 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 +4 -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 +190 -0
- package/src/common/types/options/redis.options.js +191 -0
- package/src/common/types/options/redis.options.js.map +1 -0
- package/src/common/types/options/server-info.options.d.ts +4 -0
- package/src/common/types/options/transport.options.d.ts +148 -0
- package/src/common/types/options/transport.options.js +121 -0
- package/src/common/types/options/transport.options.js.map +1 -0
- package/src/common/utils/global-config.utils.d.ts +36 -0
- package/src/common/utils/global-config.utils.js +44 -0
- package/src/common/utils/global-config.utils.js.map +1 -0
- package/src/common/utils/index.d.ts +1 -0
- package/src/common/utils/index.js +1 -0
- package/src/common/utils/index.js.map +1 -1
- package/src/completion/flows/complete.flow.d.ts +6 -8
- 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 +4 -1
- package/src/errors/index.js.map +1 -1
- package/src/errors/mcp.error.d.ts +16 -0
- package/src/errors/mcp.error.js +29 -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 +474 -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/index.d.ts +1 -0
- package/src/front-mcp/index.js +3 -0
- package/src/front-mcp/index.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 +9 -5
- package/src/index.js +21 -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 +6 -8
- 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 +14 -8
- package/src/prompt/flows/prompts-list.flow.d.ts +8 -7
- 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 +8 -9
- package/src/resource/flows/resource-templates-list.flow.d.ts +8 -7
- package/src/resource/flows/resources-list.flow.d.ts +8 -7
- package/src/resource/flows/subscribe-resource.flow.d.ts +6 -8
- package/src/resource/flows/unsubscribe-resource.flow.d.ts +6 -8
- 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/store/adapters/store.vercel-kv.adapter.d.ts +86 -0
- package/src/store/adapters/store.vercel-kv.adapter.js +155 -0
- package/src/store/adapters/store.vercel-kv.adapter.js.map +1 -0
- package/src/store/index.d.ts +2 -0
- package/src/store/index.js +2 -0
- package/src/store/index.js.map +1 -1
- package/src/store/store.factory.d.ts +86 -0
- package/src/store/store.factory.js +194 -0
- package/src/store/store.factory.js.map +1 -0
- package/src/tool/flows/call-tool.flow.d.ts +38 -19
- 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 +14 -17
- package/src/tool/flows/tools-list.flow.js +84 -33
- package/src/tool/flows/tools-list.flow.js.map +1 -1
- package/src/tool/tool.instance.d.ts +1 -4
- package/src/tool/ui/index.d.ts +4 -4
- package/src/tool/ui/index.js +4 -4
- package/src/tool/ui/index.js.map +1 -1
- package/src/tool/ui/platform-adapters.d.ts +2 -2
- package/src/tool/ui/platform-adapters.js +3 -3
- package/src/tool/ui/platform-adapters.js.map +1 -1
- package/src/tool/ui/template-helpers.d.ts +5 -7
- package/src/tool/ui/template-helpers.js +9 -26
- package/src/tool/ui/template-helpers.js.map +1 -1
- package/src/tool/ui/ui-resource.handler.d.ts +1 -1
- package/src/tool/ui/ui-resource.handler.js +5 -5
- package/src/tool/ui/ui-resource.handler.js.map +1 -1
- 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 +4 -15
- package/src/transport/mcp-handlers/get-prompt-request.handler.d.ts +5 -15
- package/src/transport/mcp-handlers/index.d.ts +67 -195
- 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 +5 -15
- package/src/transport/mcp-handlers/list-resource-templates-request.handler.d.ts +5 -15
- package/src/transport/mcp-handlers/list-resources-request.handler.d.ts +5 -15
- package/src/transport/mcp-handlers/list-tools-request.handler.d.ts +5 -15
- package/src/transport/mcp-handlers/logging-set-level-request.handler.d.ts +3 -14
- package/src/transport/mcp-handlers/read-resource-request.handler.d.ts +4 -15
- package/src/transport/mcp-handlers/subscribe-request.handler.d.ts +3 -14
- package/src/transport/mcp-handlers/unsubscribe-request.handler.d.ts +3 -14
- package/src/transport/transport.registry.d.ts +72 -4
- package/src/transport/transport.registry.js +342 -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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp.error.js","sourceRoot":"","sources":["../../../src/errors/mcp.error.ts"],"names":[],"mappings":";;;AA2aA,sCAEC;AAKD,gCAUC;AAKD,wDAGC;AApcD,sBAAsB;AACtB,mCAAqC;AAErC;;;GAGG;AACU,QAAA,eAAe,GAAG;IAC7B,kCAAkC;IAClC,kBAAkB,EAAE,CAAC,KAAK;IAC1B,+BAA+B;IAC/B,eAAe,EAAE,CAAC,KAAK;IACvB,gCAAgC;IAChC,gBAAgB,EAAE,CAAC,KAAK;IACxB,8BAA8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C/C,CAAC;AAED;;GAEG;AACH,SAAgB,sBAAsB,CAAC,KAAU,EAAE,gBAAyB,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,YAAY;IAClH,MAAM,QAAQ,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC;IACnC,OAAO,QAAQ,CAAC,UAAU,CAAC,aAAa,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["// errors/mcp.error.ts\nimport { randomBytes } from 'crypto';\n\n/**\n * MCP-specific error codes per JSON-RPC specification.\n * These codes are used in the JSON-RPC error response format.\n */\nexport const MCP_ERROR_CODES = {\n /** Resource not found (-32002) */\n RESOURCE_NOT_FOUND: -32002,\n /** Invalid request (-32600) */\n INVALID_REQUEST: -32600,\n /** Method not found (-32601) */\n METHOD_NOT_FOUND: -32601,\n /** Invalid params (-32602) */\n INVALID_PARAMS: -32602,\n /** Internal error (-32603) */\n INTERNAL_ERROR: -32603,\n /** Parse error (-32700) */\n PARSE_ERROR: -32700,\n} as const;\n\nexport type McpErrorCode = (typeof MCP_ERROR_CODES)[keyof typeof MCP_ERROR_CODES];\n\n/**\n * Base class for all MCP-related errors\n */\nexport abstract class McpError extends Error {\n /**\n * Unique error ID for tracking in logs\n */\n errorId: string;\n\n /**\n * Whether this error should expose details to the client\n */\n abstract readonly isPublic: boolean;\n\n /**\n * HTTP status code equivalent (for reference)\n */\n abstract readonly statusCode: number;\n\n /**\n * Error code for categorization\n */\n abstract readonly code: string;\n\n protected constructor(message: string, errorId?: string) {\n super(message);\n this.name = this.constructor.name;\n this.errorId = errorId || this.generateErrorId();\n Error.captureStackTrace(this, this.constructor);\n }\n\n private generateErrorId(): string {\n return `err_${randomBytes(8).toString('hex')}`;\n }\n\n /**\n * Get the public-facing error message\n */\n abstract getPublicMessage(): string;\n\n /**\n * Get the internal error message (for logging)\n */\n getInternalMessage(): string {\n return this.message;\n }\n\n /**\n * Convert to MCP error response format\n */\n toMcpError(isDevelopment = false): {\n content: Array<{ type: 'text'; text: string }>;\n isError: true;\n _meta?: {\n errorId: string;\n code: string;\n timestamp: string;\n stack?: string;\n };\n } {\n const message = isDevelopment ? this.getInternalMessage() : this.getPublicMessage();\n\n return {\n content: [\n {\n type: 'text',\n text: message,\n },\n ],\n isError: true,\n _meta: {\n errorId: this.errorId,\n code: this.code,\n timestamp: new Date().toISOString(),\n ...(isDevelopment && { stack: this.stack }),\n },\n };\n }\n}\n\n/**\n * Public errors - safe to expose to clients\n * These include validation errors, not found errors, etc.\n */\nexport class PublicMcpError extends McpError {\n readonly isPublic = true;\n readonly statusCode: number;\n readonly code: string;\n\n constructor(message: string, code = 'PUBLIC_ERROR', statusCode = 400) {\n super(message);\n this.code = code;\n this.statusCode = statusCode;\n }\n\n getPublicMessage(): string {\n return this.message;\n }\n}\n\n/**\n * Internal errors - should not expose details to clients\n * These are server errors, unexpected failures, etc.\n */\nexport class InternalMcpError extends McpError {\n readonly isPublic = false;\n readonly statusCode = 500;\n readonly code: string;\n\n constructor(message: string, code = 'INTERNAL_ERROR') {\n super(message);\n this.code = code;\n }\n\n getPublicMessage(): string {\n return `Internal FrontMCP error. Please contact support with error ID: ${this.errorId}`;\n }\n}\n\n// ============================================================================\n// Specific Error Classes\n// ============================================================================\n\n/**\n * Tool not found error\n */\nexport class ToolNotFoundError extends PublicMcpError {\n constructor(toolName: string) {\n super(`Tool \"${toolName}\" not found`, 'TOOL_NOT_FOUND', 404);\n }\n}\n\n/**\n * Resource not found error\n */\nexport class ResourceNotFoundError extends PublicMcpError {\n readonly uri: string;\n readonly mcpErrorCode = MCP_ERROR_CODES.RESOURCE_NOT_FOUND;\n\n constructor(uri: string) {\n super(`Resource not found: ${uri}`, 'RESOURCE_NOT_FOUND', 404);\n this.uri = uri;\n }\n\n /**\n * Convert to JSON-RPC error format per MCP specification.\n *\n * @example\n * {\n * \"code\": -32002,\n * \"message\": \"Resource not found: file:///missing.txt\",\n * \"data\": { \"uri\": \"file:///missing.txt\" }\n * }\n */\n toJsonRpcError(): {\n code: number;\n message: string;\n data?: { uri: string };\n } {\n return {\n code: this.mcpErrorCode,\n message: this.getPublicMessage(),\n data: { uri: this.uri },\n };\n }\n}\n\n/**\n * Resource read error (internal)\n */\nexport class ResourceReadError extends InternalMcpError {\n readonly originalError?: Error;\n\n constructor(uri: string, originalError?: Error) {\n super(`Resource \"${uri}\" read failed: ${originalError?.message || 'Unknown error'}`, 'RESOURCE_READ_ERROR');\n this.originalError = originalError;\n }\n\n override getInternalMessage(): string {\n if (this.originalError?.stack) {\n return `${this.message}\\n\\nOriginal error:\\n${this.originalError.stack}`;\n }\n return this.message;\n }\n}\n\n/**\n * Invalid resource URI error\n */\nexport class InvalidResourceUriError extends PublicMcpError {\n constructor(uri: string, reason?: string) {\n super(`Invalid resource URI: ${uri}${reason ? ` (${reason})` : ''}`, 'INVALID_RESOURCE_URI', 400);\n }\n}\n\n/**\n * Invalid input validation error\n */\nexport class InvalidInputError extends PublicMcpError {\n readonly validationErrors?: any;\n\n constructor(message = 'Invalid input: validation failed', validationErrors?: any) {\n super(message, 'INVALID_INPUT', 400);\n this.validationErrors = validationErrors;\n }\n\n override getInternalMessage(): string {\n return this.message + (this.validationErrors ? `\\nDetails: ${JSON.stringify(this.validationErrors, null, 2)}` : '');\n }\n override getPublicMessage(): string {\n if (this.validationErrors) {\n return `${this.message}\\nDetails: ${JSON.stringify(this.validationErrors, null, 2)}`;\n }\n return this.message;\n }\n}\n\n/**\n * Invalid output validation error (internal - don't expose schema details)\n */\nexport class InvalidOutputError extends InternalMcpError {\n private readonly hasCustomErrorId: boolean;\n\n constructor(errorId?: string) {\n super('Tool output validation failed', 'INVALID_OUTPUT');\n this.hasCustomErrorId = !!errorId;\n if (errorId) {\n this.errorId = errorId;\n }\n }\n\n override getPublicMessage(): string {\n // If a custom errorId was provided (e.g., request ID), include it for correlation\n // Otherwise, use a simpler message since the auto-generated ID isn't meaningful to users\n if (this.hasCustomErrorId) {\n return `Output validation failed. Please contact support with error ID: ${this.errorId}`;\n }\n return 'Output validation failed. Please contact support.';\n }\n}\n\n/**\n * Invalid method error\n */\nexport class InvalidMethodError extends PublicMcpError {\n constructor(method: string, expected: string) {\n super(`Invalid method \"${method}\". Expected \"${expected}\"`, 'INVALID_METHOD', 400);\n }\n}\n\n/**\n * Tool execution error (internal)\n */\nexport class ToolExecutionError extends InternalMcpError {\n readonly originalError?: Error;\n\n constructor(toolName: string, originalError?: Error) {\n super(`Tool \"${toolName}\" execution failed: ${originalError?.message || 'Unknown error'}`, 'TOOL_EXECUTION_ERROR');\n this.originalError = originalError;\n }\n\n override getInternalMessage(): string {\n if (this.originalError?.stack) {\n return `${this.message}\\n\\nOriginal error:\\n${this.originalError.stack}`;\n }\n return this.message;\n }\n}\n\n/**\n * Rate limit error\n */\nexport class RateLimitError extends PublicMcpError {\n constructor(retryAfter?: number) {\n const message = retryAfter ? `Rate limit exceeded. Retry after ${retryAfter} seconds` : 'Rate limit exceeded';\n super(message, 'RATE_LIMIT_EXCEEDED', 429);\n }\n}\n\n/**\n * Quota exceeded error\n */\nexport class QuotaExceededError extends PublicMcpError {\n constructor(quotaType = 'usage') {\n super(`${quotaType} quota exceeded`, 'QUOTA_EXCEEDED', 429);\n }\n}\n\n/**\n * Unauthorized error\n */\nexport class UnauthorizedError extends PublicMcpError {\n constructor(message = 'Unauthorized') {\n super(message, 'UNAUTHORIZED', 401);\n }\n}\n\n/**\n * Generic server error wrapper\n */\nexport class GenericServerError extends InternalMcpError {\n readonly originalError?: Error;\n\n constructor(message: string, originalError?: Error) {\n super(message, 'SERVER_ERROR');\n this.originalError = originalError;\n }\n\n override getInternalMessage(): string {\n if (this.originalError?.stack) {\n return `${this.message}\\n\\nOriginal error:\\n${this.originalError.stack}`;\n }\n return this.message;\n }\n}\n\n/**\n * Dependency not found error (internal) - thrown when a required dependency\n * is not found in a registry during initialization.\n */\nexport class DependencyNotFoundError extends InternalMcpError {\n constructor(registryName: string, dependencyName: string) {\n super(`Dependency \"${dependencyName}\" not found in ${registryName}`, 'DEPENDENCY_NOT_FOUND');\n }\n}\n\n/**\n * Invalid hook flow error - thrown when a hook is registered with a flow\n * that is not supported by the entry type (e.g., tool hook on resource class).\n */\nexport class InvalidHookFlowError extends InternalMcpError {\n constructor(message: string) {\n super(message, 'INVALID_HOOK_FLOW');\n }\n}\n\n/**\n * Auth configuration error - thrown when auth configuration is invalid\n * (e.g., transparent mode on parent with multiple child providers).\n */\nexport class AuthConfigurationError extends PublicMcpError {\n readonly errors: string[];\n readonly suggestion?: string;\n\n constructor(message: string, options?: { errors?: string[]; suggestion?: string }) {\n super(message, 'AUTH_CONFIGURATION_ERROR', 500);\n this.errors = options?.errors ?? [message];\n this.suggestion = options?.suggestion;\n }\n\n override getPublicMessage(): string {\n let msg = this.message;\n if (this.suggestion) {\n msg += `\\n\\nTo fix this issue:\\n${this.suggestion}`;\n }\n return msg;\n }\n}\n\n// ============================================================================\n// Prompt Errors\n// ============================================================================\n\n/**\n * Prompt not found error.\n */\nexport class PromptNotFoundError extends PublicMcpError {\n constructor(promptName: string) {\n super(`Prompt not found: ${promptName}`, 'PROMPT_NOT_FOUND', 404);\n }\n}\n\n/**\n * Prompt execution error - wraps errors during prompt execution.\n */\nexport class PromptExecutionError extends InternalMcpError {\n readonly promptName: string;\n readonly originalError?: Error;\n\n constructor(promptName: string, cause?: Error) {\n super(\n cause ? `Prompt execution failed: ${cause.message}` : `Prompt execution failed: ${promptName}`,\n 'PROMPT_EXECUTION_FAILED',\n );\n this.promptName = promptName;\n this.originalError = cause;\n }\n\n override getInternalMessage(): string {\n if (this.originalError?.stack) {\n return `${this.message}\\n\\nOriginal error:\\n${this.originalError.stack}`;\n }\n return this.message;\n }\n}\n\n// ============================================================================\n// Error Utilities\n// ============================================================================\n\n/**\n * Check if the error is a public error that can be safely shown to users\n */\nexport function isPublicError(error: any): error is PublicMcpError {\n return error instanceof McpError && error.isPublic;\n}\n\n/**\n * Convert any error to an MCP error\n */\nexport function toMcpError(error: any): McpError {\n if (error instanceof McpError) {\n return error;\n }\n\n if (error instanceof Error) {\n return new GenericServerError(error.message, error);\n }\n\n return new GenericServerError(String(error));\n}\n\n/**\n * Format error for MCP response\n */\nexport function formatMcpErrorResponse(error: any, isDevelopment: boolean = process.env['NODE_ENV'] !== 'production') {\n const mcpError = toMcpError(error);\n return mcpError.toMcpError(isDevelopment);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"mcp.error.js","sourceRoot":"","sources":["../../../src/errors/mcp.error.ts"],"names":[],"mappings":";;;AA+cA,sCAEC;AAKD,gCAUC;AAKD,wDAGC;AAxeD,sBAAsB;AACtB,mCAAqC;AAErC;;;GAGG;AACU,QAAA,eAAe,GAAG;IAC7B,kCAAkC;IAClC,kBAAkB,EAAE,CAAC,KAAK;IAC1B,+BAA+B;IAC/B,eAAe,EAAE,CAAC,KAAK;IACvB,gCAAgC;IAChC,gBAAgB,EAAE,CAAC,KAAK;IACxB,8BAA8B;IAC9B,cAAc,EAAE,CAAC,KAAK;IACtB,8BAA8B;IAC9B,cAAc,EAAE,CAAC,KAAK;IACtB,2BAA2B;IAC3B,WAAW,EAAE,CAAC,KAAK;CACX,CAAC;AAIX;;GAEG;AACH,MAAsB,QAAS,SAAQ,KAAK;IAC1C;;OAEG;IACH,OAAO,CAAS;IAiBhB,YAAsB,OAAe,EAAE,OAAgB;QACrD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;QAClC,IAAI,CAAC,OAAO,GAAG,OAAO,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;QACjD,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IAClD,CAAC;IAEO,eAAe;QACrB,OAAO,OAAO,IAAA,oBAAW,EAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;IACjD,CAAC;IAOD;;OAEG;IACH,kBAAkB;QAChB,OAAO,IAAI,CAAC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Y;IAClH,MAAM,QAAQ,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC;IACnC,OAAO,QAAQ,CAAC,UAAU,CAAC,aAAa,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["// errors/mcp.error.ts\nimport { randomBytes } from 'crypto';\n\n/**\n * MCP-specific error codes per JSON-RPC specification.\n * These codes are used in the JSON-RPC error response format.\n */\nexport const MCP_ERROR_CODES = {\n /** Resource not found (-32002) */\n RESOURCE_NOT_FOUND: -32002,\n /** Invalid request (-32600) */\n INVALID_REQUEST: -32600,\n /** Method not found (-32601) */\n METHOD_NOT_FOUND: -32601,\n /** Invalid params (-32602) */\n INVALID_PARAMS: -32602,\n /** Internal error (-32603) */\n INTERNAL_ERROR: -32603,\n /** Parse error (-32700) */\n PARSE_ERROR: -32700,\n} as const;\n\nexport type McpErrorCode = (typeof MCP_ERROR_CODES)[keyof typeof MCP_ERROR_CODES];\n\n/**\n * Base class for all MCP-related errors\n */\nexport abstract class McpError extends Error {\n /**\n * Unique error ID for tracking in logs\n */\n errorId: string;\n\n /**\n * Whether this error should expose details to the client\n */\n abstract readonly isPublic: boolean;\n\n /**\n * HTTP status code equivalent (for reference)\n */\n abstract readonly statusCode: number;\n\n /**\n * Error code for categorization\n */\n abstract readonly code: string;\n\n protected constructor(message: string, errorId?: string) {\n super(message);\n this.name = this.constructor.name;\n this.errorId = errorId || this.generateErrorId();\n Error.captureStackTrace(this, this.constructor);\n }\n\n private generateErrorId(): string {\n return `err_${randomBytes(8).toString('hex')}`;\n }\n\n /**\n * Get the public-facing error message\n */\n abstract getPublicMessage(): string;\n\n /**\n * Get the internal error message (for logging)\n */\n getInternalMessage(): string {\n return this.message;\n }\n\n /**\n * Convert to MCP error response format\n */\n toMcpError(isDevelopment = false): {\n content: Array<{ type: 'text'; text: string }>;\n isError: true;\n _meta?: {\n errorId: string;\n code: string;\n timestamp: string;\n stack?: string;\n };\n } {\n const message = isDevelopment ? this.getInternalMessage() : this.getPublicMessage();\n\n return {\n content: [\n {\n type: 'text',\n text: message,\n },\n ],\n isError: true,\n _meta: {\n errorId: this.errorId,\n code: this.code,\n timestamp: new Date().toISOString(),\n ...(isDevelopment && { stack: this.stack }),\n },\n };\n }\n}\n\n/**\n * Public errors - safe to expose to clients\n * These include validation errors, not found errors, etc.\n */\nexport class PublicMcpError extends McpError {\n readonly isPublic = true;\n readonly statusCode: number;\n readonly code: string;\n\n constructor(message: string, code = 'PUBLIC_ERROR', statusCode = 400) {\n super(message);\n this.code = code;\n this.statusCode = statusCode;\n }\n\n getPublicMessage(): string {\n return this.message;\n }\n}\n\n/**\n * Internal errors - should not expose details to clients\n * These are server errors, unexpected failures, etc.\n */\nexport class InternalMcpError extends McpError {\n readonly isPublic = false;\n readonly statusCode = 500;\n readonly code: string;\n\n constructor(message: string, code = 'INTERNAL_ERROR') {\n super(message);\n this.code = code;\n }\n\n getPublicMessage(): string {\n return `Internal FrontMCP error. Please contact support with error ID: ${this.errorId}`;\n }\n}\n\n// ============================================================================\n// Specific Error Classes\n// ============================================================================\n\n/**\n * Tool not found error\n */\nexport class ToolNotFoundError extends PublicMcpError {\n constructor(toolName: string) {\n super(`Tool \"${toolName}\" not found`, 'TOOL_NOT_FOUND', 404);\n }\n}\n\n/**\n * Resource not found error\n */\nexport class ResourceNotFoundError extends PublicMcpError {\n readonly uri: string;\n readonly mcpErrorCode = MCP_ERROR_CODES.RESOURCE_NOT_FOUND;\n\n constructor(uri: string) {\n super(`Resource not found: ${uri}`, 'RESOURCE_NOT_FOUND', 404);\n this.uri = uri;\n }\n\n /**\n * Convert to JSON-RPC error format per MCP specification.\n *\n * @example\n * {\n * \"code\": -32002,\n * \"message\": \"Resource not found: file:///missing.txt\",\n * \"data\": { \"uri\": \"file:///missing.txt\" }\n * }\n */\n toJsonRpcError(): {\n code: number;\n message: string;\n data?: { uri: string };\n } {\n return {\n code: this.mcpErrorCode,\n message: this.getPublicMessage(),\n data: { uri: this.uri },\n };\n }\n}\n\n/**\n * Resource read error (internal)\n */\nexport class ResourceReadError extends InternalMcpError {\n readonly originalError?: Error;\n\n constructor(uri: string, originalError?: Error) {\n super(`Resource \"${uri}\" read failed: ${originalError?.message || 'Unknown error'}`, 'RESOURCE_READ_ERROR');\n this.originalError = originalError;\n }\n\n override getInternalMessage(): string {\n if (this.originalError?.stack) {\n return `${this.message}\\n\\nOriginal error:\\n${this.originalError.stack}`;\n }\n return this.message;\n }\n}\n\n/**\n * Invalid resource URI error\n */\nexport class InvalidResourceUriError extends PublicMcpError {\n constructor(uri: string, reason?: string) {\n super(`Invalid resource URI: ${uri}${reason ? ` (${reason})` : ''}`, 'INVALID_RESOURCE_URI', 400);\n }\n}\n\n/**\n * Invalid input validation error\n */\nexport class InvalidInputError extends PublicMcpError {\n readonly validationErrors?: any;\n\n constructor(message = 'Invalid input: validation failed', validationErrors?: any) {\n super(message, 'INVALID_INPUT', 400);\n this.validationErrors = validationErrors;\n }\n\n override getInternalMessage(): string {\n return this.message + (this.validationErrors ? `\\nDetails: ${JSON.stringify(this.validationErrors, null, 2)}` : '');\n }\n override getPublicMessage(): string {\n if (this.validationErrors) {\n return `${this.message}\\nDetails: ${JSON.stringify(this.validationErrors, null, 2)}`;\n }\n return this.message;\n }\n}\n\n/**\n * Invalid output validation error (internal - don't expose schema details)\n */\nexport class InvalidOutputError extends InternalMcpError {\n private readonly hasCustomErrorId: boolean;\n\n constructor(errorId?: string) {\n super('Tool output validation failed', 'INVALID_OUTPUT');\n this.hasCustomErrorId = !!errorId;\n if (errorId) {\n this.errorId = errorId;\n }\n }\n\n override getPublicMessage(): string {\n // If a custom errorId was provided (e.g., request ID), include it for correlation\n // Otherwise, use a simpler message since the auto-generated ID isn't meaningful to users\n if (this.hasCustomErrorId) {\n return `Output validation failed. Please contact support with error ID: ${this.errorId}`;\n }\n return 'Output validation failed. Please contact support.';\n }\n}\n\n/**\n * Invalid method error\n */\nexport class InvalidMethodError extends PublicMcpError {\n constructor(method: string, expected: string) {\n super(`Invalid method \"${method}\". Expected \"${expected}\"`, 'INVALID_METHOD', 400);\n }\n}\n\n/**\n * Tool execution error (internal)\n */\nexport class ToolExecutionError extends InternalMcpError {\n readonly originalError?: Error;\n\n constructor(toolName: string, originalError?: Error) {\n super(`Tool \"${toolName}\" execution failed: ${originalError?.message || 'Unknown error'}`, 'TOOL_EXECUTION_ERROR');\n this.originalError = originalError;\n }\n\n override getInternalMessage(): string {\n if (this.originalError?.stack) {\n return `${this.message}\\n\\nOriginal error:\\n${this.originalError.stack}`;\n }\n return this.message;\n }\n}\n\n/**\n * Rate limit error\n */\nexport class RateLimitError extends PublicMcpError {\n constructor(retryAfter?: number) {\n const message = retryAfter ? `Rate limit exceeded. Retry after ${retryAfter} seconds` : 'Rate limit exceeded';\n super(message, 'RATE_LIMIT_EXCEEDED', 429);\n }\n}\n\n/**\n * Quota exceeded error\n */\nexport class QuotaExceededError extends PublicMcpError {\n constructor(quotaType = 'usage') {\n super(`${quotaType} quota exceeded`, 'QUOTA_EXCEEDED', 429);\n }\n}\n\n/**\n * Unauthorized error\n */\nexport class UnauthorizedError extends PublicMcpError {\n constructor(message = 'Unauthorized') {\n super(message, 'UNAUTHORIZED', 401);\n }\n}\n\n/**\n * Generic server error wrapper\n */\nexport class GenericServerError extends InternalMcpError {\n readonly originalError?: Error;\n\n constructor(message: string, originalError?: Error) {\n super(message, 'SERVER_ERROR');\n this.originalError = originalError;\n }\n\n override getInternalMessage(): string {\n if (this.originalError?.stack) {\n return `${this.message}\\n\\nOriginal error:\\n${this.originalError.stack}`;\n }\n return this.message;\n }\n}\n\n/**\n * Dependency not found error (internal) - thrown when a required dependency\n * is not found in a registry during initialization.\n */\nexport class DependencyNotFoundError extends InternalMcpError {\n constructor(registryName: string, dependencyName: string) {\n super(`Dependency \"${dependencyName}\" not found in ${registryName}`, 'DEPENDENCY_NOT_FOUND');\n }\n}\n\n/**\n * Invalid hook flow error - thrown when a hook is registered with a flow\n * that is not supported by the entry type (e.g., tool hook on resource class).\n */\nexport class InvalidHookFlowError extends InternalMcpError {\n constructor(message: string) {\n super(message, 'INVALID_HOOK_FLOW');\n }\n}\n\n/**\n * Request context not available error - thrown when code attempts to access\n * RequestContext outside of a request scope (i.e., without AsyncLocalStorage context).\n */\nexport class RequestContextNotAvailableError extends InternalMcpError {\n constructor(\n message = 'RequestContext not available. Ensure execution runs within a request scope created by RequestContextStorage.run().',\n ) {\n super(message, 'REQUEST_CONTEXT_NOT_AVAILABLE');\n }\n}\n\n/**\n * Auth configuration error - thrown when auth configuration is invalid\n * (e.g., transparent mode on parent with multiple child providers).\n */\nexport class AuthConfigurationError extends PublicMcpError {\n readonly errors: string[];\n readonly suggestion?: string;\n\n constructor(message: string, options?: { errors?: string[]; suggestion?: string }) {\n super(message, 'AUTH_CONFIGURATION_ERROR', 500);\n this.errors = options?.errors ?? [message];\n this.suggestion = options?.suggestion;\n }\n\n override getPublicMessage(): string {\n let msg = this.message;\n if (this.suggestion) {\n msg += `\\n\\nTo fix this issue:\\n${this.suggestion}`;\n }\n return msg;\n }\n}\n\n// ============================================================================\n// Prompt Errors\n// ============================================================================\n\n/**\n * Prompt not found error.\n */\nexport class PromptNotFoundError extends PublicMcpError {\n constructor(promptName: string) {\n super(`Prompt not found: ${promptName}`, 'PROMPT_NOT_FOUND', 404);\n }\n}\n\n/**\n * Prompt execution error - wraps errors during prompt execution.\n */\nexport class PromptExecutionError extends InternalMcpError {\n readonly promptName: string;\n readonly originalError?: Error;\n\n constructor(promptName: string, cause?: Error) {\n super(\n cause ? `Prompt execution failed: ${cause.message}` : `Prompt execution failed: ${promptName}`,\n 'PROMPT_EXECUTION_FAILED',\n );\n this.promptName = promptName;\n this.originalError = cause;\n }\n\n override getInternalMessage(): string {\n if (this.originalError?.stack) {\n return `${this.message}\\n\\nOriginal error:\\n${this.originalError.stack}`;\n }\n return this.message;\n }\n}\n\n// ============================================================================\n// Configuration Errors\n// ============================================================================\n\n/**\n * Global configuration not found error - thrown when a plugin requires\n * global configuration that is not defined in @FrontMcp decorator.\n */\nexport class GlobalConfigNotFoundError extends PublicMcpError {\n readonly pluginName: string;\n readonly configKey: string;\n\n constructor(pluginName: string, configKey: string) {\n super(\n `Plugin \"${pluginName}\" requires global \"${configKey}\" configuration. ` +\n `Add \"${configKey}\" to your @FrontMcp decorator options.`,\n 'GLOBAL_CONFIG_NOT_FOUND',\n 500,\n );\n this.pluginName = pluginName;\n this.configKey = configKey;\n }\n}\n\n// ============================================================================\n// Error Utilities\n// ============================================================================\n\n/**\n * Check if the error is a public error that can be safely shown to users\n */\nexport function isPublicError(error: any): error is PublicMcpError {\n return error instanceof McpError && error.isPublic;\n}\n\n/**\n * Convert any error to an MCP error\n */\nexport function toMcpError(error: any): McpError {\n if (error instanceof McpError) {\n return error;\n }\n\n if (error instanceof Error) {\n return new GenericServerError(error.message, error);\n }\n\n return new GenericServerError(String(error));\n}\n\n/**\n * Format error for MCP response\n */\nexport function formatMcpErrorResponse(error: any, isDevelopment: boolean = process.env['NODE_ENV'] !== 'production') {\n const mcpError = toMcpError(error);\n return mcpError.toMcpError(isDevelopment);\n}\n"]}
|
|
@@ -12,5 +12,21 @@ export declare class FlowInstance<Name extends FlowName> extends FlowEntry<Name>
|
|
|
12
12
|
constructor(scope: Scope, record: FlowRecord, deps: Set<Reference>, globalProviders: ProviderRegistry);
|
|
13
13
|
protected initialize(): Promise<void>;
|
|
14
14
|
canActivate(request: ServerRequest): Promise<boolean>;
|
|
15
|
+
/**
|
|
16
|
+
* Get FrontMcpContextStorage from providers (with fallback).
|
|
17
|
+
* Returns undefined if not available (backward compatibility).
|
|
18
|
+
*/
|
|
19
|
+
private getContextStorage;
|
|
20
|
+
/**
|
|
21
|
+
* Run flow wrapped in FrontMcpContext.
|
|
22
|
+
* This ensures ALL stages have access to the context via AsyncLocalStorage.
|
|
23
|
+
*
|
|
24
|
+
* @param storage - FrontMcpContextStorage instance
|
|
25
|
+
* @param request - The HTTP request
|
|
26
|
+
* @param input - Flow input
|
|
27
|
+
* @param deps - Flow dependencies
|
|
28
|
+
* @returns Flow output or undefined
|
|
29
|
+
*/
|
|
30
|
+
private runWithContext;
|
|
15
31
|
run(input: FlowInputOf<Name>, deps: Map<Token, Type>): Promise<FlowOutputOf<Name> | undefined>;
|
|
16
32
|
}
|
|
@@ -7,6 +7,9 @@ require("reflect-metadata");
|
|
|
7
7
|
const common_1 = require("../common");
|
|
8
8
|
const flow_stages_1 = require("./flow.stages");
|
|
9
9
|
const server_validation_1 = require("../server/server.validation");
|
|
10
|
+
const context_1 = require("../context");
|
|
11
|
+
const mcp_error_1 = require("../errors/mcp.error");
|
|
12
|
+
const crypto_1 = require("crypto");
|
|
10
13
|
const CAP = (s) => (s ? s[0].toUpperCase() + s.slice(1) : s);
|
|
11
14
|
const WILL = (s) => `will${CAP(s)}`;
|
|
12
15
|
const DID = (s) => `did${CAP(s)}`;
|
|
@@ -47,8 +50,12 @@ class FlowInstance extends common_1.FlowEntry {
|
|
|
47
50
|
const canActivate = await this.canActivate(request);
|
|
48
51
|
if (!canActivate)
|
|
49
52
|
return next();
|
|
53
|
+
// Get context storage to wrap entire flow in FrontMcpContext
|
|
54
|
+
const contextStorage = this.getContextStorage();
|
|
50
55
|
try {
|
|
51
|
-
|
|
56
|
+
// Use runWithContext to wrap entire flow execution in AsyncLocalStorage context
|
|
57
|
+
// This ensures all stages have access to FrontMcpContext
|
|
58
|
+
const result = await this.runWithContext(contextStorage, request, { request, response, next }, new Map());
|
|
52
59
|
if (result)
|
|
53
60
|
return (0, server_validation_1.writeHttpResponse)(response, result);
|
|
54
61
|
}
|
|
@@ -67,8 +74,12 @@ class FlowInstance extends common_1.FlowEntry {
|
|
|
67
74
|
return (0, server_validation_1.writeHttpResponse)(response, e.output);
|
|
68
75
|
}
|
|
69
76
|
}
|
|
70
|
-
//
|
|
71
|
-
//
|
|
77
|
+
// Log unhandled errors for visibility (non-FlowControl errors indicate bugs)
|
|
78
|
+
// Note: Using structured logging to avoid Node.js util.inspect issues with Zod errors
|
|
79
|
+
console.error('[FlowInstance] Unhandled error:', {
|
|
80
|
+
name: e instanceof Error ? e.name : 'UnknownError',
|
|
81
|
+
message: e instanceof Error ? e.message : String(e),
|
|
82
|
+
});
|
|
72
83
|
return (0, server_validation_1.writeHttpResponse)(response, {
|
|
73
84
|
kind: 'text',
|
|
74
85
|
status: 500,
|
|
@@ -92,18 +103,82 @@ class FlowInstance extends common_1.FlowEntry {
|
|
|
92
103
|
const results = await Promise.all(canActivate.map((m) => m(request, this.scope)));
|
|
93
104
|
return results.every((r) => r);
|
|
94
105
|
}
|
|
106
|
+
/**
|
|
107
|
+
* Get FrontMcpContextStorage from providers (with fallback).
|
|
108
|
+
* Returns undefined if not available (backward compatibility).
|
|
109
|
+
*/
|
|
110
|
+
getContextStorage() {
|
|
111
|
+
try {
|
|
112
|
+
return this.globalProviders.get(context_1.FrontMcpContextStorage);
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
return undefined;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Run flow wrapped in FrontMcpContext.
|
|
120
|
+
* This ensures ALL stages have access to the context via AsyncLocalStorage.
|
|
121
|
+
*
|
|
122
|
+
* @param storage - FrontMcpContextStorage instance
|
|
123
|
+
* @param request - The HTTP request
|
|
124
|
+
* @param input - Flow input
|
|
125
|
+
* @param deps - Flow dependencies
|
|
126
|
+
* @returns Flow output or undefined
|
|
127
|
+
*/
|
|
128
|
+
async runWithContext(storage, request, input, deps) {
|
|
129
|
+
// If no storage available, run without context (backward compatibility)
|
|
130
|
+
if (!storage) {
|
|
131
|
+
return this.run(input, deps);
|
|
132
|
+
}
|
|
133
|
+
// Extract context parameters from request
|
|
134
|
+
const headers = (request.headers ?? {});
|
|
135
|
+
// Generate unique ID for anonymous sessions to prevent session collision
|
|
136
|
+
// All unauthenticated requests previously shared 'anonymous', causing data leakage
|
|
137
|
+
// Handle empty strings explicitly: '' ?? 'fallback' returns '', not 'fallback'
|
|
138
|
+
const headerSessionId = typeof headers['mcp-session-id'] === 'string' ? headers['mcp-session-id'].trim() : '';
|
|
139
|
+
const sessionId = headerSessionId.length > 0 ? headerSessionId : `anon:${(0, crypto_1.randomUUID)()}`;
|
|
140
|
+
const scope = this.globalProviders.getActiveScope();
|
|
141
|
+
// Wrap ENTIRE flow execution in AsyncLocalStorage context
|
|
142
|
+
return storage.runFromHeaders(headers, {
|
|
143
|
+
sessionId,
|
|
144
|
+
scopeId: scope.id,
|
|
145
|
+
}, async () => {
|
|
146
|
+
return this.run(input, deps);
|
|
147
|
+
});
|
|
148
|
+
}
|
|
95
149
|
async run(input, deps) {
|
|
96
150
|
const scope = this.globalProviders.getActiveScope();
|
|
97
151
|
const { FlowClass, plan, name } = this;
|
|
152
|
+
// Build provider views for scoped DI
|
|
153
|
+
// This enables CONTEXT scoped providers to be resolved
|
|
154
|
+
const contextStorage = this.getContextStorage();
|
|
155
|
+
const currentContext = contextStorage?.getStore();
|
|
156
|
+
// Get session ID from context - should always be available since runWithContext wraps the entire flow
|
|
157
|
+
// If unavailable, it indicates a bug in context propagation (not a normal case)
|
|
158
|
+
const sessionKey = currentContext?.sessionId;
|
|
159
|
+
if (!sessionKey) {
|
|
160
|
+
// This should never happen since runWithContext wraps the entire flow execution
|
|
161
|
+
// If we reach here, there's a bug in context propagation
|
|
162
|
+
throw new mcp_error_1.RequestContextNotAvailableError('FrontMcpContext unavailable - session ID required for provider resolution. Ensure flow is wrapped with runWithContext.');
|
|
163
|
+
}
|
|
164
|
+
// Build views with current context if available
|
|
165
|
+
const views = await this.globalProviders.buildViews(sessionKey, currentContext ? new Map([[context_1.FRONTMCP_CONTEXT, currentContext]]) : undefined);
|
|
166
|
+
// Merge context-scoped providers into deps for resolution by FlowClass
|
|
167
|
+
const mergedDeps = new Map(deps);
|
|
168
|
+
for (const [token, instance] of views.context) {
|
|
169
|
+
mergedDeps.set(token, instance);
|
|
170
|
+
}
|
|
98
171
|
// Clone stages so we can merge injections safely per run.
|
|
99
172
|
const baseStages = this.stages;
|
|
100
|
-
|
|
173
|
+
const stages = (0, flow_stages_1.cloneStageMap)(baseStages);
|
|
101
174
|
// Compute next order base after any class-defined entries.
|
|
102
175
|
let orderBase = Math.max(0, ...Object.values(stages).flatMap((list) => list.map((e) => e._order ?? 0))) + 1;
|
|
103
176
|
// Get tool owner ID if this is a tool call flow
|
|
104
177
|
// The tool owner ID is set by the CallToolFlow.findTool stage
|
|
105
178
|
const toolOwnerId = input?._toolOwnerId;
|
|
106
179
|
const initialInjectedHooks = this.hooks.getFlowHooksForOwner(name, toolOwnerId) ?? [];
|
|
180
|
+
// FlowClass generic type is erased at runtime, so we use FlowBase<any>
|
|
181
|
+
// to avoid complex type gymnastics while maintaining basic type safety
|
|
107
182
|
let context;
|
|
108
183
|
let contextReady = false;
|
|
109
184
|
const materializeAndMerge = async (newHooks, opts) => {
|
|
@@ -116,7 +191,6 @@ class FlowInstance extends common_1.FlowEntry {
|
|
|
116
191
|
}
|
|
117
192
|
catch (e) {
|
|
118
193
|
// Use safe logging to avoid Node.js 24 util.inspect bug with Zod errors
|
|
119
|
-
// eslint-disable-next-line no-console
|
|
120
194
|
console.warn('[flow] Ignoring injected hook that failed to materialize:', e instanceof Error ? e.message : 'Unknown error');
|
|
121
195
|
}
|
|
122
196
|
}
|
|
@@ -130,8 +204,9 @@ class FlowInstance extends common_1.FlowEntry {
|
|
|
130
204
|
const appendContextHooks = async (hooks) => {
|
|
131
205
|
await materializeAndMerge(hooks);
|
|
132
206
|
};
|
|
133
|
-
// Construct flow instance
|
|
134
|
-
|
|
207
|
+
// Construct flow instance with merged dependencies (includes scoped providers)
|
|
208
|
+
// eslint-disable-next-line prefer-const -- declaration must precede helper functions that close over context
|
|
209
|
+
context = new FlowClass(this.metadata, input, scope, appendContextHooks, mergedDeps);
|
|
135
210
|
// Now injections can materialize
|
|
136
211
|
contextReady = true;
|
|
137
212
|
// Initial registry hooks should not pre-empt stages; they just get registered
|
|
@@ -237,97 +312,108 @@ class FlowInstance extends common_1.FlowEntry {
|
|
|
237
312
|
const runErrorStage = async () => {
|
|
238
313
|
await runStageGroup(plan.error, false, { ignoreRespond: true });
|
|
239
314
|
};
|
|
240
|
-
const runFinalizeStage = async () => {
|
|
241
|
-
await runStageGroup(plan.finalize, false);
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
try {
|
|
251
|
-
await runErrorStage();
|
|
252
|
-
}
|
|
253
|
-
finally {
|
|
254
|
-
await runFinalizeStage();
|
|
255
|
-
}
|
|
256
|
-
if (post.outcome === 'fail')
|
|
257
|
-
throw post.control;
|
|
258
|
-
throw post.control;
|
|
259
|
-
}
|
|
260
|
-
if (post.outcome === 'abort' || post.outcome === 'next' || post.outcome === 'handled') {
|
|
261
|
-
await runFinalizeStage();
|
|
262
|
-
throw post.control;
|
|
263
|
-
}
|
|
264
|
-
await runFinalizeStage();
|
|
265
|
-
return responded;
|
|
315
|
+
const runFinalizeStage = async (options) => {
|
|
316
|
+
const res = await runStageGroup(plan.finalize, false);
|
|
317
|
+
// Handle finalize stage errors
|
|
318
|
+
if (res.outcome === 'unknown_error' || res.outcome === 'fail') {
|
|
319
|
+
const finalizeError = res.control ?? new mcp_error_1.InternalMcpError('Finalize stage failed');
|
|
320
|
+
if (options?.suppressErrors) {
|
|
321
|
+
// Log finalizes errors but doesn't throw when called from finally blocks
|
|
322
|
+
// This prevents masking the original error
|
|
323
|
+
this.scope.logger.error('[FrontMCP] Finalize stage error (suppressed to preserve original error):', finalizeError);
|
|
324
|
+
return res;
|
|
266
325
|
}
|
|
267
|
-
|
|
326
|
+
throw finalizeError;
|
|
327
|
+
}
|
|
328
|
+
return res;
|
|
329
|
+
};
|
|
330
|
+
// ---------- PRE ----------
|
|
331
|
+
{
|
|
332
|
+
const pre = await runStageGroup(plan.pre, true);
|
|
333
|
+
if (pre.outcome === 'respond') {
|
|
334
|
+
const post = await runStageGroup(plan.post, false);
|
|
335
|
+
if (post.outcome === 'unknown_error' || post.outcome === 'fail') {
|
|
268
336
|
try {
|
|
269
337
|
await runErrorStage();
|
|
270
338
|
}
|
|
271
339
|
finally {
|
|
272
|
-
await runFinalizeStage();
|
|
340
|
+
await runFinalizeStage({ suppressErrors: true });
|
|
273
341
|
}
|
|
274
|
-
|
|
275
|
-
throw pre.control;
|
|
276
|
-
throw pre.control;
|
|
342
|
+
throw post.control ?? new mcp_error_1.InternalMcpError('Missing control for fail/error outcome');
|
|
277
343
|
}
|
|
278
|
-
if (
|
|
279
|
-
await runFinalizeStage();
|
|
280
|
-
|
|
344
|
+
if (post.outcome === 'abort' || post.outcome === 'next' || post.outcome === 'handled') {
|
|
345
|
+
await runFinalizeStage({ suppressErrors: true });
|
|
346
|
+
if (!(post.control instanceof common_1.FlowControl)) {
|
|
347
|
+
throw new mcp_error_1.InternalMcpError('Expected FlowControl but received different error type');
|
|
348
|
+
}
|
|
349
|
+
throw post.control;
|
|
281
350
|
}
|
|
351
|
+
await runFinalizeStage();
|
|
352
|
+
return responded;
|
|
282
353
|
}
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
if (exec.outcome === 'respond') {
|
|
287
|
-
// continue to post + finalize
|
|
354
|
+
if (pre.outcome === 'unknown_error' || pre.outcome === 'fail') {
|
|
355
|
+
try {
|
|
356
|
+
await runErrorStage();
|
|
288
357
|
}
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
await runErrorStage();
|
|
292
|
-
}
|
|
293
|
-
finally {
|
|
294
|
-
await runFinalizeStage();
|
|
295
|
-
}
|
|
296
|
-
if (exec.outcome === 'fail')
|
|
297
|
-
throw exec.control;
|
|
298
|
-
throw exec.control;
|
|
358
|
+
finally {
|
|
359
|
+
await runFinalizeStage({ suppressErrors: true });
|
|
299
360
|
}
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
361
|
+
throw pre.control ?? new mcp_error_1.InternalMcpError('Missing control for fail/error outcome');
|
|
362
|
+
}
|
|
363
|
+
if (pre.outcome === 'abort' || pre.outcome === 'next' || pre.outcome === 'handled') {
|
|
364
|
+
await runFinalizeStage({ suppressErrors: true });
|
|
365
|
+
if (!(pre.control instanceof common_1.FlowControl)) {
|
|
366
|
+
throw new mcp_error_1.InternalMcpError('Expected FlowControl but received different error type');
|
|
303
367
|
}
|
|
368
|
+
throw pre.control;
|
|
304
369
|
}
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
if (post.outcome === 'fail')
|
|
316
|
-
throw post.control;
|
|
317
|
-
throw post.control;
|
|
370
|
+
}
|
|
371
|
+
// ---------- EXECUTE ----------
|
|
372
|
+
if (!responded) {
|
|
373
|
+
const exec = await runStageGroup(plan.execute, true);
|
|
374
|
+
if (exec.outcome === 'respond') {
|
|
375
|
+
// continue to post + finalize
|
|
376
|
+
}
|
|
377
|
+
else if (exec.outcome === 'unknown_error' || exec.outcome === 'fail') {
|
|
378
|
+
try {
|
|
379
|
+
await runErrorStage();
|
|
318
380
|
}
|
|
319
|
-
|
|
320
|
-
await runFinalizeStage();
|
|
321
|
-
|
|
381
|
+
finally {
|
|
382
|
+
await runFinalizeStage({ suppressErrors: true });
|
|
383
|
+
}
|
|
384
|
+
throw exec.control ?? new mcp_error_1.InternalMcpError('Missing control for fail/error outcome');
|
|
385
|
+
}
|
|
386
|
+
else if (exec.outcome === 'abort' || exec.outcome === 'next' || exec.outcome === 'handled') {
|
|
387
|
+
await runFinalizeStage({ suppressErrors: true });
|
|
388
|
+
if (!(exec.control instanceof common_1.FlowControl)) {
|
|
389
|
+
throw new mcp_error_1.InternalMcpError('Expected FlowControl but received different error type');
|
|
322
390
|
}
|
|
391
|
+
throw exec.control;
|
|
323
392
|
}
|
|
324
|
-
// ---------- FINALIZE ----------
|
|
325
|
-
await runFinalizeStage();
|
|
326
|
-
return responded;
|
|
327
393
|
}
|
|
328
|
-
|
|
329
|
-
|
|
394
|
+
// ---------- POST ----------
|
|
395
|
+
{
|
|
396
|
+
const post = await runStageGroup(plan.post, false);
|
|
397
|
+
if (post.outcome === 'unknown_error' || post.outcome === 'fail') {
|
|
398
|
+
try {
|
|
399
|
+
await runErrorStage();
|
|
400
|
+
}
|
|
401
|
+
finally {
|
|
402
|
+
await runFinalizeStage({ suppressErrors: true });
|
|
403
|
+
}
|
|
404
|
+
throw post.control ?? new mcp_error_1.InternalMcpError('Missing control for fail/error outcome');
|
|
405
|
+
}
|
|
406
|
+
if (post.outcome === 'abort' || post.outcome === 'next' || post.outcome === 'handled') {
|
|
407
|
+
await runFinalizeStage({ suppressErrors: true });
|
|
408
|
+
if (!(post.control instanceof common_1.FlowControl)) {
|
|
409
|
+
throw new mcp_error_1.InternalMcpError('Expected FlowControl but received different error type');
|
|
410
|
+
}
|
|
411
|
+
throw post.control;
|
|
412
|
+
}
|
|
330
413
|
}
|
|
414
|
+
// ---------- FINALIZE ----------
|
|
415
|
+
await runFinalizeStage();
|
|
416
|
+
return responded;
|
|
331
417
|
}
|
|
332
418
|
}
|
|
333
419
|
exports.FlowInstance = FlowInstance;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flow.instance.js","sourceRoot":"","sources":["../../../src/flows/flow.instance.ts"],"names":[],"mappings":";AAAA,wCAAwC;AACxC,yBAAyB;;;AAEzB,4BAA0B;AAC1B,sCAiBmB;AAEnB,+CAAwG;AACxG,mEAAgE;AAYhE,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACrE,MAAM,IAAI,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC,EAA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CAAC;oBACzB,MAAM,IAAI,CAAC,OAAsB,CAAC;gBACpC,CAAC;YACH,CAAC;YAED,iCAAiC;YACjC,MAAM,gBAAgB,EAAE,CAAC;YAEzB,OAAO,SAAS,CAAC;QACnB,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,MAAM,CAAC,CAAC;QACV,CAAC;IACH,CAAC;CACF;AAlVD,oCAkVC","sourcesContent":["// noinspection ExceptionCaughtLocallyJS\n// flows/flow.instance.ts\n\nimport 'reflect-metadata';\nimport {\n FlowControl,\n FlowCtxOf,\n FlowEntry,\n FlowInputOf,\n FlowName,\n FlowOutputOf,\n FlowPlan,\n FlowRecord,\n FlowStagesOf,\n FlowType,\n HookEntry,\n HookMetadata,\n Reference,\n ServerRequest,\n Token,\n Type,\n} from '../common';\nimport ProviderRegistry from '../provider/provider.registry';\nimport { collectFlowHookMap, StageMap, cloneStageMap, mergeHookMetasIntoStageMap } from './flow.stages';\nimport { writeHttpResponse } from '../server/server.validation';\nimport { Scope } from '../scope';\nimport HookRegistry from '../hooks/hook.registry';\nimport { rpcError } from '../transport/transport.error';\n\ntype StageOutcome = 'ok' | 'respond' | 'next' | 'handled' | 'fail' | 'abort' | 'unknown_error';\n\ninterface StageResult {\n outcome: StageOutcome;\n control?: FlowControl | Error;\n}\n\nconst CAP = (s: string) => (s ? s[0].toUpperCase() + s.slice(1) : s);\nconst WILL = (s: string) => `will${CAP(s)}`;\nconst DID = (s: string) => `did${CAP(s)}`;\nconst AROUND = (s: string) => `around${CAP(s)}`;\n\nfunction parseTypedKey(k: string): { base: string; type?: 'will' | 'did' | 'around' } {\n const lc = k.toLowerCase();\n if (lc.startsWith('will') && k.length > 4) return { base: k.slice(4, 5).toLowerCase() + k.slice(5), type: 'will' };\n if (lc.startsWith('did') && k.length > 3) return { base: k.slice(3, 4).toLowerCase() + k.slice(4), type: 'did' };\n if (lc.startsWith('around') && k.length > 6)\n return { base: k.slice(6, 7).toLowerCase() + k.slice(7), type: 'around' };\n return { base: k };\n}\n\nexport class FlowInstance<Name extends FlowName> extends FlowEntry<Name> {\n readonly deps: Reference[];\n readonly globalProviders: ProviderRegistry;\n private plan: FlowPlan<never>;\n private FlowClass: FlowType;\n private stages: StageMap<FlowType>;\n private hooks: HookRegistry;\n\n constructor(scope: Scope, record: FlowRecord, deps: Set<Reference>, globalProviders: ProviderRegistry) {\n super(scope, record);\n this.deps = [...deps];\n this.globalProviders = globalProviders;\n this.FlowClass = this.record.provide;\n this.ready = this.initialize();\n this.plan = this.record.metadata.plan;\n this.hooks = scope.providers.getHooksRegistry();\n }\n\n protected async initialize() {\n const server = this.globalProviders.getActiveServer();\n\n this.stages = collectFlowHookMap(this.FlowClass);\n\n const { middleware } = this.metadata;\n if (middleware) {\n const path = typeof middleware.path === 'string' ? middleware.path : '';\n server.registerMiddleware(path, async (request, response, next) => {\n const canActivate = await this.canActivate(request);\n if (!canActivate) return next();\n\n try {\n const result = await this.run({ request, response, next } as any, new Map());\n if (result) return writeHttpResponse(response, result);\n } catch (e) {\n if (e instanceof FlowControl) {\n switch (e.type) {\n case 'abort':\n return writeHttpResponse(response, { kind: 'text', status: 500, body: 'Aborted' });\n case 'fail':\n return writeHttpResponse(response, { kind: 'text', status: 500, body: 'Internal Server Error' });\n case 'handled':\n return;\n case 'next':\n return next();\n case 'respond':\n return writeHttpResponse(response, e.output as any);\n }\n }\n // Skip console.error due to Node.js 24 util.inspect bug with Zod validation errors\n // The error will be returned to the client as a 500 response\n return writeHttpResponse(response, {\n kind: 'text',\n status: 500,\n body: 'Internal Server Error',\n });\n }\n\n return next();\n });\n }\n\n return Promise.resolve();\n }\n\n async canActivate(request: ServerRequest): Promise<boolean> {\n if (this.method && request.method !== this.method) return false;\n\n const canActivate = this.metadata.middleware?.canActivate ?? [];\n if ((this.FlowClass as any)['canActivate']) {\n canActivate.push((this.FlowClass as any)['canActivate']);\n }\n if (canActivate.length === 0) return true;\n\n const results = await Promise.all(canActivate.map((m) => m(request, this.scope)));\n return results.every((r) => r);\n }\n\n async run(input: FlowInputOf<Name>, deps: Map<Token, Type>): Promise<FlowOutputOf<Name> | undefined> {\n const scope = this.globalProviders.getActiveScope();\n const { FlowClass, plan, name } = this;\n\n // Clone stages so we can merge injections safely per run.\n const baseStages = this.stages;\n let stages: StageMap<any> = cloneStageMap(baseStages);\n\n // Compute next order base after any class-defined entries.\n let orderBase = Math.max(0, ...Object.values(stages).flatMap((list) => list.map((e: any) => e._order ?? 0))) + 1;\n\n // Get tool owner ID if this is a tool call flow\n // The tool owner ID is set by the CallToolFlow.findTool stage\n const toolOwnerId = (input as any)?._toolOwnerId;\n\n const initialInjectedHooks =\n (this.hooks.getFlowHooksForOwner(name, toolOwnerId) as HookEntry<\n FlowInputOf<Name>,\n Name,\n FlowStagesOf<Name>,\n FlowCtxOf<Name>\n >[]) ?? [];\n\n let context: any;\n let contextReady = false;\n\n const materializeAndMerge = async (\n newHooks: HookEntry<FlowInputOf<Name>, Name, FlowStagesOf<Name>, FlowCtxOf<Name>>[],\n opts?: { orderStart?: number },\n ) => {\n if (!newHooks?.length || !contextReady) return;\n\n const metas: HookMetadata[] = [];\n for (const h of newHooks) {\n try {\n metas.push(h.metadata);\n } catch (e) {\n // Use safe logging to avoid Node.js 24 util.inspect bug with Zod errors\n // eslint-disable-next-line no-console\n console.warn(\n '[flow] Ignoring injected hook that failed to materialize:',\n e instanceof Error ? e.message : 'Unknown error',\n );\n }\n }\n\n if (metas.length) {\n const start = opts?.orderStart ?? orderBase;\n mergeHookMetasIntoStageMap(FlowClass, stages, metas, start);\n if (opts?.orderStart === undefined) orderBase += metas.length;\n }\n };\n\n const appendContextHooks = async (\n hooks: HookEntry<FlowInputOf<Name>, Name, FlowStagesOf<Name>, FlowCtxOf<Name>>[],\n ) => {\n await materializeAndMerge(hooks);\n };\n\n // Construct flow instance\n context = new FlowClass(this.metadata, input, scope, appendContextHooks, deps);\n\n // Now injections can materialize\n contextReady = true;\n\n // Initial registry hooks should not pre-empt stages; they just get registered\n await materializeAndMerge(initialInjectedHooks, { orderStart: -1_000_000 });\n\n // Refresh order base to be after everything currently present\n orderBase = Math.max(0, ...Object.values(stages).flatMap((list) => list.map((e: any) => e._order ?? 0))) + 1;\n\n let responded: FlowOutputOf<Name> | undefined;\n\n // Robust list runner (doesn't skip mid-run insertions)\n const runList = async (key: string, opts?: { ignoreRespond?: boolean }): Promise<StageResult> => {\n const getList = () => ((stages as any)[key] ?? []) as Array<{ method: (ctx: any) => Promise<void> }>;\n const seen = new Set<any>();\n\n while (true) {\n const list = getList();\n const item = list.find((e) => !seen.has(e));\n if (!item) break;\n seen.add(item);\n\n try {\n await item.method(context);\n } catch (e: any) {\n if (e instanceof FlowControl) {\n if (e.type === 'respond') {\n if (!opts?.ignoreRespond) {\n responded = e.output as FlowOutputOf<Name>;\n return { outcome: 'respond', control: e };\n }\n continue;\n }\n return { outcome: e.type, control: e };\n }\n return { outcome: 'unknown_error', control: e as Error };\n }\n }\n return { outcome: 'ok' };\n };\n\n // Run exactly one stage in order: will → around → stage → did (did runs once)\n const runOneStage = async (stageName: string, stopOnRespond: boolean): Promise<StageResult> => {\n // 1) willStage\n {\n const res = await runList(WILL(stageName));\n if (res.outcome === 'respond' && stopOnRespond) return res;\n if (res.outcome !== 'ok' && res.outcome !== 'respond') return res;\n }\n\n // 2) aroundStage (acts as pre-handlers unless you later add true wrapping)\n {\n const res = await runList(AROUND(stageName));\n if (res.outcome === 'respond' && stopOnRespond) return res;\n if (res.outcome !== 'ok' && res.outcome !== 'respond') return res;\n }\n\n // 3) stage\n let bodyOutcome: StageResult = { outcome: 'ok' };\n {\n const res = await runList(stageName, { ignoreRespond: false });\n bodyOutcome = res;\n if (res.outcome !== 'ok' && res.outcome !== 'respond') {\n // fail/abort/next/handled/unknown → do NOT run did\n return res;\n }\n }\n\n // 4) didStage (run once regardless of body respond)\n {\n const res = await runList(DID(stageName), { ignoreRespond: true });\n if (res.outcome !== 'ok' && res.outcome !== 'respond') return res;\n }\n\n if (bodyOutcome.outcome === 'respond') return bodyOutcome;\n return { outcome: 'ok' };\n };\n\n // IMPORTANT: ignore typed stage names in plan arrays.\n // Only base stage names in the plan drive execution; typed hooks run *with* their base.\n const runStageGroup = async (\n group: Array<string> | undefined,\n stopOnRespond: boolean,\n opts?: { ignoreRespond?: boolean },\n ): Promise<StageResult> => {\n if (!group || group.length === 0) return { outcome: 'ok' };\n\n const seenBase = new Set<string>();\n for (const rawKey of group) {\n const { base, type } = parseTypedKey(rawKey);\n if (type) {\n // Soft warning once per typed key occurrence (optional)\n // console.warn(`[flow] Ignoring typed stage \"${rawKey}\" in plan; hooks will run with base \"${base}\".`);\n continue; // Do not run typed keys as standalone stages\n }\n if (seenBase.has(base)) continue;\n seenBase.add(base);\n\n const res = await runOneStage(base, stopOnRespond);\n if (res.outcome === 'respond') {\n if (stopOnRespond) return res;\n // else keep going\n } else if (res.outcome !== 'ok') {\n return res;\n }\n }\n return { outcome: 'ok' };\n };\n\n const runErrorStage = async () => {\n await runStageGroup((plan as any).error, false, { ignoreRespond: true });\n };\n\n const runFinalizeStage = async () => {\n await runStageGroup((plan as any).finalize, false);\n };\n\n try {\n // ---------- PRE ----------\n {\n const pre = await runStageGroup((plan as any).pre, true);\n if (pre.outcome === 'respond') {\n const post = await runStageGroup((plan as any).post, false);\n if (post.outcome === 'unknown_error' || post.outcome === 'fail') {\n try {\n await runErrorStage();\n } finally {\n await runFinalizeStage();\n }\n if (post.outcome === 'fail') throw post.control!;\n throw post.control!;\n }\n if (post.outcome === 'abort' || post.outcome === 'next' || post.outcome === 'handled') {\n await runFinalizeStage();\n throw post.control as FlowControl;\n }\n await runFinalizeStage();\n return responded;\n }\n if (pre.outcome === 'unknown_error' || pre.outcome === 'fail') {\n try {\n await runErrorStage();\n } finally {\n await runFinalizeStage();\n }\n if (pre.outcome === 'fail') throw pre.control!;\n throw pre.control!;\n }\n if (pre.outcome === 'abort' || pre.outcome === 'next' || pre.outcome === 'handled') {\n await runFinalizeStage();\n throw pre.control as FlowControl;\n }\n }\n\n // ---------- EXECUTE ----------\n if (!responded) {\n const exec = await runStageGroup((plan as any).execute, true);\n if (exec.outcome === 'respond') {\n // continue to post + finalize\n } else if (exec.outcome === 'unknown_error' || exec.outcome === 'fail') {\n try {\n await runErrorStage();\n } finally {\n await runFinalizeStage();\n }\n if (exec.outcome === 'fail') throw exec.control!;\n throw exec.control!;\n } else if (exec.outcome === 'abort' || exec.outcome === 'next' || exec.outcome === 'handled') {\n await runFinalizeStage();\n throw exec.control as FlowControl;\n }\n }\n\n // ---------- POST ----------\n {\n const post = await runStageGroup((plan as any).post, false);\n if (post.outcome === 'unknown_error' || post.outcome === 'fail') {\n try {\n await runErrorStage();\n } finally {\n await runFinalizeStage();\n }\n if (post.outcome === 'fail') throw post.control!;\n throw post.control!;\n }\n if (post.outcome === 'abort' || post.outcome === 'next' || post.outcome === 'handled') {\n await runFinalizeStage();\n throw post.control as FlowControl;\n }\n }\n\n // ---------- FINALIZE ----------\n await runFinalizeStage();\n\n return responded;\n } catch (e) {\n throw e;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"flow.instance.js","sourceRoot":"","sources":["../../../src/flows/flow.instance.ts"],"names":[],"mappings":";AAAA,wCAAwC;AACxC,yBAAyB;;;AAEzB,4BAA0B;AAC1B,sCAkBmB;AAEnB,+CAAwG;AACxG,mEAAgE;AAIhE,wCAAsE;AACtE,mDAAwF;AACxF,mCAAoC;AASpC,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACrE,MAAM,IAAI,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;AAC5C,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC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';\nimport {\n FlowBase,\n FlowControl,\n FlowCtxOf,\n FlowEntry,\n FlowInputOf,\n FlowName,\n FlowOutputOf,\n FlowPlan,\n FlowRecord,\n FlowStagesOf,\n FlowType,\n HookEntry,\n HookMetadata,\n Reference,\n ServerRequest,\n Token,\n Type,\n} from '../common';\nimport ProviderRegistry from '../provider/provider.registry';\nimport { collectFlowHookMap, StageMap, cloneStageMap, mergeHookMetasIntoStageMap } from './flow.stages';\nimport { writeHttpResponse } from '../server/server.validation';\nimport { Scope } from '../scope';\nimport HookRegistry from '../hooks/hook.registry';\nimport { rpcError } from '../transport/transport.error';\nimport { FrontMcpContextStorage, FRONTMCP_CONTEXT } from '../context';\nimport { RequestContextNotAvailableError, InternalMcpError } from '../errors/mcp.error';\nimport { randomUUID } from 'crypto';\n\ntype StageOutcome = 'ok' | 'respond' | 'next' | 'handled' | 'fail' | 'abort' | 'unknown_error';\n\ninterface StageResult {\n outcome: StageOutcome;\n control?: FlowControl | Error;\n}\n\nconst CAP = (s: string) => (s ? s[0].toUpperCase() + s.slice(1) : s);\nconst WILL = (s: string) => `will${CAP(s)}`;\nconst DID = (s: string) => `did${CAP(s)}`;\nconst AROUND = (s: string) => `around${CAP(s)}`;\n\nfunction parseTypedKey(k: string): { base: string; type?: 'will' | 'did' | 'around' } {\n const lc = k.toLowerCase();\n if (lc.startsWith('will') && k.length > 4) return { base: k.slice(4, 5).toLowerCase() + k.slice(5), type: 'will' };\n if (lc.startsWith('did') && k.length > 3) return { base: k.slice(3, 4).toLowerCase() + k.slice(4), type: 'did' };\n if (lc.startsWith('around') && k.length > 6)\n return { base: k.slice(6, 7).toLowerCase() + k.slice(7), type: 'around' };\n return { base: k };\n}\n\nexport class FlowInstance<Name extends FlowName> extends FlowEntry<Name> {\n readonly deps: Reference[];\n readonly globalProviders: ProviderRegistry;\n private plan: FlowPlan<never>;\n private FlowClass: FlowType;\n private stages: StageMap<FlowType>;\n private hooks: HookRegistry;\n\n constructor(scope: Scope, record: FlowRecord, deps: Set<Reference>, globalProviders: ProviderRegistry) {\n super(scope, record);\n this.deps = [...deps];\n this.globalProviders = globalProviders;\n this.FlowClass = this.record.provide;\n this.ready = this.initialize();\n this.plan = this.record.metadata.plan;\n this.hooks = scope.providers.getHooksRegistry();\n }\n\n protected async initialize() {\n const server = this.globalProviders.getActiveServer();\n\n this.stages = collectFlowHookMap(this.FlowClass);\n\n const { middleware } = this.metadata;\n if (middleware) {\n const path = typeof middleware.path === 'string' ? middleware.path : '';\n server.registerMiddleware(path, async (request, response, next) => {\n const canActivate = await this.canActivate(request);\n if (!canActivate) return next();\n\n // Get context storage to wrap entire flow in FrontMcpContext\n const contextStorage = this.getContextStorage();\n\n try {\n // Use runWithContext to wrap entire flow execution in AsyncLocalStorage context\n // This ensures all stages have access to FrontMcpContext\n const result = await this.runWithContext(\n contextStorage,\n request,\n { request, response, next } as any,\n new Map(),\n );\n if (result) return writeHttpResponse(response, result);\n } catch (e) {\n if (e instanceof FlowControl) {\n switch (e.type) {\n case 'abort':\n return writeHttpResponse(response, { kind: 'text', status: 500, body: 'Aborted' });\n case 'fail':\n return writeHttpResponse(response, { kind: 'text', status: 500, body: 'Internal Server Error' });\n case 'handled':\n return;\n case 'next':\n return next();\n case 'respond':\n return writeHttpResponse(response, e.output as any);\n }\n }\n // Log unhandled errors for visibility (non-FlowControl errors indicate bugs)\n // Note: Using structured logging to avoid Node.js util.inspect issues with Zod errors\n console.error('[FlowInstance] Unhandled error:', {\n name: e instanceof Error ? e.name : 'UnknownError',\n message: e instanceof Error ? e.message : String(e),\n });\n return writeHttpResponse(response, {\n kind: 'text',\n status: 500,\n body: 'Internal Server Error',\n });\n }\n\n return next();\n });\n }\n\n return Promise.resolve();\n }\n\n async canActivate(request: ServerRequest): Promise<boolean> {\n if (this.method && request.method !== this.method) return false;\n\n const canActivate = this.metadata.middleware?.canActivate ?? [];\n if ((this.FlowClass as any)['canActivate']) {\n canActivate.push((this.FlowClass as any)['canActivate']);\n }\n if (canActivate.length === 0) return true;\n\n const results = await Promise.all(canActivate.map((m) => m(request, this.scope)));\n return results.every((r) => r);\n }\n\n /**\n * Get FrontMcpContextStorage from providers (with fallback).\n * Returns undefined if not available (backward compatibility).\n */\n private getContextStorage(): FrontMcpContextStorage | undefined {\n try {\n return this.globalProviders.get(FrontMcpContextStorage);\n } catch {\n return undefined;\n }\n }\n\n /**\n * Run flow wrapped in FrontMcpContext.\n * This ensures ALL stages have access to the context via AsyncLocalStorage.\n *\n * @param storage - FrontMcpContextStorage instance\n * @param request - The HTTP request\n * @param input - Flow input\n * @param deps - Flow dependencies\n * @returns Flow output or undefined\n */\n private async runWithContext(\n storage: FrontMcpContextStorage | undefined,\n request: ServerRequest,\n input: FlowInputOf<Name>,\n deps: Map<Token, Type>,\n ): Promise<FlowOutputOf<Name> | undefined> {\n // If no storage available, run without context (backward compatibility)\n if (!storage) {\n return this.run(input, deps);\n }\n\n // Extract context parameters from request\n const headers = (request.headers ?? {}) as Record<string, unknown>;\n // Generate unique ID for anonymous sessions to prevent session collision\n // All unauthenticated requests previously shared 'anonymous', causing data leakage\n // Handle empty strings explicitly: '' ?? 'fallback' returns '', not 'fallback'\n const headerSessionId = typeof headers['mcp-session-id'] === 'string' ? headers['mcp-session-id'].trim() : '';\n const sessionId = headerSessionId.length > 0 ? headerSessionId : `anon:${randomUUID()}`;\n const scope = this.globalProviders.getActiveScope();\n\n // Wrap ENTIRE flow execution in AsyncLocalStorage context\n return storage.runFromHeaders(\n headers,\n {\n sessionId,\n scopeId: scope.id,\n },\n async () => {\n return this.run(input, deps);\n },\n );\n }\n\n async run(input: FlowInputOf<Name>, deps: Map<Token, Type>): Promise<FlowOutputOf<Name> | undefined> {\n const scope = this.globalProviders.getActiveScope();\n const { FlowClass, plan, name } = this;\n\n // Build provider views for scoped DI\n // This enables CONTEXT scoped providers to be resolved\n const contextStorage = this.getContextStorage();\n const currentContext = contextStorage?.getStore();\n // Get session ID from context - should always be available since runWithContext wraps the entire flow\n // If unavailable, it indicates a bug in context propagation (not a normal case)\n const sessionKey = currentContext?.sessionId;\n if (!sessionKey) {\n // This should never happen since runWithContext wraps the entire flow execution\n // If we reach here, there's a bug in context propagation\n throw new RequestContextNotAvailableError(\n 'FrontMcpContext unavailable - session ID required for provider resolution. Ensure flow is wrapped with runWithContext.',\n );\n }\n\n // Build views with current context if available\n const views = await this.globalProviders.buildViews(\n sessionKey,\n currentContext ? new Map([[FRONTMCP_CONTEXT, currentContext]]) : undefined,\n );\n\n // Merge context-scoped providers into deps for resolution by FlowClass\n const mergedDeps = new Map(deps);\n for (const [token, instance] of views.context) {\n mergedDeps.set(token, instance as Type);\n }\n\n // Clone stages so we can merge injections safely per run.\n const baseStages = this.stages;\n const stages: StageMap<any> = cloneStageMap(baseStages);\n\n // Compute next order base after any class-defined entries.\n let orderBase = Math.max(0, ...Object.values(stages).flatMap((list) => list.map((e: any) => e._order ?? 0))) + 1;\n\n // Get tool owner ID if this is a tool call flow\n // The tool owner ID is set by the CallToolFlow.findTool stage\n const toolOwnerId = (input as any)?._toolOwnerId;\n\n const initialInjectedHooks =\n (this.hooks.getFlowHooksForOwner(name, toolOwnerId) as HookEntry<\n FlowInputOf<Name>,\n Name,\n FlowStagesOf<Name>,\n FlowCtxOf<Name>\n >[]) ?? [];\n\n // FlowClass generic type is erased at runtime, so we use FlowBase<any>\n // to avoid complex type gymnastics while maintaining basic type safety\n let context: FlowBase<any>;\n let contextReady = false;\n\n const materializeAndMerge = async (\n newHooks: HookEntry<FlowInputOf<Name>, Name, FlowStagesOf<Name>, FlowCtxOf<Name>>[],\n opts?: { orderStart?: number },\n ) => {\n if (!newHooks?.length || !contextReady) return;\n\n const metas: HookMetadata[] = [];\n for (const h of newHooks) {\n try {\n metas.push(h.metadata);\n } catch (e) {\n // Use safe logging to avoid Node.js 24 util.inspect bug with Zod errors\n\n console.warn(\n '[flow] Ignoring injected hook that failed to materialize:',\n e instanceof Error ? e.message : 'Unknown error',\n );\n }\n }\n\n if (metas.length) {\n const start = opts?.orderStart ?? orderBase;\n mergeHookMetasIntoStageMap(FlowClass, stages, metas, start);\n if (opts?.orderStart === undefined) orderBase += metas.length;\n }\n };\n\n const appendContextHooks = async (\n hooks: HookEntry<FlowInputOf<Name>, Name, FlowStagesOf<Name>, FlowCtxOf<Name>>[],\n ) => {\n await materializeAndMerge(hooks);\n };\n\n // Construct flow instance with merged dependencies (includes scoped providers)\n // eslint-disable-next-line prefer-const -- declaration must precede helper functions that close over context\n context = new FlowClass(this.metadata, input, scope, appendContextHooks, mergedDeps);\n\n // Now injections can materialize\n contextReady = true;\n\n // Initial registry hooks should not pre-empt stages; they just get registered\n await materializeAndMerge(initialInjectedHooks, { orderStart: -1_000_000 });\n\n // Refresh order base to be after everything currently present\n orderBase = Math.max(0, ...Object.values(stages).flatMap((list) => list.map((e: any) => e._order ?? 0))) + 1;\n\n let responded: FlowOutputOf<Name> | undefined;\n\n // Robust list runner (doesn't skip mid-run insertions)\n const runList = async (key: string, opts?: { ignoreRespond?: boolean }): Promise<StageResult> => {\n const getList = () => ((stages as any)[key] ?? []) as Array<{ method: (ctx: any) => Promise<void> }>;\n const seen = new Set<any>();\n\n while (true) {\n const list = getList();\n const item = list.find((e) => !seen.has(e));\n if (!item) break;\n seen.add(item);\n\n try {\n await item.method(context);\n } catch (e: any) {\n if (e instanceof FlowControl) {\n if (e.type === 'respond') {\n if (!opts?.ignoreRespond) {\n responded = e.output as FlowOutputOf<Name>;\n return { outcome: 'respond', control: e };\n }\n continue;\n }\n return { outcome: e.type, control: e };\n }\n return { outcome: 'unknown_error', control: e as Error };\n }\n }\n return { outcome: 'ok' };\n };\n\n // Run exactly one stage in order: will → around → stage → did (did runs once)\n const runOneStage = async (stageName: string, stopOnRespond: boolean): Promise<StageResult> => {\n // 1) willStage\n {\n const res = await runList(WILL(stageName));\n if (res.outcome === 'respond' && stopOnRespond) return res;\n if (res.outcome !== 'ok' && res.outcome !== 'respond') return res;\n }\n\n // 2) aroundStage (acts as pre-handlers unless you later add true wrapping)\n {\n const res = await runList(AROUND(stageName));\n if (res.outcome === 'respond' && stopOnRespond) return res;\n if (res.outcome !== 'ok' && res.outcome !== 'respond') return res;\n }\n\n // 3) stage\n let bodyOutcome: StageResult = { outcome: 'ok' };\n {\n const res = await runList(stageName, { ignoreRespond: false });\n bodyOutcome = res;\n if (res.outcome !== 'ok' && res.outcome !== 'respond') {\n // fail/abort/next/handled/unknown → do NOT run did\n return res;\n }\n }\n\n // 4) didStage (run once regardless of body respond)\n {\n const res = await runList(DID(stageName), { ignoreRespond: true });\n if (res.outcome !== 'ok' && res.outcome !== 'respond') return res;\n }\n\n if (bodyOutcome.outcome === 'respond') return bodyOutcome;\n return { outcome: 'ok' };\n };\n\n // IMPORTANT: ignore typed stage names in plan arrays.\n // Only base stage names in the plan drive execution; typed hooks run *with* their base.\n const runStageGroup = async (\n group: Array<string> | undefined,\n stopOnRespond: boolean,\n opts?: { ignoreRespond?: boolean },\n ): Promise<StageResult> => {\n if (!group || group.length === 0) return { outcome: 'ok' };\n\n const seenBase = new Set<string>();\n for (const rawKey of group) {\n const { base, type } = parseTypedKey(rawKey);\n if (type) {\n // Soft warning once per typed key occurrence (optional)\n // console.warn(`[flow] Ignoring typed stage \"${rawKey}\" in plan; hooks will run with base \"${base}\".`);\n continue; // Do not run typed keys as standalone stages\n }\n if (seenBase.has(base)) continue;\n seenBase.add(base);\n\n const res = await runOneStage(base, stopOnRespond);\n if (res.outcome === 'respond') {\n if (stopOnRespond) return res;\n // else keep going\n } else if (res.outcome !== 'ok') {\n return res;\n }\n }\n return { outcome: 'ok' };\n };\n\n const runErrorStage = async () => {\n await runStageGroup((plan as any).error, false, { ignoreRespond: true });\n };\n\n const runFinalizeStage = async (options?: { suppressErrors?: boolean }) => {\n const res = await runStageGroup((plan as any).finalize, false);\n // Handle finalize stage errors\n if (res.outcome === 'unknown_error' || res.outcome === 'fail') {\n const finalizeError = res.control ?? new InternalMcpError('Finalize stage failed');\n if (options?.suppressErrors) {\n // Log finalizes errors but doesn't throw when called from finally blocks\n // This prevents masking the original error\n this.scope.logger.error(\n '[FrontMCP] Finalize stage error (suppressed to preserve original error):',\n finalizeError,\n );\n return res;\n }\n throw finalizeError;\n }\n return res;\n };\n\n // ---------- PRE ----------\n {\n const pre = await runStageGroup((plan as any).pre, true);\n if (pre.outcome === 'respond') {\n const post = await runStageGroup((plan as any).post, false);\n if (post.outcome === 'unknown_error' || post.outcome === 'fail') {\n try {\n await runErrorStage();\n } finally {\n await runFinalizeStage({ suppressErrors: true });\n }\n throw post.control ?? new InternalMcpError('Missing control for fail/error outcome');\n }\n if (post.outcome === 'abort' || post.outcome === 'next' || post.outcome === 'handled') {\n await runFinalizeStage({ suppressErrors: true });\n if (!(post.control instanceof FlowControl)) {\n throw new InternalMcpError('Expected FlowControl but received different error type');\n }\n throw post.control;\n }\n await runFinalizeStage();\n return responded;\n }\n if (pre.outcome === 'unknown_error' || pre.outcome === 'fail') {\n try {\n await runErrorStage();\n } finally {\n await runFinalizeStage({ suppressErrors: true });\n }\n throw pre.control ?? new InternalMcpError('Missing control for fail/error outcome');\n }\n if (pre.outcome === 'abort' || pre.outcome === 'next' || pre.outcome === 'handled') {\n await runFinalizeStage({ suppressErrors: true });\n if (!(pre.control instanceof FlowControl)) {\n throw new InternalMcpError('Expected FlowControl but received different error type');\n }\n throw pre.control;\n }\n }\n\n // ---------- EXECUTE ----------\n if (!responded) {\n const exec = await runStageGroup((plan as any).execute, true);\n if (exec.outcome === 'respond') {\n // continue to post + finalize\n } else if (exec.outcome === 'unknown_error' || exec.outcome === 'fail') {\n try {\n await runErrorStage();\n } finally {\n await runFinalizeStage({ suppressErrors: true });\n }\n throw exec.control ?? new InternalMcpError('Missing control for fail/error outcome');\n } else if (exec.outcome === 'abort' || exec.outcome === 'next' || exec.outcome === 'handled') {\n await runFinalizeStage({ suppressErrors: true });\n if (!(exec.control instanceof FlowControl)) {\n throw new InternalMcpError('Expected FlowControl but received different error type');\n }\n throw exec.control;\n }\n }\n\n // ---------- POST ----------\n {\n const post = await runStageGroup((plan as any).post, false);\n if (post.outcome === 'unknown_error' || post.outcome === 'fail') {\n try {\n await runErrorStage();\n } finally {\n await runFinalizeStage({ suppressErrors: true });\n }\n throw post.control ?? new InternalMcpError('Missing control for fail/error outcome');\n }\n if (post.outcome === 'abort' || post.outcome === 'next' || post.outcome === 'handled') {\n await runFinalizeStage({ suppressErrors: true });\n if (!(post.control instanceof FlowControl)) {\n throw new InternalMcpError('Expected FlowControl but received different error type');\n }\n throw post.control;\n }\n }\n\n // ---------- FINALIZE ----------\n await runFinalizeStage();\n\n return responded;\n }\n}\n"]}
|
|
@@ -11,4 +11,9 @@ export default class FlowRegistry extends RegistryAbstract<FlowInstance<FlowName
|
|
|
11
11
|
private initializeOne;
|
|
12
12
|
registryFlows(rawFlows: FlowType[]): Promise<void>;
|
|
13
13
|
runFlow<Name extends FlowName>(name: Name, input: FlowInputOf<Name>, deps?: Map<Token, Type>): Promise<FlowOutputOf<Name> | undefined>;
|
|
14
|
+
/**
|
|
15
|
+
* Get FrontMcpContextStorage from providers (with fallback).
|
|
16
|
+
* Returns undefined if not available (backward compatibility).
|
|
17
|
+
*/
|
|
18
|
+
private getContextStorage;
|
|
14
19
|
}
|