Logo de Nestjs MCP Server

Nestjs MCP Server

Comunidade
adrian-d-hidalgo

NestJS MCP Server is a modular library for building Model Context Protocol (MCP) servers using NestJS. It provides decorators, modules, and integration patterns to expose MCP resources, tools, and…

Publicado poradrian-d-hidalgo
Repositórionestjs-mcp-server
IdiomaTypeScript
Forks
4
Estrelas
40
Ferramentas disponíveis
0
Tipo de transportestdio
LicençaMIT
Links
  • Conecte ferramentas a fluxos de trabalho de IA

    Nestjs MCP Server disponibiliza recursos MCP que podem ser usados por clientes e agentes de IA compatíveis.

  • 0 ferramentas disponíveis

    Confira abaixo as ações que podem ser chamadas, incluindo nomes e descrições quando fornecidos pelo servidor.

  • Configuração pronta para copiar

    Use os exemplos de instalação para configurar este servidor no seu cliente MCP preferido.

  • Indicadores da comunidade de código aberto

    40 estrelas e 4 forks no repositório vinculado.

MCP Server NestJS Module Library

NPM Version Semantic Release Downloads CI Pipeline codecov Known Vulnerabilities MIT License PRs Welcome Contributor Covenant


Overview

NestJS MCP Server is a modular library for building Model Context Protocol (MCP) servers using NestJS. It provides decorators, modules, and integration patterns to expose MCP resources, tools, and prompts in a scalable, maintainable way. This project is a wrapper for the official @modelcontextprotocol/sdk and is always kept compatible with its types and specification.


Table of Contents


Installation

sh
npm install @nestjs-mcp/server @modelcontextprotocol/sdk zod
# or
yarn add @nestjs-mcp/server @modelcontextprotocol/sdk zod
# or
pnpm add @nestjs-mcp/server @modelcontextprotocol/sdk zod

Quickstart

Register the MCP module in your NestJS app and expose a simple tool:

ts
import { Module } from '@nestjs/common';

import { CallToolResult } from '@modelcontextprotocol/sdk/types';

import { Resolver, Tool, McpModule } from '@nestjs-mcp/server';

@Resolver()
export class HealthResolver {
  /**
   * Simple health check tool
   */
  @Tool({ name: 'server_health_check' })
  healthCheck(): CallToolResult {
    return {
      content: [
        {
          type: 'text',
          text: 'Server is operational. All systems running normally.',
        },
      ],
    };
  }
}

@Module({
  imports: [
    McpModule.forRoot({
      name: 'My MCP Server',
      version: '1.0.0',
    }),
  ],
  providers: [HealthResolver],
})
export class AppModule {}

What is MCP?

The Model Context Protocol (MCP) is an open protocol for connecting LLMs to external data, tools, and prompts. MCP servers expose resources (data), tools (actions), and prompts (conversational flows) in a standardized way, enabling seamless integration with LLM-powered clients.


Core Concepts

Server

The MCP Server is the main entry point for exposing capabilities to LLMs. It manages the registration and discovery of resources, tools, and prompts.

Resource

A Resource represents structured data or documents that can be queried or retrieved by LLMs. Resources are typically read-only and are identified by a unique URI.

Tool

A Tool is an action or function that can be invoked by LLMs. Tools may have side effects and can accept parameters to perform computations or trigger operations.

Prompt

A Prompt defines a conversational flow, template, or interaction pattern for LLMs. Prompts help guide the model's behavior in specific scenarios.

See the Capabilities section for implementation details and code examples.


Module API

McpModule.forRoot

Registers the MCP Server globally in your NestJS application.

Parameters:

  • options: McpModuleOptions — Main server configuration object:
    • name: string: The name of your MCP server.
    • version: string: The version of your MCP server.
    • instructions?: string: Optional description of the MCP server for the client.
    • capabilities?: Record<string, unknown>: Optional additional capabilities metadata.
    • providers?: Provider[]: Optional array of NestJS providers to include in the module.
    • imports?: any[]: Optional array of NestJS modules to import.
    • logging?: McpLoggingOptions: Optional logging configuration:
      • enabled?: boolean (default: true): Enable/disable logging.
      • level?: 'error' | 'warn' | 'log' | 'debug' | 'verbose' (default: 'verbose'): Set the logging level.
    • transports?: McpModuleTransportOptions: Optional transport configuration (see Transport Options).
    • protocolOptions?: Record<string, unknown>: Optional parameters passed directly to the underlying @modelcontextprotocol/sdk server instance.

Returns:

  • A dynamic NestJS module with all MCP providers registered.

Example:

ts
import { Module } from '@nestjs/common';
import { McpModule } from '@nestjs-mcp/server';

@Module({
  imports: [
    McpModule.forRoot({
      name: 'My Server',
      version: '1.0.0',
      instructions: 'A server providing utility tools and data.',
      logging: { level: 'log' },
      transport: { legacy: 'reject' }, // Modern-era clients only
      // ...other MCP options
    }),
  ],
})
export class AppModule {}

McpModule.forRootAsync

Registers the MCP Server globally using asynchronous options, useful for integrating with configuration modules like @nestjs/config.

Note:

  • The imports array should include any modules that provide dependencies required by your useFactory (e.g., ConfigModule if you inject ConfigService).
  • Use forRootAsync only once in your root module (AppModule).
  • See McpModuleAsyncOptions for all available options.

Parameters:

  • options: McpModuleAsyncOptions — Asynchronous configuration object:
    • imports?: any[]: Optional modules to import before the factory runs.
    • useFactory: (...args: any[]) => Promise<McpModuleOptions> | McpModuleOptions: A factory function that returns the McpModuleOptions.
    • inject?: any[]: Optional providers to inject into the useFactory.

Returns:

  • A dynamic NestJS module.

Example (with ConfigModule):

ts
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { McpModule } from '@nestjs-mcp/server';

@Module({
  imports: [
    ConfigModule.forRoot(), // Make sure ConfigModule is imported
    McpModule.forRootAsync({
      imports: [ConfigModule], // Import ConfigModule here too
      useFactory: (configService: ConfigService) => ({
        name: configService.get<string>('MCP_SERVER_NAME', 'Default Server'),
        version: configService.get<string>('MCP_SERVER_VERSION', '1.0.0'),
        instructions: configService.get<string>('MCP_SERVER_DESC'),
        logging: {
          level: configService.get('MCP_LOG_LEVEL', 'verbose'),
        },
        // ... other options from configService
      }),
      inject: [ConfigService], // Inject ConfigService into the factory
    }),
  ],
})
export class AppModule {}

McpModule.forFeature

Registers additional MCP resources, tools, or prompts within a feature module. Use this to organize large servers into multiple modules. Resolvers containing MCP capabilities must be included in the providers array of the feature module.

Parameters:

  • options?: McpFeatureOptions (Currently unused, reserved for future enhancements).

Returns:

  • A dynamic module.

Example:

ts
// src/status/status.resolver.ts
import { Resolver, Tool } from '@nestjs-mcp/server';
import { CallToolResult } from '@modelcontextprotocol/sdk/types';

@Resolver('status')
export class StatusResolver {
  @Tool({ name: 'health_check' })
  healthCheck(): CallToolResult {
    return { content: [{ type: 'text', text: 'OK' }] };
  }
}

// src/status/status.module.ts
import { Module } from '@nestjs/common';
import { McpModule } from '@nestjs-mcp/server';
import { StatusResolver } from './status.resolver';

@Module({
  imports: [McpModule.forFeature()], // Import forFeature here
  providers: [StatusResolver], // Register your resolver
})
export class StatusModule {}

Module Usage

This library provides two main ways to register MCP capabilities in your NestJS application:

1. Global Registration with McpModule.forRoot

Use McpModule.forRoot in your root application module to configure and register the MCP server globally. This is required for every MCP server application.

ts
import { Module } from '@nestjs/common';
import { McpModule } from '@nestjs-mcp/server';
import { PromptsResolver } from './prompts.resolver';

@Module({
  imports: [
    McpModule.forRoot({
      name: 'My MCP Server',
      version: '1.0.0',
      // ...other MCP options
    }),
  ],
  providers: [PromptsResolver],
})
export class AppModule {}

2. Feature Module Registration with McpModule.forFeature

Use McpModule.forFeature in feature modules to register additional resolvers, tools, or resources. This is useful for organizing large servers into multiple modules.

ts
import { Module } from '@nestjs/common';
import { McpModule } from '@nestjs-mcp/server';

import { ToolsResolver } from './tools.resolver';

@Module({
  imports: [McpModule.forFeature()],
  providers: [ToolsResolver],
})
export class ToolsModule {}
  • Use forRoot or forRootAsync only once in your root module (AppModule).
  • Use forFeature in any feature module where you define MCP capabilities (@Resolver classes).
  • Ensure all Resolvers are listed in the providers array of their respective modules.

Capabilities

This library provides a set of decorators to define MCP capabilities and apply cross-cutting concerns such as guards. Decorators can be used at both the Resolver (class) level and the method level.

Resolver Decorator

A Resolver is a class that groups related MCP capabilities. All MCP capability methods (@Prompt, @Resource, @Tool) must belong to a class decorated with @Resolver.

  • No @Injectable() Needed: Resolver classes are automatically treated as providers by the MCP module and do not require the @Injectable() decorator.
  • Dependency Injection: Standard NestJS dependency injection works within Resolver constructors.
  • Namespacing: You can optionally provide a string argument to @Resolver('my_namespace') to namespace the capabilities within that resolver.
  • Access defaults: @Resolver({ name, scopes, public, hideOutOfScope }) sets defaults for every capability of the class — see Resolver defaults.
  • Guards: Guards can be applied at the class level using @UseGuards().

Example:

ts
import { Resolver, Prompt, Resource, Tool } from '@nestjs-mcp/server';
// Import any services you need to inject
import { SomeService } from '../some.service';

@Resolver('workspace') // No @Injectable()
export class MyResolver {
  // Inject dependencies as usual
  constructor(private readonly someService: SomeService) {}

  @Prompt({ name: 'greet_user' }) // Capabilities must be inside a Resolver
  greetPrompt(/*...args...*/) {
    const greeting = this.someService.getGreeting();
    /* ... */
  }

  @Resource({ name: 'user_profile', uri: 'user://{id}' })
  getUserResource(/*...args...*/) {
    /* ... */
  }

  @Tool({ name: 'calculate_sum' })
  sumTool(/*...args...*/) {
    /* ... */
  }
}

You can also apply guards at the resolver level:

ts
import { UseGuards, Resolver } from '@nestjs-mcp/server';
import { MyGuard } from './guards/my.guard';

@UseGuards(MyGuard) // Applied to all capabilities in this Resolver
@Resolver('secure') // No @Injectable()
export class SecureResolver {
  // All capabilities in this resolver will use MyGuard
}

Prompt Decorator

Decorate methods within a Resolver class to expose them as MCP Prompts. Accepts options compatible with server.prompt() from @modelcontextprotocol/sdk. The name should use snake_case.

ts
import { Prompt, Resolver } from '@nestjs-mcp/server';
import { McpContext } from '@nestjs-mcp/server'; // Handler context type
import { z } from 'zod'; // Example if using Zod schema

// Optional: Define schema if needed
// const SummaryArgs = z.object({ topic: z.string() });

@Resolver('prompts') // Must be in a Resolver class
export class MyPrompts {
  @Prompt({
    name: 'generate_summary',
    description: 'Generates a summary for the given text.',
    // argsSchema: SummaryArgs
  })
  generateSummaryPrompt(
    // params: z.infer<typeof SummaryArgs>, // Arguments based on argsSchema (if defined)
    ctx: McpContext, // The request this call arrived on
  ) {
    console.log(`Generating summary for ${ctx.mcpReq.method}`);
    /* ... return CallPromptResult ... */
    return { content: [{ type: 'text', text: 'Summary generated.' }] };
  }
}

Resource Decorator

Decorate methods within a Resolver class to expose them as MCP Resources. Accepts options compatible with server.resource() from @modelcontextprotocol/sdk. The name should use snake_case.

ts
import { Resource, Resolver } from '@nestjs-mcp/server';
import { McpContext } from '@nestjs-mcp/server'; // Handler context type
import { URL } from 'url'; // Type for URI resource
import { z } from 'zod'; // Example if using Zod template

// Optional: Define template schema if needed
// const DocQueryTemplate = z.object({ query: z.string() });

@Resolver('data') // Must be in a Resolver class
export class MyResources {
  @Resource({
    name: 'user_profile',
    uri: 'user://profiles/{userId}',
    // metadata: { description: '...' } // Optional
  })
  getUserProfile(
    uri: URL, // First argument is the parsed URI
    // metadata: Record<string, any> // Second argument if is defined
    ctx: McpContext, // The request this call arrived on
  ) {
    const userId = uri.pathname.split('/').pop(); // Example: Extract ID from URI
    console.log(`Fetching profile for ${userId}`);
    /* ... return CallResourceResult ... */
    return { content: [{ type: 'text', text: `Profile data for ${userId}` }] };
  }

  @Resource({
    name: 'document_list',
    template: { type: 'string', description: 'Document content query' }, // Simple template example
    // metadata: { list: true } // Optional
  })
  findDocuments(
    uri: URL, // First arg based on simple template type
    variables: Record<string, string>, // Second arg is path params (if any)
    ctx: McpContext, // The request this call arrived on
  ) {
    console.log(`Finding documents matching '${query}'`);
    /* ... return CallResourceResult ... */
    return { content: [{ type: 'text', text: 'List of documents.' }] };
  }
}

Tool Decorator

Decorate methods within a Resolver class to expose them as MCP Tools. Accepts options compatible with server.tool() from @modelcontextprotocol/sdk. The name should use snake_case.

ts
import { Tool, Resolver } from '@nestjs-mcp/server';
import { McpContext } from '@nestjs-mcp/server';
import { z } from 'zod';
import { CallToolResult } from '@modelcontextprotocol/sdk/types';

@Resolver('user_tools')
export class UserToolsResolver {
  @Tool({
    name: 'delete_user',
    description: 'Deletes a user by ID',
    paramsSchema: z.object({ userId: z.string() }),
    annotations: { destructiveHint: true, readOnlyHint: false },
  })
  deleteUser({ userId }: { userId: string }, ctx: McpContext): CallToolResult {
    // ...logic...
    return { content: [{ type: 'text', text: `User ${userId} deleted.` }] };
  }
}

Tool Annotations

The annotations field allows you to provide protocol-level hints about the tool's behavior, such as whether it is destructive, read-only, idempotent, or has other special properties. These hints can be used by clients, UIs, or the protocol itself to display warnings, optimize calls, or enforce policies.

Common annotation keys:

  • destructiveHint (boolean): Indicates the tool performs a destructive action (e.g., deletes data).
  • readOnlyHint (boolean): Indicates the tool does not modify any data.
  • idempotentHint (boolean): Indicates the tool can be safely called multiple times with the same effect.
  • openWorldHint (boolean): Indicates the tool may have side effects outside the current system.

Example:

ts
@Tool({
  name: 'reset_password',
  paramsSchema: z.object({ userId: z.string() }),
  annotations: { destructiveHint: true, idempotentHint: false }
})
resetPassword({ userId }: { userId: string }): CallToolResult {
  // ...
}

ToolOptions Variants

VariantRequired Fields
ToolBaseOptionsname
ToolWithDescriptionOptionsname, description
ToolWithParamOrAnnotationsOptionsname, paramsSchemaOrAnnotations
ToolWithParamOrAnnotationsAndDescriptionOptionsname, paramsSchemaOrAnnotations, description
ToolWithParamAndAnnotationsOptionsname, paramsSchema, annotations
ToolWithParamAndAnnotationsAndDescriptionOptionsname, paramsSchema, annotations, description
  • paramsSchema and paramsSchemaOrAnnotations can be a Zod schema for input validation.
  • annotations is an object with protocol-level hints as described above.

McpContext Argument

All MCP capability methods (@Prompt, @Resource, @Tool) receive an McpContext object as their last parameter. It extends the SDK's own ServerContext with the Express request the call arrived on.

Renamed in 2.0. This was RequestHandlerExtra, a type the MCP SDK removed in v2. See Migrating from 1.x to 2.x.

Properties from the SDK:

  • mcpReq.id — the JSON-RPC id of this request
  • mcpReq.method — the method being served, e.g. tools/call
  • mcpReq._meta / mcpReq.envelope — request metadata and the 2026-07-28 envelope
  • http.authInfo — validated access-token information, when auth middleware ran
  • sessionId — undefined on 2026-07-28 traffic. Protocol revision 2026-07-28 retired sessions. It may still be populated for 2025-era clients served through the legacy fallback. Never branch on it for authorization.

Added by @nestjs-mcp/server:

  • request — the live Express request for this call
  • headers — shorthand for request.headers
  • reportProgress(progress, total?, message?) — sends a progress update to the caller; see Reporting progress

Usage Example:

ts
import { McpContext, Resolver, Tool } from '@nestjs-mcp/server';
import { CallToolResult } from '@modelcontextprotocol/server';
import { z } from 'zod';

@Resolver('auth')
export class AuthResolver {
  @Tool({
    name: 'authenticate_user',
    description: 'Authenticates a user with credentials',
    paramsSchema: z.object({ username: z.string(), password: z.string() }),
  })
  authenticateUser(
    params: { username: string; password: string },
    ctx: McpContext, // Always the last parameter
  ): CallToolResult {
    // Headers of THIS call, not of the connection handshake
    const authHeader = ctx.headers.authorization;
    const userAgent = ctx.headers['user-agent'];
    console.log(`Serving ${ctx.mcpReq.method} for: ${String(userAgent)}`);

    // Anything Nest middleware attached upstream is reachable too
    console.log(ctx.request.ip);

    return {
      content: [{ type: 'text', text: 'Authentication successful' }],
    };
  }
}

Important Notes:

  • ctx is always the last parameter in any method decorated with @Resource, @Prompt, or @Tool
  • headers changed meaning in 2.0. Before 2.0 they were the headers of the request that opened the connection — the initialize POST — frozen for its lifetime. They are now this call's own headers, so credentials that expire or are revoked mid-conversation are seen correctly. Code that compiled against 1.x keeps compiling and starts receiving a different (correct) value.
  • ctx is not JSON-serializable: request is an Express object with circular references, so JSON.stringify(ctx) throws. Read the fields you need.

Reporting progress

A long-running tool, prompt or resource can tell the caller how far along it is:

ts
@Tool({
  name: 'analyze_files',
  paramsSchema: z.object({ files: z.array(z.string()) }),
})
async analyzeFiles(
  params: { files: string[] },
  ctx: McpContext,
): Promise<CallToolResult> {
  const total = params.files.length;

  for (let i = 0; i < total; i++) {
    await this.analyzer.analyze(params.files[i]);
    await ctx.reportProgress(i + 1, total, `analyzed ${i + 1}/${total}`);
  }

  return { content: [{ type: 'text', text: `analyzed ${total} files` }] };
}

reportProgress sends a notifications/progress correlated with the progressToken the client put in the request's _meta:

  • No token, no-op. A client that did not ask for progress (most do not) gets nothing, and the call answers exactly as it would have without it.
  • Never rejects. An update that can no longer be delivered — the exchange already ended — is logged at debug and dropped. void ctx.reportProgress(…) is safe.
  • Safe to detach. It never reads this, so it can be passed to a service as a plain callback: await importer.run(rows, ctx.reportProgress).
  • Whether it is delivered depends on responseMode — see Progress and responseMode.
  • No validation or throttling: keep progress increasing, and keep the update rate sensible.

⚠️ message reaches the caller verbatim. Do not put secrets, credentials or other tenants' data in progress messages.


Dynamic Capabilities

@Tool, @Prompt and @Resource all accept an optional enabled option that decides, per request, whether that capability is advertised and invocable.

ts
type McpCapabilityToggle = boolean | Type<McpCapabilityGate>;

interface McpCapabilityGate {
  isEnabled(context: McpRegistrationContext): boolean | Promise<boolean>;
}

interface McpRegistrationContext {
  /** The HTTP request whose capability set is being assembled. */
  request: Request; // express
  /** The effective AuthInfo produced by `auth.strategies` / `auth.authorizers`. */
  authInfo?: AuthInfo; // import type { AuthInfo } from '@nestjs-mcp/server'
  /** 'modern' (2026-07-28) or 'legacy' (2025-era clients). */
  era: ProtocolEra;
}

Two forms, one option key. Omitting enabled is the default and behaves exactly as it did before the option existed: always registered, always enabled, and it costs the request nothing.

Static toggle

For a capability that is simply off. It needs no class, no provider and no await.

ts
@Tool({
  name: 'legacy_tool',
  description: 'Kept for compatibility, not offered to clients',
  enabled: false,
})
legacyTool(): CallToolResult {
  /* ... */
}

Capability gate

For a decision the server has to make. A gate is a class, resolved from the Nest container exactly as a guard is — so it can inject services — and its verdict is awaited, so it can do real asynchronous work.

ts
import { Injectable } from '@nestjs/common';
import {
  McpCapabilityGate,
  McpRegistrationContext,
  Resolver,
  Tool,
} from '@nestjs-mcp/server';

@Injectable()
export class AdminGate implements McpCapabilityGate {
  constructor(private readonly permissions: PermissionsService) {}

  // `authInfo` may be undefined — always optional-chain it.
  async isEnabled(context: McpRegistrationContext): Promise<boolean> {
    if (context.request.headers['x-role'] === 'admin') return true;

    return this.permissions.isAdmin(context.authInfo?.clientId);
  }
}

@Resolver('admin')
export class AdminResolver {
  @Tool({
    name: 'rotate_keys',
    description: 'Only advertised to admin connections',
    enabled: AdminGate,
  })
  rotateKeys(): CallToolResult {
    /* ... */
  }
}

Register the gate as a provider in the module that owns the resolver:

ts
@Module({
  imports: [McpModule.forRoot({ name: 'admin', version: '1.0.0' })],
  providers: [PermissionsService, AdminGate, AdminResolver],
})
export class AppModule {}

Pass the class, never an instance — an instance built at module scope cannot reach the container, which is the whole reason the gate is a class. A gate may also answer synchronously (isEnabled(): boolean) when the check is a cheap in-memory one; boolean | Promise<boolean> covers both.

Note that McpRegistrationContext carries no sessionId, deliberately. It exists under SSE at registration time but not under streamable HTTP, where the transport assigns it while handling the initialize POST — after registration has already run. Exposing it would make the same gate behave differently per transport.

What the client sees

A disabled capability is registered and then disabled, never skipped. It is therefore absent from tools/list / prompts/list / resources/list, and invoking it answers Tool <name> disabled rather than Tool <name> not found — the two are distinct in the SDK and the first is the correct answer for a capability that exists but is off for you.

Fail-closed, in five cases

A gate that cannot answer never leaves a capability exposed:

CaseResult
isEnabled throws synchronouslydisabled, error logged
isEnabled returns a rejecting promisedisabled, error logged
the gate class cannot be resolved from the containerdisabled, error logged — it is never silently built with new, because such a gate has undefined dependencies and could answer something accidentally truthy
a gate is declared but no registration context existsdisabled, error logged
disable() itself throwsthe capability remains enabled, and the log says so — the one residual fail-open, because there is no other way to disable

A failing gate never affects the capabilities beside it, and never turns the request into a 500. Log lines name the capability and the failure only — never the request, its headers, or a token.

Rules you must know before using this

  • Evaluated once per request. A fresh MCP server is built for every HTTP request — that is what makes the server stateless — and enabled is resolved while it is being populated. Changing whatever the gate reads takes effect on the client's very next call; no reconnect is needed. (Before 2.0 the verdict was frozen for the life of a connection.)
  • No listChanged notification is emitted. Every toggle is applied before the server is connected to its transport, where the SDK gates notification dispatch. This library never sends notifications/tools/list_changed or its prompt/resource equivalents. Do not expect a connected client to be told that something changed — nothing changes mid-session.
  • Keep gates cheap — they are on the request path. Every tools/list and every tools/call settles every gate before the client is served, so a gate that queries a database is a per-request database query. This is the most important behavioural change in 2.0 for anyone already using the option. The library bounds what it can: registration stays synchronous, all gates settle in one concurrency wave (the added latency is the slowest single gate, not the sum), and each distinct gate class is both resolved from the container and asked once per request however many capabilities share it. What it cannot bound is the gate itself — do your caching in the injected service, at provider scope. There is no built-in timeout: a gate that never settles leaves the request unanswered.
  • A gate with no registration context fails closed. Both built-in transports always pass a context. If you call RegistryService.registerAll(server) yourself with a single argument, any capability declaring a gate is disabled and the reason is logged. Static true / false and capabilities with no enabled option are unaffected.
  • authInfo may be undefined. It is only populated when an auth strategy authenticated the caller (see Authentication & authorization), or when middleware upstream set req.auth. Write context.authInfo?.scopes — a gate that dereferences it unguarded throws, and then fails closed, which silently removes the capability.
  • Request-scoped gate providers are not supported. A gate is resolved with moduleRef.get(..., { strict: false }), falling back to moduleRef.create. Neither handles a request-scoped provider cleanly. Use a singleton gate that reads what it needs from the registration context.

This is not a replacement for guards

enabled is discovery-level defence-in-depth, not the authorization mechanism. Guards are: they run on every capability invocation, against that invocation's own context.

The reason changed in 2.0, and the conclusion survives it. Before 2.0 the argument was mechanical: the registration context was built from the initialize POST and nothing else, so later calls were never re-examined. That is no longer true — a gate now sees each call's own request and req.auth. What remains is the difference in kind: a gate omits a capability from a listing, while a guard refuses an invocation. Omission is not refusal. A client that already knows a tool's name can call it without ever reading the list, and only a guard stops that.

This is the same line the MCP SDK draws for its own per-request factory: the HTTP layer verifies the bearer token, while per-tool checks live in the handler, because "the handler is the authoritative source for the executing tool."

Use enabled to decide what a caller should even see; use a guard to decide whether a call is allowed. Both now see the same request, so a predicate can be factored between them — but hiding a capability is not enforcement: a client that already knows the tool name can still call it, and only a guard stops that.

If you call RegistryService directly

RegistryService.registerAll is async and its second argument — the registration context — is required:

ts
await registry.registerAll(server, { request, era: 'modern' });

Only code that drives the registry itself is affected; using McpModule normally is not. See Migrating from 1.x to 2.x for the full 2.0 change list.

A runnable example lives in examples/dynamic/ — EXAMPLE=dynamic pnpm start:example.


Guards

Apply one or more guards to a Resolver, to individual methods, or globally. Guards must implement the NestJS CanActivate interface.

Global-level guards

This approach uses the standard NestJS global guard system (APP_GUARD). A global guard will protect all NestJS routes, including the MCP endpoint (/mcp). Use this for broad authentication or checks that apply before any MCP-specific logic runs.

ts
// src/guards/global-auth.guard.ts
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Request } from 'express';

@Injectable()
export class GlobalAuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest<Request>();
    const apiKey = request.headers['x-api-key'];
    // Example: Check for a valid API key
    return !!apiKey && apiKey === 'EXPECTED_KEY';
  }
}

Register the guard globally in your main module:

ts
// src/app.module.ts
import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { McpModule } from '@nestjs-mcp/server';
import { GlobalAuthGuard } from './guards/global-auth.guard';

@Module({
  imports: [McpModule.forRoot(/*...*/)],
  providers: [
    {
      provide: APP_GUARD,
      useClass: GlobalAuthGuard,
    },
  ],
})
export class AppModule {}

Guards attached with @UseGuards receive an McpExecutionContext, not Nest's ExecutionContext. Implement McpGuard (optionally McpGuard<YourExtra> for a typed identity) rather than CanActivate: CanActivate types its parameter as ExecutionContext, so implements CanActivate with an McpExecutionContext parameter does not compile under strict mode. @UseGuards accepts both. Global APP_GUARD guards are ordinary Nest guards and keep using CanActivate.

Resolver-level guards

This is a custom feature of this library. Resolver-level guards are applied using the @UseGuards() decorator (exported from @nestjs-mcp/server) on a Resolver class. All MCP methods (@Prompt, @Resource, @Tool) within that specific resolver will be protected by these guards. Use this to enforce logic (e.g., role checks) for a group of related capabilities.

ts
import { UseGuards, Resolver, Prompt } from '@nestjs-mcp/server';
import { RoleGuard } from './guards/role.guard';

@UseGuards(RoleGuard)
@Resolver('admin')
export class AdminResolver {
  @Prompt({ name: 'admin_action' })
  adminAction(/*...*/) {
    /* ... */
  }
  // ... other admin capabilities
}

Method-level guards

This is a custom feature of this library. Method-level guards are applied using the @UseGuards() decorator directly on an MCP capability method (@Prompt, @Resource, @Tool). Only the decorated method will be protected by these guards. Use this for fine-grained access control on specific capabilities.

ts
import { UseGuards, Resolver, Prompt, Tool } from '@nestjs-mcp/server';
import { SpecificCheckGuard } from './guards/specific-check.guard';

@Resolver('mixed')
export class MixedResolver {
  @Prompt({ name: 'public_prompt' })
  publicPrompt() {
    /* Publicly accessible */
  }

  @UseGuards(SpecificCheckGuard)
  @Tool({ name: 'protected_tool' })
  protectedTool(/*...*/) {
    /* Requires SpecificCheckGuard to pass */
  }
}

Important: Resolver and Method-level guards only run for MCP capability invocations, not for the initial connection establishment handled by global guards. They use the custom McpExecutionContext.

Guard Example

A guard for Resolver or Method-level protection:

ts
// src/guards/my-mcp.guard.ts
import { Injectable } from '@nestjs/common';
import { McpExecutionContext, McpGuard } from '@nestjs-mcp/server';

@Injectable()
export class MyMcpGuard implements McpGuard {
  canActivate(context: McpExecutionContext): boolean {
    const request = context.getRequest();
    const userAgent = request.headers['user-agent'];

    const handlerArgs = context.getArgs();

    console.log(
      `Guard activated for ${context.getContext().mcpReq.method} from ${String(userAgent)}`,
    );
    console.log('Handler args:', handlerArgs);

    return true;
  }
}

MCP Execution Context

When implementing Resolver-level or Method-level guards using @UseGuards() from this library, your canActivate method receives an McpExecutionContext. It provides access to MCP-specific information:

typescript
import { Injectable } from '@nestjs/common';
import { McpExecutionContext, McpGuard } from '@nestjs-mcp/server';

@Injectable()
export class McpAuthGuard implements McpGuard {
  canActivate(context: McpExecutionContext): boolean {
    // The request this capability was INVOKED on — not the connection
    // handshake, as it was before 2.0.
    const request = context.getRequest();

    const authHeader = request.headers.authorization;
    if (!authHeader?.startsWith('Bearer ')) {
      console.log('Guard Denied: Missing or invalid Bearer token.');
      return false;
    }

    const token = authHeader.split(' ')[1];
    return token === 'VALID_TOKEN';
  }
}

Key points for McpExecutionContext:

  • getRequest() — the Express request this capability was invoked on. Since 2.0 it is the call's own request, so expiring or revoked credentials are seen correctly. In 1.x it was the connection handshake, frozen for the connection's lifetime.
  • getContext() — the full McpContext: mcpReq (id, method, _meta, envelope) and http.authInfo.
  • getArgs() — the arguments passed to the MCP handler being invoked. Their shape depends on the capability type; narrow on the type discriminator.
  • getClass() / getHandler() — the resolver class and method.
  • getAuthInfo?.() — the effective AuthInfo (after auth.authorizers), or undefined for an anonymous request. Optional on the interface so existing test doubles keep compiling.
  • getSessionId() was removed in 2.0. Protocol revision 2026-07-28 retired sessions, so there is no id to return and no store to look one up in.
  • This is not Nest's ExecutionContext: there is no switchToHttp(). Use getRequest() directly.

Guards with Dependency Injection

Guards can inject NestJS providers. Use @Injectable() and register the guard as a provider:

typescript
@Injectable()
export class AuthGuard implements McpGuard {
  constructor(private readonly tokens: TokenService) {}

  async canActivate(context: McpExecutionContext): Promise<boolean> {
    const header = context.getRequest().headers.authorization;
    if (!header) return false;

    // Revocation works now: this is the token sent with THIS call.
    return this.tokens.isValid(header.replace('Bearer ', ''));
  }
}

@Module({
  imports: [McpModule.forRoot({ name: 'my-server', version: '1.0.0' })],
  providers: [AuthGuard, TokenService, MyResolver],
})
export class AppModule {}

A guard class the container cannot resolve or create denies the call and logs an error (since 2.1). Register guards with dependencies as providers.


Authentication & authorization

Bring your own authentication. The library does not decide how callers authenticate, nor where the credential travels. Your application registers authentication strategies — an API key in the header, query parameter or cookie of your choice, Basic auth, a session cookie, a client certificate, a JWT, an opaque OAuth token: anything that can be read from the HTTP request. The library provides the infrastructure around them: it runs them before the MCP handler, writes the 401/403/429 answers with the challenges your strategies declare, carries the resulting identity to authorizers, gates, guards and handlers, and — only if you use OAuth — serves the discovery metadata. Authorization is a separate layer you own: request authorizers, per-capability scopes, gates and guards.

HTTP request ─► Layer 1  authentication (strategies, once per request)     ─► req.auth: AuthInfo | 401
             ─► Layer 2a request authorization (authorizers, once per request) ─► req.auth narrowed | 403
             ─► Layer 2b capability authorization (scopes, gates, guards)   ─► handler | 403 / hidden / denied

Evaluation order for one request: strategies → authorizers → gates (enabled, at registration) → the SDK's scopes challenge → guards (@UseGuards) → handler. Absent auth, the endpoint behaves exactly as before.

Configuring auth

typescript
import { Module } from '@nestjs/common';
import { McpModule } from '@nestjs-mcp/server';

@Module({
  imports: [
    McpModule.forRoot({
      name: 'notes',
      version: '1.0.0',
      auth: {
        strategies: [ApiKeyStrategy, JwtStrategy], // in order; first AuthInfo wins
        authorizers: [WorkspaceAuthorizer], // optional, see below
        optional: false, // default: unrecognized caller → 401
        hideOutOfScope: false, // default: see "Per-capability scopes"
        protectedResource: {
          // optional: OAuth discovery, see below
          resource: 'https://notes.example.com/mcp',
          authorizationServers: ['https://auth.example.com'],
          scopesSupported: ['notes:read', 'notes:write'],
          resourceName: 'Notes',
        },
      },
    }),
  ],
  // Strategies and authorizers are ordinary providers, so they can inject
  // services. They may be declared in any module.
  providers: [ApiKeyStrategy, JwtStrategy, WorkspaceAuthorizer, NotesResolver],
})
export class AppModule {}

Every strategy and authorizer is resolved from the container at boot. A class that cannot be resolved stops the application from starting — the library never falls back to new, which would bypass DI.

With forRootAsync, declare the classes in providers next to the module, and pass the static protectedResourceMetadata: true flag if the factory returns a protectedResource (Nest fixes controllers before the factory runs):

typescript
McpModule.forRootAsync({
  imports: [ConfigModule],
  inject: [ConfigService],
  providers: [JwtStrategy],
  protectedResourceMetadata: true,
  useFactory: (config: ConfigService) => ({
    name: 'notes',
    version: '1.0.0',
    auth: {
      strategies: [JwtStrategy],
      protectedResource: {
        resource: config.getOrThrow('MCP_RESOURCE'),
        authorizationServers: [config.getOrThrow('OAUTH_ISSUER')],
      },
    },
  }),
});

Writing a strategy

A strategy returns the SDK's AuthInfo (re-exported from this package), null ("no credentials for me, try the next one"), or throws:

OutcomeHTTP answer
returns AuthInfocontinues; later strategies are skipped
every strategy returns null401 + WWW-Authenticate with every registered challenge (no error=)
throw new McpUnauthorizedError(description)401 {"error":"unauthorized"} + the registered challenges; stops
throw new OAuthError(OAuthErrorCode.InvalidToken)401 + Bearer error="invalid_token" challenge (OAuth strategies); stops
throw new McpHttpError(status, body, headers)written as-is (e.g. 429 with Retry-After)
anything else500, logged without headers or token

AuthInfo is the MCP SDK's identity type (it is what handlers receive as ctx.http.authInfo), whatever the method: clientId is the id of the authenticated principal and token the credential that was presented. Both are required, and expiresAt is in seconds since the epoch. A returned AuthInfo without a string token, a string clientId and a scopes array of strings, or with an expiresAt that is clearly milliseconds (above 1e11), is a bug answered 500; one whose expiresAt has already passed is answered 401 invalid_token. Put application identity (user id, key id, workspace) in AuthInfo.extra. CORS preflight (OPTIONS) is never authenticated. Never put the credential in an error message: an unexpected error is logged by its class and message.

Challenges. A strategy may declare readonly challenge — the RFC 9110 challenge that tells clients how to present its credential, e.g. ApiKey header="x-api-key" or Basic realm="notes". Every 401 lists all declared challenges; when protectedResource is set, the Bearer challenge with resource_metadata comes first (MCP clients look for it). With no declared challenge and no protectedResource, the header is a bare Bearer. A challenge that is not one valid RFC 9110 challenge stops the application at boot, and so does a scopesSupported or decorator scopes entry that is not an OAuth scope-token (no spaces, quotes, backslashes or control characters).

API key from a header you choose (not OAuth; no OAuth vocabulary needed):

typescript
import { Injectable } from '@nestjs/common';
import {
  AuthenticatedRequest,
  AuthInfo,
  McpAuthStrategy,
  McpUnauthorizedError,
} from '@nestjs-mcp/server';

@Injectable()
export class ApiKeyStrategy implements McpAuthStrategy {
  readonly challenge = 'ApiKey header="x-api-key"';

  constructor(private readonly keys: ApiKeyService) {}

  async authenticate(req: AuthenticatedRequest): Promise<AuthInfo | null> {
    const key = req.headers['x-api-key'];
    if (typeof key !== 'string') return null; // not mine

    const record = await this.keys.find(key);
    if (!record) throw new McpUnauthorizedError('Unknown API key');

    return { token: key, clientId: record.id, scopes: record.scopes };
  }
}

The credential's location is entirely the strategy's decision: read req.query.api_key, req.cookies.session, req.socket.getPeerCertificate() or any header. Prefer headers: query strings end up in access logs and proxies, and the MCP authorization spec forbids them for OAuth access tokens.

API key via Bearer is the same strategy reading Authorization. Return null for a Bearer value that is not one of your keys (for example, one with a JWT's xxx.yyy.zzz shape) so a JWT strategy later in the list still gets it.

JWT with jose — checking t

Use o MCP de Nestjs MCP Server com vários modelos de IA

O TypingMind conecta as ferramentas MCP no nível do espaço de trabalho. Assim, após conectar Nestjs MCP Server, é possível usá-lo com diferentes modelos de IA no TypingMind, em vez de configurá-lo separadamente para cada modelo. Este MCP é executado localmente no seu dispositivo por meio do conector MCP do TypingMind.

Guia de configuração para usar o conector local

Use esta opção quando o servidor MCP precisar acessar arquivos locais, aplicativos ou recursos privados no seu computador.

1

Abra as configurações de MCP

No TypingMind, vá até Configurações, Configurações avançadas e depois Model Context Protocol e selecione Configurar conector.

  1. Abra o TypingMind no navegador.
  2. Clique no ícone de Ajustes.
  3. Acesse Configurações avançadas.
  4. Abra a seção Model Context Protocol.
  5. Clique em Configurar conector e selecione Este dispositivo.
Tela de configuração do conector MCP do TypingMind com a opção Este dispositivo selecionada
2

Execute o comando do conector

Selecione Este dispositivo, copie o comando do TypingMind e execute-o no Terminal. Mantenha o processo em execução enquanto usa o MCP.

  1. Copie o comando de configuração exibido pelo TypingMind.
  2. Abra o Terminal no macOS ou o Windows Terminal no Windows.
  3. Cole e execute o comando.
  4. Autorize a instalação do pacote se o Terminal pedir confirmação para continuar.
  5. Mantenha o processo em execução na janela do Terminal enquanto usa as ferramentas MCP.
3

Adicione Nestjs MCP Server como servidor

Quando o status do conector for Pronto, clique em Editar e cole a configuração do servidor MCP.

  1. Aguarde até que o status do conector mostre Pronto.
  2. Clique em Editar.
  3. Cole a configuração do servidor MCP de Nestjs MCP Server.
  4. Salve a lista de servidores.
  5. Atualize para confirmar se o conector ainda está pronto para uso.
Configurações de MCP do TypingMind mostrando um servidor ativo e o botão Editar
{
  "mcpServers": {
    "nestjs-mcp-server": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

Use a conexão com diferentes modelos

Salve a lista de servidores, abra Plugins, ative as ferramentas MCP de Nestjs MCP Server, selecione qualquer modelo de IA compatível no TypingMind e use as ferramentas no chat ou atribua-as a um agente de IA.

  1. Abra a página Plugins no TypingMind.
  2. Ative as ferramentas MCP de Nestjs MCP Server.
  3. Inicie um chat e escolha o modelo de IA que deseja usar.
  4. Use as ferramentas MCP no chat ou atribua-as a um agente de IA.
  5. Mude para outro modelo de IA sempre que necessário, sem reconectar o MCP.
Chat do TypingMind usando ferramentas MCP ativadas com um modelo de IA selecionado
Pode usar Nestjs MCP Server para me ajudar nesta tarefa?
Nestjs MCP Server
Claro. Já li.
Veja o que encontrei usando Nestjs MCP Server.

Perguntas frequentes

Para que serve o servidor MCP Nestjs MCP Server?

Nestjs MCP Server é um servidor MCP que permite que aplicativos de IA compatíveis se conectem a ferramentas externas e informações de contexto. No TypingMind, basta adicionar esse servidor MCP uma vez para disponibilizar suas ferramentas no seu espaço de trabalho com IA.

Posso usar o MCP Nestjs MCP Server com vários modelos de IA no TypingMind?

Sim. O TypingMind conecta as ferramentas MCP no nível do espaço de trabalho, permitindo usar Nestjs MCP Server com diferentes modelos de IA, como Claude, ChatGPT, Gemini ou outros modelos configurados no TypingMind, sem configurar o servidor MCP separadamente para cada modelo.

Por que usar o MCP Nestjs MCP Server com o TypingMind?

O TypingMind é uma das melhores interfaces de chat com LLMs porque reúne vários modelos de IA, prompts, plugins, agentes de IA, chaves de API e ferramentas MCP em um só espaço de trabalho. Com Nestjs MCP Server conectado, é possível usar suas ferramentas MCP nos seus modelos preferidos e manter seu fluxo de trabalho de chat organizado no TypingMind.

Como conecto o MCP Nestjs MCP Server ao TypingMind?

Nestjs MCP Server funciona por meio do conector MCP local do TypingMind. Essa é a melhor opção quando o servidor MCP precisa acessar arquivos locais, apps de desktop, ferramentas de linha de comando ou recursos privados no seu computador.

Quais ferramentas o MCP Nestjs MCP Server oferece no TypingMind?

Nestjs MCP Server disponibiliza recursos MCP que podem ser ativados na página Plugins do TypingMind e usados no chat ou atribuídos a agentes de IA.

Preciso compartilhar minhas chaves de API com o TypingMind para usar o MCP Nestjs MCP Server?

Não. O TypingMind prioriza o uso local e permite manter seus provedores de modelos, chaves de API, prompts e configuração MCP sob seu controle. Se Nestjs MCP Server exigir autenticação, adicione os cabeçalhos, as configurações OAuth ou a configuração local exigidos por esse servidor MCP ao criar a conexão.

Servidores MCP relacionados

Ver todos

Crie seu próprio espaço de IA agora

Inscreva-se na nossa newsletter para receber novidades sobre recursos e futuros sorteios 👇