| 1 | import { |
| 2 | applyDecorators, |
| 3 | Body, |
| 4 | CanActivate, |
| 5 | Controller, |
| 6 | Delete, |
| 7 | Get, |
| 8 | Inject, |
| 9 | Logger, |
| 10 | Post, |
| 11 | Req, |
| 12 | Res, |
| 13 | Type, |
| 14 | UseGuards, |
| 15 | } from '@nestjs/common' |
| 16 | |
| 17 | import { McpOptions } from '../interfaces' |
| 18 | import { McpStreamableHttpService } from '../services/mcp-streamable-http.service' |
| 19 | import { normalizeEndpoint } from '../utils/normalize-endpoint' |
| 20 | |
| 21 | /** |
| 22 | * Creates a controller for handling Streamable HTTP connections and tool executions |
| 23 | */ |
| 24 | export function createStreamableHttpController( |
| 25 | endpoint: string, |
| 26 | apiPrefix: string, |
| 27 | guards: Type<CanActivate>[] = [], |
| 28 | decorators: ClassDecorator[] = [], |
| 29 | ) { |
| 30 | @Controller() |
| 31 | @applyDecorators(...decorators) |
| 32 | class StreamableHttpController { |
| 33 | public readonly logger = new Logger(StreamableHttpController.name) |
| 34 | |
| 35 | constructor( |
| 36 | @Inject('MCP_OPTIONS') public readonly options: McpOptions, |
| 37 | public readonly mcpStreamableHttpService: McpStreamableHttpService, |
| 38 | ) {} |
| 39 | |
| 40 | /** |
| 41 | * Main HTTP endpoint for both initialization and subsequent requests |
| 42 | */ |
| 43 | @Post(`${normalizeEndpoint(`${apiPrefix}/${endpoint}`)}`) |
| 44 | @UseGuards(...guards) |
| 45 | async handlePostRequest( |
| 46 | @Req() req: any, |
| 47 | @Res() res: any, |
| 48 | @Body() body: unknown, |
| 49 | ): Promise<void> { |
| 50 | await this.mcpStreamableHttpService.handlePostRequest(req, res, body) |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * GET endpoint for SSE streams - not supported in stateless mode |
| 55 | */ |
| 56 | @Get(`${normalizeEndpoint(`${apiPrefix}/${endpoint}`)}`) |
| 57 | @UseGuards(...guards) |
| 58 | async handleGetRequest(@Req() req: any, @Res() res: any): Promise<void> { |
| 59 | await this.mcpStreamableHttpService.handleGetRequest(req, res) |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * DELETE endpoint for terminating sessions - not supported in stateless mode |
| 64 | */ |
| 65 | @Delete(`${normalizeEndpoint(`${apiPrefix}/${endpoint}`)}`) |
| 66 | @UseGuards(...guards) |
| 67 | async handleDeleteRequest(@Req() req: any, @Res() res: any): Promise<void> { |
| 68 | await this.mcpStreamableHttpService.handleDeleteRequest(req, res) |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | return StreamableHttpController |
| 73 | } |
| 74 |