Skip to main content
Glama
MCP Server Template

MCP Server Template

by hpartidas

MCP Server Template

A template for remote Model Context Protocol (MCP) servers. It serves MCP spec revision 2026-07-28 over Streamable HTTP with the official TypeScript SDK (@modelcontextprotocol/server 2.x), on NestJS 11 and Fastify, with Prisma 7 on Supabase Postgres and Zod-first tool schemas. Servers made from it expose tools that call external APIs and tools that read a database.

The founding decision is ADR-MCP-0001. Read it before changing anything under src/mcp/.

Stack

  • Runtime: Node.js 24 LTS

  • Protocol: MCP 2026-07-28, Streamable HTTP, @modelcontextprotocol/server 2.x (see ADR-MCP-0001)

  • Framework: NestJS 11.x on Fastify (the MCP endpoint is mounted directly on the Fastify instance, not Nest-routed)

  • Database: PostgreSQL (Supabase) with Prisma 7.x (pg driver adapter)

  • Auth: generic OAuth 2.1 / JWKS resource server for any issuer that publishes a JWKS and issues at+jwt access tokens (no identity-provider coupling)

  • Validation: Zod 4.x, passed directly as a tool's inputSchema/outputSchema to the SDK

  • Logging: structured JSON via nestjs-pino (request id, secret redaction)

  • Rate limiting: @nestjs/throttler, general routes globally, /mcp itself keyed by the caller's owner key (the socket address before the token verifies), counted before any scope check

  • Language: TypeScript 5.x (strict, CommonJS)

  • Testing: Jest 30.x with ts-jest, 100% coverage gate, CI-enforced, plus the official MCP conformance suite

Related MCP server: Remote MCP Server Template

Quick Start

Prerequisites

  • Node.js 24+

  • PostgreSQL (Supabase Postgres locally via Docker, or a real Supabase project)

Setup

# Create a new server from this template
gh repo create <owner>/<server-name> --template hpartidas/mcp-server-template-typescript --private --clone
cd <server-name>

# Install dependencies
npm install

# Copy environment file and fill in real values (see Configuration below)
cp .env.example .env

# One-time admin bootstrap per environment (ADR-MCP-0012), as the Supabase
# project's postgres role, BEFORE the first migration. service_schema is
# required — there is no placeholder default, so a run without it fails
# clearly instead of silently bootstrapping the wrong schema.
psql "$DATABASE_ADMIN_URL" -v ON_ERROR_STOP=1 -v service_schema=<service> -f prisma/bootstrap.sql

# Generate the Prisma client (also runs automatically on install)
npm run db:generate

# Apply database migrations
npm run db:migrate

# Start the development server
npm run dev

Call the server with a valid Bearer token (see Configuration for AUTH_ISSUER/AUTH_JWKS_URL):

curl -X POST http://localhost:3000/mcp \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

Using Docker

# Build and run everything (app + Postgres)
docker compose up -d

# View logs
docker compose logs -f app

docker-compose.yml and CI both run repository tests against supabase/postgres:17.6.1.165 (Docker Hub), the same Postgres image family Supabase runs in production, so EXPLAIN, extensions and role behavior match.

Migrations in production: run db:migrate:deploy as a dedicated release/CD step, not on container start, running it in every replica's entrypoint races on multi-instance deploys. The container only serves traffic.

Local development

npm run dev starts the whole stack with one command: the local Supabase Postgres container (docker compose up -d --wait db), the idempotent npm run db:setup (bootstrap, role passwords, migrations, safe to re-run, and completes a setup that stopped half way rather than skipping it), the local JWKS server for npm run dev:token tokens, and the server itself in watch mode as the <service>_app role. AUTH_ISSUER, AUTH_JWKS_URL and MCP_RESOURCE_URL are forced to the local development issuer so locally minted tokens verify; everything else is read from .env.local (git-ignored, never committed) if present.

Run npm run dev -- --real-auth to keep a real authorization server's settings (AUTH_ISSUER, AUTH_JWKS_URL, MCP_RESOURCE_URL, AUTH_TENANT_CLAIM) from .env.local or the shell instead of forcing the local issuer, useful for testing a real client's sign-in flow against the local stack. This mode does not start the local JWKS server, so npm run dev:token tokens will not verify against it (run npm run dev:jwks yourself if you need both at once).

Naming rule for a server built from this template: if you want a one-word command for --real-auth mode, add your own dev:<provider> script named after your authorization provider (for example dev:auth0), never after the technology, that runs node scripts/dev.mjs --real-auth, optionally with your own provider defaults layered into .env.local first. The template itself ships no such script: it has no fixed provider to name one after.

npm run db:setup runs prisma/bootstrap.sql as the local admin against the compose db service's postgres database (not app, the image's postgres role owns postgres and cannot create schemas in a compose-provisioned one), sets local passwords for the <service>_owner and <service>_app roles, then applies migrations as the owner role. The schema name comes from one value, SERVICE_SCHEMA (default mcp_example, matching prisma/bootstrap.sql's placeholder), rename both together for a real server. Setting DATABASE_ADMIN_URL (CI, or any other reachable Postgres) switches from docker compose exec db psql to a host psql against that URL instead.

npm run dev:token prints an access token for local use, signed with a key pair it generates on first run in .dev-keys/ (git-ignored, or DEV_KEYS_DIR when set). Flags: --sub (default dev-user), --scope (default: every scope this server declares, from TOOL_SCOPES/RESOURCE_SCOPES/PROMPT_SCOPES in src/mcp/tools/tool-scopes.ts), --tenant and --no-tenant (only meaningful once AUTH_TENANT_CLAIM is set, --tenant needs a claim name to attach its value to, and fails with a clear message if none is configured), and --ttl (seconds, default 3600). npm run dev:jwks serves the public key at http://127.0.0.1:3999/.well-known/jwks.json (DEV_JWKS_PORT to change the port) for the server to verify against; npm run dev starts this for you already. These tokens use the development issuer, which the server refuses in production.

Every git worktree of this repo shares one local database container: docker-compose.yml sets a fixed compose project name, so a second worktree's npm run dev reuses the same db container instead of failing to bind its port a second time (local data is then shared between worktrees, which is fine for development). The db service listens on host port ${LOCAL_DB_PORT:-54322}, Supabase's local CLI default, not 5432, so it does not collide with a system-wide Postgres; override LOCAL_DB_PORT if that is taken too.

Configuration

All variables are documented with safe example values in .env.example.

Variable

Purpose

NODE_ENV, PORT

Standard

HOST

Interface to bind (optional, default 127.0.0.1). The Dockerfile and docker-compose.yml set 0.0.0.0

DATABASE_URL

Pooled runtime connection (Prisma client)

DIRECT_DATABASE_URL

Direct connection, migrations only (prisma migrate)

DATABASE_POOL_MAX

Per-instance pool size. Optional in development/test (default 4); REQUIRED in production (ADR-MCP-0012 MCP-NFR-AVAIL-0002)

DATABASE_STATEMENT_TIMEOUT_MS

Per-query timeout, ms. Optional in development/test (default 30000); REQUIRED in production (same NFR)

MCP_ALLOWED_ORIGINS

Hostnames allowed on the Origin header for /mcp (comma-separated, no wildcard, ADR-MCP-0001 MCP-NFR-SEC-0001)

MCP_ALLOWED_HOSTS

Hostnames allowed on the Host header for /mcp (comma-separated, no wildcard)

MCP_RESOURCE_URL

This server's canonical URL, the required token audience (RFC 8707)

MCP_MAX_REQUEST_BODY_BYTES

Upper bound on a POST body (optional, default 4 MiB)

MCP_REQUEST_STATE_KEY

HMAC-SHA256 key for the MRTR requestState codec (>= 32 bytes, shared across every replica)

AUTH_ISSUER, AUTH_JWKS_URL

The authorization server: any issuer publishing a JWKS; both must be https in production

AUTH_REQUIRE_AT_JWT_TYP, AUTH_TYP_EXCEPTION_REASON, AUTH_TYP_EXCEPTION_ISSUER

The typ: at+jwt check is on by default. To accept an issuer that omits typ, set all three: false, a reason of at least 20 characters, and the issuer, which must equal AUTH_ISSUER

AUTH_TENANT_CLAIM

Optional. Name of the claim carrying the caller's organization. When set, tokens without a valid value get 403 not_linked

AUTH_REQUIRED_SCOPES

Endpoint-wide required scopes, comma-separated (optional; on top of each tool's own scope). Each must be <domain>:read or <domain>:write, or startup fails. A bare scope such as mcp no longer works

UPSTREAM_BASE_URL, UPSTREAM_API_KEY, UPSTREAM_TIMEOUT_MS

The example upstream client's own credential (never the caller's MCP token)

The MCP Endpoint

One endpoint, POST /mcp. GET/DELETE return 405. No session id is ever issued or read; the server is stateless (ADR-MCP-0001).

Tool catalog

Tool

Scope

Annotations

Purpose

widgets.get

widgets:read

readOnlyHint

Read one widget owned by the caller, by id

widgets.delete

widgets:write

destructiveHint, idempotentHint

Delete one widget owned by the caller, after MRTR confirmation

upstream.lookup

upstream:read

readOnlyHint

Query the example directory upstream service by a free-text query

Plus one resource (widgets://summary, a per-caller widget count, cacheScope: "private") and one prompt (widgets.explain, drafts a one-sentence explanation of a named widget).

Auth

The server is an OAuth 2.1 resource server: it verifies access tokens issued by AUTH_ISSUER/AUTH_JWKS_URL, and never issues tokens itself. The required audience is MCP_RESOURCE_URL. Caller identity comes only from the verified token (clientId, mapped from the JWT sub, falling back to client_id/azp), never from a tool argument. A missing or invalid token gets 401, including a token whose typ is not at+jwt; a token missing a required scope gets 403 insufficient_scope (<domain>:write also satisfies <domain>:read), and a request for a tool, resource URI, completion or prompt with no entry in src/mcp/tools/tool-scopes.ts, or for a method outside the protocol allow-list, gets the SDK's own not-found answer from a server that holds nothing, because the scope check runs at dispatch and denies by default; when AUTH_TENANT_CLAIM is set, a token without a valid tenant gets 403 not_linked. Token scopes outside the <domain>:read|write grammar are ignored. The caller's subject comes from the first of sub, client_id and azp in the token and must be 1 to 255 printable ASCII characters with no spaces, or the token gets 401. The caller's principal_kind is client when the token has no user (no sub, or sub equal to client_id or azp, the same rule as the actor_type log field) and user otherwise; rate limits, owner-scoped rows and requestState are keyed by <principal_kind>:<subject>, so a user token and a machine token with the same subject string are different callers. Upstream clients receive the caller as a VerifiedCaller, which only the auth module can build, and send its subject, principal kind and, when set, tenant as X-Caller-Subject, X-Caller-Kind and X-Caller-Tenant beside their own credential. Protected Resource Metadata (RFC 9728) is served at /.well-known/oauth-protected-resource and /.well-known/oauth-protected-resource/mcp.

Upgrading: owner key

This version stores and queries widget owners by owner key, <principal_kind>:<subject> (for example user:alice). The migration 20260930120000_rename_widget_owner_key renames the column ownerSub to ownerKey (and its index), then prefixes every existing value with legacy:. New owner keys always start with user: or client:, so no caller of the new code can reach a row stored before the upgrade, even one whose old subject was itself user:bob, until you map it.

Deploy order, with no rolling deploy: stop every instance running the old code (it queries ownerSub and fails once the migration has run), run npm run db:migrate:deploy, map the legacy rows, then start the new code.

To map the legacy rows, decide for each one whether a user token or a machine token (no sub, or sub equal to client_id, or sub equal to azp) wrote it. The database does not record this, so the migration does not guess. For rows you know were written by user tokens:

-- Run as the owner role; <service> is the schema in ?schema=<service>.
SET search_path TO "<service>";
UPDATE "Widget" SET "ownerKey" = 'user:' || substring("ownerKey" FROM 8)
  WHERE "ownerKey" LIKE 'legacy:%' /* AND the rows you identified */;

Use 'client:' for rows written by machine tokens. Rows left as legacy: stay unreachable.

To return to code released before this version, stop the new code and run the rollback script as the owner role, passing the schema:

psql "postgresql://<service>_owner:<password>@<host>:5432/postgres" \
  -v ON_ERROR_STOP=1 -v schema=<service> \
  -f prisma/rollback/20260930120000_rename_widget_owner_key.down.sql

The script sets search_path to that schema inside its transaction. It strips the one prefix each row carries, renames the column and index back, and removes the migration's row from _prisma_migrations. It is an operator script, not a Prisma migration; migrations stay forward-only (ADR-MCP-0012).

Destructive tools and MRTR

A destructive tool (widgets.delete) never acts on its first call. It returns input_required asking the caller to confirm; the client retries with the accepted inputResponses and the echoed requestState. requestState is HMAC-signed (MCP_REQUEST_STATE_KEY), bound to the caller and the originating method, and additionally carries the target resource id, so a confirmed retry cannot be redirected to a different resource by editing the tool arguments alone.

Project Structure

prisma/
└── schema.prisma                  Prisma schema (models, datasource, generator)
prisma.config.ts                   Prisma 7 config (DIRECT_DATABASE_URL for migrate)
src/
├── main.ts                        Bootstrap (Fastify adapter, global filter, listen)
├── app.module.ts                  Root module
├── common/                        AppError hierarchy + global exception filter
├── config/                        Global ConfigService + Zod schema (fail-fast)
├── prisma/                        Global Prisma module (shared client)
├── mcp/                           The MCP endpoint itself (ADR-MCP-0001)
│   ├── mcp.module.ts                  Mounts POST /mcp on the Fastify instance
│   ├── mcp-server.factory.ts           Builds one McpServer per request, fixed registration order
│   ├── request-state.provider.ts       The MRTR requestState HMAC codec
│   ├── origin-host-hooks.ts            Origin/Host validation (route-scoped to /mcp)
│   ├── auth/                           JWKS verifier and VerifiedCaller, scope grammar, the combined auth+tenant+rate-limit guard, Protected Resource Metadata
│   ├── tools/<domain>/<domain>-<verb>.tool.ts   One tool per file
│   ├── resources/                      One resource per file
│   └── prompts/                        One prompt per file
├── upstream/upstream-http.client.ts   Shared HTTP class: call.start at info, call.end at info, warn or error by outcome (ADR-MCP-0011 A1)
├── upstream/<name>/<name>.client.ts    One client per external API, its own credential; takes the VerifiedCaller
└── modules/                       Feature modules (service + repository + model; no controller)
    ├── health/                        Liveness/readiness probes (unauthenticated)
    └── widgets/                       ★ Normative example feature module

The widgets module is the normative example of the per-feature convention: copy its shape (and its tool files under src/mcp/tools/widgets/) for a real feature, then delete both once your server has its own. See ADR-MCP-0003 and .ai/standards/typescript/architecture.md.

Available Scripts

Script

Description

npm run dev

Start the whole local stack: database, db:setup, local JWKS server, server in watch mode (see Local development)

npm run dev -- --real-auth

Same stack, but keep a real authorization server's settings from .env.local instead of forcing the local dev issuer

npm run dev:server

Start just the server with hot reload (nest start --watch), no database or JWKS wiring

npm run db:setup

Bootstrap the local schema and roles, then apply migrations (idempotent; also works with DATABASE_ADMIN_URL for CI)

npm run dev:token

Print a local access token signed with the key pair in .dev-keys/

npm run dev:jwks

Serve the local JWKS used to verify dev:token tokens

npm run build

Build for production (nest build)

npm start

Start production server (node dist/main.js)

npm run lint

Run ESLint

npm run format:check

Check formatting without writing

npm run type-check

Run TypeScript type checking

npm run validate

Run lint + format:check + type-check

npm test

Run Jest unit and e2e specs (mocked repository, no database)

npm run test:coverage

Run tests with coverage, enforces the 100% gate

npm run test:integration

Run *.integration.spec.ts against a real database (needs DATABASE_URL/DIRECT_DATABASE_URL pointed at a running Postgres)

npm run conformance

Run the official MCP conformance suite against the auth proxy on 127.0.0.1:3100 (see Conformance suite)

npm run conformance:fixture-server

Start the real chassis with the conformance suite's reference fixtures registered, via ts-node (never built)

npm run db:generate

Generate the Prisma client from prisma/schema.prisma

npm run db:migrate

Create and apply a migration in development

npm run db:migrate:deploy

Apply pending migrations (CI / production)

Testing

jest.config.ts enforces 100% statements/branches/functions/lines over src/, and CI runs the suite with coverage. Tests are split two ways:

  • Unit specs (src/**/*.spec.ts): mock at the layer boundary (a mocked repository for a service, a mocked service for a tool). Fill in branches an end-to-end call can't reach (defensive checks, non-Error rejections, a network timeout).

  • End-to-end specs (test/mcp/**/*.spec.ts): the real @modelcontextprotocol/client, over StreamableHTTPClientTransport, routed through Fastify's .inject() (test/mcp/support/inject-fetch.ts), no socket, no mocked SDK. These drive the real McpModule (Origin/Host hooks, McpHttpGuard, createMcpHandler) exactly as a real client would.

  • Repository integration specs (src/**/*.integration.spec.ts): a real Postgres (supabase/postgres:17.6.1.165), migrations applied, no mocked Prisma. Excluded from the default npm test/coverage run; run explicitly with npm run test:integration against docker-compose.yml's db service or CI's service container.

Every test that proves an ADR-MCP-0001 requirement is tagged with its ID in the test name, for example it('rejects a disallowed Origin ... [MCP-NFR-SEC-0001]'), so grep -rn "\[MCP-" test/ src/ maps every requirement to its tests.

Conformance suite

CI runs the official MCP conformance suite (@modelcontextprotocol/conformance, 0.2.0-alpha.11) for real against the chassis, through two pieces that exist only for this job (ADR-MCP-0001 Amendment A3):

  • A conformance fixture server (test/conformance/fixture-server.ts, run with ts-node, never built): the real AppModule/McpModule/auth guard/ScopedRegistrar, with the suite's reference "everything"-server fixtures (test_simple_text, etc.) registered alongside the template's own tools. tsconfig.build.json excludes test/ outright, so dist/main.js never carries these fixtures (test/conformance/fixture-isolation.spec.ts proves it).

  • An auth proxy (scripts/conformance-auth-proxy.mjs): the conformance CLI has no flag to attach a bearer token, and this server requires Authorization: Bearer <token> on every POST /mcp. The proxy sits in front of the fixture server and injects the one header, forwarding everything else (including Host/Origin) unchanged.

The server's own auth stays on throughout. Run it locally the same way CI does, in four terminals (or background each step):

# 1. Local JWKS server for the dev issuer
npm run dev:jwks

# 2. The conformance fixture server (real chassis + reference fixtures)
NODE_ENV=test PORT=3000 \
  MCP_ALLOWED_ORIGINS=localhost,127.0.0.1 MCP_ALLOWED_HOSTS=localhost,127.0.0.1 \
  MCP_RESOURCE_URL=http://localhost:3000/mcp \
  MCP_REQUEST_STATE_KEY=ci-conformance-request-state-hmac-key-32-bytes-min \
  AUTH_ISSUER=https://dev-issuer.example.test \
  AUTH_JWKS_URL=http://127.0.0.1:3999/.well-known/jwks.json \
  npm run conformance:fixture-server

# 3. Mint a token and start the auth proxy in front of it
TOKEN=$(AUTH_ISSUER=https://dev-issuer.example.test MCP_RESOURCE_URL=http://localhost:3000/mcp \
  npm run -s dev:token -- --sub ci-conformance \
  --scope "widgets:read widgets:write upstream:read conformance:read")
CONFORMANCE_AUTH_TOKEN="$TOKEN" node scripts/conformance-auth-proxy.mjs

# 4. Run the suite (targets the proxy on :3100, see package.json)
npm run conformance

All 20 active-suite scenarios pass this way (verified locally 2026-10-06, 40/40 checks).

Architecture

Feature modules follow ADR-MCP-0003's vertical, module-based convention: Service → Repository → Model, colocated under src/modules/<feature>/. There is no Controller layer for MCP-only features; src/mcp/tools/<domain>/ plays that role (ADR-MCP-0001), calling the feature's service the same way a controller would.

POST /mcp → Origin/Host validation (route-scoped, ADR-MCP-0001 MCP-NFR-SEC-0001)
          → McpHttpGuard (Bearer verification, per-caller rate limit, tenant gate when AUTH_TENANT_CLAIM is set, dispatch scope check)
          → createMcpHandler (SDK: JSON-RPC, headers, MRTR, server/discover)
          → McpServerFactory.create() (fresh McpServer per request)
          → tool/resource/prompt handler → Service → Repository
          → structuredContent + text block

Two hard rules, unchanged from the service-template ancestor:

  1. Services never import PrismaService. All data access goes through the feature's repository, which extends BaseRepository and queries only inside logged_db_call. eslint.config.mjs blocks the listed forms of importing it elsewhere. The readiness probe pings the database through PrismaHealthCheck (src/prisma/prisma-health.check.ts), the one consumer of PrismaService outside the repositories (ADR-MCP-0003 Amendment A1). The ping and PrismaService's $connect/$disconnect log no call lines (CLAUDE.md § Database).

  2. A tool never reads identity from its arguments or _meta. The caller is ctx.http.authInfo, from the verified token, always.

Error Handling

Throw domain errors from services:

import { NotFoundError } from '@/common/exceptions';

if (!widget) {
  throw new NotFoundError('Widget', id);
}

A tool catches its own service errors and maps them to a safe isError result (never a stack trace, SQL detail, or upstream body). AllExceptionsFilter still covers the health and well-known routes, the only remaining Nest-routed surfaces.

ADRs

Architectural Decision Records live in .ai/decisions/. Founding set:

CI

All workflows are self-contained and run with the built-in GITHUB_TOKEN: CI (lint, type check, tests with the 100% coverage gate, repository integration tests, build, MCP conformance, npm audit), Semgrep (sast.yml), gitleaks (secret-scan.yml) and semantic-release (release.yml, tags and GitHub Releases only, no commit back to main).

Optional GitHub Actions secret: SNYK_TOKEN, enables the Snyk Agent Scan job against the running server's tool descriptions. The job is skipped when the secret is unset.

License

MIT

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      B
      maintenance
      A production-minded MCP server kit that provides OAuth 2.1/PKCE authentication, rate limiting, scope-gated tools, and two-phase confirmation for building secure MCP servers with custom tools, identity, and storage.
      16 npm
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables MCP clients to connect over stateless Streamable HTTP and authenticate through an existing OAuth 2.1 / OpenID Connect authorization server, with JWT validation, per-tool scope enforcement, and step-up challenges. It ships example scoped tools for reading and creating per-user notes that developers replace with their own.
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables wrapping a SaaS API as a hosted, stateless MCP server over Streamable HTTP, with OAuth 2.1 brokered login, CIMD/dynamic client registration, scope checks, and upstream tokens kept server-side. Write tools default to dry-run previews, read-only mode hides them entirely, every call is written to an audit log, and a built-in mock notes API lets the full flow run locally with no real account.
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables running a stateless Streamable HTTP MCP server on AWS Lambda behind API Gateway with JWT bearer authentication, per-scope tool allowlists, OAuth protected-resource metadata, and a CDK construct for deployment.
      MIT