{"_id":"@ascentic/mcp-nest","_rev":"2-321812817fe924697c5a89c78edb18bb","name":"@ascentic/mcp-nest","dist-tags":{"latest":"1.6.4"},"versions":{"1.6.3":{"name":"@ascentic/mcp-nest","version":"1.6.3","license":"MIT","_id":"@ascentic/mcp-nest@1.6.3","maintainers":[{"name":"ascentic","email":"contato@ascentic.com.br"}],"dist":{"shasum":"54c7abac86433f872338ad359c613ecdeb08442b","tarball":"https://registry.npmjs.org/@ascentic/mcp-nest/-/mcp-nest-1.6.3.tgz","fileCount":123,"integrity":"sha512-RkDyF9838FEFUk9U6g1dcrzmn3heBdQ2sM+0gIHCqGfvOaVltz8/ncomet0Q8wfmiLVQ6PSsMmHcW3YZbi/VaQ==","signatures":[{"sig":"MEQCIDbqSVCvMdlyu5oRslUllNmgNHdIHrM6AhkI4rnceuMRAiBzqo+PWu+i3aW/9gPUc8siQOkSMXSWrDDWYLwR6sxDyg==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":315861},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"381b650071199d7e07b064ed9dd9e2ad277b6cf6","scripts":{"lint":"eslint \"{src,apps,libs,tests}/**/*.ts\" --fix","test":"npx --node-options=--experimental-vm-modules jest","build":"tsc -p tsconfig.build.json --sourceMap --inlineSources","format":"prettier --write \"src/**/*.ts\" \"tests/**/*.ts\"","prepare":"npm run build","test:watch":"npx --node-options=--experimental-vm-modules jest --watch","start:playground":"ts-node-dev --respawn playground/servers/server-stateful.ts"},"_npmUser":{"name":"ascentic","email":"contato@ascentic.com.br"},"_npmVersion":"10.9.2","description":"NestJS module for creating Model Context Protocol (MCP) servers","directories":{},"_nodeVersion":"22.16.0","dependencies":{"path-to-regexp":"^8.2.0"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^29.7.0","eslint":"^9.18.0","express":"^4.21.2","ts-jest":"^29.2.5","supertest":"^7.1.0","@eslint/js":"^9.18.0","typescript":"^5.7.3","@types/jest":"^29.5.14","@types/node":"^22.10.10","ts-node-dev":"^2.0.0","@nestjs/core":"^11.1.1","@nestjs/common":"^11.1.1","@types/express":"^5.0.2","@nestjs/testing":"^11.1.1","@eslint/eslintrc":"^3.2.0","@types/supertest":"^6.0.3","typescript-eslint":"^8.20.0","eslint-config-prettier":"^10.0.1","eslint-plugin-prettier":"^5.2.3","@nestjs/platform-express":"^11.1.1","@modelcontextprotocol/sdk":"^1.13.0"},"peerDependencies":{"zod":"^3.0.0","express":">=4.0.0","@nestjs/core":">=9.0.0","@nestjs/common":">=9.0.0","reflect-metadata":">=0.1.14","zod-to-json-schema":">=3.23.0","@modelcontextprotocol/sdk":">=1.10.0"},"_npmOperationalInternal":{"tmp":"tmp/mcp-nest_1.6.3_1752962203535_0.28273921441592154","host":"s3://npm-registry-packages-npm-production"}},"1.6.4":{"name":"@ascentic/mcp-nest","version":"1.6.4","description":"NestJS module for creating Model Context Protocol (MCP) servers","main":"dist/index.js","license":"MIT","types":"dist/index.d.ts","publishConfig":{"access":"public"},"scripts":{"build":"tsc -p tsconfig.build.json --sourceMap --inlineSources","prepare":"npm run build","start:playground":"ts-node-dev --respawn playground/servers/server-stateful.ts","test":"npx --node-options=--experimental-vm-modules jest","test:watch":"npx --node-options=--experimental-vm-modules jest --watch","lint":"eslint \"{src,apps,libs,tests}/**/*.ts\" --fix","format":"prettier --write \"src/**/*.ts\" \"tests/**/*.ts\""},"peerDependencies":{"@modelcontextprotocol/sdk":">=1.10.0","@nestjs/common":">=9.0.0","@nestjs/core":">=9.0.0","express":">=4.0.0","reflect-metadata":">=0.1.14","zod":"^3.0.0","zod-to-json-schema":">=3.23.0"},"devDependencies":{"@eslint/eslintrc":"^3.2.0","@eslint/js":"^9.18.0","@modelcontextprotocol/sdk":"^1.13.0","@nestjs/common":"^11.1.1","@nestjs/core":"^11.1.1","@nestjs/platform-express":"^11.1.1","@nestjs/testing":"^11.1.1","@types/express":"^5.0.2","@types/jest":"^29.5.14","@types/node":"^22.10.10","@types/supertest":"^6.0.3","eslint":"^9.18.0","eslint-config-prettier":"^10.0.1","eslint-plugin-prettier":"^5.2.3","express":"^4.21.2","jest":"^29.7.0","supertest":"^7.1.0","ts-jest":"^29.2.5","ts-node-dev":"^2.0.0","typescript":"^5.7.3","typescript-eslint":"^8.20.0"},"dependencies":{"path-to-regexp":"^8.2.0"},"_id":"@ascentic/mcp-nest@1.6.4","gitHead":"381b650071199d7e07b064ed9dd9e2ad277b6cf6","_nodeVersion":"22.16.0","_npmVersion":"10.9.2","dist":{"integrity":"sha512-+twgIZ470zCoO2iu4jFsBxKhXSfjOCc/YCftzGbhnYxhUbb3SrGB8nfOfpMGJs5bbx5l4sstAOKuFoiTE/bcCA==","shasum":"7ea56a7d9cb9c286b0c54e9d5b127154fa0d6069","tarball":"https://registry.npmjs.org/@ascentic/mcp-nest/-/mcp-nest-1.6.4.tgz","fileCount":123,"unpackedSize":316653,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCICUjR0ZadoG8l2AppOcPcO8384rfTD9DgELu8NfbXW1TAiEA4Z8ubNyP9BN74+PlolvmGP7DBQYuinTXQCpecAMgsK0="}]},"_npmUser":{"name":"ascentic","email":"contato@ascentic.com.br"},"directories":{},"maintainers":[{"name":"ascentic","email":"contato@ascentic.com.br"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/mcp-nest_1.6.4_1752962385656_0.15036733229206778"},"_hasShrinkwrap":false}},"time":{"created":"2025-07-19T21:56:43.441Z","modified":"2025-07-19T21:59:46.066Z","1.6.3":"2025-07-19T21:56:43.813Z","1.6.4":"2025-07-19T21:59:45.883Z"},"license":"MIT","description":"NestJS module for creating Model Context Protocol (MCP) servers","maintainers":[{"name":"ascentic","email":"contato@ascentic.com.br"}],"readme":"# NestJS MCP Server Module\n\n<div align=\"center\">\n  <img src=\"https://raw.githubusercontent.com/rekog-labs/MCP-Nest/main/image.png\" height=\"200\">\n\n[![CI][ci-image]][ci-url]\n[![Code Coverage][code-coverage-image]][code-coverage-url]\n[![NPM Version][npm-version-image]][npm-url]\n[![NPM Downloads][npm-downloads-image]][npm-url]\n[![NPM License][npm-license-image]][npm-url]\n\n</div>\n\nA NestJS module to effortlessly expose tools, resources, and prompts for AI, from your NestJS applications using the **Model Context Protocol (MCP)**.\n\nWith `@rekog/mcp-nest` you define tools, resources, and prompts in a way that's familiar in NestJS and leverage the full power of dependency injection to utilize your existing codebase in building complex enterprise ready MCP servers.\n\n## Features\n\n- 🚀 Support for all Transport Types:\n  - Streamable HTTP\n  - HTTP+SSE\n  - STDIO\n- 🔍 Automatic `tool`, `resource`, and `prompt` discovery and registration\n- 💯 Zod-based tool call validation\n- 📊 Progress notifications\n- 🔒 Guard-based authentication\n- 🌐 Access to HTTP Request information within MCP Resources (Tools, Resources, Prompts)\n\n## Installation\n\n```bash\nnpm install @rekog/mcp-nest @modelcontextprotocol/sdk zod\n```\n\n## Quick Start\n\n### 1. Import Module\n\n```typescript\n// app.module.ts\nimport { Module } from '@nestjs/common';\nimport { McpModule } from '@rekog/mcp-nest';\nimport { GreetingTool } from './greeting.tool';\n\n@Module({\n  imports: [\n    McpModule.forRoot({\n      name: 'my-mcp-server',\n      version: '1.0.0',\n    }),\n  ],\n  providers: [GreetingTool],\n})\nexport class AppModule {}\n```\n\n### 2. Define Tools and Resource\n\n```typescript\n// greeting.tool.ts\nimport type { Request } from 'express';\nimport { Injectable } from '@nestjs/common';\nimport { Tool, Resource, Context } from '@rekog/mcp-nest';\nimport { z } from 'zod';\nimport { Progress } from '@modelcontextprotocol/sdk/types';\n\n@Injectable()\nexport class GreetingTool {\n  constructor() {}\n\n  @Tool({\n    name: 'hello-world',\n    description:\n      'Returns a greeting and simulates a long operation with progress updates',\n    parameters: z.object({\n      name: z.string().default('World'),\n    }),\n  })\n  async sayHello({ name }, context: Context, request: Request) {\n    const userAgent = request.get('user-agent') || 'Unknown';\n    const greeting = `Hello, ${name}! Your user agent is: ${userAgent}`;\n    const totalSteps = 5;\n    for (let i = 0; i < totalSteps; i++) {\n      await new Promise((resolve) => setTimeout(resolve, 100));\n\n      // Send a progress update.\n      await context.reportProgress({\n        progress: (i + 1) * 20,\n        total: 100,\n      } as Progress);\n    }\n\n    return {\n      content: [{ type: 'text', text: greeting }],\n    };\n  }\n\n  @Resource({\n    uri: 'mcp://hello-world/{userName}',\n    name: 'Hello World',\n    description: 'A simple greeting resource',\n    mimeType: 'text/plain',\n  })\n  // Different from the SDK, we put the parameters and URI in the same object.\n  async getCurrentSchema({ uri, userName }) {\n    return {\n      content: [\n        {\n          uri,\n          text: `User is ${userName}`,\n          mimeType: 'text/plain',\n        },\n      ],\n    };\n  }\n}\n```\n\nYou are done!\n\n> [!TIP]\n> The above example shows how HTTP `Request` headers are accessed within MCP Tools. This is useful for identifying users, adding client-specific logic, and many other use cases. For more examples, see the [Authentication Tests](./tests/mcp-tool-auth.e2e.spec.ts).\n\n## Quick Start for STDIO\n\nThe main difference is that you need to provide the `transport` option when importing the module.\n\n```typescript\nMcpModule.forRoot({\n  name: 'playground-stdio-server',\n  version: '0.0.1',\n  transport: McpTransportType.STDIO,\n});\n```\n\nThe rest is the same, you can define tools, resources, and prompts as usual. An example of a standalone NestJS application using the STDIO transport is the following:\n\n```typescript\nasync function bootstrap() {\n  const app = await NestFactory.createApplicationContext(AppModule, {\n    logger: false,\n  });\n  return app.close();\n}\n\nvoid bootstrap();\n```\n\nNext, you can use the MCP server with an MCP Stdio Client ([see example](playground/clients/stdio-client.ts)), or after building your project you can use it with the following MCP Client configuration:\n\n```json\n{\n  \"mcpServers\": {\n    \"greeting\": {\n      \"command\": \"node\",\n      \"args\": [\n        \"<path to dist js file>\",\n      ]\n    }\n  }\n}\n```\n\n## API Endpoints\n\nHTTP+SSE transport exposes two endpoints:\n\n- `GET /sse`: SSE connection endpoint (Protected by guards if configured)\n- `POST /messages`: Tool execution endpoint (Protected by guards if configured)\n\nStreamable HTTP transport exposes the following endpoints:\n\n- `POST /mcp`: Main endpoint for all MCP operations (tool execution, resource access, etc.). In stateful mode, this creates and maintains sessions.\n- `GET /mcp`: Establishes Server-Sent Events (SSE) streams for real-time updates and progress notifications. **Only available in stateful mode.**\n- `DELETE /mcp`: Terminates MCP sessions. **Only available in stateful mode.**\n\n### Tips\n\nIt's possible to use the module with global prefix, but the recommended way is to exclude those endpoints with:\n\n```typescript\napp.setGlobalPrefix('/api', { exclude: ['sse', 'messages', 'mcp'] });\n```\n\n## Authentication\n\nYou can secure your MCP endpoints using standard NestJS Guards.\n\n### 1. Create a Guard\n\nImplement the `CanActivate` interface. The guard should handle request validation (e.g., checking JWTs, API keys) and optionally attach user information to the request object.\n\nNothing special, check the NestJS documentation for more details.\n\n### 2. Apply the Guard\n\nPass your guard(s) to the `McpModule.forRoot` configuration. The guard(s) will be applied to both the `/sse` and `/messages` endpoints.\n\n```typescript\n// app.module.ts\nimport { Module } from '@nestjs/common';\nimport { McpModule } from '@rekog/mcp-nest';\nimport { GreetingTool } from './greeting.tool';\nimport { AuthGuard } from './auth.guard';\n\n@Module({\n  imports: [\n    McpModule.forRoot({\n      name: 'my-mcp-server',\n      version: '1.0.0',\n      guards: [AuthGuard], // Apply the guard here\n    }),\n  ],\n  providers: [GreetingTool, AuthGuard], // Ensure the Guard is also provided\n})\nexport class AppModule {}\n```\n\nThat's it! The rest is the same as NestJS Guards.\n\n## Playground\n\nThe `playground` directory contains examples to quickly test MCP and `@rekog/mcp-nest` features.\nRefer to the [`playground/README.md`](playground/README.md) for more details.\n\n## Configuration\n\nThe `McpModule.forRoot()` method accepts an `McpOptions` object to configure the server. Here are the available options:\n\n| Option             | Description                                                                                                                               | Default                                                              |\n| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |\n| `name`             | **Required.** The name of your MCP server.                                                                                                | -                                                                    |\n| `version`          | **Required.** The version of your MCP server.                                                                                             | -                                                                    |\n| `capabilities`     | Optional MCP server capabilities to advertise. See [@modelcontextprotocol/sdk](https://www.npmjs.com/package/@modelcontextprotocol/sdk). | `undefined`                                                          |\n| `instructions`     | Optional instructions for the client on how to interact with the server.                                                                    | `undefined`                                                          |\n| `transport`        | Specifies the transport type(s) to enable.                                                                                                | `[McpTransportType.SSE, McpTransportType.STREAMABLE_HTTP, McpTransportType.STDIO]` |\n| `sseEndpoint`      | The endpoint path for the SSE connection (used with `SSE` transport).                                                                     | `'sse'`                                                              |\n| `messagesEndpoint` | The endpoint path for sending messages (used with `SSE` transport).                                                                       | `'messages'`                                                         |\n| `mcpEndpoint`      | The base endpoint path for MCP operations (used with `STREAMABLE_HTTP` transport).                                                        | `'mcp'`                                                              |\n| `apiPrefix` | A prefix for all MCP endpoints. Useful if integrating into an existing application. | `''` |\n| `guards`           | An array of NestJS Guards to apply to the MCP endpoints for authentication/authorization.                                                   | `[]`                                                                 |\n| `decorators`       | An array of NestJS Class Decorators to apply to the generated MCP controllers.                                                            | `[]`                                                                 |\n| `sse`              | Configuration specific to the `SSE` transport.                                                                                            | `{ pingEnabled: true, pingIntervalMs: 30000 }`                       |\n| `sse.pingEnabled`  | Whether to enable periodic SSE ping messages to keep the connection alive.                                                                | `true`                                                               |\n| `sse.pingIntervalMs` | The interval (in milliseconds) for sending SSE ping messages.                                                                             | `30000`                                                              |\n| `streamableHttp`   | Configuration specific to the `STREAMABLE_HTTP` transport.                                                                                | `{ enableJsonResponse: true, sessionIdGenerator: undefined, statelessMode: true }` |\n| `streamableHttp.enableJsonResponse` | If `true`, allows the `/mcp` endpoint to return JSON responses for non-streaming requests (like `listTools`).                             | `true`                                                               |\n| `streamableHttp.sessionIdGenerator` | A function to generate unique session IDs when running in stateful mode. Required if `statelessMode` is `false`.                            | `undefined`                                                          |\n| `streamableHttp.statelessMode` | If `true`, the `STREAMABLE_HTTP` transport operates statelessly (no sessions). If `false`, it operates statefully, requiring a `sessionIdGenerator`. | `true`                                                               |\n\n<!-- Badges -->\n[ci-url]: https://github.com/rekog-labs/MCP-Nest/actions/workflows/pipeline.yml\n[ci-image]: https://github.com/rekog-labs/MCP-Nest/actions/workflows/pipeline.yml/badge.svg\n[npm-url]: https://www.npmjs.com/package/@rekog/mcp-nest\n[npm-version-image]: https://img.shields.io/npm/v/@rekog/mcp-nest\n[npm-downloads-image]: https://img.shields.io/npm/dm/@rekog/mcp-nest\n[npm-license-image]: https://img.shields.io/npm/l/@rekog/mcp-nest\n[code-coverage-url]: https://codecov.io/gh/rekog-labs/mcp-nest\n[code-coverage-image]: https://codecov.io/gh/rekog-labs/mcp-nest/branch/main/graph/badge.svg\n","readmeFilename":"README.md"}