type
status
date
slug
summary
tags
category
icon
password
核心价值
该模块的主要价值在于简化了 MCP 服务器在 NestJS 中的开发流程,让开发者可以:
- 无需关心连接传输层的细节
- 无需管理 MCP 服务器的生命周期
- 无需手动实例化 MCP 服务器
- 专注于开发 MCP 工具本身
特点
- 轻量级封装 - 模块仅管理 MCP Server 实例和 SSE Transport,不对原生 MCP Server 方法进行封装
- 多实例支持 - 可以管理多个 MCP Server 实例
- 自动生命周期管理 - 自动处理 SSE 连接的生命周期
安装方法
使用方法
1. 导入模块
可以通过三种方式导入模块:
register
: 每次注册一个独立实例,不与其他模块共享
forRoot
: 通常在根模块注册,可以被其他模块共享
forFeature
: 与 forRoot 注册的模块共享 Service 实例
基本导入示例:
2. 操作 MCP Server
获取 MCP Server 实例后,可以使用原生的 MCP Server 方法,例如注册工具:
3. 手动注册服务器实例
除了在模块配置中注册服务器,还可以在控制器或服务中手动注册:
访问端点
模块会自动创建两个端点:
- SSE 连接端点:
/{controllerBaseUrl}/{serverId}/sse
- 消息处理端点:
/{controllerBaseUrl}/{serverId}/messages
例如,使用
controllerBaseUrl: 'api/mcp'
和 serverId: 'my-mcp-server'
时:- SSE 连接:
http://localhost:3000/api/mcp/my-mcp-server/sse
- 消息处理:
http://localhost:3000/api/mcp/my-mcp-server/messages
API 参考
McpModule.register 配置选项
- controllerBaseUrl: MCP Controller 的基本 URL 路径
- sseEndpoint: SSE 连接端点名称 (默认为
sse
)
- messagesEndpoint: 消息处理端点名称 (默认为
messages
)
- mcpServerConfigs: MCP 服务器配置数组
- serverId: 服务器标识符
- serverInfo: 服务器信息
- serverOptions: 服务器选项
McpServerService 方法
- registerServer: 注册 MCP 服务器实例
- getServer: 获取指定的 MCP 服务器实例
- getServerIds: 获取所有已注册的服务器 ID
- hasServer: 检查是否存在指定 ID 的服务器
- connect: 连接服务器到传输层 (通常不需要手动调用)
McpTransportService 方法
- getTransport: 获取特定传输连接
- getActiveSessionIds: 获取服务器的所有活跃会话 ID
高级配置
可以自定义端点名称:
总结
nest-mcp-sse 模块为 NestJS 应用提供了一种简单方式来集成 MCP 服务器,特别是使用 SSE 作为传输层时。它简化了配置和管理过程,同时保持了对原生 MCP Server API 的完整访问,让开发者可以专注于业务逻辑而非基础设施搭建。
- Author:二师兄
- URL:https://cloudesx.com/article/nest-mcp-sse
- Copyright:All articles in this blog, except for special statements, adopt BY-NC-SA agreement. Please indicate the source!