🚀 NestJS MCP 模块
NestJS MCP 模块专为 NestJS 应用程序打造,实现了 Model Context Protocol (MCP)。它能简化与 MCP 兼容客户端和服务的集成,提供工具管理、上下文模型交互及服务器端能力声明等功能。
🚀 快速开始
要在项目中使用 @rekog/mcp-nest
模块,请通过以下命令进行安装:
npm install @rekog/mcp-nest
✨ 主要特性
工具管理
通过 MCP 模块,你可以轻松注册和管理多种工具:
this.mcp.registerTool('my-tool', {
input: 'string',
output: 'string',
description: 'A simple echo tool'
});
const tools = [
{ name: 'tool1', input: 'string', output: 'string' },
{ name: 'tool2', input: 'number', output: 'number' }
];
this.mcp.registerTools(tools);
上下文管理
MCP 模块支持复杂的上下文模型交互:
const ctx = this.mcp.createContext('my-context-id');
ctx.update({
inputs: { text: 'Hello MCP' },
parameters: { temperature: 0.7 }
});
this.mcp.getContextStatus(ctx.id());
服务器端能力声明
配置和管理服务器端能力:
this.mcp.registerModel('gpt-3.5-turbo', {
type: 'llm',
capabilities: ['text-generation']
});
const models = [
{ name: 'gpt-4', type: 'llm', capabilities: ['text-generation'] },
{ name: 'image-generator', type: 'image', capabilities: ['image-generation'] }
];
this.mcp.registerModels(models);
安全机制
MCP 模块内置了多项安全特性,确保数据交互的安全性:
- 认证与授权:支持多种身份验证机制,如 OAuth、API 密钥等。
- 速率限制:防止滥用和 Dos 攻击。
- 数据加密:在传输过程中对敏感数据进行加密处理。
运输层协议
MCP 模块支持多种运输层协议,以满足不同场景的需求:
服务器发送事件(SSE)
使用 SSE 实现实时双向通信:
import { Server } from 'http';
import { McpModule, McpTransportType } from '@rekog/mcp-nest';
const server = new Server(3000);
server.on('connection', (stream) => {
const mcp = new Mcp(stream, { transport: McpTransportType.SSE });
});
可流式处理的 HTTP
通过可流式处理的 HTTP 实现高效的数据传输:
import { McpModule, McpTransportType } from '@rekog/mcp-nest';
const mcp = new Mcp(httpStream, {
transport: McpTransportType.STREAMABLE_HTTP,
});
💻 使用示例
基础用法
在你的 NestJS 应用主模块中引入 MCP 模块:
import { Module } from '@nestjs/common';
import { McpModule } from '@rekog/mcp-nest';
@Module({
imports: [McpModule.forRoot()],
})
export class AppModule {}
高级用法
根据需求自定义 MCP 配置:
import { Module } from '@nestjs/common';
import { McpModule } from '@rekog/mcp-nest';
@Module({
imports: [
McpModule.forRoot({
name: 'My MCP Server',
version: '1.0.0',
capabilities: {
tools: ['my-tool'],
models: ['gpt-3.5-turbo']
},
instructions: 'Please refer to the API documentation for usage details.',
transport: [McpTransportType.SSE, McpTransportType.STREAMABLE_HTTP],
}),
],
})
export class AppModule {}
📚 详细文档
配置选项
以下是 MCP 模块的主要配置参数:
参数名 |
类型 |
描述 |
默认值 |
name |
string |
服务器名称 |
'NestJS MCP Server' |
version |
string |
服务器版本号 |
'1.0.0' |
capabilities |
object<string, any> |
服务器端能力声明 |
{} |
instructions |
string |
使用说明 |
undefined |
transport |
McpTransportType[] |
支持的运输层协议 |
[McpTransportType.SSE, McpTransportType.STREAMABLE_HTTP] |
心跳机制
为了保持连接活性,可以配置心跳检测:
const mcp = new Mcp(stream, {
transport: McpTransportType.SSE,
heartbeatInterval: 30000
});
其他资源
徽章
 |
 |
npm 版本 |
依赖项 |
通过 NestJS MCP 模块,你可以轻松地将 MCP 协议集成到你的 NestJS 应用中,实现工具管理、上下文模型交互以及服务器端能力声明等功能。如需更多详细信息,请参考完整文档或源代码。