raiton 6.4.0-beta.12 → 6.6.0-beta.14
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/CHANGELOG.md +27 -0
- package/build/bin/index.mjs +20449 -2153
- package/docs/contributors/framework/plugins/csrf.md +277 -0
- package/docs/contributors/framework/plugins/security.md +40 -6
- package/docs/user-guide/README.md +9 -4
- package/docs/user-guide/best-practices.md +1 -0
- package/docs/user-guide/csrf.md +557 -0
- package/docs/user-guide/decorators/README.md +4 -0
- package/docs/user-guide/decorators/health-check.md +125 -0
- package/docs/user-guide/decorators/mcp.md +70 -0
- package/docs/user-guide/health-check.md +117 -0
- package/docs/user-guide/mcp.md +120 -0
- package/docs/user-guide/plugins.md +1 -0
- package/docs/user-guide/security.md +8 -2
- package/package.json +1 -1
- package/source/core/application.ts +1 -1
- package/source/core/builder.ts +12 -0
- package/source/core/controller/builder.ts +31 -2
- package/source/core/index.ts +1 -0
- package/source/core/mcp/builder.ts +76 -0
- package/source/core/mcp/index.ts +3 -0
- package/source/core/mcp/metadata.ts +80 -0
- package/source/core/mcp/tracker.ts +28 -0
- package/source/core/thread.ts +5 -1
- package/source/framework/artifacts.ts +32 -0
- package/source/framework/constants/decorators.constant.ts +6 -0
- package/source/framework/decorators/csrf-guard.decorator.ts +60 -0
- package/source/framework/decorators/csrf-token.decorator.ts +20 -0
- package/source/framework/decorators/health-check.decorator.ts +50 -0
- package/source/framework/decorators/index.ts +5 -1
- package/source/framework/decorators/mcp.decorator.ts +170 -0
- package/source/framework/enums/csrf.enum.ts +4 -0
- package/source/framework/enums/index.ts +2 -1
- package/source/framework/health-check.ts +137 -0
- package/source/framework/index.ts +2 -0
- package/source/framework/mcp/handler.ts +369 -0
- package/source/framework/mcp/index.ts +3 -0
- package/source/framework/mcp/protocol.ts +50 -0
- package/source/framework/mcp/streamable-http.ts +94 -0
- package/source/framework/plugins/index.ts +2 -1
- package/source/framework/plugins/mcp.plugin.ts +87 -0
- package/source/framework/plugins/security/csrf.ts +145 -0
- package/source/framework/plugins/security/index.ts +2 -0
- package/source/framework/utilities/artifact.util.ts +8 -0
- package/source/framework/utilities/csrf.util.ts +162 -0
- package/source/framework/utilities/index.ts +2 -1
- package/source/framework/utilities/openapi.utils.ts +81 -0
- package/source/types/application.ts +1 -1
- package/source/types/csrf.ts +38 -0
- package/source/types/index.ts +3 -1
- package/source/types/mcp.ts +118 -0
- package/source/types/raiton.ts +1 -0
- package/source/types/runtime.ts +1 -1
- /package/source/framework/utilities/{https.ts → https.util.ts} +0 -0
- /package/source/framework/utilities/{url.ts → url.util.ts} +0 -0
package/source/core/thread.ts
CHANGED
|
@@ -15,6 +15,7 @@ import {ApplicationInterface} from "../types/application";
|
|
|
15
15
|
import {Runtime} from "../framework/runtime";
|
|
16
16
|
import {LBadge, Logger} from "@protorians/logger";
|
|
17
17
|
import {ControllerBuilder} from "./controller";
|
|
18
|
+
import {registerDefaultHealthCheck} from "../framework/health-check";
|
|
18
19
|
import {bodyParserPlugin} from "../framework/plugins/body-parser.plugin";
|
|
19
20
|
import {Injection} from "./injection/injection";
|
|
20
21
|
import {Throwable} from "../framework/exceptions";
|
|
@@ -88,7 +89,10 @@ export class RaitonThread implements ThreadInterface {
|
|
|
88
89
|
if (!this.runtime)
|
|
89
90
|
throw new Throwable('Runtime not defined');
|
|
90
91
|
|
|
91
|
-
if (this.builder.source)
|
|
92
|
+
if (this.builder.source) {
|
|
93
|
+
await ControllerBuilder.scan(this.builder.source)
|
|
94
|
+
registerDefaultHealthCheck(this.application)
|
|
95
|
+
}
|
|
92
96
|
|
|
93
97
|
if (this._options.serve) {
|
|
94
98
|
process.on('SIGINT', async () => {
|
|
@@ -3,6 +3,7 @@ import {Logger} from "@protorians/logger";
|
|
|
3
3
|
import type {ConstructorType} from "../types";
|
|
4
4
|
import {Raiton} from "../core/raiton";
|
|
5
5
|
import {isArtifact} from "./utilities";
|
|
6
|
+
import {compileMcp} from "../core/mcp/builder";
|
|
6
7
|
|
|
7
8
|
export type HmrChannel =
|
|
8
9
|
| 'hmr:di'
|
|
@@ -10,6 +11,8 @@ export type HmrChannel =
|
|
|
10
11
|
| 'hmr:socket'
|
|
11
12
|
| 'hmr:middleware'
|
|
12
13
|
| 'hmr:hook'
|
|
14
|
+
| 'hmr:mcp'
|
|
15
|
+
| 'hmr:health-check'
|
|
13
16
|
|
|
14
17
|
export interface ArtifactClassification {
|
|
15
18
|
channel: HmrChannel
|
|
@@ -43,6 +46,8 @@ export const HMR_CHANNELS: Record<HmrChannel, readonly string[]> = {
|
|
|
43
46
|
'hmr:socket': ['socket'],
|
|
44
47
|
'hmr:middleware': ['middleware'],
|
|
45
48
|
'hmr:hook': ['hook', 'event', 'listener'],
|
|
49
|
+
'hmr:mcp': ['mcp'],
|
|
50
|
+
'hmr:health-check': ['health-check'],
|
|
46
51
|
}
|
|
47
52
|
|
|
48
53
|
export class Artifacts {
|
|
@@ -78,6 +83,7 @@ export class Artifacts {
|
|
|
78
83
|
'schema',
|
|
79
84
|
'socket',
|
|
80
85
|
'mcp',
|
|
86
|
+
'health-check',
|
|
81
87
|
]
|
|
82
88
|
|
|
83
89
|
static register(type: string) {
|
|
@@ -205,4 +211,30 @@ export class Artifacts {
|
|
|
205
211
|
}
|
|
206
212
|
}
|
|
207
213
|
}
|
|
214
|
+
|
|
215
|
+
static reloadMcp(modulo: any, filename?: string) {
|
|
216
|
+
|
|
217
|
+
if (Raiton.thread?.builder.options.serve === false)
|
|
218
|
+
return Logger.warn(
|
|
219
|
+
'Artifact reload is only available in development mode'
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
const app = Raiton.thread?.application
|
|
223
|
+
if (!app) return
|
|
224
|
+
|
|
225
|
+
const rootScope = (app as any).root
|
|
226
|
+
if (!rootScope?.router) return
|
|
227
|
+
|
|
228
|
+
for (const mod of Object.values(modulo)) {
|
|
229
|
+
const name = (mod && typeof mod === 'object' && 'name' in mod) ? mod.name : (
|
|
230
|
+
typeof mod === 'function' ? mod.name ?? mod.constructor.name : undefined
|
|
231
|
+
);
|
|
232
|
+
|
|
233
|
+
if (typeof name === 'string' && typeof mod === 'function') {
|
|
234
|
+
Injection.invalidateCascade(name)
|
|
235
|
+
if (filename) Injection.registerArtifactPath(name, filename)
|
|
236
|
+
compileMcp(mod)
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
208
240
|
}
|
|
@@ -18,4 +18,10 @@ export const METADATA_KEYS = {
|
|
|
18
18
|
API_PROPERTY: Symbol('api:property'),
|
|
19
19
|
// Route interaction metadata key
|
|
20
20
|
ROUTE_INTERACTION: Symbol('route:interaction'),
|
|
21
|
+
// Health check metadata key
|
|
22
|
+
HEALTH_CHECK: Symbol('health:check'),
|
|
23
|
+
// MCP metadata keys
|
|
24
|
+
MCP: Symbol('mcp:meta'),
|
|
25
|
+
MCP_ELEMENTS: Symbol('mcp:elements'),
|
|
26
|
+
MCP_ARGUMENTS: Symbol('mcp:arguments'),
|
|
21
27
|
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import {MiddlewareParametersInterface, CsrfGuardOptions} from "../../types";
|
|
2
|
+
import {Middleware} from "./middleware.decorator";
|
|
3
|
+
import {HttpStatus, RaitonResponses} from "..";
|
|
4
|
+
import {CsrfUtil} from "../utilities/csrf.util";
|
|
5
|
+
|
|
6
|
+
const DEFAULT_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE']
|
|
7
|
+
const DEFAULT_HEADER_NAME = 'X-CSRF-Token'
|
|
8
|
+
const DEFAULT_COOKIE_NAME = '_csrf'
|
|
9
|
+
|
|
10
|
+
export function CsrfGuard(options: CsrfGuardOptions = {}) {
|
|
11
|
+
return Middleware(async ({context, next}: MiddlewareParametersInterface) => {
|
|
12
|
+
const method = (context.req.method ?? '').toUpperCase()
|
|
13
|
+
const methods = (options.methods ?? DEFAULT_METHODS).map(m => m.toUpperCase())
|
|
14
|
+
|
|
15
|
+
if (!methods.includes(method)) {
|
|
16
|
+
return next()
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
if (options.skipPaths) {
|
|
20
|
+
const requestPath = new URL(context.req.url, 'http://localhost').pathname
|
|
21
|
+
if (options.skipPaths.some(p => requestPath.startsWith(p))) {
|
|
22
|
+
return next()
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const headerToken = context.req.headers.get(DEFAULT_HEADER_NAME.toLowerCase())
|
|
27
|
+
const cookieHeader = context.req.headers.get('cookie') ?? ''
|
|
28
|
+
const cookieToken = CsrfUtil.extractCookieValue(cookieHeader, DEFAULT_COOKIE_NAME)
|
|
29
|
+
|
|
30
|
+
if (!headerToken || !cookieToken) {
|
|
31
|
+
context.reply.status(HttpStatus.FORBIDDEN)
|
|
32
|
+
return context.reply.send(
|
|
33
|
+
RaitonResponses(
|
|
34
|
+
'CSRF token missing',
|
|
35
|
+
null,
|
|
36
|
+
HttpStatus.FORBIDDEN,
|
|
37
|
+
{error: true}
|
|
38
|
+
)
|
|
39
|
+
)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const valid = CsrfUtil.timingSafeEqual(cookieToken, headerToken)
|
|
43
|
+
if (!valid) {
|
|
44
|
+
context.reply.status(HttpStatus.FORBIDDEN)
|
|
45
|
+
return context.reply.send(
|
|
46
|
+
RaitonResponses(
|
|
47
|
+
'CSRF token mismatch',
|
|
48
|
+
null,
|
|
49
|
+
HttpStatus.FORBIDDEN,
|
|
50
|
+
{error: true}
|
|
51
|
+
)
|
|
52
|
+
)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
context.state = context.state ?? {}
|
|
56
|
+
context.state.csrfValidated = true
|
|
57
|
+
|
|
58
|
+
await next()
|
|
59
|
+
})
|
|
60
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import {getControllerMetadata} from "../../core";
|
|
2
|
+
|
|
3
|
+
export function CsrfToken() {
|
|
4
|
+
return (target: any, propertyKey?: string) => {
|
|
5
|
+
const meta = getControllerMetadata(target.prototype || target)
|
|
6
|
+
const segment = propertyKey ? propertyKey : '@'
|
|
7
|
+
|
|
8
|
+
if (!meta.middlewares[segment]) {
|
|
9
|
+
meta.middlewares[segment] = []
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
meta.middlewares[segment].push(async ({context, next}: any) => {
|
|
13
|
+
const token = context.state?.csrfToken
|
|
14
|
+
if (token) {
|
|
15
|
+
context.reply.header('X-CSRF-Token', token)
|
|
16
|
+
}
|
|
17
|
+
await next()
|
|
18
|
+
})
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import "reflect-metadata";
|
|
2
|
+
import {METADATA_KEYS} from "../constants/decorators.constant";
|
|
3
|
+
import {getControllerMetadata} from "../../core/controller";
|
|
4
|
+
import {RouteMetaInterface} from "../../types";
|
|
5
|
+
|
|
6
|
+
export interface HealthCheckOptions {
|
|
7
|
+
path?: string;
|
|
8
|
+
tags?: string[];
|
|
9
|
+
summary?: string;
|
|
10
|
+
description?: string;
|
|
11
|
+
excludeFromDocs?: boolean;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface HealthCheckMetadata {
|
|
15
|
+
options: HealthCheckOptions;
|
|
16
|
+
routeMeta?: RouteMetaInterface;
|
|
17
|
+
controllerPrefix?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const DEFAULT_HEALTH_CHECK_OPTIONS: HealthCheckOptions = {
|
|
21
|
+
path: '/health',
|
|
22
|
+
tags: ['Health'],
|
|
23
|
+
summary: 'Health check endpoint',
|
|
24
|
+
description: 'Returns the health status of the application',
|
|
25
|
+
excludeFromDocs: false,
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export function HealthCheck(options: HealthCheckOptions = {}) {
|
|
29
|
+
return (target: any, propertyKey: string) => {
|
|
30
|
+
const mergedOptions = {...DEFAULT_HEALTH_CHECK_OPTIONS, ...options};
|
|
31
|
+
const controllerMeta = getControllerMetadata(target.prototype || target);
|
|
32
|
+
const route = controllerMeta.routes.find(r => r.propertyKey === propertyKey);
|
|
33
|
+
|
|
34
|
+
const metadata: HealthCheckMetadata = {
|
|
35
|
+
options: mergedOptions,
|
|
36
|
+
routeMeta: route,
|
|
37
|
+
controllerPrefix: controllerMeta.prefix,
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
Reflect.defineMetadata(METADATA_KEYS.HEALTH_CHECK, metadata, target, propertyKey);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function getHealthCheckMetadata(target: any, propertyKey: string): HealthCheckMetadata | undefined {
|
|
45
|
+
return Reflect.getMetadata(METADATA_KEYS.HEALTH_CHECK, target, propertyKey);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function isHealthCheck(target: any, propertyKey: string): boolean {
|
|
49
|
+
return Reflect.hasMetadata(METADATA_KEYS.HEALTH_CHECK, target, propertyKey);
|
|
50
|
+
}
|
|
@@ -5,6 +5,10 @@ export * from "./routable.decorator"
|
|
|
5
5
|
export * from "./parametrable.decorator"
|
|
6
6
|
export * from "./injection.decorator"
|
|
7
7
|
export * from "./guard.decorator"
|
|
8
|
+
export * from "./csrf-guard.decorator"
|
|
9
|
+
export * from "./csrf-token.decorator"
|
|
8
10
|
export * from "./api-response.decorator"
|
|
9
11
|
export * from "./api.decorator"
|
|
10
|
-
export * from "./route-interaction.decorator"
|
|
12
|
+
export * from "./route-interaction.decorator"
|
|
13
|
+
export * from "./health-check.decorator"
|
|
14
|
+
export * from "./mcp.decorator"
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import "reflect-metadata";
|
|
2
|
+
import {registerMcpServer, unregisterMcpServer, getMcpServerMetadata} from "../../core/mcp";
|
|
3
|
+
import {Injectable} from ".";
|
|
4
|
+
import {LifetimeEnum} from "@protorians/core";
|
|
5
|
+
import {METADATA_KEYS} from "../constants";
|
|
6
|
+
import type {
|
|
7
|
+
McpArgumentMetaInterface,
|
|
8
|
+
McpArgumentSchema,
|
|
9
|
+
McpElementMetaInterface,
|
|
10
|
+
McpElementType,
|
|
11
|
+
McpServerOptionsInterface,
|
|
12
|
+
} from "../../types";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Decorate a class as an MCP server. The class methods decorated with
|
|
16
|
+
* {@link McpTool}, {@link McpPrompt}, {@link McpResource} and
|
|
17
|
+
* {@link McpResourceTemplate} become the server's exposed elements.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```ts
|
|
21
|
+
* @McpServer({ name: 'math', version: '1.0.0', path: '/mcp' })
|
|
22
|
+
* class MathServer {
|
|
23
|
+
* @McpTool({ name: 'add', description: 'Add two numbers' })
|
|
24
|
+
* add(@McpArg('a', 'First operand', Number) a: number, @McpArg('b') b: number) {
|
|
25
|
+
* return a + b
|
|
26
|
+
* }
|
|
27
|
+
* }
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
export function McpServer(options: McpServerOptionsInterface = {}) {
|
|
31
|
+
return (target: any) => {
|
|
32
|
+
Injectable(LifetimeEnum.TRANSIENT, options.name || target.name)(target)
|
|
33
|
+
|
|
34
|
+
const meta = getMcpServerMetadata(target.prototype || target)
|
|
35
|
+
meta.name = options.name || target.name
|
|
36
|
+
meta.version = options.version || '1.0.0'
|
|
37
|
+
meta.description = options.description
|
|
38
|
+
meta.path = options.path || '/mcp'
|
|
39
|
+
meta.instructions = options.instructions
|
|
40
|
+
|
|
41
|
+
unregisterMcpServer(options.name || target.name)
|
|
42
|
+
registerMcpServer(target)
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function createElementDecorator(type: McpElementType) {
|
|
47
|
+
return (nameOrOptions?: string | {name?: string; description?: string; uri?: string; mimeType?: string; title?: string}) =>
|
|
48
|
+
(target: any, propertyKey: string) => {
|
|
49
|
+
const meta = getMcpServerMetadata(target)
|
|
50
|
+
const name = typeof nameOrOptions === 'string'
|
|
51
|
+
? nameOrOptions
|
|
52
|
+
: nameOrOptions?.name || propertyKey
|
|
53
|
+
|
|
54
|
+
const element: McpElementMetaInterface = {
|
|
55
|
+
type,
|
|
56
|
+
name,
|
|
57
|
+
description: typeof nameOrOptions === 'string' ? undefined : nameOrOptions?.description,
|
|
58
|
+
propertyKey,
|
|
59
|
+
arguments: [],
|
|
60
|
+
uri: typeof nameOrOptions === 'object' ? nameOrOptions?.uri : undefined,
|
|
61
|
+
mimeType: typeof nameOrOptions === 'object' ? nameOrOptions?.mimeType : undefined,
|
|
62
|
+
title: typeof nameOrOptions === 'object' ? nameOrOptions?.title : undefined,
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const list = meta[elementChildren(type)]
|
|
66
|
+
if (list) list.push(element)
|
|
67
|
+
|
|
68
|
+
// Capture argument metadata supplied via parameter decorators
|
|
69
|
+
const arguments_ = Reflect.getMetadata(METADATA_KEYS.MCP_ARGUMENTS, target, propertyKey) || []
|
|
70
|
+
element.arguments = arguments_
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function elementChildren(type: McpElementType) {
|
|
75
|
+
return (type === 'tool' ? 'tools' : type === 'prompt' ? 'prompts' : type === 'resource' ? 'resources' : 'resourceTemplates')
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Expose a class method as an MCP tool.
|
|
80
|
+
*/
|
|
81
|
+
export function McpTool(options: {name?: string; description?: string} = {}) {
|
|
82
|
+
return createElementDecorator('tool')(options)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Expose a class method as an MCP prompt template.
|
|
87
|
+
*/
|
|
88
|
+
export function McpPrompt(options: {name?: string; description?: string} = {}) {
|
|
89
|
+
return createElementDecorator('prompt')(options)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Expose a class method as an MCP resource.
|
|
94
|
+
*/
|
|
95
|
+
export function McpResource(options: {uri: string; name?: string; description?: string; mimeType?: string}) {
|
|
96
|
+
return createElementDecorator('resource')({...options, name: options.name || options.uri})
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Expose a class method as an MCP resource template.
|
|
101
|
+
*/
|
|
102
|
+
export function McpResourceTemplate(options: {uriTemplate: string; name?: string; description?: string; mimeType?: string}) {
|
|
103
|
+
return createElementDecorator('resource-template')({
|
|
104
|
+
name: options.name || options.uriTemplate,
|
|
105
|
+
description: options.description,
|
|
106
|
+
uri: options.uriTemplate,
|
|
107
|
+
mimeType: options.mimeType,
|
|
108
|
+
})
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Shortcut to mark a method as a resource reader (deprecated form, kept for compatibility).
|
|
113
|
+
*/
|
|
114
|
+
export function McpRead(uri?: string) {
|
|
115
|
+
return createElementDecorator('resource')({uri: uri || ''})
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Declare an argument for an MCP tool, prompt or resource handler.
|
|
120
|
+
* Applied to method parameters, in declaration order.
|
|
121
|
+
*/
|
|
122
|
+
export function McpArg(
|
|
123
|
+
nameOrOptions: string | McpArgumentMetaInterface,
|
|
124
|
+
description?: string,
|
|
125
|
+
metatype?: any,
|
|
126
|
+
): any {
|
|
127
|
+
return (target: any, propertyKey: string, parameterIndex: number) => {
|
|
128
|
+
const arguments_ = Reflect.getMetadata(METADATA_KEYS.MCP_ARGUMENTS, target, propertyKey) || []
|
|
129
|
+
arguments_[parameterIndex] = normalizeArgument(nameOrOptions, description, metatype)
|
|
130
|
+
Reflect.defineMetadata(METADATA_KEYS.MCP_ARGUMENTS, arguments_, target, propertyKey)
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export {McpArg as McpArgument}
|
|
135
|
+
|
|
136
|
+
function normalizeArgument(
|
|
137
|
+
nameOrOptions: string | McpArgumentMetaInterface,
|
|
138
|
+
description?: string,
|
|
139
|
+
metatype?: any,
|
|
140
|
+
): McpArgumentMetaInterface {
|
|
141
|
+
if (typeof nameOrOptions === 'string') {
|
|
142
|
+
return {name: nameOrOptions, description, schema: schemaFromMetatype(metatype), metatype}
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
name: nameOrOptions.name,
|
|
146
|
+
description: nameOrOptions.description,
|
|
147
|
+
schema: nameOrOptions.schema || schemaFromMetatype(nameOrOptions.metatype),
|
|
148
|
+
required: nameOrOptions.required,
|
|
149
|
+
metatype: nameOrOptions.metatype || metatype,
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function schemaFromMetatype(metatype?: any): McpArgumentSchema | undefined {
|
|
154
|
+
if (!metatype || metatype === Object) return undefined
|
|
155
|
+
const name = metatype.name
|
|
156
|
+
switch (name) {
|
|
157
|
+
case 'String':
|
|
158
|
+
return {type: 'string'}
|
|
159
|
+
case 'Number':
|
|
160
|
+
return {type: 'number'}
|
|
161
|
+
case 'Boolean':
|
|
162
|
+
return {type: 'boolean'}
|
|
163
|
+
case 'Object':
|
|
164
|
+
return {type: 'object'}
|
|
165
|
+
case 'Array':
|
|
166
|
+
return {type: 'array'}
|
|
167
|
+
default:
|
|
168
|
+
return undefined
|
|
169
|
+
}
|
|
170
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import {HttpStatus, HttpMethod} from "./enums";
|
|
2
|
+
import {RaitonResponses} from "./responses/helpers";
|
|
3
|
+
import {ApplicationInterface} from "../types/application";
|
|
4
|
+
import {RequestContext} from "../core/context";
|
|
5
|
+
|
|
6
|
+
export interface HealthCheckConfig {
|
|
7
|
+
enabled: boolean;
|
|
8
|
+
path: string;
|
|
9
|
+
response?: {
|
|
10
|
+
status?: 'healthy' | 'unhealthy' | 'degraded';
|
|
11
|
+
statusCode?: HttpStatus;
|
|
12
|
+
message?: string;
|
|
13
|
+
};
|
|
14
|
+
checks?: HealthCheckCheck[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export type HealthCheckStatus = 'healthy' | 'unhealthy' | 'degraded';
|
|
18
|
+
|
|
19
|
+
export interface HealthCheckResult {
|
|
20
|
+
name: string;
|
|
21
|
+
status: HealthCheckStatus;
|
|
22
|
+
message?: string;
|
|
23
|
+
duration?: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface HealthCheckCheck {
|
|
27
|
+
name: string;
|
|
28
|
+
check: () => Promise<{ status: HealthCheckStatus; message?: string }> | { status: HealthCheckStatus; message?: string };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const DEFAULT_HEALTH_CHECK_CONFIG: HealthCheckConfig = {
|
|
32
|
+
enabled: true,
|
|
33
|
+
path: '/health',
|
|
34
|
+
response: {
|
|
35
|
+
status: 'healthy',
|
|
36
|
+
statusCode: HttpStatus.OK,
|
|
37
|
+
message: 'Service is healthy',
|
|
38
|
+
},
|
|
39
|
+
checks: [],
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export class HealthCheckManager {
|
|
43
|
+
private static _config: HealthCheckConfig = {...DEFAULT_HEALTH_CHECK_CONFIG};
|
|
44
|
+
private static _customHandler: ((ctx: RequestContext) => Promise<any> | any) | null = null;
|
|
45
|
+
|
|
46
|
+
static configure(config: Partial<HealthCheckConfig>): void {
|
|
47
|
+
this._config = {...this._config, ...config};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
static getConfig(): HealthCheckConfig {
|
|
51
|
+
return {...this._config};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
static registerCustomHandler(handler: (ctx: RequestContext) => Promise<any> | any): void {
|
|
55
|
+
this._customHandler = handler;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
static async runChecks(): Promise<HealthCheckResult[]> {
|
|
59
|
+
const results: HealthCheckResult[] = [];
|
|
60
|
+
|
|
61
|
+
for (const check of this._config.checks || []) {
|
|
62
|
+
const start = Date.now();
|
|
63
|
+
try {
|
|
64
|
+
const result = await check.check();
|
|
65
|
+
results.push({
|
|
66
|
+
name: check.name,
|
|
67
|
+
status: result.status,
|
|
68
|
+
message: result.message,
|
|
69
|
+
duration: Date.now() - start,
|
|
70
|
+
});
|
|
71
|
+
} catch (error: any) {
|
|
72
|
+
results.push({
|
|
73
|
+
name: check.name,
|
|
74
|
+
status: 'unhealthy',
|
|
75
|
+
message: error.message || 'Check failed',
|
|
76
|
+
duration: Date.now() - start,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return results;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
static async handleHealthCheck(ctx: RequestContext): Promise<any> {
|
|
85
|
+
if (this._customHandler) {
|
|
86
|
+
return this._customHandler(ctx);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const checks = await this.runChecks();
|
|
90
|
+
const timestamp = new Date().toISOString();
|
|
91
|
+
|
|
92
|
+
let overallStatus: HealthCheckStatus = 'healthy';
|
|
93
|
+
if (checks.some(c => c.status === 'unhealthy')) {
|
|
94
|
+
overallStatus = 'unhealthy';
|
|
95
|
+
} else if (checks.some(c => c.status === 'degraded')) {
|
|
96
|
+
overallStatus = 'degraded';
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const statusCode = overallStatus === 'unhealthy'
|
|
100
|
+
? HttpStatus.SERVICE_UNAVAILABLE
|
|
101
|
+
: (this._config.response?.statusCode || HttpStatus.OK);
|
|
102
|
+
|
|
103
|
+
return RaitonResponses(
|
|
104
|
+
this._config.response?.message || `Service is ${overallStatus}`,
|
|
105
|
+
{
|
|
106
|
+
status: overallStatus,
|
|
107
|
+
timestamp,
|
|
108
|
+
checks: checks.length > 0 ? checks : undefined,
|
|
109
|
+
uptime: process.uptime(),
|
|
110
|
+
version: process.env.npm_package_version || '0.0.0',
|
|
111
|
+
},
|
|
112
|
+
statusCode,
|
|
113
|
+
{error: overallStatus === 'unhealthy'}
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function hasRegisteredHealthCheck(app: ApplicationInterface): boolean {
|
|
119
|
+
const config = HealthCheckManager.getConfig();
|
|
120
|
+
const rootScope = (app as any).root;
|
|
121
|
+
if (!rootScope?.router) return false;
|
|
122
|
+
|
|
123
|
+
const routes = rootScope.router.getRoutes();
|
|
124
|
+
return routes.some((route: any) =>
|
|
125
|
+
route.path === config.path && route.method === HttpMethod.GET
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function registerDefaultHealthCheck(app: ApplicationInterface): void {
|
|
130
|
+
const config = HealthCheckManager.getConfig();
|
|
131
|
+
if (!config.enabled) return;
|
|
132
|
+
if (hasRegisteredHealthCheck(app)) return;
|
|
133
|
+
|
|
134
|
+
app.get(config.path, (ctx: RequestContext) => {
|
|
135
|
+
return HealthCheckManager.handleHealthCheck(ctx);
|
|
136
|
+
});
|
|
137
|
+
}
|
|
@@ -5,7 +5,9 @@ export * from "./responses/index"
|
|
|
5
5
|
export * from "./decorators/index"
|
|
6
6
|
export * from "./plugins/index"
|
|
7
7
|
export * from "./runtime/index"
|
|
8
|
+
export * from "./mcp/index"
|
|
8
9
|
export * from "./exceptions/index"
|
|
10
|
+
export * from "./health-check"
|
|
9
11
|
export * from "./controllers"
|
|
10
12
|
export * from "./data-transfer-object"
|
|
11
13
|
export * from "./view-model"
|