🚀 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 應用中,實現工具管理、上下文模型交互以及服務器端能力聲明等功能。如需更多詳細信息,請參考完整文檔或源代碼。