npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@haneinfo/mcp-server

v4.3.0

Published

Readme

@haneinfo/mcp-server

The MCP server provides stateless HTTP transport for employee (/mcp) and admin (/mcp/admin) MCP resources, RFC 9728 Protected Resource Metadata (PRM), and a minimal /mcp/health endpoint. See agent-guide.md for client requirements.

Routing and setGlobalPrefix

Each enabled resource exposes an OAuth 2.0 Protected Resource Metadata document per RFC 9728 §3.1 at /.well-known/oauth-protected-resource<resource-path> (for example, https://h/x/mcp serves metadata at https://h/.well-known/oauth-protected-resource/x/mcp).

If your NestJS application calls app.setGlobalPrefix(...), exclude .well-known/oauth-protected-resource so PRM routes remain mounted at the host root:

app.setGlobalPrefix('x', {
  exclude: ['.well-known/oauth-protected-resource/*path'],
});

Health Check (/mcp/health)

GET /mcp/health returns {"status":"ok"} with Cache-Control: no-store and no server metadata or tool counts.

An optional challenge query parameter is echoed back when it matches ^[A-Za-z0-9._~-]{1,128}$. Any invalid challenge value returns HTTP 400.

Tool Registration (@haneinfo/commands + McpModule.forRoot)

@haneinfo/commands (CommandRegistry) is the sole source of MCP tools. Legacy decorator and registry registration APIs (@McpTool(), registerMcpToolsFromInstance(), McpToolRegistry.registerTool(), registerToolSource(), refreshToolSources(), MCP_TOOLS, and * wildcard scope matching) have been removed.

Pass a sealed CommandRegistry and positive integer lockTimeoutMs to McpModule.forRoot(deployment, options):

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

@Module({
  imports: [
    McpModule.forRoot(deployment, {
      commands: sealedCommandRegistry,
      lockTimeoutMs: 2000,
    }),
  ],
})
export class AppMcpModule {}
  • /mcp exposes commands with surface 'mcp'; /mcp/admin exposes commands with surface 'mcp-admin'.
  • tools/list filters by resource, surface, App admission, exact OAuth scope match, RBAC (or resource-ACL declaration permissions: []), mcp-server.disabledTools, and dynamic source visibility.
  • tools/call re-runs full authorization before validating inputSchema and returns byte-for-byte identical JSON-RPC -32602 (data.code: 'tool_unavailable') for missing, disabled, unauthorized, wrong-surface, or insufficient-scope tools.
  • access: 'read' commands run with PRISMA; access: 'write' commands run inside a ReadCommitted transaction with authorizeWriteInTransaction (-32090 lock_timeout, -32091 authorization_stale).
  • Write commands requiring confirmation (confirmation: 'required', and all writes on mcp-admin) use the 2026-07-28 input_required elicitation confirmation flow (see below); when the confirmation gate is not met, tools/call returns JSON-RPC -32092 (data.code: 'confirmation_unavailable').
  • Throwing CommandToolError(payload) from a command handler returns { isError: true, content: [{ type: 'text', text: JSON.stringify(payload) }] } without structuredContent.

Dynamic tool updates

The dynamic tool source integration does not send notifications/tools/list_changed. When generated tools change, clients must refresh tools/list proactively.

Admin Endpoint (/mcp/admin) Configuration and Checks

When mcp.admin.enabled is true, McpIamDeploymentConfig.mcp.admin requires:

  • requiredScope?: string — Single OAuth scope required for /mcp/admin. Required when enabled is true; must be a non-empty string without whitespace, double quotes, backslashes, or control characters.
  • adminRoleNames?: readonly string[] — App RBAC role names granting admin access. Defaults to ['ADMIN'] (SYSTEM_ADMIN_ROLE) when omitted; must be a non-empty array if provided.
  • stepUpAcrValues?: string — Space-delimited acr_values returned in RFC 9470 step-up challenges. Required when enabled is true; must be a non-empty string without double quotes, backslashes, or control characters.

After token verification and local App admission succeed, /mcp/admin enforces three checks in order and returns the first failure:

  1. Management scope (claims.scopes includes requiredScope):
    • Failure: HTTP 403 { "error": "insufficient_scope" } with WWW-Authenticate: Bearer error="insufficient_scope", scope="<requiredScope>", resource_metadata="<admin-prm-url>".
  2. App RBAC admin role (live RBAC_POLICY.rolesForUser(userId) intersects adminRoleNames; token role claims are never read):
    • Failure: HTTP 403 { "error": "insufficient_role" } (without WWW-Authenticate).
  3. MFA & auth_time freshness (mfa === true, authTime is an integer, authTime <= nowSeconds, and nowSeconds - authTime <= maxAuthAgeSeconds with no clock tolerance):
    • Failure: HTTP 401 { "error": "insufficient_user_authentication" } with WWW-Authenticate: Bearer error="insufficient_user_authentication", acr_values="<stepUpAcrValues>", max_age="<maxAuthAgeSeconds>", resource_metadata="<admin-prm-url>".

Cross-Replica Rate Limiting (MCP_RATE_LIMITER)

@haneinfo/mcp-server provides a PostgreSQL-backed fixed-window rate limiter (PgMcpRateLimiter) as the default MCP_RATE_LIMITER implementation, using @haneinfo/common's PrismaService. Applications can override MCP_RATE_LIMITER in NestJS DI if they supply a custom McpRateLimiterPort.

Database Table and Migrations

The Prisma model McpRateLimitBucket (mcp_rate_limit_buckets) is shipped as a schema fragment in prisma/mcp-rate-limit.prisma. @haneinfo/mcp-server never creates tables or runs migrations at runtime: haneinfo build (@haneinfo/plugin-cli's Prisma composer) composes the fragment into the host App's schema.prisma, and the host App owns and applies the Prisma migration.

Keys are always SHA-256 hashed before storage; raw client IPs and user identifiers are never persisted in mcp_rate_limit_buckets.

Request Flow and Failure Behavior

  • RPC endpoints (/mcp, /mcp/admin) process requests in this exact order:
    1. Resource enabled check: Disabled or unconfigured resources return HTTP 404 {"error":"not_found"}.
    2. Host validation (MCP_ALLOWED_HOSTNAMES): Fail closed when unset or unlisted (HTTP 403).
    3. Origin validation (MCP_ALLOWED_ORIGINS): Requests without an Origin header are allowed. When present, Origin must be a single valid scheme://host[:port] URL matching an entry in MCP_ALLOWED_ORIGINS (empty string, null, multiple values, malformed URLs, or scheme/host/port mismatches return HTTP 403 {"error":"forbidden_origin"}).
    4. Per-replica concurrency limit (MCP_MAX_CONCURRENT_PER_SOURCE, default 20): Tracked in memory per replica by req.ip + normalized resource path and released when the HTTP exchange ends (response completion or connection close). A slot counts an in-flight HTTP exchange, not tool work: when a client aborts, the SDK ends the exchange and the slot is released while the tool handler may still be running, so abort-and-resend is bounded by the pre-auth and post-auth rate quotas rather than by this limit. Exceeding the limit returns HTTP 429 with Retry-After: 1 and {"error":"too_many_concurrent_requests"}. The effective cluster-wide concurrency limit is MCP_MAX_CONCURRENT_PER_SOURCE * replicas.
    5. Pre-auth rate limit: Keyed by req.ip + normalized resource path. Quota exceeded returns HTTP 429 with Retry-After and {"error":"rate_limited"}.
    6. HTTP method, request size, JSON object, and batch checks:
      • Non-POST methods (GET, DELETE, etc.) return HTTP 405 with Allow: POST and {"error":"method_not_allowed"}.
      • A non-integer or oversized Content-Length (> MCP_MAX_BODY_BYTES, default 1048576) returns HTTP 413 {"error":"payload_too_large"}. A request without Content-Length (HTTP/1.1 chunked, HTTP/2) is allowed; its size is limited only by the host body parser. Host applications using NestJS/Express must configure their Express JSON body parser limit to the same MCP_MAX_BODY_BYTES value so oversized bodies are rejected before parsing.
      • Non-object JSON bodies return HTTP 400 (-32600). JSON-RPC batch arrays return HTTP 400 with JSON-RPC error -32600 after pre-auth quota has been charged.
    7. M2M rejection, token verification, local admission, and admin checks: Unauthenticated callers receive HTTP 401 (with WWW-Authenticate: Bearer resource_metadata="...") or 403 without protocol-layer details (except size and batch rejections in step 6).
    8. Post-auth rate limit: Keyed by issuer, actingUserId, clientId, and resource.
    9. Protocol routing, version check, and method check:
      • Modern 2026-07-28 envelope (params._meta['io.modelcontextprotocol/protocolVersion']): subscriptions/listen returns HTTP 200 application/json JSON-RPC -32601 (never opens SSE); all other requests route to the modern stateless createMcpHandler (legacy: 'reject', responseMode: 'json', inputRequired: { legacyShim: false }).
      • Non-envelope initialize: params.protocolVersion must equal 2025-11-25 (older versions return HTTP 400).
      • Non-envelope non-initialize: MCP-Protocol-Version header must equal 2025-11-25 (missing or other values return HTTP 400). Only initialize, notifications/initialized, ping, tools/list, and tools/call are allowed; any other method (including subscriptions/listen) returns HTTP 200 application/json JSON-RPC -32601.
    10. Handler execution: Never emits Mcp-Session-Id. Both 2026-07-28 and 2025-11-25 allow read commands and confirmation: 'exempt' writes on /mcp; confirmation-required writes (and all writes on /mcp/admin) are listed in 2026-07-28 tools/list, hidden in 2025-11-25 tools/list, and require the confirmation gate in tools/call.
  • Public metadata (/mcp/health, /.well-known/oauth-protected-resource/*): Rate-limited under the independent public-meta bucket (keyed by client IP) so public metadata probes do not interfere with RPC quotas.
  • Cost weighting: tools/call consumes MCP_RATE_LIMIT_TOOLS_CALL_COST (default 5), while other methods consume MCP_RATE_LIMIT_DEFAULT_COST (default 1). JSON-RPC batch arrays sum the cost of their items against pre-auth.
  • Quota exceeded: Returns HTTP 429 with Retry-After (integer seconds, at least 1) and JSON body {"error":"rate_limited"}.
  • Backend unavailable (timeout > 1000 ms or DB failure): Returns HTTP 503 with {"error":"rate_limiter_unavailable"} on /mcp and /mcp/admin without entering authentication or handlers. By architectural choice, PRM and /mcp/health also return HTTP 503 {"error":"rate_limiter_unavailable"} when the rate limiter throws.
  • IAM backend lookup failure: If OIDC_IDENTITY_LOOKUP, IDENTITY_STORE, or RBAC_POLICY throws during authentication, the server returns HTTP 503 with {"error":"service_unavailable"} without leaking internal error details.

Express trust proxy Requirement

Client IP resolution relies strictly on Express req.ip and never parses X-Forwarded-For directly. Host applications running behind a reverse proxy or load balancer must configure Express trust proxy accurately (for example, app.set('trust proxy', 1) or trusted proxy CIDRs) so req.ip reflects the real client address rather than the proxy or a spoofed header.

Environment Variables and Defaults

All limits, windows, costs, and timeouts must be positive integers (tools/call cost must be strictly greater than the default cost). Invalid values fail fast at module startup.

| Variable | Default | Description | | --- | --- | --- | | MCP_RATE_LIMIT_PRE_AUTH_LIMIT | 120 | Max cost units per window for pre-auth (req.ip + path). Sized to absorb shared corporate NAT traffic while blocking unauthenticated floods. | | MCP_RATE_LIMIT_PRE_AUTH_WINDOW_SECONDS | 60 | Fixed window duration in seconds for pre-auth. | | MCP_RATE_LIMIT_POST_AUTH_LIMIT | 120 | Max cost units per window for post-auth (issuer + actingUserId + clientId + resource). Allows ~24 tools/call or 120 metadata calls per minute per client/user/resource. | | MCP_RATE_LIMIT_POST_AUTH_WINDOW_SECONDS | 60 | Fixed window duration in seconds for post-auth. | | MCP_RATE_LIMIT_PUBLIC_META_LIMIT | 60 | Max requests per window for public-meta (PRM and /mcp/health, keyed by req.ip). | | MCP_RATE_LIMIT_PUBLIC_META_WINDOW_SECONDS | 60 | Fixed window duration in seconds for public-meta. | | MCP_RATE_LIMIT_DEFAULT_COST | 1 | Cost per non-tools/call JSON-RPC request (such as initialize or tools/list). | | MCP_RATE_LIMIT_TOOLS_CALL_COST | 5 | Cost per tools/call invocation (must be greater than MCP_RATE_LIMIT_DEFAULT_COST). | | MCP_RATE_LIMIT_TIMEOUT_MS | 1000 | Client-side deadline in milliseconds before failing closed with 503. The query itself is not cancelled by this deadline; set statement_timeout on the database role (for example ALTER ROLE <app_role> SET statement_timeout = '1s') as the server-side bound. |

Protocol, Origin, and Pre-Processing Environment Variables

| Variable | Default | Description | | --- | --- | --- | | MCP_ALLOWED_HOSTNAMES | (unset — fail closed) | Comma-separated allowed Host header hostnames. All RPC requests are rejected when unset or empty. | | MCP_ALLOWED_ORIGINS | (unset — fail closed for browser Origin) | Comma-separated exact allowed origins (scheme://host[:port], no path, query, fragment, or wildcard). Requests without Origin are allowed. | | MCP_MAX_CONCURRENT_PER_SOURCE | 20 | Initial value without load measurements (maintainer 2026-11-15); tune it from real traffic. Per-replica in-memory concurrent request limit per req.ip + resource path. Effective cluster-wide limit is MCP_MAX_CONCURRENT_PER_SOURCE * replicas. | | MCP_MAX_BODY_BYTES | 1048576 | Maximum allowed Content-Length in bytes (1 MiB). Set the host Express JSON body parser limit to the same value. |

Removed in 4.0: MCP_ALLOWED_ORIGIN_HOSTNAMES (replaced by MCP_ALLOWED_ORIGINS; startup fails if the old variable is set without the new one), MCP_MAX_LEGACY_SESSIONS, and MCP_LEGACY_SESSION_IDLE_TTL_MS.

Scheduling Bucket Cleanup

Expired rows in mcp_rate_limit_buckets are not deleted on the request path. Schedule purgeExpiredRateLimitBuckets(prisma, olderThan) from a periodic background job (for example, hourly or daily via @haneinfo/background-jobs or a cron worker), passing a cutoff timestamp older than the longest configured rate-limit window (e.g. new Date(Date.now() - 3600_000)).

Write Confirmation (input_required, Receipts, requestState, and Audit)

Write commands with confirmation: 'required' (and all write commands on /mcp/admin, regardless of confirmation) require per-invocation user confirmation over MCP 2026-07-28 form elicitation (input_required).

Confirmation Gate & MCP_REQUEST_STATE_KEY

On both the initial tools/call and every resume carrying requestState, the executor verifies three gate conditions:

  1. Protocol revision is 2026-07-28.
  2. The current request declares elicitation.form in params._meta['io.modelcontextprotocol/clientCapabilities'].
  3. MCP_REQUEST_STATE_KEY is configured as a base64-encoded key that decodes to at least 32 bytes (shared across all replicas; never committed to source control).

If any condition fails, the server returns HTTP 200 with JSON-RPC error.code: -32092 and error.data.code: 'confirmation_unavailable' without creating a receipt or executing any write.

requestState is signed using @modelcontextprotocol/server's createRequestStateCodec (HMAC-SHA256) with a 120-second TTL (DEFAULT_REQUEST_STATE_TTL_SECONDS = 120), bound to (method, issuer, subject, resource). The signed payload contains only { toolName, schemaVersion, argsDigest, operationId } (no raw arguments).

Receipt Table and Migrations

The McpConfirmationReceipt (mcp_confirmation_receipts) model is shipped in the same Prisma schema fragment prisma/mcp-rate-limit.prisma alongside McpRateLimitBucket. haneinfo build (@haneinfo/plugin-cli) composes it into the host App's schema.prisma, and the host App owns and applies the Prisma migration. Every DateTime column in the fragment is @db.Timestamptz(3) and updatedAt has a database default, because both tables are written with raw SQL; the generated migration must keep those types. Schedule expirePendingConfirmationReceipts(prisma, { logger }) (for example every minute) so abandoned confirmations reach expired and are audited.

Receipt reads/writes run inside the App's ReadCommitted Prisma TransactionClient (FOR UPDATE row lock + WHERE status = 'pending'):

  • pending: Inserted before returning input_required, binding operationId, correlationId, issuer, subject, actingUserId, clientId, resource, toolName, schemaVersion, argsDigest, and expiresAt.
  • committed: Transitions only on accept with confirm === true after acquiring the receipt lock (FOR UPDATE), re-checking requestState, token exp, admin auth_time, and Step 5 RBAC/user locks (authorizeWriteInTransaction), and executing command.handler(actor, input, tx) in the same transaction.
  • declined / cancelled: Transitions on valid decline, cancel, or confirm === false without executing the handler.
  • expired: Transitions lazily on resume if expiresAt <= now, and via expirePendingConfirmationReceipts(prisma, { now, logger, batchSize, retentionDays }) scheduled periodically by the host App. Maintenance processes pending → expired in bounded batches (default 500 per batch, auditing only actual transitions) and prunes terminal receipts (committed, declined, cancelled, expired) older than retentionDays (default 7 days) in bounded batches.
  • Retry / Replay: Retrying a committed operationId first passes live command-level authorization (authorizer.authorize), and then inside the transaction:
    • If the command defines authorizeReplay(actor, input, tx), it runs inside the same transaction; if it returns false, replay fails with -32602 (data.code: 'tool_unavailable') without returning the stored result.
    • Otherwise, if the command declares resourceAclReason and has no authorizeReplay hook, replay returns { status: 'committed', correlationId } (both serialized in content[0].text and as structuredContent) without returning stored resultJson.
    • Commands without resourceAclReason (or with authorizeReplay returning true) return the stored resultJson without re-executing command.handler.

Structured Audit Events

McpService emits single-line JSON audit events via Nest Logger (ConfirmationAuditEvent) with a server-generated correlationId linking confirmation_issued, confirmation_accepted, confirmation_declined, confirmation_cancelled, confirmation_expired, confirmation_replayed, confirmation_authz_denied, confirmation_write_succeeded, confirmation_write_failed, confirmation_gate_rejected, and confirmation_binding_rejected.

Each event records event, timestamp, correlationId, operationId, resource, issuer, subject, actingUserId, clientId, toolName, resultCode, and workflowId (external correlation only; never proof of identity or confirmation). Bearer tokens, full requestState strings, and raw tool arguments are never logged.

Commands under a plugin host

Declare 'haneinfo.mcp-commands': true in hostCapabilities. This is a capability marker; the providers themselves belong in an application-owned global platform module. Import the generated connector manifest as an object and share one registry and lock timeout between Web and MCP:

import { Global, Module } from '@nestjs/common';
import { COMMANDS_WEB_OPTIONS } from '@haneinfo/commands/nest';
import { MCP_COMMANDS_OPTIONS, provideMcpCommands } from '@haneinfo/mcp-server';
import connectorManifest from './.haneinfo/generated/connector-manifest.json';

@Global()
@Module({
  imports: [AppPluginComposition],
  providers: [
    ...provideMcpCommands({
      inject: [AppTools],
      register: (registry, tools: AppTools) => {
        for (const command of tools.commands()) registry.register(command);
      },
      connectorManifest,
      lockTimeoutMs: 5000,
    }),
  ],
  exports: [MCP_COMMANDS_OPTIONS, COMMANDS_WEB_OPTIONS],
})
export class PlatformModule {}

The composition must export AppTools. Tool classes used to register commands must not depend on McpModule services: that creates a circular dependency and startup is refused. Invalid options also refuse startup; if no commands token is supplied, all MCP resources remain disabled.