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.
Files changed (55) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/build/bin/index.mjs +20449 -2153
  3. package/docs/contributors/framework/plugins/csrf.md +277 -0
  4. package/docs/contributors/framework/plugins/security.md +40 -6
  5. package/docs/user-guide/README.md +9 -4
  6. package/docs/user-guide/best-practices.md +1 -0
  7. package/docs/user-guide/csrf.md +557 -0
  8. package/docs/user-guide/decorators/README.md +4 -0
  9. package/docs/user-guide/decorators/health-check.md +125 -0
  10. package/docs/user-guide/decorators/mcp.md +70 -0
  11. package/docs/user-guide/health-check.md +117 -0
  12. package/docs/user-guide/mcp.md +120 -0
  13. package/docs/user-guide/plugins.md +1 -0
  14. package/docs/user-guide/security.md +8 -2
  15. package/package.json +1 -1
  16. package/source/core/application.ts +1 -1
  17. package/source/core/builder.ts +12 -0
  18. package/source/core/controller/builder.ts +31 -2
  19. package/source/core/index.ts +1 -0
  20. package/source/core/mcp/builder.ts +76 -0
  21. package/source/core/mcp/index.ts +3 -0
  22. package/source/core/mcp/metadata.ts +80 -0
  23. package/source/core/mcp/tracker.ts +28 -0
  24. package/source/core/thread.ts +5 -1
  25. package/source/framework/artifacts.ts +32 -0
  26. package/source/framework/constants/decorators.constant.ts +6 -0
  27. package/source/framework/decorators/csrf-guard.decorator.ts +60 -0
  28. package/source/framework/decorators/csrf-token.decorator.ts +20 -0
  29. package/source/framework/decorators/health-check.decorator.ts +50 -0
  30. package/source/framework/decorators/index.ts +5 -1
  31. package/source/framework/decorators/mcp.decorator.ts +170 -0
  32. package/source/framework/enums/csrf.enum.ts +4 -0
  33. package/source/framework/enums/index.ts +2 -1
  34. package/source/framework/health-check.ts +137 -0
  35. package/source/framework/index.ts +2 -0
  36. package/source/framework/mcp/handler.ts +369 -0
  37. package/source/framework/mcp/index.ts +3 -0
  38. package/source/framework/mcp/protocol.ts +50 -0
  39. package/source/framework/mcp/streamable-http.ts +94 -0
  40. package/source/framework/plugins/index.ts +2 -1
  41. package/source/framework/plugins/mcp.plugin.ts +87 -0
  42. package/source/framework/plugins/security/csrf.ts +145 -0
  43. package/source/framework/plugins/security/index.ts +2 -0
  44. package/source/framework/utilities/artifact.util.ts +8 -0
  45. package/source/framework/utilities/csrf.util.ts +162 -0
  46. package/source/framework/utilities/index.ts +2 -1
  47. package/source/framework/utilities/openapi.utils.ts +81 -0
  48. package/source/types/application.ts +1 -1
  49. package/source/types/csrf.ts +38 -0
  50. package/source/types/index.ts +3 -1
  51. package/source/types/mcp.ts +118 -0
  52. package/source/types/raiton.ts +1 -0
  53. package/source/types/runtime.ts +1 -1
  54. /package/source/framework/utilities/{https.ts → https.util.ts} +0 -0
  55. /package/source/framework/utilities/{url.ts → url.util.ts} +0 -0
@@ -0,0 +1,369 @@
1
+ import type {
2
+ JsonRpcRequest,
3
+ JsonRpcResponse,
4
+ McpElementMetaInterface,
5
+ McpServerRegistrationInterface,
6
+ McpToolResultContent,
7
+ } from "../../types";
8
+ import {
9
+ JsonRpcErrorCode,
10
+ LatestProtocolVersion,
11
+ rpcError,
12
+ rpcFailure,
13
+ rpcSuccess,
14
+ } from "./protocol";
15
+ import {Injection} from "../../core/injection";
16
+
17
+ export interface McpHandleResult {
18
+ kind: 'response' | 'notification';
19
+ message?: JsonRpcResponse | JsonRpcResponse[];
20
+ }
21
+
22
+ export async function handleMcpRequest(
23
+ registryEntry: McpServerRegistrationInterface,
24
+ body: any,
25
+ ): Promise<McpHandleResult> {
26
+ const requests = Array.isArray(body) ? body : [body];
27
+ const responses: JsonRpcResponse[] = [];
28
+ let notificationOnly = true;
29
+
30
+ for (const raw of requests) {
31
+ if (!raw || typeof raw !== 'object' || typeof raw.method !== 'string') {
32
+ responses.push(rpcFailure(null, rpcError(
33
+ JsonRpcErrorCode.INVALID_REQUEST,
34
+ 'Invalid JSON-RPC request'
35
+ )));
36
+ notificationOnly = false;
37
+ continue;
38
+ }
39
+
40
+ const request = raw as JsonRpcRequest
41
+ const isNotification = request.id === undefined || request.id === null
42
+
43
+ const handled = await dispatchMcpMethod(registryEntry, request)
44
+ if (handled.kind === 'response' && handled.message) {
45
+ const message = Array.isArray(handled.message) ? handled.message[0] : handled.message
46
+ // Notifications never carry a response unless it's part of a batch with ids
47
+ if (message && (!isNotification || (requests.length > 1 && request.id !== null && request.id !== undefined))) {
48
+ responses.push(message)
49
+ }
50
+ if (!isNotification) notificationOnly = false
51
+ }
52
+ }
53
+
54
+ if (responses.length > 0) {
55
+ const message = responses.length === 1 ? responses[0] : responses
56
+ return {kind: 'response', message}
57
+ }
58
+
59
+ if (notificationOnly) {
60
+ return {kind: 'notification'}
61
+ }
62
+
63
+ return {kind: 'response', message: rpcFailure(requests[0]?.id ?? null, rpcError(
64
+ JsonRpcErrorCode.INTERNAL_ERROR,
65
+ 'No response'
66
+ ))}
67
+ }
68
+
69
+ async function dispatchMcpMethod(
70
+ entry: McpServerRegistrationInterface,
71
+ request: JsonRpcRequest,
72
+ ): Promise<McpHandleResult> {
73
+ const method = request.method
74
+ const params = request.params || {}
75
+
76
+ try {
77
+ switch (method) {
78
+ case 'initialize':
79
+ return {kind: 'response', message: rpcSuccess(request.id, handleInitialize(entry, params))}
80
+
81
+ case 'notifications/initialized':
82
+ return {kind: 'notification'}
83
+
84
+ case 'ping':
85
+ return {kind: 'response', message: rpcSuccess(request.id, {})}
86
+
87
+ case 'tools/list':
88
+ return {kind: 'response', message: rpcSuccess(request.id, listTools(entry))}
89
+
90
+ case 'tools/call':
91
+ return {kind: 'response', message: await callTool(entry, request.id, params)}
92
+
93
+ case 'prompts/list':
94
+ return {kind: 'response', message: rpcSuccess(request.id, listPrompts(entry))}
95
+
96
+ case 'prompts/get':
97
+ return {kind: 'response', message: await getPrompt(entry, request.id, params)}
98
+
99
+ case 'resources/list':
100
+ return {kind: 'response', message: rpcSuccess(request.id, getResourceList(entry))}
101
+
102
+ case 'resources/templates/list':
103
+ return {kind: 'response', message: rpcSuccess(request.id, getResourceTemplateList(entry))}
104
+
105
+ case 'resources/read':
106
+ return {kind: 'response', message: await readResource(entry, request.id, params)}
107
+
108
+ case 'logging/setLevel':
109
+ return {kind: 'notification'}
110
+
111
+ default:
112
+ return {kind: 'response', message: rpcFailure(request.id, rpcError(
113
+ JsonRpcErrorCode.METHOD_NOT_FOUND,
114
+ `Method not found: ${method}`
115
+ ))}
116
+ }
117
+ } catch (e: any) {
118
+ return {kind: 'response', message: rpcFailure(request.id, rpcError(
119
+ JsonRpcErrorCode.INTERNAL_ERROR,
120
+ e.message ?? 'Internal error'
121
+ ))}
122
+ }
123
+ }
124
+
125
+ function handleInitialize(entry: McpServerRegistrationInterface, params: any) {
126
+ return {
127
+ protocolVersion: LatestProtocolVersion,
128
+ capabilities: {
129
+ tools: entry.metadata.tools.length > 0 ? {listChanged: false} : undefined,
130
+ prompts: entry.metadata.prompts.length > 0 ? {listChanged: false} : undefined,
131
+ resources: (entry.metadata.resources.length > 0 || entry.metadata.resourceTemplates.length > 0)
132
+ ? {subscribe: false, listChanged: false}
133
+ : undefined,
134
+ },
135
+ serverInfo: {
136
+ name: entry.name,
137
+ version: entry.version,
138
+ },
139
+ ...(entry.metadata.instructions ? {instructions: entry.metadata.instructions} : {}),
140
+ }
141
+ }
142
+
143
+ function listTools(entry: McpServerRegistrationInterface) {
144
+ return {
145
+ tools: entry.metadata.tools.map(element => ({
146
+ name: element.name,
147
+ description: element.description,
148
+ inputSchema: argumentsToSchema(element.arguments),
149
+ })),
150
+ }
151
+ }
152
+
153
+ function argumentsToSchema(args: {name: string; description?: string; required?: boolean; schema?: any}[]) {
154
+ const properties: Record<string, any> = {}
155
+ const required: string[] = []
156
+ for (const arg of args) {
157
+ const schema = arg.schema ? {...arg.schema} : {type: 'string'}
158
+ if (arg.description) schema.description = arg.description
159
+ properties[arg.name] = schema
160
+ if (arg.required) required.push(arg.name)
161
+ }
162
+ return {
163
+ type: 'object',
164
+ properties,
165
+ ...(required.length > 0 ? {required} : {}),
166
+ }
167
+ }
168
+
169
+ async function callTool(entry: McpServerRegistrationInterface, id: JsonRpcRequest['id'], params: any): Promise<JsonRpcResponse> {
170
+ const name = params?.name
171
+ const input = params?.arguments || {}
172
+ if (!name) {
173
+ return rpcFailure(id, rpcError(JsonRpcErrorCode.INVALID_PARAMS, 'Tool name required'))
174
+ }
175
+
176
+ const tool = entry.metadata.tools.find(t => t.name === name)
177
+ if (!tool) {
178
+ return rpcFailure(id, rpcError(JsonRpcErrorCode.METHOD_NOT_FOUND, `Tool not found: ${name}`))
179
+ }
180
+
181
+ const instance: any = Injection.resolve(entry.construct)
182
+ if (!instance || typeof instance[tool.propertyKey] !== 'function') {
183
+ return rpcFailure(id, rpcError(JsonRpcErrorCode.INTERNAL_ERROR, `Tool handler unavailable: ${name}`))
184
+ }
185
+
186
+ try {
187
+ const args = collectArguments(instance, tool, input)
188
+ const result = await instance[tool.propertyKey](...args)
189
+
190
+ const content: McpToolResultContent[] = [{
191
+ type: 'text',
192
+ text: normalizeToolResult(result),
193
+ }]
194
+
195
+ return rpcSuccess(id, {
196
+ content,
197
+ isError: false,
198
+ })
199
+ } catch (e: any) {
200
+ return rpcSuccess(id, {
201
+ content: [{type: 'text', text: `Error: ${e.message ?? e}`}],
202
+ isError: true,
203
+ })
204
+ }
205
+ }
206
+
207
+ function normalizeToolResult(result: any): string {
208
+ if (result === null || result === undefined) return ''
209
+ if (typeof result === 'string') return result
210
+ try {
211
+ return JSON.stringify(result)
212
+ } catch {
213
+ return String(result)
214
+ }
215
+ }
216
+
217
+ function listPrompts(entry: McpServerRegistrationInterface) {
218
+ return {
219
+ prompts: entry.metadata.prompts.map(element => ({
220
+ name: element.name,
221
+ description: element.description,
222
+ arguments: element.arguments
223
+ .filter(a => a.required !== false)
224
+ .map(a => ({
225
+ name: a.name,
226
+ description: a.description,
227
+ required: a.required ?? true,
228
+ })),
229
+ })),
230
+ }
231
+ }
232
+
233
+ async function getPrompt(entry: McpServerRegistrationInterface, id: JsonRpcRequest['id'], params: any): Promise<JsonRpcResponse> {
234
+ const name = params?.name
235
+ if (!name) {
236
+ return rpcFailure(id, rpcError(JsonRpcErrorCode.INVALID_PARAMS, 'Prompt name required'))
237
+ }
238
+
239
+ const prompt = entry.metadata.prompts.find(p => p.name === name)
240
+ if (!prompt) {
241
+ return rpcFailure(id, rpcError(JsonRpcErrorCode.METHOD_NOT_FOUND, `Prompt not found: ${name}`))
242
+ }
243
+
244
+ const instance: any = Injection.resolve(entry.construct)
245
+ const args = collectArguments(instance, prompt, params?.arguments || {})
246
+ const result = await instance[prompt.propertyKey](...args)
247
+
248
+ const rendered = normalizeTemplate(prompt, result)
249
+ return rpcSuccess(id, {
250
+ description: prompt.description,
251
+ messages: [
252
+ {
253
+ role: 'user',
254
+ content: {type: 'text', text: rendered},
255
+ },
256
+ ],
257
+ })
258
+ }
259
+
260
+ function normalizeTemplate(prompt: McpElementMetaInterface, result: any): string {
261
+ if (typeof result === 'string') return result
262
+ if (result && typeof result === 'object' && 'messages' in result) return JSON.stringify(result.messages)
263
+ return normalizeToolResult(result)
264
+ }
265
+
266
+ function getResourceList(entry: McpServerRegistrationInterface) {
267
+ const resources = entry.metadata.resources.map(element => ({
268
+ uri: element.uri,
269
+ name: element.name || element.propertyKey,
270
+ description: element.description,
271
+ mimeType: element.mimeType,
272
+ }))
273
+ return {resources}
274
+ }
275
+
276
+ function getResourceTemplateList(entry: McpServerRegistrationInterface) {
277
+ const templates = entry.metadata.resourceTemplates.map(element => ({
278
+ uriTemplate: element.uri,
279
+ name: element.name || element.propertyKey,
280
+ description: element.description,
281
+ mimeType: element.mimeType,
282
+ }))
283
+ return {resourceTemplates: templates}
284
+ }
285
+
286
+ async function readResource(entry: McpServerRegistrationInterface, id: JsonRpcRequest['id'], params: any): Promise<JsonRpcResponse> {
287
+ const uri = params?.uri
288
+ if (!uri) {
289
+ return rpcFailure(id, rpcError(JsonRpcErrorCode.INVALID_PARAMS, 'Resource URI required'))
290
+ }
291
+
292
+ const resource = entry.metadata.resources.find(r => r.uri === uri)
293
+ || entry.metadata.resourceTemplates.find(r => !!r.uri && matchesTemplate(r.uri, uri))
294
+ if (!resource || !resource.uri) {
295
+ return rpcFailure(id, rpcError(JsonRpcErrorCode.METHOD_NOT_FOUND, `Resource not found: ${uri}`))
296
+ }
297
+
298
+ const instance: any = Injection.resolve(entry.construct)
299
+ if (!instance || typeof instance[resource.propertyKey] !== 'function') {
300
+ return rpcFailure(id, rpcError(JsonRpcErrorCode.INTERNAL_ERROR, `Resource handler unavailable: ${uri}`))
301
+ }
302
+
303
+ try {
304
+ const templateArgs = extractTemplateArgs(resource.uri, uri)
305
+ const args = collectArguments(instance, resource, templateArgs)
306
+ const result = await instance[resource.propertyKey](...args)
307
+
308
+ const contents = [{
309
+ uri,
310
+ mimeType: resource.mimeType || 'text/plain',
311
+ text: normalizeToolResult(result),
312
+ }]
313
+
314
+ return rpcSuccess(id, {contents})
315
+ } catch (e: any) {
316
+ return rpcFailure(id, rpcError(JsonRpcErrorCode.INTERNAL_ERROR, e.message ?? 'Resource read error'))
317
+ }
318
+ }
319
+
320
+ function matchesTemplate(template: string, uri: string): boolean {
321
+ return templateToRegExp(template).test(uri)
322
+ }
323
+
324
+ function extractTemplateArgs(template: string, uri: string): Record<string, any> {
325
+ const regex = templateToRegExp(template)
326
+ const match = uri.match(regex)
327
+ if (!match) return {}
328
+ const names = (template.match(/\{([^}]+)\}/g) || []).map(n => n.slice(1, -1))
329
+ const args: Record<string, any> = {}
330
+ names.forEach((name, index) => {
331
+ args[name] = match[index + 1]
332
+ })
333
+ return args
334
+ }
335
+
336
+ function templateToRegExp(template: string): RegExp {
337
+ const escapedTemplate = template.replace(/\{[^}]+\}/g, '([^/]+)')
338
+ return new RegExp(`^${escapedTemplate}$`)
339
+ }
340
+
341
+ // Collect arguments from the decorated method, mapping MCP argument metadata to positional values.
342
+ // When no argument metadata is declared, the full input object (or a single argument value) is passed through.
343
+ function collectArguments(instance: any, element: McpElementMetaInterface, input: Record<string, any>): any[] {
344
+ if (element.arguments.length === 0) {
345
+ return [input]
346
+ }
347
+ const args: any[] = []
348
+ for (const arg of element.arguments) {
349
+ const value = input[arg.name] ?? arg.schema?.default ?? undefined
350
+ args.push(coerceArgument(value, arg))
351
+ }
352
+ return args
353
+ }
354
+
355
+ function coerceArgument(value: any, arg: {schema?: any; metatype?: any}): any {
356
+ if (value === undefined) return undefined
357
+ const type = arg.schema?.type || (arg.metatype?.name?.toLowerCase())
358
+ switch (type) {
359
+ case 'number':
360
+ case 'integer':
361
+ return typeof value === 'number' ? value : Number(value)
362
+ case 'boolean':
363
+ return typeof value === 'boolean' ? value : value === 'true' || value === true || value === '1'
364
+ case 'string':
365
+ return typeof value === 'string' ? value : String(value)
366
+ default:
367
+ return value
368
+ }
369
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./protocol"
2
+ export * from "./handler"
3
+ export * from "./streamable-http"
@@ -0,0 +1,50 @@
1
+ import type {
2
+ JsonRpcError,
3
+ JsonRpcRequest,
4
+ JsonRpcResponse,
5
+ } from "../../types";
6
+
7
+ export const McpVersion = '2024-11-05'
8
+ export const LatestProtocolVersion = '2024-11-05'
9
+
10
+ export enum JsonRpcErrorCode {
11
+ PARSE_ERROR = -32700,
12
+ INVALID_REQUEST = -32600,
13
+ METHOD_NOT_FOUND = -32601,
14
+ INVALID_PARAMS = -32602,
15
+ INTERNAL_ERROR = -32603,
16
+ SERVER_NOT_INITIALIZED = -32002,
17
+ }
18
+
19
+ export function rpcError(code: number, message: string, data?: any): JsonRpcError {
20
+ return {code, message, ...(data !== undefined ? {data} : {})}
21
+ }
22
+
23
+ export function rpcSuccess(id: JsonRpcRequest['id'], result: any): JsonRpcResponse {
24
+ return {jsonrpc: '2.0', id: id ?? null, result}
25
+ }
26
+
27
+ export function rpcFailure(id: JsonRpcRequest['id'], error: JsonRpcError): JsonRpcResponse {
28
+ return {jsonrpc: '2.0', id: id ?? null, error}
29
+ }
30
+
31
+ export function isJsonRpcRequest(value: any): value is JsonRpcRequest {
32
+ return typeof value === 'object'
33
+ && value !== null
34
+ && typeof value.method === 'string'
35
+ && ('jsonrpc' in value ? (value as any).jsonrpc === '2.0' : true)
36
+ && !('result' in value)
37
+ && !('error' in value)
38
+ }
39
+
40
+ export function parseJsonRpc(body: any): JsonRpcRequest[] {
41
+ if (body === null || body === undefined) return []
42
+ if (Array.isArray(body)) {
43
+ const requests: JsonRpcRequest[] = []
44
+ for (const item of body) {
45
+ if (isJsonRpcRequest(item)) requests.push(item)
46
+ }
47
+ return requests
48
+ }
49
+ return isJsonRpcRequest(body) ? [body] : []
50
+ }
@@ -0,0 +1,94 @@
1
+ import type {
2
+ McpServerRegistrationInterface,
3
+ } from "../../types";
4
+ import {McpVersion} from "./protocol";
5
+ import {handleMcpRequest} from "./handler";
6
+
7
+ export const SESSION_HEADER = 'mcp-session-id'
8
+
9
+ function randomId(): string {
10
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
11
+ }
12
+
13
+ const SUPPORTED_VERSIONS = new Set(['2024-11-05', '2025-03-26', '2025-06-18', '2025-11-25'])
14
+
15
+ function isCompatibleVersion(version: string | undefined): boolean {
16
+ if (version === undefined || version === null) return false
17
+ return SUPPORTED_VERSIONS.has(version)
18
+ }
19
+
20
+ export function isMcpJsonRpc(body: any): boolean {
21
+ if (Array.isArray(body)) {
22
+ const first = body.find((r: any) => r && typeof r.method === 'string')
23
+ return !!first
24
+ }
25
+ return body && typeof body === 'object' && typeof body.method === 'string'
26
+ }
27
+
28
+ export interface McpHttpResult {
29
+ status: number
30
+ body: any
31
+ contentType: string
32
+ headers: Record<string, string>
33
+ }
34
+
35
+ export async function mcpHandlePost(
36
+ entry: McpServerRegistrationInterface,
37
+ body: any,
38
+ existingSessionId?: string,
39
+ ): Promise<McpHttpResult> {
40
+ if (!body || (!Array.isArray(body) && typeof body !== 'object')) {
41
+ return {
42
+ status: 400,
43
+ body: {error: {code: -32700, message: 'Invalid JSON-RPC request'}},
44
+ contentType: 'application/json',
45
+ headers: {},
46
+ }
47
+ }
48
+
49
+ const requests = Array.isArray(body) ? body : [body]
50
+ const initializes = requests.filter((r: any) => r && r.method === 'initialize')
51
+ if (initializes.length > 0) {
52
+ const version = initializes[0].params?.protocolVersion
53
+ if (!isCompatibleVersion(version)) {
54
+ return {
55
+ status: 406,
56
+ body: {error: {code: -32600, message: `Unsupported protocol version. Expected: ${McpVersion}`}},
57
+ contentType: 'application/json',
58
+ headers: {},
59
+ }
60
+ }
61
+ }
62
+
63
+ const sessionId = existingSessionId || randomId()
64
+ const result = await handleMcpRequest(entry, body)
65
+
66
+ if (result.kind === 'notification') {
67
+ return {
68
+ status: 202,
69
+ body: '',
70
+ contentType: '',
71
+ headers: {[SESSION_HEADER]: sessionId},
72
+ }
73
+ }
74
+
75
+ return {
76
+ status: 200,
77
+ body: result.message as any,
78
+ contentType: 'application/json',
79
+ headers: {[SESSION_HEADER]: sessionId},
80
+ }
81
+ }
82
+
83
+ export function mcpHandleGet(
84
+ entry: McpServerRegistrationInterface,
85
+ existingSessionId?: string,
86
+ ): McpHttpResult {
87
+ const sessionId = existingSessionId || randomId()
88
+ return {
89
+ status: 200,
90
+ body: {jsonrpc: '2.0', id: null, result: {status: 'connected', sessionId}},
91
+ contentType: 'application/json',
92
+ headers: {[SESSION_HEADER]: sessionId},
93
+ }
94
+ }
@@ -1,3 +1,4 @@
1
1
  export * from "./body-parser.plugin";
2
2
  export * from "./security/index";
3
- export * from "./openapi.plugin";
3
+ export * from "./openapi.plugin";
4
+ export * from "./mcp.plugin";
@@ -0,0 +1,87 @@
1
+ import type {PluginInterface} from "../../types";
2
+ import type {ContextInterface} from "../../types/core";
3
+ import {PluginScope} from "../../core";
4
+ import {findMcpServerForPath} from "../../core/mcp/metadata";
5
+ import {isMcpJsonRpc, mcpHandleGet, mcpHandlePost, SESSION_HEADER} from "../mcp/streamable-http";
6
+
7
+ export interface McpPluginOptions {
8
+ /**
9
+ * Global prefix for all MCP endpoints.
10
+ * A POST route will be registered at this path.
11
+ * @default '/mcp'
12
+ */
13
+ path?: string;
14
+
15
+ /**
16
+ * Enable the GET endpoint (returns a JSON session handshake).
17
+ * @default false
18
+ */
19
+ enableGet?: boolean;
20
+ }
21
+
22
+ export function mcpPlugin(options: McpPluginOptions = {}): PluginInterface {
23
+ const {
24
+ path = '/mcp',
25
+ enableGet = false,
26
+ } = options;
27
+
28
+ return {
29
+ name: 'mcp-plugin',
30
+ setup: (scope: PluginScope) => {
31
+
32
+ scope.route('POST', path, async (context: ContextInterface) => {
33
+ const entry = findMcpServerForPath(path, undefined)
34
+ if (!entry) {
35
+ return {error: {code: -32002, message: 'MCP server not registered at this path'}}
36
+ }
37
+
38
+ const existingSessionId = readSessionId(context)
39
+
40
+ if (!isMcpJsonRpc(context.req.body)) {
41
+ return {error: {code: -32700, message: 'Invalid JSON-RPC request'}}
42
+ }
43
+
44
+ const result = await mcpHandlePost(entry, context.req.body, existingSessionId)
45
+ context.reply.status(result.status)
46
+ if (result.headers[SESSION_HEADER]) {
47
+ context.reply.header(SESSION_HEADER, result.headers[SESSION_HEADER])
48
+ }
49
+ if (result.body === '') {
50
+ context.reply.send('')
51
+ return
52
+ }
53
+ return result.body
54
+ })
55
+
56
+ if (enableGet) {
57
+ scope.route('GET', path, async (context: ContextInterface) => {
58
+ const entry = findMcpServerForPath(path, undefined)
59
+ if (!entry) {
60
+ return {error: {code: -32002, message: 'MCP server not registered at this path'}}
61
+ }
62
+
63
+ const existingSessionId = readSessionId(context)
64
+ const result = mcpHandleGet(entry, existingSessionId)
65
+ context.reply.status(result.status)
66
+ if (result.headers[SESSION_HEADER]) {
67
+ context.reply.header(SESSION_HEADER, result.headers[SESSION_HEADER])
68
+ }
69
+ return result.body
70
+ })
71
+ }
72
+ }
73
+ }
74
+ }
75
+
76
+ function readSessionId(context: any): string | undefined {
77
+ const req = context.req
78
+ if (req?.headers?.get) {
79
+ const value = req.headers.get(SESSION_HEADER)
80
+ if (value) return value
81
+ }
82
+ if (req?.headers && typeof req.headers === 'object') {
83
+ const value = (req.headers as any)[SESSION_HEADER]
84
+ if (value) return value
85
+ }
86
+ return undefined
87
+ }