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
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# `@McpServer()` et décorateurs MCP
|
|
2
|
+
|
|
3
|
+
> **Navigation :** [← guard](guard.md) | [README →](README.md)
|
|
4
|
+
|
|
5
|
+
Les décorateurs MCP servent à définir un serveur **Model Context Protocol** : outils, prompts et ressources accessibles aux clients IA.
|
|
6
|
+
|
|
7
|
+
## Décorateurs concernés
|
|
8
|
+
|
|
9
|
+
- `@McpServer()`
|
|
10
|
+
- `@McpTool()`
|
|
11
|
+
- `@McpPrompt()`
|
|
12
|
+
- `@McpResource()`
|
|
13
|
+
- `@McpResourceTemplate()`
|
|
14
|
+
- `@McpArg()` (alias `@McpArgument()`)
|
|
15
|
+
|
|
16
|
+
## Pourquoi utilisé
|
|
17
|
+
|
|
18
|
+
- regrouper une logique exposée aux clients IA dans une classe
|
|
19
|
+
- garder une structure cohérente avec les contrôleurs HTTP
|
|
20
|
+
- réutiliser l’injection de dépendances
|
|
21
|
+
|
|
22
|
+
## Comment l’utiliser
|
|
23
|
+
|
|
24
|
+
- marquez la classe avec `@McpServer({ name, version, path })`
|
|
25
|
+
- ajoutez les éléments sur les méthodes
|
|
26
|
+
- déclarez les paramètres avec `@McpArg` dans l’ordre des arguments
|
|
27
|
+
- si une méthode n’a aucun `@McpArg`, elle reçoit l’objet d’entrée complet en premier argument
|
|
28
|
+
|
|
29
|
+
## Exemple
|
|
30
|
+
|
|
31
|
+
```typescript
|
|
32
|
+
import { McpServer, McpTool, McpResource, McpArg } from "raiton/framework"
|
|
33
|
+
|
|
34
|
+
@McpServer({ name: "math", version: "1.0.0", path: "/mcp" })
|
|
35
|
+
export class MathServer {
|
|
36
|
+
@McpTool({ name: "add", description: "Additionne deux nombres" })
|
|
37
|
+
add(
|
|
38
|
+
@McpArg("a", "Premier opérande", Number) a: number,
|
|
39
|
+
@McpArg("b", "Second opérande", Number) b: number,
|
|
40
|
+
) {
|
|
41
|
+
return a + b
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
@McpResource({ uri: "config://app", name: "Configuration", mimeType: "application/json" })
|
|
45
|
+
config() {
|
|
46
|
+
return { env: "production" }
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Options
|
|
52
|
+
|
|
53
|
+
`@McpServer` accepte `name`, `version`, `description`, `path` et `instructions`.
|
|
54
|
+
|
|
55
|
+
`@McpResourceTemplate` accepte `uriTemplate`, `name`, `description` et `mimeType` ; les variables `{...}` de l’URI sont transmises à la méthode.
|
|
56
|
+
|
|
57
|
+
## Avantages
|
|
58
|
+
|
|
59
|
+
- API déclarative et lisible
|
|
60
|
+
- métadonnées de type pour générer automatiquement le schéma des arguments
|
|
61
|
+
- pas de serveur séparé : cohabite avec HTTP et sockets
|
|
62
|
+
|
|
63
|
+
## Inconvénients
|
|
64
|
+
|
|
65
|
+
- l’inférence de type repose sur le métatype fourni à `@McpArg`
|
|
66
|
+
- certains éléments (ex. notifications SSE) restent simples
|
|
67
|
+
|
|
68
|
+
---
|
|
69
|
+
|
|
70
|
+
[← guard](guard.md) | [README →](README.md)
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# Health-check
|
|
2
|
+
|
|
3
|
+
> **Navigation :** [← security](security.md) | [https →](https.md)
|
|
4
|
+
|
|
5
|
+
Les health-checks permettent d'exposer un endpoint de contrôle pour les sondes d'infrastructure (load balancer, orchestrateur, « liveness » / « readiness »). Raiton fournit un endpoint **par défaut** et vous permet de le **personnaliser** grâce à `@HealthCheck()` et `HealthCheckManager`.
|
|
6
|
+
|
|
7
|
+
## Endpoint par défaut
|
|
8
|
+
|
|
9
|
+
Sans aucune configuration, Raiton enregistre automatiquement `GET /health` **après** le scan des contrôleurs.
|
|
10
|
+
|
|
11
|
+
```json
|
|
12
|
+
{
|
|
13
|
+
"statusCode": 200,
|
|
14
|
+
"message": "Service is healthy",
|
|
15
|
+
"data": {
|
|
16
|
+
"status": "healthy",
|
|
17
|
+
"timestamp": "2026-09-03T12:00:00.000Z",
|
|
18
|
+
"uptime": 42.1,
|
|
19
|
+
"version": "0.0.0"
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Dès que vous définissez votre propre health-check, le défaut est remplacé.
|
|
25
|
+
|
|
26
|
+
## Définir un health-check personnalisé
|
|
27
|
+
|
|
28
|
+
Utilisez `@HealthCheck()` sur une méthode combinée à un décorateur de route.
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
import { Controllable, Get, HealthCheck, HttpStatus, RaitonResponses } from "raiton/framework"
|
|
32
|
+
|
|
33
|
+
@Controllable()
|
|
34
|
+
export class HealthController {
|
|
35
|
+
@Get("/health")
|
|
36
|
+
@HealthCheck({ summary: "État de l'application" })
|
|
37
|
+
check() {
|
|
38
|
+
return RaitonResponses(
|
|
39
|
+
"Service is healthy",
|
|
40
|
+
{ status: "healthy" },
|
|
41
|
+
HttpStatus.OK,
|
|
42
|
+
{ error: false }
|
|
43
|
+
)
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Vous pouvez renvoyer un code `503 Service Unavailable` dans le cas où l'application est en mauvaise santé.
|
|
49
|
+
|
|
50
|
+
## Configurer le comportement par défaut
|
|
51
|
+
|
|
52
|
+
`HealthCheckManager.configure(...)` agit sur le health-check par défaut (et sur les sauts de middleware applicables).
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
import { HealthCheckManager, HttpStatus } from "raiton/framework"
|
|
56
|
+
|
|
57
|
+
HealthCheckManager.configure({
|
|
58
|
+
path: "/health",
|
|
59
|
+
response: {
|
|
60
|
+
statusCode: HttpStatus.OK,
|
|
61
|
+
message: "All systems operational"
|
|
62
|
+
}
|
|
63
|
+
})
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### Vérifications personnalisées
|
|
67
|
+
|
|
68
|
+
Ajoutez des vérifications de dépendances pour enrichir la réponse.
|
|
69
|
+
|
|
70
|
+
```typescript
|
|
71
|
+
HealthCheckManager.configure({
|
|
72
|
+
checks: [
|
|
73
|
+
{
|
|
74
|
+
name: "database",
|
|
75
|
+
check: async () => {
|
|
76
|
+
// testez votre connexion
|
|
77
|
+
return { status: "healthy" as const }
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
name: "cache",
|
|
82
|
+
check: async () => ({ status: "degraded" as const, message: "cache partiellement disponible" })
|
|
83
|
+
}
|
|
84
|
+
]
|
|
85
|
+
})
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Les résultats sont agrégés dans `data.checks`. Le statut global est :
|
|
89
|
+
- `unhealthy` si au moins une vérification échoue (code `503`)
|
|
90
|
+
- `degraded` sinon
|
|
91
|
+
- `healthy` par défaut (code `200`)
|
|
92
|
+
|
|
93
|
+
### Handler entièrement personnalisé
|
|
94
|
+
|
|
95
|
+
`registerCustomHandler` remplace entièrement la logique de réponse du health-check par défaut.
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
HealthCheckManager.registerCustomHandler((ctx) => {
|
|
99
|
+
return { ok: true, memory: process.memoryUsage() }
|
|
100
|
+
})
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Types et options
|
|
104
|
+
|
|
105
|
+
- `HealthCheckManager.configure(config)` : `path`, `response` (`statusCode`, `message`), `checks`.
|
|
106
|
+
- `@HealthCheck(options)` : `path`, `tags`, `summary`, `description`, `excludeFromDocs`.
|
|
107
|
+
- `HealthCheckCheck` : `{ name, check }` où `check` renvoie `{ status, message? }`.
|
|
108
|
+
|
|
109
|
+
## Bon usage
|
|
110
|
+
|
|
111
|
+
- garder le endpoint de santé léger et sans logique métier lourde
|
|
112
|
+
- utiliser `checks` pour les dépendances critiques (base de données, cache)
|
|
113
|
+
- renvoyer `503` quand l'application ne peut plus traiter de requêtes
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
[← security](security.md) | [https →](https.md)
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
# MCP (Model Context Protocol)
|
|
2
|
+
|
|
3
|
+
> **Navigation :** [← sockets](sockets.md) | [types →](types.md)
|
|
4
|
+
|
|
5
|
+
Raiton permet de créer un serveur **MCP (Model Context Protocol)** facilement, avec des décorateurs, et de le faire coexister avec le serveur HTTP et les sockets sur le même processus et le même port.
|
|
6
|
+
|
|
7
|
+
## De quoi s’agit-il
|
|
8
|
+
|
|
9
|
+
MCP est un protocole qui expose des **outils (tools)**, des **prompts** et des **ressources (resources)** à des clients IA (assistants, agents, IDE…). Raiton implémente le transport **Streamable HTTP** : un simple endpoint qui accepte des requêtes JSON-RPC `POST`, identique au reste de l’API.
|
|
10
|
+
|
|
11
|
+
## Pourquoi utilisé
|
|
12
|
+
|
|
13
|
+
- exposer une logique applicative existante à des assistants IA
|
|
14
|
+
- réutiliser les services et l’injection de dépendances existants
|
|
15
|
+
- cohabiter avec les contrôleurs HTTP et les sockets sans serveur séparé
|
|
16
|
+
- bénéficier du HMR, des artifacts et d’OpenAPI, comme pour le reste du framework
|
|
17
|
+
|
|
18
|
+
## Comment l’utiliser
|
|
19
|
+
|
|
20
|
+
1. Créez un fichier artifact `*.mcp.ts` (reconnu automatiquement)
|
|
21
|
+
2. Déclarez une classe avec `@McpServer()`
|
|
22
|
+
3. Ajoutez des méthodes avec `@McpTool()`, `@McpPrompt()`, `@McpResource()` ou `@McpResourceTemplate()`
|
|
23
|
+
4. Déclarez les paramètres avec `@McpArg()`
|
|
24
|
+
5. Le chemin `path` du serveur devient automatiquement accessible en `POST`
|
|
25
|
+
|
|
26
|
+
## Exemple
|
|
27
|
+
|
|
28
|
+
```typescript
|
|
29
|
+
import { McpServer, McpTool, McpPrompt, McpResource, McpResourceTemplate, McpArg } from "raiton/framework"
|
|
30
|
+
|
|
31
|
+
@McpServer({ name: "math", version: "1.0.0", path: "/mcp" })
|
|
32
|
+
export class MathServer {
|
|
33
|
+
@McpTool({ name: "add", description: "Additionne deux nombres" })
|
|
34
|
+
add(
|
|
35
|
+
@McpArg("a", "Premier opérande", Number) a: number,
|
|
36
|
+
@McpArg("b", "Second opérande", Number) b: number,
|
|
37
|
+
) {
|
|
38
|
+
return a + b
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
@McpPrompt({ name: "resume", description: "Résume un texte" })
|
|
42
|
+
resume(@McpArg("text", "Le texte à résumer", String) text: string) {
|
|
43
|
+
return `Résume le texte suivant :\n\n${text}`
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
@McpResource({ uri: "config://app", name: "Configuration", mimeType: "application/json" })
|
|
47
|
+
config() {
|
|
48
|
+
return { env: "production" }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
@McpResourceTemplate({ uriTemplate: "user://{id}", name: "Utilisateur par id" })
|
|
52
|
+
user({ id }: any) {
|
|
53
|
+
return { id, name: `User-${id}` }
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Aucun enregistrement supplémentaire n’est nécessaire : le scanner détecte `*.mcp.ts`, compile la classe, enregistre le serveur dans le registre MCP et ajoute automatiquement les routes `POST /mcp` et `GET /mcp` sur l’application.
|
|
59
|
+
|
|
60
|
+
## Points d’extensibilité
|
|
61
|
+
|
|
62
|
+
### Enregistrement manuel
|
|
63
|
+
|
|
64
|
+
Vous pouvez aussi compiler et enregistrer un serveur MCP explicitement :
|
|
65
|
+
|
|
66
|
+
```typescript
|
|
67
|
+
import { compileMcp } from "raiton/core"
|
|
68
|
+
|
|
69
|
+
compileMcp(MathServer)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### Plugin MCP
|
|
73
|
+
|
|
74
|
+
Le plugin `mcpPlugin()` permet un montage explicite sur un chemin personnalisé et d’activer le endpoint `GET` :
|
|
75
|
+
|
|
76
|
+
```typescript
|
|
77
|
+
import { app } from "raiton"
|
|
78
|
+
|
|
79
|
+
app.register(mcpPlugin({ path: "/mcp", enableGet: true }))
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
> Les routes étant normalement auto-générées par la compilation, le plugin est surtout utile lorsque vous gérez vous-même l’enregistrement ou souhaitez un contrôle fin.
|
|
83
|
+
|
|
84
|
+
## Protocole
|
|
85
|
+
|
|
86
|
+
Le endpoint répond au protocole MCP sur JSON-RPC 2.0 :
|
|
87
|
+
|
|
88
|
+
- `initialize` — négociation de la version et des capacités
|
|
89
|
+
- `ping` — test de disponibilité
|
|
90
|
+
- `tools/list` / `tools/call`
|
|
91
|
+
- `prompts/list` / `prompts/get`
|
|
92
|
+
- `resources/list` / `resources/templates/list` / `resources/read`
|
|
93
|
+
- `logging/setLevel` / `notifications/initialized`
|
|
94
|
+
|
|
95
|
+
La version du protocole est vérifiée : une version non supportée renvoie `406`. Les réponses utilisent le header `mcp-session-id`.
|
|
96
|
+
|
|
97
|
+
## HMR
|
|
98
|
+
|
|
99
|
+
Les fichiers `*.mcp.ts` bénéficient du **hot reload** : une modification recharge le serveur MCP sans redémarrer le process, exactement comme les contrôleurs et les sockets.
|
|
100
|
+
|
|
101
|
+
## OpenAPI
|
|
102
|
+
|
|
103
|
+
Les serveurs MCP sont documentés dans le contrat OpenAPI généré, avec une extension `x-mcp` listant outils, prompts et ressources.
|
|
104
|
+
|
|
105
|
+
## Avantages
|
|
106
|
+
|
|
107
|
+
- intégration native avec le serveur HTTP existant
|
|
108
|
+
- réutilise l’injection de dépendances
|
|
109
|
+
- HMR, artifacts et OpenAPI homogènes avec le reste du framework
|
|
110
|
+
- aucun serveur ni processus séparé
|
|
111
|
+
|
|
112
|
+
## Inconvénients
|
|
113
|
+
|
|
114
|
+
- transport limité au Streamable HTTP (pas de stdio fourni)
|
|
115
|
+
- les notifications serveur `GET` (SSE) restent basiques
|
|
116
|
+
- le protocole évolue vite, la liste des versions supportées doit être suivie
|
|
117
|
+
|
|
118
|
+
---
|
|
119
|
+
|
|
120
|
+
[← sockets](sockets.md) | [types →](types.md)
|
|
@@ -9,6 +9,7 @@ Les plugins servent à brancher des fonctionnalités réutilisables à l’éche
|
|
|
9
9
|
- [body-parser.md](body-parser.md)
|
|
10
10
|
- [security.md](security.md)
|
|
11
11
|
- [openapi/README.md](openapi/README.md)
|
|
12
|
+
- [mcp.md](mcp.md) (plugin optionnel `mcpPlugin()`)
|
|
12
13
|
|
|
13
14
|
## Vue d’ensemble
|
|
14
15
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Sécurité
|
|
2
2
|
|
|
3
|
-
> **Navigation :** [← body-parser](body-parser.md) | [
|
|
3
|
+
> **Navigation :** [← body-parser](body-parser.md) | [csrf →](csrf.md)
|
|
4
4
|
|
|
5
5
|
Les plugins de sécurité servent à protéger une API exposée publiquement.
|
|
6
6
|
|
|
@@ -8,6 +8,7 @@ Les plugins de sécurité servent à protéger une API exposée publiquement.
|
|
|
8
8
|
|
|
9
9
|
- `Security.headers()`
|
|
10
10
|
- `Security.cors()`
|
|
11
|
+
- `Security.csrf()` — [Documentation complète](csrf.md)
|
|
11
12
|
- `Security.rateLimit()`
|
|
12
13
|
- `Security.bodyLimit()`
|
|
13
14
|
- `Security.methodGuard()`
|
|
@@ -19,6 +20,7 @@ app.register({
|
|
|
19
20
|
plugins: [
|
|
20
21
|
Security.headers(),
|
|
21
22
|
Security.cors({ origin: "*" }),
|
|
23
|
+
Security.csrf({ mode: CSRFModeEnum.DOUBLE_SUBMIT, secret: process.env.CSRF_SECRET }),
|
|
22
24
|
Security.rateLimit({ max: 100, windowMs: 60000 }),
|
|
23
25
|
Security.bodyLimit(1_000_000)
|
|
24
26
|
]
|
|
@@ -30,17 +32,21 @@ app.register({
|
|
|
30
32
|
- réduire les abus
|
|
31
33
|
- contrôler les origines autorisées
|
|
32
34
|
- limiter la taille des payloads
|
|
35
|
+
- protéger contre les attaques CSRF (Cross-Site Request Forgery)
|
|
33
36
|
|
|
34
37
|
## Avantages
|
|
35
38
|
|
|
36
39
|
- facile à activer
|
|
37
40
|
- couvre plusieurs protections de base
|
|
41
|
+
- CSRF supporte le mode stateless (double-submit) et stateful (synchronizer)
|
|
42
|
+
- détection automatique des clients mobile/desktop
|
|
38
43
|
|
|
39
44
|
## Inconvénients
|
|
40
45
|
|
|
41
46
|
- `rateLimit()` est en mémoire, donc non distribué
|
|
42
47
|
- `cors()` doit être configuré selon le contexte réel
|
|
48
|
+
- `csrf()` nécessite une configuration côté client pour les navigateurs
|
|
43
49
|
|
|
44
50
|
---
|
|
45
51
|
|
|
46
|
-
[← body-parser](body-parser.md) | [
|
|
52
|
+
[← body-parser](body-parser.md) | [csrf →](csrf.md)
|
package/package.json
CHANGED
|
@@ -8,7 +8,7 @@ import {Logger} from "@protorians/logger";
|
|
|
8
8
|
import {RaitonConfig} from "./config";
|
|
9
9
|
import {Artifacts} from "../framework/artifacts";
|
|
10
10
|
import {Injection} from "./injection";
|
|
11
|
-
import {HttpsConfigInterface, resolveHttpsConfig} from "../framework/utilities/https";
|
|
11
|
+
import {HttpsConfigInterface, resolveHttpsConfig} from "../framework/utilities/https.util";
|
|
12
12
|
|
|
13
13
|
export class Application implements ApplicationInterface {
|
|
14
14
|
private root: PluginScope
|
package/source/core/builder.ts
CHANGED
|
@@ -117,6 +117,7 @@ export class RaitonBuilder implements BuilderInterface {
|
|
|
117
117
|
this.listenHmrSocket()
|
|
118
118
|
this.listenHmrMiddleware()
|
|
119
119
|
this.listenHmrHook()
|
|
120
|
+
this.listenHmrMcp()
|
|
120
121
|
this.watching();
|
|
121
122
|
}
|
|
122
123
|
|
|
@@ -178,6 +179,17 @@ export class RaitonBuilder implements BuilderInterface {
|
|
|
178
179
|
)
|
|
179
180
|
}
|
|
180
181
|
|
|
182
|
+
protected listenHmrMcp(): void {
|
|
183
|
+
Raiton.signals.listen(
|
|
184
|
+
'hmr:mcp',
|
|
185
|
+
async ({filename, version, timestamp}) => {
|
|
186
|
+
const imported = await import(`${filename}?v=${version || 1}&t=${timestamp || Date.now()}`)
|
|
187
|
+
Artifacts.reloadMcp(imported, filename)
|
|
188
|
+
Logger.log(LBadge.debug('HMR'), `[mcp] ${path.relative(this.workdir, filename)}`)
|
|
189
|
+
}
|
|
190
|
+
)
|
|
191
|
+
}
|
|
192
|
+
|
|
181
193
|
protected async build(thread: ThreadInterface): Promise<this> {
|
|
182
194
|
if (!this._source) throw new Error('Application source not found');
|
|
183
195
|
if (!this._out) throw new Error('Application output not found');
|
|
@@ -3,9 +3,11 @@ import {BuilderHMRDeclarationInterface} from "../../types";
|
|
|
3
3
|
import {LBadge, Logger} from "@protorians/logger";
|
|
4
4
|
import {compileController} from "./compiler";
|
|
5
5
|
import {compileSocket} from "../socket/builder";
|
|
6
|
+
import {compileMcp} from "../mcp/builder";
|
|
6
7
|
import {RaitonThread} from "../thread";
|
|
7
8
|
import {Injection} from "../injection";
|
|
8
|
-
import {isControllerArtifact, isSocketArtifact} from "../../framework";
|
|
9
|
+
import {isControllerArtifact, isSocketArtifact, isMcpArtifact} from "../../framework";
|
|
10
|
+
import {Artifacts} from "../../framework/artifacts";
|
|
9
11
|
import path from "node:path";
|
|
10
12
|
import {ControllerRouteTracker} from "./tracker";
|
|
11
13
|
|
|
@@ -15,6 +17,14 @@ export class ControllerBuilder {
|
|
|
15
17
|
const files = fs.readdirSync(workdir, {recursive: true})
|
|
16
18
|
.map(file => file.toString());
|
|
17
19
|
const output: any[] = []
|
|
20
|
+
const timestamp = Date.now()
|
|
21
|
+
|
|
22
|
+
for (const file of files) {
|
|
23
|
+
const filename = path.join(workdir, file);
|
|
24
|
+
const classification = Artifacts.classify(filename);
|
|
25
|
+
if (classification?.channel !== 'hmr:di') continue;
|
|
26
|
+
await this.loadDiArtifact(filename, 1, timestamp);
|
|
27
|
+
}
|
|
18
28
|
|
|
19
29
|
for (const file of files) {
|
|
20
30
|
output.push(await this.build<any>({filename: path.join(workdir, file), version: 1, timestamp: Date.now()}))
|
|
@@ -23,11 +33,26 @@ export class ControllerBuilder {
|
|
|
23
33
|
return output.filter(f => typeof f !== 'undefined');
|
|
24
34
|
}
|
|
25
35
|
|
|
36
|
+
static async loadDiArtifact(filename: string, version = 1, timestamp = Date.now()): Promise<void> {
|
|
37
|
+
const imported = await import(`${filename}?v=${version || 1}&t=${timestamp || Date.now()}`)
|
|
38
|
+
|
|
39
|
+
for (const mod of Object.values(imported)) {
|
|
40
|
+
const name = (mod && typeof mod === 'object' && 'name' in mod) ? mod.name : (
|
|
41
|
+
typeof mod === 'function' ? mod.name ?? mod.constructor.name : undefined
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
if (typeof name === 'string' && Injection.has(name)) {
|
|
45
|
+
Injection.registerArtifactPath(name, filename)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
26
50
|
static async build<T>({filename, version, timestamp}: BuilderHMRDeclarationInterface): Promise<T | undefined> {
|
|
27
51
|
const isController = isControllerArtifact(filename);
|
|
28
52
|
const isSocket = isSocketArtifact(filename);
|
|
53
|
+
const isMcp = isMcpArtifact(filename);
|
|
29
54
|
|
|
30
|
-
if (!isController && !isSocket)
|
|
55
|
+
if (!isController && !isSocket && !isMcp)
|
|
31
56
|
return undefined;
|
|
32
57
|
|
|
33
58
|
const imported = await import(`${filename}?v=${version || 1}&t=${timestamp || Date.now()}`)
|
|
@@ -43,6 +68,10 @@ export class ControllerBuilder {
|
|
|
43
68
|
return compileSocket(artifact) as any;
|
|
44
69
|
}
|
|
45
70
|
|
|
71
|
+
if (isMcp) {
|
|
72
|
+
return compileMcp(artifact) as any;
|
|
73
|
+
}
|
|
74
|
+
|
|
46
75
|
const compilated = compileController(artifact, RaitonThread.current.application);
|
|
47
76
|
return compilated;
|
|
48
77
|
}
|
package/source/core/index.ts
CHANGED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import {registerMcpServer, unregisterMcpServer, getMcpServerMetadata} from "./metadata";
|
|
2
|
+
import {Injection} from "../injection";
|
|
3
|
+
import {McpServerRegistrationInterface} from "../../types";
|
|
4
|
+
import {McpRouteTracker} from "./tracker";
|
|
5
|
+
import {RaitonThread} from "../thread";
|
|
6
|
+
import {HttpMethod} from "../../framework/enums";
|
|
7
|
+
import {mcpHandleGet, mcpHandlePost, isMcpJsonRpc, SESSION_HEADER} from "../../framework/mcp/streamable-http";
|
|
8
|
+
import type {ContextInterface} from "../../types/core";
|
|
9
|
+
|
|
10
|
+
export function compileMcp(McpServerClass: any): McpServerRegistrationInterface | undefined {
|
|
11
|
+
const metadata = getMcpServerMetadata(McpServerClass.prototype || McpServerClass)
|
|
12
|
+
const name = metadata.name || McpServerClass.name
|
|
13
|
+
if (!metadata.path) return undefined
|
|
14
|
+
|
|
15
|
+
unregisterMcpServer(name)
|
|
16
|
+
Injection.invalidateCascade(name)
|
|
17
|
+
const entry = registerMcpServer(McpServerClass)
|
|
18
|
+
|
|
19
|
+
const app = RaitonThread.current?.application
|
|
20
|
+
const rootScope = (app as any)?.root
|
|
21
|
+
|
|
22
|
+
McpRouteTracker.removeRoutes(name, rootScope?.router)
|
|
23
|
+
|
|
24
|
+
if (app && rootScope?.router) {
|
|
25
|
+
const path = metadata.path
|
|
26
|
+
const postRoute = rootScope.route(
|
|
27
|
+
HttpMethod.POST,
|
|
28
|
+
path,
|
|
29
|
+
async (context: ContextInterface) => {
|
|
30
|
+
if (!isMcpJsonRpc(context.req.body)) {
|
|
31
|
+
return {error: {code: -32700, message: 'Invalid JSON-RPC request'}}
|
|
32
|
+
}
|
|
33
|
+
const existingSessionId = readSessionId(context)
|
|
34
|
+
const result = await mcpHandlePost(entry, context.req.body, existingSessionId)
|
|
35
|
+
context.reply.status(result.status)
|
|
36
|
+
if (result.headers[SESSION_HEADER]) {
|
|
37
|
+
context.reply.header(SESSION_HEADER, result.headers[SESSION_HEADER])
|
|
38
|
+
}
|
|
39
|
+
if (result.body === '') {
|
|
40
|
+
context.reply.send('')
|
|
41
|
+
return
|
|
42
|
+
}
|
|
43
|
+
return result.body
|
|
44
|
+
}
|
|
45
|
+
)
|
|
46
|
+
const getRoute = rootScope.route(
|
|
47
|
+
HttpMethod.GET,
|
|
48
|
+
path,
|
|
49
|
+
async (context: ContextInterface) => {
|
|
50
|
+
const existingSessionId = readSessionId(context)
|
|
51
|
+
const result = mcpHandleGet(entry, existingSessionId)
|
|
52
|
+
context.reply.status(result.status)
|
|
53
|
+
if (result.headers[SESSION_HEADER]) {
|
|
54
|
+
context.reply.header(SESSION_HEADER, result.headers[SESSION_HEADER])
|
|
55
|
+
}
|
|
56
|
+
return result.body
|
|
57
|
+
}
|
|
58
|
+
)
|
|
59
|
+
McpRouteTracker.setRoutes(name, [postRoute, getRoute])
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return entry
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function readSessionId(context: any): string | undefined {
|
|
66
|
+
const req = context.req
|
|
67
|
+
if (req?.headers?.get) {
|
|
68
|
+
const value = req.headers.get(SESSION_HEADER)
|
|
69
|
+
if (value) return value
|
|
70
|
+
}
|
|
71
|
+
if (req?.headers && typeof req.headers === 'object') {
|
|
72
|
+
const value = (req.headers as any)[SESSION_HEADER]
|
|
73
|
+
if (value) return value
|
|
74
|
+
}
|
|
75
|
+
return undefined
|
|
76
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import {McpServerMetaInterface, McpServerRegistrationInterface} from "../../types";
|
|
2
|
+
import {METADATA_KEYS} from "../../framework/constants";
|
|
3
|
+
import "reflect-metadata";
|
|
4
|
+
|
|
5
|
+
const registry = new Map<string, McpServerRegistrationInterface>();
|
|
6
|
+
|
|
7
|
+
export function getMcpServerMetadata(target: any): McpServerMetaInterface {
|
|
8
|
+
let metadata = Reflect.getMetadata(METADATA_KEYS.MCP, target);
|
|
9
|
+
if (!metadata) {
|
|
10
|
+
metadata = {
|
|
11
|
+
name: undefined,
|
|
12
|
+
version: '1.0.0',
|
|
13
|
+
description: undefined,
|
|
14
|
+
path: '/mcp',
|
|
15
|
+
instructions: undefined,
|
|
16
|
+
tools: [],
|
|
17
|
+
prompts: [],
|
|
18
|
+
resources: [],
|
|
19
|
+
resourceTemplates: [],
|
|
20
|
+
};
|
|
21
|
+
Reflect.defineMetadata(METADATA_KEYS.MCP, metadata, target);
|
|
22
|
+
}
|
|
23
|
+
return metadata;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function registerMcpServer(construct: any): McpServerRegistrationInterface {
|
|
27
|
+
const metadata: McpServerMetaInterface = getMcpServerMetadata(construct.prototype || construct);
|
|
28
|
+
const name = metadata.name || construct.name;
|
|
29
|
+
const path = normalizePath(metadata.path || '/mcp');
|
|
30
|
+
const entry: McpServerRegistrationInterface = {
|
|
31
|
+
path,
|
|
32
|
+
name,
|
|
33
|
+
version: metadata.version || '1.0.0',
|
|
34
|
+
description: metadata.description,
|
|
35
|
+
construct,
|
|
36
|
+
metadata,
|
|
37
|
+
};
|
|
38
|
+
registry.set(name, entry);
|
|
39
|
+
return entry;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function unregisterMcpServer(constructOrName: string | any): boolean {
|
|
43
|
+
if (typeof constructOrName === 'string') {
|
|
44
|
+
return registry.delete(constructOrName);
|
|
45
|
+
}
|
|
46
|
+
const metadata: McpServerMetaInterface = getMcpServerMetadata(constructOrName.prototype || constructOrName);
|
|
47
|
+
const name = metadata.name || constructOrName.name;
|
|
48
|
+
return registry.delete(name);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function getMcpServerRegistry(): Map<string, McpServerRegistrationInterface> {
|
|
52
|
+
return registry;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function getMcpServer(name: string): McpServerRegistrationInterface | undefined {
|
|
56
|
+
return registry.get(name);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function findMcpServerForPath(pathname: string, prefix?: string): McpServerRegistrationInterface | undefined {
|
|
60
|
+
const normalized = normalizePath(pathname);
|
|
61
|
+
for (const entry of registry.values()) {
|
|
62
|
+
if (entry.path === normalized) return entry;
|
|
63
|
+
if (prefix && prefix !== '/' && entry.path.startsWith(prefix)) {
|
|
64
|
+
if (entry.path === `${prefix}${normalized}`) return entry;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function clearMcpServerRegistry(): void {
|
|
71
|
+
registry.clear();
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function normalizePath(pathname: string): string {
|
|
75
|
+
if (!pathname.startsWith('/')) pathname = `/${pathname}`;
|
|
76
|
+
if (pathname.length > 1 && pathname.endsWith('/')) {
|
|
77
|
+
pathname = pathname.slice(0, -1);
|
|
78
|
+
}
|
|
79
|
+
return pathname;
|
|
80
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import {Route} from "../router"
|
|
2
|
+
|
|
3
|
+
const mcpRouteMap = new Map<string, Route[]>()
|
|
4
|
+
|
|
5
|
+
export class McpRouteTracker {
|
|
6
|
+
static getRoutes(serverName: string): Route[] {
|
|
7
|
+
return mcpRouteMap.get(serverName) || []
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
static setRoutes(serverName: string, routes: Route[]): void {
|
|
11
|
+
mcpRouteMap.set(serverName, routes)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
static removeRoutes(serverName: string, router?: { remove(route: Route): void }): void {
|
|
15
|
+
const routes = mcpRouteMap.get(serverName)
|
|
16
|
+
if (!routes) return
|
|
17
|
+
if (router) {
|
|
18
|
+
for (const route of routes) {
|
|
19
|
+
router.remove(route)
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
mcpRouteMap.delete(serverName)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
static clear(): void {
|
|
26
|
+
mcpRouteMap.clear()
|
|
27
|
+
}
|
|
28
|
+
}
|