Back to blog
November 4, 2026•48 views

How to Build a Production MCP Server in Next.js: Auth, Tool Schemas, Observability, and Deployment

MCPNext.jsAI automationNode.jsDockerAWSTypeScript
How to Build a Production MCP Server in Next.js: Auth, Tool Schemas, Observability, and Deployment

Most MCP tutorials stop at the "hello world" tool. You spin up a route handler, expose a greet or add tool, connect Claude Desktop, watch it work once, and call it a day. That is fine for learning. It is nowhere near what you need when a real business depends on the thing.

I have built MCP servers that sit behind actual products, including the automation layer for a marketing platform I work on. The gap between the demo and something you can leave running is enormous, and it is almost entirely about four things: authentication, tool schema design, observability, and deployment topology. This guide is about closing that gap. If you are trying to run a production MCP server in Next.js, these are the decisions that will actually bite you.

First, the architecture decision nobody talks about

Before you write a line of auth code, decide where the MCP server lives. There are two real options, and they have very different operational profiles.

Embedded in your Next.js app. You expose an MCP endpoint at something like /api/mcp inside an existing Next.js project. Same deploy, same database, same env vars. Fast to build, easy to keep in sync with your app's data.

A separate long-running service. Your MCP server is its own Node process (or NestJS app), deployed independently, and your Next.js app talks to it or agents connect to it directly. More moving parts, but far more control over transport, timeouts, and scaling.

Here is how I actually think about the tradeoff:

Factor Embedded in Next.js Separate service
Time to first deploy Hours Days
Data access (Prisma/Postgres) Direct, trivial Needs shared DB or API calls
Transport support HTTP/SSE only, no stdio Full: stdio, SSE, streamable HTTP
Long-running tool calls Fights serverless timeouts No timeout ceiling
Scaling model Scales with web app Scale independently
Observability Mixed with web logs Clean, isolated telemetry
Best for Internal tools, light workloads Customer-facing, heavy or stateful tools

My rule of thumb: start embedded if the tools are read-mostly and fast (under a few seconds). Move to a separate service the moment you have a tool that streams, runs longer than your platform's timeout, or needs stdio. On Vercel specifically, a serverless function has a configurable execution ceiling (set via maxDuration, bounded by your plan), so any tool that calls a slow upstream API or processes a document can hit it. That is not a bug you can code around; it is a topology problem. See the Vercel Functions limits documentation for the current per-plan maximums.

For the rest of this article I will assume the embedded Next.js approach, because that is the harder one to get right and the one most people reach for first. I will flag where the separate-service model changes things. If you are still choosing a framework for an AI-enhanced app, my breakdown of Next.js vs Remix vs Astro for AI-enhanced web apps in 2026 covers the tradeoffs in more depth.

Authentication for your MCP server

MCP servers get connected to by agents, and agents are just clients with credentials. You need to treat your MCP endpoint exactly like any other authenticated API. There are three patterns I use, depending on who is connecting.

Pattern 1: API keys for trusted server-to-server clients

If you control both ends (your own agent, your own automation), a bearer token is enough. Keep keys in the database, hashed, with scopes and an expiry.

// lib/auth.ts
import { createHash, timingSafeEqual } from "crypto";
import { db } from "@/lib/db";

export async function authenticateRequest(req: Request) {
  const header = req.headers.get("authorization") ?? "";
  const token = header.replace(/^Bearer\s+/i, "");
  if (!token) return null;

  const hash = createHash("sha256").update(token).digest("hex");
  const key = await db.apiKey.findUnique({ where: { hash } });
  if (!key || key.revokedAt || key.expiresAt < new Date()) return null;

  return { clientId: key.clientId, scopes: key.scopes };
}

Store the hash, never the raw key. If you ever compare secrets directly in code, use timingSafeEqual to avoid timing side channels. And give keys scopes so a read-only integration cannot call your destructive tools.

Pattern 2: OAuth for third-party agents

When an outside agent (a hosted assistant, a marketplace app) connects on behalf of a user, you want OAuth 2.1 with PKCE, not a shared key. The MCP authorization spec has moved toward OAuth for exactly this reason; see the MCP authorization specification for the current requirements. In Next.js you can implement the authorization server endpoints as route handlers, or delegate to a provider. The important part is that the access token carries the user identity, so every tool call runs with the right permissions, not as an admin service account.

Pattern 3: Session tokens for browser-based clients

If your MCP endpoint is called from a web UI you own, reuse your existing session cookie, but add CSRF protection and origin checks. Do not let a cookie-authenticated endpoint accept cross-origin POSTs from anywhere.

Whichever pattern you pick, put the auth check in one place and call it at the top of every MCP request handler. I have seen servers where auth lived inside individual tools, and one forgotten tool was the whole breach. If you are connecting third-party tools, the lessons in Figma MCP access restrictions are a good reminder that access control is where integrations quietly fail.

Tool schema design that won't break your agents

The MCP tool schema is a contract. Get it wrong and the model will call your tool with garbage, or refuse to call it at all. Two things matter: precise input validation, and descriptions a model can actually reason about.

Validate everything with Zod

Never trust the arguments an agent sends. Define a Zod schema per tool and parse before you touch anything.

import { z } from "zod";

const createInvoiceSchema = z.object({
  customerId: z.string().uuid(),
  amount: z.number().positive().max(1_000_000),
  currency: z.enum(["USD", "BDT", "AUD", "CAD", "NZD"]),
  dueDate: z.string().datetime().optional(),
  notes: z.string().max(500).optional(),
});

type CreateInvoiceInput = z.infer<typeof createInvoiceSchema>;

Then in the tool handler, parse and return a structured error instead of throwing a raw exception:

const parsed = createInvoiceSchema.safeParse(args);
if (!parsed.success) {
  return {
    content: [{ type: "text", text: JSON.stringify({ error: "invalid_input", issues: parsed.error.issues }) }],
    isError: true,
  };
}

Returning the validation issues as text is important. The model reads that and can retry with corrected arguments. A thrown stack trace just breaks the loop.

Write descriptions for the model, not for yourself

The tool description and the parameter descriptions are part of your prompt. Be explicit about units, formats, and side effects. "amount in the smallest currency unit (e.g. cents)" saves you from a class of bugs where the model sends dollars and you store cents. Mention whether a tool is read-only, destructive, or idempotent. That is the difference between an agent that uses your tool safely and one that creates three duplicate invoices.

Version your schemas

When you change a tool's input shape, you break every agent that cached the old schema. Either add a new tool (create_invoice_v2) or accept both shapes during a deprecation window. I keep a small changelog in the repo and bump a TOOL_SCHEMA_VERSION constant so I can trace which contract a client is on.

Observability for MCP servers

This is where most tutorials go silent, and it is where production actually lives. An MCP server that fails silently is worse than no server, because the agent just hallucinates around the failure.

Structured logs on every tool call

Log the tool name, the client, a request id, duration, success/failure, and the validation outcome. Never log raw secrets or full PII payloads. A single JSON line per call is enough to reconstruct what happened.

async function withToolLogging<T>(name: string, clientId: string, fn: () => Promise<T>) {
  const start = performance.now();
  const requestId = crypto.randomUUID();
  try {
    const result = await fn();
    console.log(JSON.stringify({ level: "info", requestId, tool: name, clientId, ms: Math.round(performance.now() - start), ok: true }));
    return result;
  } catch (err) {
    console.error(JSON.stringify({ level: "error", requestId, tool: name, clientId, ms: Math.round(performance.now() - start), ok: false, message: (err as Error).message }));
    throw err;
  }
}

Metrics that tell you something

Track four numbers per tool: call count, error rate, p95 latency, and validation-failure rate. A rising validation-failure rate is your early warning that a model or client changed its behavior. Wire these into whatever you already run (CloudWatch, Grafana, Datadog). If you are on AWS, CloudWatch Embedded Metric Format lets you emit metrics straight from those log lines.

Traces across the tool boundary

When a tool calls three downstream services, a flat log line is not enough. Use OpenTelemetry and wrap each tool execution in a span, with child spans for DB and HTTP calls. Then a failing invoice creation shows you exactly which hop timed out.

Error handling that helps the agent recover

Distinguish between errors the agent can fix (bad input, missing field) and errors it cannot (upstream down, auth expired). For fixable errors, return structured, human-readable messages. For unfixable ones, return a clear isError with a short reason and let the agent decide to retry later or escalate. Do not leak internal stack traces or SQL to the model.

Deploying your MCP server with Docker

For a separate-service deployment, Docker is the cleanest path to consistency across environments. Here is a production-minded Dockerfile for a Node MCP server.

FROM node:22-alpine AS base
WORKDIR /app

FROM base AS deps
COPY package.json package-lock.json ./
RUN npm ci --omit=dev

FROM base AS build
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM base AS runner
ENV NODE_ENV=production
COPY --from=deps /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]

A few non-negotiables:

  • Run as a non-root user (the USER node line above).
  • Health check endpoint separate from the MCP route so your orchestrator can probe it.
  • Graceful shutdown: on SIGTERM, stop accepting new calls and let in-flight tools finish before exiting.
  • Config from environment only. No secrets baked into the image.

On AWS, I run these on ECS Fargate behind an ALB for most workloads. It gives you horizontal scaling, health checks, and clean log shipping to CloudWatch without managing servers. If you need stdio transport, it does not fit a container behind a load balancer, so that is a local or sidecar deployment instead. If you are standing up the surrounding infrastructure too, my guide to n8n AWS setup pitfalls covers the networking and IAM mistakes that trip people up.

If you stay on Vercel

Embedded MCP on Vercel works, with caveats. Keep every tool under the function timeout, avoid long streams, and set maxDuration deliberately. Use the edge runtime only if your tool does no database or Node-only work. The moment you need a tool that runs longer than your plan's function limit, move it to a container. I have watched teams fight Vercel timeouts for a week when the real fix was a separate service.

A production checklist

Before you point real agents at your server, walk this list:

Area Check
Auth Every route authenticated; keys hashed; scopes enforced
Input Zod schema per tool; validation errors returned as text
Descriptions Units, side effects, and read-only flags documented
Logging Structured JSON per call with request id and duration
Metrics Call count, error rate, p95 latency, validation failures
Traces OpenTelemetry spans across downstream calls
Errors Fixable vs fatal separated; no internal detail leaked
Rate limits Per-client limits to stop runaway loops
Secrets Env-only, rotated, never in images or logs
Deploy Non-root, health check, graceful shutdown, pinned versions
Versioning Tool schema version tracked and changelogged

Rate limiting deserves a special mention. An agent in a retry loop can hammer a tool hundreds of times a minute. A per-client token bucket in Redis, or even an in-memory limiter for a single instance, will save you from a surprise bill and a locked database.

Where this leaves you

A production MCP server in Next.js is not hard to build. It is hard to build so that it keeps working when an agent does something you did not expect at 2am. Auth at the edge, Zod at the boundary, structured logs and traces underneath, and a deployment topology that matches your tool's real runtime. Get those four right and the rest is iteration.

If you are wiring AI automation into a real product and want someone who has shipped this before, that is most of what I do. I build Next.js apps and MCP servers for founders and teams across Bangladesh, Australia, the USA, Canada and New Zealand, and I am happy to talk through your architecture before you commit to one. Reach out and tell me what your agents need to do.

Frequently asked questions

Can I run an MCP server on Vercel?

Yes, embedded in a Next.js app over HTTP. The main constraint is the serverless function timeout, so keep tools short and avoid long-running streams. Anything that needs to exceed your plan's maxDuration limit, or needs stdio transport, should run as a separate container instead.

How do I secure an MCP server?

Authenticate every request (API keys for server-to-server, OAuth with PKCE for third-party agents), validate all tool input with Zod before execution, enforce per-tool scopes, add per-client rate limits, and never log secrets or full PII. Treat the MCP endpoint exactly like any other public API.

Should the MCP server be part of my Next.js app or a separate service?

Embed it when tools are fast, read-mostly, and you want direct database access. Split it into its own service when you need stdio transport, long-running or streaming tools, independent scaling, or clean isolated telemetry. Many teams start embedded and refactor to a separate service once load grows.

What should I log for each MCP tool call?

The tool name, client id, a request id, duration, success or failure, and the validation outcome, as one structured JSON line. Add OpenTelemetry spans when a tool touches multiple downstream services so you can pinpoint which hop failed.

Share this post

Native Web Share is available on mobile, so that share sheet includes Instagram and any other app you have installed.

Let's Connect

Get In Touch

Let's build something premium together.

Contact info

Follow me
Chat on WhatsApp