### Install NestJS MCP dependencies Source: https://github.com/bamada/nestjs-mcp/blob/main/README.md Commands to install the @bamada/nestjs-mcp package using common Node.js package managers. ```bash npm install @bamada/nestjs-mcp yarn add @bamada/nestjs-mcp ``` -------------------------------- ### Configure McpModule Source: https://github.com/bamada/nestjs-mcp/blob/main/README.md Provides examples for both synchronous and asynchronous configuration of the McpModule, including server information, transport selection, and server options. ```typescript // Synchronous Configuration @Module({ imports: [ McpModule.forRoot({ serverInfo: { name: 'my-mcp-server', version: '0.1.0' }, transport: TransportType.SSE, serverOptions: { maxConnections: 10 }, }), ], }) export class AppModule {} // Asynchronous Configuration @Module({ imports: [ ConfigModule.forRoot(), McpModule.forRootAsync({ imports: [ConfigModule], useFactory: (configService: ConfigService) => ({ serverInfo: { name: configService.get('MCP_SERVER_NAME', 'default-mcp-server'), version: configService.get('APP_VERSION', '0.0.1'), }, transport: configService.get('MCP_TRANSPORT', TransportType.SSE), serverOptions: { maxConnections: configService.get('MCP_MAX_CONNECTIONS') }, }), inject: [ConfigService], }), ], }) export class AppModule {} ``` -------------------------------- ### GET /api/mcp/sse Source: https://context7.com/bamada/nestjs-mcp/llms.txt Establishes a Server-Sent Events (SSE) connection to the MCP server for real-time communication. ```APIDOC ## GET /api/mcp/sse ### Description Establishes an SSE connection to the MCP server. This endpoint is used by clients to subscribe to events from the server. ### Method GET ### Endpoint /api/mcp/sse ### Parameters #### Query Parameters - **None** ### Request Example curl -N -H "Accept: text/event-stream" http://localhost:3000/api/mcp/sse ### Response #### Success Response (200) - **event** (string) - The type of event (e.g., open, message) - **data** (object) - The event payload containing session details or JSON-RPC messages #### Response Example event: open data: {"sessionId":"abc123"} ``` -------------------------------- ### Configure McpModule in AppModule Source: https://github.com/bamada/nestjs-mcp/blob/main/README.md Setup the McpModule in a NestJS application by importing it into the root module and configuring the server information and transport type. ```typescript import { Module } from '@nestjs/common'; import { McpModule, TransportType } from '@bamada/nestjs-mcp'; import { MyMcpProvider } from './my-mcp.provider'; @Module({ imports: [ McpModule.forRoot({ serverInfo: { name: 'my-awesome-mcp-app', version: '1.0.0', }, serverOptions: {}, transport: TransportType.SSE, }), ], providers: [MyMcpProvider], }) export class AppModule {} ``` -------------------------------- ### GET /api/mcp/health Source: https://context7.com/bamada/nestjs-mcp/llms.txt Performs a health check on the MCP server instance. ```APIDOC ## GET /api/mcp/health ### Description Returns the current health status of the MCP server. ### Method GET ### Endpoint /api/mcp/health ### Parameters - **None** ### Response #### Success Response (200) - **status** (string) - The health status (e.g., "ok") - **timestamp** (string) - The current server time #### Response Example { "status": "ok", "timestamp": "2025-04-26T12:00:00.000Z" } ``` -------------------------------- ### GET mcp://my-app/users/{userId}/profile Source: https://context7.com/bamada/nestjs-mcp/llms.txt Retrieves user profile information based on a dynamic userId extracted from the URI template. ```APIDOC ## GET mcp://my-app/users/{userId}/profile ### Description Provides user profile data based on the userId provided in the URI path. ### Method GET ### Endpoint mcp://my-app/users/{userId}/profile ### Parameters #### Path Parameters - **userId** (string) - Required - The unique identifier of the user. ### Request Example N/A (MCP Resource Request) ### Response #### Success Response (200) - **contents** (array) - Array containing the resource data. #### Response Example { "contents": [ { "type": "application/json", "text": "{\"id\":\"123\",\"name\":\"User 123\",\"email\":\"123@example.com\"}", "uri": "mcp://my-app/users/123/profile" } ] } ``` -------------------------------- ### GET mcp://my-app/users/{userId}/posts/{postId} Source: https://context7.com/bamada/nestjs-mcp/llms.txt Retrieves a specific post authored by a user, utilizing two dynamic URI parameters. ```APIDOC ## GET mcp://my-app/users/{userId}/posts/{postId} ### Description Retrieves a specific post by a user using both userId and postId from the URI. ### Method GET ### Endpoint mcp://my-app/users/{userId}/posts/{postId} ### Parameters #### Path Parameters - **userId** (string) - Required - The unique identifier of the user. - **postId** (string) - Required - The unique identifier of the post. ### Request Example N/A (MCP Resource Request) ### Response #### Success Response (200) - **contents** (array) - Array containing the resource data. #### Response Example { "contents": [ { "type": "application/json", "text": "{\"postId\":\"456\",\"authorId\":\"123\",\"title\":\"Post 456 by User 123\"}", "uri": "mcp://my-app/users/123/posts/456" } ] } ``` -------------------------------- ### Dynamic Registration with McpService Source: https://context7.com/bamada/nestjs-mcp/llms.txt Shows how to inject McpService to dynamically register tools and resources at runtime. This is useful for advanced scenarios where static decorators are insufficient. ```typescript import { Injectable, OnModuleInit } from '@nestjs/common'; import { McpService } from '@bamada/nestjs-mcp'; import { z } from 'zod'; @Injectable() export class DynamicToolService implements OnModuleInit { constructor(private readonly mcpService: McpService) {} onModuleInit() { // Access the underlying McpServer instance const server = this.mcpService.getServer(); // Dynamically register a tool at runtime this.mcpService.registerTool( { name: 'dynamic-tool', description: 'A dynamically registered tool', paramsSchema: { input: z.string().describe('Input string'), }, }, (params, extra) => ({ content: [{ type: 'text', text: `Processed: ${params.input}` }], }), ); // Dynamically register a resource this.mcpService.registerResource( { name: 'dynamic-resource', uri: 'mcp://app/dynamic', description: 'A dynamically registered resource', }, (uri, extra) => ({ contents: [ { type: 'text/plain', text: 'Dynamic resource content', uri, }, ], }), ); } } ``` -------------------------------- ### Define an MCP Prompt Provider Source: https://github.com/bamada/nestjs-mcp/blob/main/README.md Demonstrates how to use the @McpPrompt decorator to expose a method as an MCP prompt. It accepts parameters and returns a GetPromptResult containing the assistant's message. ```typescript import { McpPrompt, RequestHandlerExtra } from '@bamada/nestjs-mcp'; import { Injectable, Logger } from '@nestjs/common'; import { Request, Notification, GetPromptResult } from '@modelcontextprotocol/sdk/types'; @Injectable() export class MyMcpProvider { private readonly logger = new Logger(AppProvider.name); @McpPrompt({ name: 'greetingPrompt', description: 'Generates a personalized greeting message', arguments: [ { name: 'userName', description: 'The name of the person to greet', required: true }, { name: 'style', description: 'Greeting style (e.g., formal, casual)', required: false }, ], }) generateGreeting( params: { userName: string; style?: string }, extra: RequestHandlerExtra, ): GetPromptResult { this.logger.log(`Prompt 'greetingPrompt' called with params: ${JSON.stringify(params)}`); const clientId = extra.authInfo?.clientId ?? extra.sessionId ?? 'Unknown Client'; const greeting = params.style === 'formal' ? 'Greetings' : 'Hello'; return { messages: [ { role: 'assistant', content: { type: 'text', text: `${greeting}, ${params.userName}! Welcome. How can I assist you today? clientId: ${clientId}` }, }, ], }; } } ``` -------------------------------- ### Register McpModule Synchronously Source: https://context7.com/bamada/nestjs-mcp/llms.txt The forRoot method is used to register the McpModule when configuration options are known at compile time. It requires server metadata and allows selection of the transport layer. ```typescript import { Module } from '@nestjs/common'; import { McpModule, TransportType } from '@bamada/nestjs-mcp'; import { MyMcpProvider } from './my-mcp.provider'; @Module({ imports: [ McpModule.forRoot({ serverInfo: { name: 'my-awesome-mcp-app', version: '1.0.0', }, serverOptions: { // Optional MCP SDK server options }, transport: TransportType.SSE, // Use HTTP/SSE controller }), ], providers: [MyMcpProvider], }) export class AppModule {} ``` -------------------------------- ### Define Dynamic MCP Resources with @McpResource Source: https://context7.com/bamada/nestjs-mcp/llms.txt Demonstrates how to use the @McpResource decorator to define resources with URI templates. The handler receives extracted variables and request context, returning a ReadResourceResult containing the resource content. ```typescript import { McpResource, RequestHandlerExtra, ReadResourceResult, Variables, } from '@bamada/nestjs-mcp'; import { Injectable, Logger } from '@nestjs/common'; import { Request, Notification } from '@modelcontextprotocol/sdk/types'; @Injectable() export class UserResourceProvider { private readonly logger = new Logger(UserResourceProvider.name); @McpResource({ name: 'user-profile', uriTemplate: 'mcp://my-app/users/{userId}/profile', description: 'Provides user profile data based on userId.', }) getUserProfile( uri: string, variables: Variables, extra: RequestHandlerExtra, ): ReadResourceResult { const clientId = extra.authInfo?.clientId ?? extra.sessionId ?? 'Unknown Client'; const userId = Array.isArray(variables.userId) ? variables.userId.join(', ') : String(variables.userId); this.logger.log(`Resource 'user-profile' requested for userId: ${userId}`); const userProfile = { id: userId, name: `User ${userId}`, email: `${userId}@example.com`, createdAt: new Date().toISOString(), clientId, }; return { contents: [ { type: 'application/json', text: JSON.stringify(userProfile), uri: uri.toString(), }, ], }; } @McpResource({ name: 'user-posts', uriTemplate: 'mcp://my-app/users/{userId}/posts/{postId}', description: 'Retrieves a specific post by a user.', }) getUserPost( uri: string, variables: Variables, extra: RequestHandlerExtra, ): ReadResourceResult { const userId = String(variables.userId); const postId = String(variables.postId); return { contents: [ { type: 'application/json', text: JSON.stringify({ postId, authorId: userId, title: `Post ${postId} by User ${userId}`, content: 'Sample post content...', }), uri: uri.toString(), }, ], }; } } ``` -------------------------------- ### Register McpModule Asynchronously Source: https://context7.com/bamada/nestjs-mcp/llms.txt The forRootAsync method allows for dynamic module configuration, which is essential when settings depend on external services like ConfigService. It supports standard NestJS factory and injection patterns. ```typescript import { Module } from '@nestjs/common'; import { McpModule, TransportType } from '@bamada/nestjs-mcp'; import { ConfigModule, ConfigService } from '@nestjs/config'; @Module({ imports: [ ConfigModule.forRoot(), McpModule.forRootAsync({ imports: [ConfigModule], useFactory: (configService: ConfigService) => ({ serverInfo: { name: configService.get('MCP_SERVER_NAME', 'default-mcp-server'), version: configService.get('APP_VERSION', '0.0.1'), }, transport: configService.get('MCP_TRANSPORT', TransportType.SSE), serverOptions: { maxConnections: configService.get('MCP_MAX_CONNECTIONS'), }, }), inject: [ConfigService], }), ], }) export class AppModule {} ``` -------------------------------- ### @McpTool Decorator Source: https://context7.com/bamada/nestjs-mcp/llms.txt Defines a method as an MCP Tool that can be invoked by clients. Tools require a name, description, and a Zod-based parameter schema for validation. ```APIDOC ## @McpTool ### Description Marks a class method as an MCP Tool handler, allowing it to be called by external MCP clients with validated parameters. ### Parameters - **name** (string) - Required - The unique name of the tool. - **description** (string) - Optional - A human-readable description of what the tool does. - **paramsSchema** (Object) - Optional - A Zod raw shape object defining the input parameters. ### Request Example { "name": "add", "params": { "a": 5, "b": 10 } } ### Response #### Success Response (200) - **content** (Array) - An array of content objects containing the tool execution result. #### Response Example { "content": [{ "type": "text", "text": "The sum is 15." }] } ``` -------------------------------- ### Define MCP Tool in NestJS Source: https://github.com/bamada/nestjs-mcp/blob/main/README.md Demonstrates how to define an MCP tool using the `@McpTool` decorator in a NestJS service. This tool, 'add', takes two numbers and an optional message, returning their sum. It includes logging and handles client identification from request context. ```typescript import { McpTool, RequestHandlerExtra, CallToolResult, } from '@bamada/nestjs-mcp'; import { Injectable, Logger } from '@nestjs/common'; import { z } from 'zod'; import { Request, Notification } from '@modelcontextprotocol/sdk/types'; @Injectable() export class MyMcpProvider { private readonly logger = new Logger(MyMcpProvider.name); @McpTool({ name: 'add', description: 'Adds two numbers together.', paramsSchema: { a: z.number().describe('The first number to add'), b: z.number().describe('The second number to add'), optionalMessage: z.string().nullable().optional().describe('An optional message'), }, }) addTool( params: { a: number; b: number; optionalMessage?: string }, extra: RequestHandlerExtra, ): CallToolResult { const clientId = extra.authInfo?.clientId ?? extra.sessionId ?? 'Unknown Client'; this.logger.log( `Tool 'add' called by client ${clientId} with params: ${JSON.stringify(params)}`, ); const sum = params.a + params.b; let resultText = `The sum is ${sum}.`; if (params.optionalMessage) { resultText += ` Your message: ${params.optionalMessage}`; } return { content: [{ type: 'text', text: resultText }], }; } } ``` -------------------------------- ### Interact with HTTP/SSE Transport Endpoints (Bash) Source: https://context7.com/bamada/nestjs-mcp/llms.txt When using `TransportType.SSE`, the NestJS MCP module automatically registers HTTP endpoints for MCP communication via Server-Sent Events. The `McpHttpController` provides three key endpoints: `/api/mcp/sse` for establishing SSE connections, `/api/mcp/messages` for sending messages to an active session, and `/api/mcp/health` for health checks. These endpoints allow clients to interact with the MCP server. ```bash # Establish an SSE connection to the MCP server curl -N -H "Accept: text/event-stream" \ http://localhost:3000/api/mcp/sse # Example response (SSE stream): # event: open # data: {"sessionId":"abc123"} # # event: message # data: {"jsonrpc":"2.0","method":"...","params":{...}} # Send a message to an existing SSE session curl -X POST \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"tools/list","id":1}' \ "http://localhost:3000/api/mcp/messages?sessionId=abc123" # Example response: # {"jsonrpc":"2.0","id":1,"result":{"tools":[{"name":"add","description":"Adds two numbers together."}]}} # Health check endpoint curl http://localhost:3000/api/mcp/health # Example response: # {"status":"ok","timestamp":"2025-04-26T12:00:00.000Z"} ``` -------------------------------- ### Define Static MCP Resource in NestJS Source: https://github.com/bamada/nestjs-mcp/blob/main/README.md Shows how to define a static MCP resource using the `@McpResource` decorator in a NestJS service. The 'static-config' resource provides fixed configuration settings from a predefined URI. It logs the request and returns JSON content. ```typescript import { RequestHandlerExtra, McpResource, ReadResourceResult, Variables, } from '@bamada/nestjs-mcp'; import { Injectable, Logger } from '@nestjs/common'; import { Request, Notification } from '@modelcontextprotocol/sdk/types'; @Injectable() export class MyMcpProvider { private readonly logger = new Logger(MyMcpProvider.name); @McpResource({ name: 'static-config', uri: 'mcp://my-app/config/settings.json', description: 'Provides static configuration settings.', }) getStaticConfig( uri: string, extra: RequestHandlerExtra, ): ReadResourceResult { this.logger.log(`Resource 'static-config' requested for URI: ${uri}`); const clientId = extra.authInfo?.clientId ?? extra.sessionId ?? 'Unknown Client'; return { contents: [ { type: 'application/json', text: JSON.stringify({ theme: 'dark', featureFlags: ['newUI'], clientId, }), uri: uri.toString(), }, ], }; } // Template Resource @McpResource({ name: 'user-profile', uriTemplate: 'mcp://my-app/users/{userId}/profile', description: 'Provides user profile data based on userId.', }) getUserProfile( uri: string, variables: Variables, extra: RequestHandlerExtra, ): ReadResourceResult { const clientId = extra.authInfo?.clientId ?? extra.sessionId ?? 'Unknown Client'; const userId = Array.isArray(variables.userId) ? variables.userId.join(', ') : String(variables.userId); this.logger.log(`Resource 'user-profile' requested for userId: ${userId}`); // Fetch user data based on userId... const userProfile = { id: userId, name: `User ${userId}`, email: `${userId}@example.com`, clientId, }; return { contents: [ { type: 'application/json', text: JSON.stringify(userProfile), uri: uri.toString(), }, ], }; } } ``` -------------------------------- ### Define MCP Prompts with @McpPrompt Decorator (TypeScript) Source: https://context7.com/bamada/nestjs-mcp/llms.txt The `@McpPrompt` decorator in TypeScript is used to define methods as MCP Prompt handlers. These handlers generate predefined message templates for MCP clients. The decorator accepts a prompt definition including name, description, and an array of arguments. The handler function returns a `GetPromptResult` object containing the messages. ```typescript import { McpPrompt, RequestHandlerExtra, } from '@bamada/nestjs-mcp'; import { Injectable, Logger } from '@nestjs/common'; import { Request, Notification, GetPromptResult, } from '@modelcontextprotocol/sdk/types'; @Injectable() export class PromptProvider { private readonly logger = new Logger(PromptProvider.name); @McpPrompt({ name: 'greetingPrompt', description: 'Generates a personalized greeting message', arguments: [ { name: 'userName', description: 'The name of the person to greet', required: true, }, { name: 'style', description: 'Greeting style (e.g., formal, casual)', required: false, }, ], }) generateGreeting( params: { userName: string; style?: string }, extra: RequestHandlerExtra, ): GetPromptResult { this.logger.log(`Prompt 'greetingPrompt' called with params: ${JSON.stringify(params)}`); const clientId = extra.authInfo?.clientId ?? extra.sessionId ?? 'Unknown Client'; const greeting = params.style === 'formal' ? 'Greetings' : 'Hello'; return { messages: [ { role: 'assistant', content: { type: 'text', text: `${greeting}, ${params.userName}! Welcome. How can I assist you today? (Client: ${clientId})`, }, }, ], }; } @McpPrompt({ name: 'codeReviewPrompt', description: 'Generates a code review prompt for a specific language', arguments: [ { name: 'language', description: 'The programming language of the code', required: true, }, { name: 'focus', description: 'Specific areas to focus on (security, performance, style)', required: false, }, ], }) generateCodeReviewPrompt( params: { language: string; focus?: string }, extra: RequestHandlerExtra, ): GetPromptResult { const focusArea = params.focus || 'general best practices'; return { messages: [ { role: 'assistant', content: { type: 'text', text: `Please review the following ${params.language} code with focus on ${focusArea}. Provide constructive feedback and suggestions for improvement.`, }, }, ], }; } } ``` -------------------------------- ### @McpResource Decorator Source: https://context7.com/bamada/nestjs-mcp/llms.txt Defines a method as an MCP Resource handler for fixed URIs. Resources allow clients to read specific data points exposed by the application. ```APIDOC ## @McpResource ### Description Marks a class method as a handler for a specific fixed URI resource, returning data to the MCP client. ### Parameters - **name** (string) - Required - The unique name of the resource. - **uri** (string) - Required - The static URI identifier for the resource. - **description** (string) - Optional - A description of the resource content. ### Request Example { "uri": "mcp://my-app/config/settings.json" } ### Response #### Success Response (200) - **contents** (Array) - An array containing the resource data, including type, text, and URI. #### Response Example { "contents": [{ "type": "application/json", "text": "{\"theme\": \"dark\"}", "uri": "mcp://my-app/config/settings.json" }] } ``` -------------------------------- ### Define Template MCP Resource in NestJS Source: https://github.com/bamada/nestjs-mcp/blob/main/README.md Illustrates defining a template MCP resource using `@McpResource` with `uriTemplate`. The 'user-profile' resource dynamically generates URIs based on a `userId` variable. It logs the request, extracts the `userId`, and returns mock user profile data. ```typescript import { RequestHandlerExtra, McpResource, ReadResourceResult, Variables, } from '@bamada/nestjs-mcp'; import { Injectable, Logger } from '@nestjs/common'; import { Request, Notification } from '@modelcontextprotocol/sdk/types'; @Injectable() export class MyMcpProvider { private readonly logger = new Logger(MyMcpProvider.name); @McpResource({ name: 'user-profile', uriTemplate: 'mcp://my-app/users/{userId}/profile', description: 'Provides user profile data based on userId.', }) getUserProfile( uri: string, variables: Variables, extra: RequestHandlerExtra, ): ReadResourceResult { const clientId = extra.authInfo?.clientId ?? extra.sessionId ?? 'Unknown Client'; const userId = Array.isArray(variables.userId) ? variables.userId.join(', ') : String(variables.userId); this.logger.log(`Resource 'user-profile' requested for userId: ${userId}`); // Fetch user data based on userId... const userProfile = { id: userId, name: `User ${userId}`, email: `${userId}@example.com`, clientId, }; return { contents: [ { type: 'application/json', text: JSON.stringify(userProfile), uri: uri.toString(), }, ], }; } } ``` -------------------------------- ### Define MCP Resources with @McpResource Source: https://context7.com/bamada/nestjs-mcp/llms.txt The @McpResource decorator exposes a method as a fixed URI resource provider. It maps a specific URI to a handler that returns a ReadResourceResult containing the resource content. ```typescript @McpResource({ name: 'static-config', uri: 'mcp://my-app/config/settings.json', description: 'Provides static configuration settings.', }) getStaticConfig( uri: string, extra: RequestHandlerExtra, ): ReadResourceResult { return { contents: [ { type: 'application/json', text: JSON.stringify({ theme: 'dark', maxItems: 100 }), uri: uri.toString(), }, ], }; } ``` -------------------------------- ### Define MCP Tools with @McpTool Source: https://context7.com/bamada/nestjs-mcp/llms.txt The @McpTool decorator registers a class method as an MCP tool. It requires a name, optional description, and a Zod-based paramsSchema for input validation, returning a CallToolResult. ```typescript @McpTool({ name: 'add', description: 'Adds two numbers together.', paramsSchema: { a: z.number().describe('The first number to add'), b: z.number().describe('The second number to add'), optionalMessage: z.string().nullable().optional().describe('An optional message'), }, }) addTool( params: { a: number; b: number; optionalMessage?: string }, extra: RequestHandlerExtra, ): CallToolResult { const sum = params.a + params.b; return { content: [{ type: 'text', text: `The sum is ${sum}.` }], }; } ``` -------------------------------- ### Configure Transport Types in NestJS MCP Source: https://context7.com/bamada/nestjs-mcp/llms.txt Demonstrates how to configure the MCP server transport layer using the TransportType enum. Options include STDIO for CLI tools, SSE for web applications, and NONE for custom implementations. ```typescript import { Module } from '@nestjs/common'; import { McpModule, TransportType } from '@bamada/nestjs-mcp'; // STDIO Transport - for CLI tools and command-line MCP servers @Module({ imports: [ McpModule.forRoot({ serverInfo: { name: 'cli-mcp-server', version: '1.0.0' }, transport: TransportType.STDIO, }), ], }) export class StdioAppModule {} // SSE Transport - for web applications with HTTP/SSE @Module({ imports: [ McpModule.forRoot({ serverInfo: { name: 'web-mcp-server', version: '1.0.0' }, transport: TransportType.SSE, }), ], }) export class SseAppModule {} // NONE Transport - for custom transport implementations @Module({ imports: [ McpModule.forRoot({ serverInfo: { name: 'custom-mcp-server', version: '1.0.0' }, transport: TransportType.NONE, }), ], }) export class CustomTransportAppModule {} ``` -------------------------------- ### POST /api/mcp/messages Source: https://context7.com/bamada/nestjs-mcp/llms.txt Sends an MCP JSON-RPC message to an active SSE session. ```APIDOC ## POST /api/mcp/messages ### Description Allows clients to send JSON-RPC messages to the server for an existing session established via SSE. ### Method POST ### Endpoint /api/mcp/messages ### Parameters #### Query Parameters - **sessionId** (string) - Required - The unique identifier for the active SSE session. #### Request Body - **jsonrpc** (string) - Required - The JSON-RPC version (e.g., "2.0") - **method** (string) - Required - The MCP method to invoke - **id** (number) - Required - Request identifier ### Request Example { "jsonrpc": "2.0", "method": "tools/list", "id": 1 } ### Response #### Success Response (200) - **result** (object) - The response data from the invoked MCP method #### Response Example { "jsonrpc": "2.0", "id": 1, "result": {"tools": [{"name": "add", "description": "Adds two numbers together."}]} } ``` -------------------------------- ### Configure StderrLogger for STDIO Transport (TypeScript) Source: https://context7.com/bamada/nestjs-mcp/llms.txt The `StderrLogger` class is a custom NestJS logger designed to redirect all log output to stderr. This is crucial when using the STDIO transport, as stdout must be reserved for MCP protocol communication. All standard logging methods (log, error, warn, debug, verbose) are overridden to write to stderr, preventing interference with the MCP protocol. ```typescript // src/main.ts import 'reflect-metadata'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { StderrLogger } from '@bamada/nestjs-mcp'; async function bootstrap() { // Use StderrLogger when using STDIO transport to prevent // log messages from interfering with MCP protocol on stdout const app = await NestFactory.create(AppModule, { logger: new StderrLogger(), }); // For STDIO transport, you might not need HTTP listener // await app.init(); // For SSE transport, start the HTTP server await app.listen(3000); console.error('NestJS MCP application started on port 3000'); } bootstrap(); ``` -------------------------------- ### Configure StderrLogger for STDIO Transport Source: https://github.com/bamada/nestjs-mcp/blob/main/README.md When using STDIO transport, standard console logs can corrupt the MCP communication stream. This snippet shows how to use StderrLogger to redirect logs to stderr. ```typescript import 'reflect-metadata'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { StderrLogger } from '@bamada/nestjs-mcp'; async function bootstrap() { const app = await NestFactory.create(AppModule, { logger: new StderrLogger(), }); await app.listen(3000); console.error('NestJS application started...'); } bootstrap(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.