Logo di Nestjs MCP Server

Nestjs MCP Server

Community
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…

Autoreadrian-d-hidalgo
Repositorynestjs-mcp-server
LinguaTypeScript
Fork
4
Stelle
40
Strumenti disponibili
0
Tipo di trasportostdio
LicenzaMIT
Link
  • Collega gli strumenti ai flussi di lavoro IA

    Nestjs MCP Server mette a disposizione funzionalità MCP utilizzabili da client e agenti IA compatibili.

  • 0 strumenti disponibili

    Esplora le azioni richiamabili qui sotto, con nomi e descrizioni quando forniti dal server.

  • Configurazione pronta da copiare

    Usa gli esempi di installazione per configurare questo server nel tuo client MCP preferito.

  • Indicatori di interesse open source

    40 stelle e 4 fork nel repository collegato.

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

Usa MCP Nestjs MCP Server con più modelli IA

TypingMind collega gli strumenti MCP a livello di area di lavoro: una volta connesso Nestjs MCP Server, puoi usarlo con diversi modelli IA in TypingMind, senza configurarlo separatamente per ogni modello. Questa integrazione MCP viene eseguita localmente sul tuo dispositivo tramite il connettore MCP di TypingMind.

Guida alla configurazione del connettore locale

Usa questo metodo quando il server MCP deve accedere a file locali, app o risorse private sul tuo computer.

1

Apri le impostazioni MCP

In TypingMind, vai su Impostazioni, Impostazioni avanzate, poi su Model Context Protocol e scegli Configura MCP.

  1. Apri TypingMind nel tuo browser.
  2. Fai clic sull'icona Impostazioni.
  3. Vai a Impostazioni avanzate.
  4. Apri la sezione Model Context Protocol.
  5. Fai clic su Configura MCP e scegli Questo dispositivo.
Schermata di configurazione del connettore MCP di TypingMind con Questo dispositivo selezionato
2

Esegui il comando del connettore

Scegli Questo dispositivo, copia il comando da TypingMind ed eseguilo nel terminale. Lascia il processo in esecuzione mentre usi MCP.

  1. Copia il comando di configurazione mostrato da TypingMind.
  2. Apri Terminale su macOS o Windows Terminal su Windows.
  3. Incolla ed esegui il comando.
  4. Conferma l'installazione del pacchetto se il terminale ti chiede di procedere.
  5. Tieni aperta la finestra del terminale con il processo in esecuzione mentre usi gli strumenti MCP.
3

Aggiungi Nestjs MCP Server come server

Quando lo stato del connettore è Pronto, fai clic su Modifica server e incolla la configurazione del server MCP.

  1. Attendi che lo stato del connettore sia Pronto.
  2. Fai clic su Modifica server.
  3. Incolla la configurazione del server MCP di Nestjs MCP Server.
  4. Salva l'elenco dei server.
  5. Aggiorna per verificare che il connettore sia ancora pronto.
Impostazioni MCP di TypingMind con un server attivo e il pulsante Modifica server
{
  "mcpServers": {
    "nestjs-mcp-server": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

Usa la connessione con diversi modelli

Salva l'elenco dei server, apri Plugin, abilita gli strumenti MCP di Nestjs MCP Server, poi seleziona un modello IA supportato in TypingMind e usa gli strumenti in chat o assegnali a un agente IA.

  1. Apri la pagina Plugin in TypingMind.
  2. Abilita gli strumenti MCP di Nestjs MCP Server.
  3. Avvia una chat e scegli il modello IA che vuoi usare.
  4. Usa gli strumenti MCP in chat o assegnali a un agente IA.
  5. Passa a un altro modello IA quando serve, senza riconnettere MCP.
Chat di TypingMind che usa gli strumenti MCP abilitati con un modello IA selezionato
Puoi usare Nestjs MCP Server per aiutarmi con questa attività?
Nestjs MCP Server
Certo. Ho letto.
Ecco cosa ho trovato con Nestjs MCP Server.

Domande frequenti

A cosa serve il server MCP Nestjs MCP Server?

Nestjs MCP Server è un server MCP che consente ai client IA compatibili di accedere a strumenti e informazioni di contesto esterni. In TypingMind puoi aggiungere questo server MCP una sola volta e rendere disponibili i suoi strumenti nella tua area di lavoro IA.

Posso usare Nestjs MCP Server MCP con più modelli IA in TypingMind?

Sì. TypingMind collega gli strumenti MCP a livello di area di lavoro, quindi puoi usare Nestjs MCP Server con diversi modelli IA come Claude, ChatGPT, Gemini o altri modelli che hai configurato in TypingMind, senza dover configurare il server MCP separatamente per ogni modello.

Perché usare il connettore MCP Nestjs MCP Server con TypingMind?

TypingMind è una delle migliori interfacce per chattare con gli LLM perché riunisce più modelli IA, prompt, plugin, agenti IA, chiavi API e strumenti MCP in un'unica area di lavoro. Collegando Nestjs MCP Server, puoi usare i suoi strumenti MCP con i tuoi modelli preferiti e mantenere organizzato il tuo flusso di lavoro in chat su TypingMind.

Come collego Nestjs MCP Server MCP a TypingMind?

Nestjs MCP Server funziona tramite il connettore MCP locale di TypingMind. È la soluzione ideale quando il server MCP deve accedere a file locali, app desktop, strumenti da riga di comando o risorse private sul tuo computer.

Quali strumenti offre Nestjs MCP Server MCP in TypingMind?

Nestjs MCP Server mette a disposizione funzionalità MCP che puoi attivare dalla pagina Plugin di TypingMind e usare in chat o assegnare agli agenti IA.

Devo condividere le mie chiavi API con TypingMind per usare Nestjs MCP Server MCP?

No. TypingMind privilegia il funzionamento in locale e ti permette di mantenere il controllo su fornitori di modelli, chiavi API, prompt e configurazione MCP. Se Nestjs MCP Server richiede l'autenticazione, aggiungi le intestazioni, le impostazioni OAuth o la configurazione locale necessarie per quel server MCP quando crei la connessione.

Server MCP correlati

Vedi tutti

Crea subito la tua area di lavoro IA

Iscriviti alla nostra newsletter per ricevere aggiornamenti sulle nuove funzionalità e sulle prossime iniziative a premi 👇