返回 AiToEarn
sse.controller.factory.ts
根目录 / project / aitoearn-backend / libs / nest-mcp / src / transport / sse.controller.factory.ts
1 import {
2 applyDecorators,
3 Body,
4 CanActivate,
5 Controller,
6 Get,
7 Inject,
8 Logger,
9 OnModuleInit,
10 Post,
11 Req,
12 Res,
13 Type,
14 UseGuards,
15 VERSION_NEUTRAL,
16 } from '@nestjs/common'
17
18 import { McpOptions } from '../interfaces'
19 import { McpSseService } from '../services/mcp-sse.service'
20 import { normalizeEndpoint } from '../utils/normalize-endpoint'
21
22 /**
23 * Creates a controller for handling SSE connections and tool executions
24 */
25 export function createSseController(
26 sseEndpoint: string,
27 messagesEndpoint: string,
28 apiPrefix: string,
29 guards: Type<CanActivate>[] = [],
30 decorators: ClassDecorator[] = [],
31 ) {
32 @Controller({
33 version: VERSION_NEUTRAL,
34 })
35 @applyDecorators(...decorators)
36 class SseController implements OnModuleInit {
37 readonly logger = new Logger(SseController.name)
38
39 constructor(
40 @Inject('MCP_OPTIONS') public readonly options: McpOptions,
41 public readonly mcpSseService: McpSseService,
42 ) {}
43
44 /**
45 * Initialize the controller and configure SSE service
46 */
47 onModuleInit() {
48 this.mcpSseService.initialize()
49 }
50
51 /**
52 * SSE connection endpoint
53 */
54 @Get(normalizeEndpoint(`${apiPrefix}/${sseEndpoint}`))
55 @UseGuards(...guards)
56 async sse(@Req() rawReq: any, @Res() rawRes: any) {
57 return this.mcpSseService.createSseConnection(
58 rawReq,
59 rawRes,
60 messagesEndpoint,
61 apiPrefix,
62 )
63 }
64
65 /**
66 * Tool execution endpoint - protected by the provided guards
67 */
68 @Post(normalizeEndpoint(`${apiPrefix}/${messagesEndpoint}`))
69 @UseGuards(...guards)
70 async messages(
71 @Req() rawReq: any,
72 @Res() rawRes: any,
73 @Body() body: unknown,
74 ): Promise<void> {
75 await this.mcpSseService.handleMessage(rawReq, rawRes, body)
76 }
77 }
78
79 return SseController
80 }
81
81 lines TYPESCRIPT