@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 {}/mcpexposes commands with surface'mcp';/mcp/adminexposes commands with surface'mcp-admin'.tools/listfilters by resource, surface, App admission, exact OAuth scope match, RBAC (or resource-ACL declarationpermissions: []),mcp-server.disabledTools, and dynamic source visibility.tools/callre-runs full authorization before validatinginputSchemaand 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 withPRISMA;access: 'write'commands run inside aReadCommittedtransaction withauthorizeWriteInTransaction(-32090lock_timeout,-32091authorization_stale).- Write commands requiring confirmation (
confirmation: 'required', and all writes onmcp-admin) use the 2026-07-28input_requiredelicitation confirmation flow (see below); when the confirmation gate is not met,tools/callreturns JSON-RPC-32092(data.code: 'confirmation_unavailable'). - Throwing
CommandToolError(payload)from a command handler returns{ isError: true, content: [{ type: 'text', text: JSON.stringify(payload) }] }withoutstructuredContent.
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 whenenabledistrue; 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-delimitedacr_valuesreturned in RFC 9470 step-up challenges. Required whenenabledistrue; 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:
- Management scope (
claims.scopesincludesrequiredScope):- Failure: HTTP
403{ "error": "insufficient_scope" }withWWW-Authenticate: Bearer error="insufficient_scope", scope="<requiredScope>", resource_metadata="<admin-prm-url>".
- Failure: HTTP
- App RBAC admin role (live
RBAC_POLICY.rolesForUser(userId)intersectsadminRoleNames; token role claims are never read):- Failure: HTTP
403{ "error": "insufficient_role" }(withoutWWW-Authenticate).
- Failure: HTTP
- MFA &
auth_timefreshness (mfa === true,authTimeis an integer,authTime <= nowSeconds, andnowSeconds - authTime <= maxAuthAgeSecondswith no clock tolerance):- Failure: HTTP
401{ "error": "insufficient_user_authentication" }withWWW-Authenticate: Bearer error="insufficient_user_authentication", acr_values="<stepUpAcrValues>", max_age="<maxAuthAgeSeconds>", resource_metadata="<admin-prm-url>".
- Failure: HTTP
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:- Resource enabled check: Disabled or unconfigured resources return HTTP
404{"error":"not_found"}. - Host validation (
MCP_ALLOWED_HOSTNAMES): Fail closed when unset or unlisted (HTTP403). - Origin validation (
MCP_ALLOWED_ORIGINS): Requests without anOriginheader are allowed. When present,Originmust be a single validscheme://host[:port]URL matching an entry inMCP_ALLOWED_ORIGINS(empty string,null, multiple values, malformed URLs, or scheme/host/port mismatches return HTTP403{"error":"forbidden_origin"}). - Per-replica concurrency limit (
MCP_MAX_CONCURRENT_PER_SOURCE, default20): Tracked in memory per replica byreq.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 HTTP429withRetry-After: 1and{"error":"too_many_concurrent_requests"}. The effective cluster-wide concurrency limit isMCP_MAX_CONCURRENT_PER_SOURCE * replicas. - Pre-auth rate limit: Keyed by
req.ip+ normalized resource path. Quota exceeded returns HTTP429withRetry-Afterand{"error":"rate_limited"}. - HTTP method, request size, JSON object, and batch checks:
- Non-
POSTmethods (GET,DELETE, etc.) return HTTP405withAllow: POSTand{"error":"method_not_allowed"}. - A non-integer or oversized
Content-Length(> MCP_MAX_BODY_BYTES, default1048576) returns HTTP413{"error":"payload_too_large"}. A request withoutContent-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 sameMCP_MAX_BODY_BYTESvalue so oversized bodies are rejected before parsing. - Non-object JSON bodies return HTTP
400(-32600). JSON-RPC batch arrays return HTTP400with JSON-RPC error-32600afterpre-authquota has been charged.
- Non-
- M2M rejection, token verification, local admission, and admin checks: Unauthenticated callers receive HTTP
401(withWWW-Authenticate: Bearer resource_metadata="...") or403without protocol-layer details (except size and batch rejections in step 6). - Post-auth rate limit: Keyed by
issuer,actingUserId,clientId, andresource. - Protocol routing, version check, and method check:
- Modern
2026-07-28envelope (params._meta['io.modelcontextprotocol/protocolVersion']):subscriptions/listenreturns HTTP200application/jsonJSON-RPC-32601(never opens SSE); all other requests route to the modern statelesscreateMcpHandler(legacy: 'reject',responseMode: 'json',inputRequired: { legacyShim: false }). - Non-envelope
initialize:params.protocolVersionmust equal2025-11-25(older versions return HTTP400). - Non-envelope non-
initialize:MCP-Protocol-Versionheader must equal2025-11-25(missing or other values return HTTP400). Onlyinitialize,notifications/initialized,ping,tools/list, andtools/callare allowed; any other method (includingsubscriptions/listen) returns HTTP200application/jsonJSON-RPC-32601.
- Modern
- Handler execution: Never emits
Mcp-Session-Id. Both2026-07-28and2025-11-25allowreadcommands andconfirmation: 'exempt'writes on/mcp; confirmation-required writes (and all writes on/mcp/admin) are listed in2026-07-28tools/list, hidden in2025-11-25tools/list, and require the confirmation gate intools/call.
- Resource enabled check: Disabled or unconfigured resources return HTTP
- Public metadata (
/mcp/health,/.well-known/oauth-protected-resource/*): Rate-limited under the independentpublic-metabucket (keyed by client IP) so public metadata probes do not interfere with RPC quotas. - Cost weighting:
tools/callconsumesMCP_RATE_LIMIT_TOOLS_CALL_COST(default5), while other methods consumeMCP_RATE_LIMIT_DEFAULT_COST(default1). JSON-RPC batch arrays sum the cost of their items againstpre-auth. - Quota exceeded: Returns HTTP
429withRetry-After(integer seconds, at least1) and JSON body{"error":"rate_limited"}. - Backend unavailable (timeout > 1000 ms or DB failure): Returns HTTP
503with{"error":"rate_limiter_unavailable"}on/mcpand/mcp/adminwithout entering authentication or handlers. By architectural choice, PRM and/mcp/healthalso return HTTP503{"error":"rate_limiter_unavailable"}when the rate limiter throws. - IAM backend lookup failure: If
OIDC_IDENTITY_LOOKUP,IDENTITY_STORE, orRBAC_POLICYthrows during authentication, the server returns HTTP503with{"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:
- Protocol revision is
2026-07-28. - The current request declares
elicitation.forminparams._meta['io.modelcontextprotocol/clientCapabilities']. MCP_REQUEST_STATE_KEYis 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 returninginput_required, bindingoperationId,correlationId,issuer,subject,actingUserId,clientId,resource,toolName,schemaVersion,argsDigest, andexpiresAt.committed: Transitions only onacceptwithconfirm === trueafter acquiring the receipt lock (FOR UPDATE), re-checkingrequestState, tokenexp, adminauth_time, and Step 5 RBAC/user locks (authorizeWriteInTransaction), and executingcommand.handler(actor, input, tx)in the same transaction.declined/cancelled: Transitions on validdecline,cancel, orconfirm === falsewithout executing the handler.expired: Transitions lazily on resume ifexpiresAt <= now, and viaexpirePendingConfirmationReceipts(prisma, { now, logger, batchSize, retentionDays })scheduled periodically by the host App. Maintenance processespending → expiredin bounded batches (default500per batch, auditing only actual transitions) and prunes terminal receipts (committed,declined,cancelled,expired) older thanretentionDays(default7days) in bounded batches.- Retry / Replay: Retrying a
committedoperationIdfirst 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 returnsfalse, replay fails with-32602(data.code: 'tool_unavailable') without returning the stored result. - Otherwise, if the command declares
resourceAclReasonand has noauthorizeReplayhook, replay returns{ status: 'committed', correlationId }(both serialized incontent[0].textand asstructuredContent) without returning storedresultJson. - Commands without
resourceAclReason(or withauthorizeReplayreturningtrue) return the storedresultJsonwithout re-executingcommand.handler.
- If the command defines
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.
