MCPAINEXT.JS 16

Build an MCP server so Claude can use your app's data

Give Claude, Cursor or any AI assistant tools that read and write your own app's data, served from a Next.js route with the official MCP SDK and locked behind a token. You'll call it from a script first, then connect Claude Code to it. Every file is shown in full, and every step was run on a fresh project before this was published.

Ali Murtaza · 11 min read

Tested step by step on with Next.js 16.4.6, the MCP TypeScript SDK 1.32.2 and Claude Code 2.1.330 (Claude Code)

By the end of this guide your Next.js app will have an MCP server at /api/mcp with three tools: search your notes, read one note, and add a note. You'll call those tools from a small script to see exactly what an AI assistant sees, and then connect Claude Code to them so you can ask, in plain English, “what did I write about invoices?” and get an answer from your own data.

MCP, the Model Context Protocol, is the standard way to give an AI assistant tools. You describe each tool once (its name, what it does, what it takes) and any assistant that speaks MCP can use it: Claude Code, Claude Desktop, Cursor, VS Code. The assistant reads your descriptions, decides when a tool helps, and calls it. Your server does the real work and answers.

Every file is shown whole, so you can copy it as it is. The guide was run from start to finish on a fresh create-next-app project and on a fresh shadcn init project, with Next.js 16.4, the MCP TypeScript SDK 1.32, Zod 4.6 and Claude Code.

Before you start

  • Node.js 20.9 or newer. Check with node -v.
  • A Next.js 16 app. A new one is fine: npx create-next-app@latest my-app --yes.
  • Claude Code, for the last step only. Everything before it works without it.

Run every command from your project’s folder, the one with package.json in it.

1. Install the SDK

The official TypeScript SDK does the protocol for you: the handshake, listing tools, checking inputs, formatting answers. Zod describes what each tool takes.

Terminalbash
npm install @modelcontextprotocol/sdk zod

2. The data your tools will use

An MCP tool is just a function your server runs, so it can read anything your app can: a database, an API, files. To keep this guide about MCP, the notes live in memory in one small module. Create lib/notes.ts:

lib/notes.tsts
export type Note = { id: number title: string body: string createdAt: string}// In memory, so it resets when the server restarts. In a real app these// functions would read and write your database instead.const notes: Note[] = [ { id: 1, title: "Invoice template", body: "Net 30, late fee after 30 days, bank details at the bottom.", createdAt: "2026-11-02", }, { id: 2, title: "Client call: Studio Nord", body: "They want monthly invoices instead of one per project.", createdAt: "2026-11-10", }, { id: 3, title: "Ideas for December", body: "A year-end summary email for every client.", createdAt: "2026-11-18", },]export function searchNotes(query: string): Note[] { const words = query.toLowerCase().split(/\s+/).filter(Boolean) return notes .filter((n) => { const text = `${n.title} ${n.body}`.toLowerCase() return words.every((w) => text.includes(w)) }) .sort((a, b) => b.createdAt.localeCompare(a.createdAt)) .slice(0, 10)}export function getNote(id: number): Note | undefined { return notes.find((n) => n.id === id)}export function addNote(title: string, body: string): Note { const note: Note = { id: Math.max(0, ...notes.map((n) => n.id)) + 1, title, body, createdAt: new Date().toISOString().slice(0, 10), } notes.push(note) return note}

3. Serve the tools from a route

Now the server itself. It’s one route handler. Each request builds a small MCP server with three tools, hands the request to the SDK’s transport, and returns the transport’s answer. Create app/api/mcp/route.ts:

app/api/mcp/route.tsts
import { timingSafeEqual } from "node:crypto"import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"import { z } from "zod"import { addNote, getNote, searchNotes } from "@/lib/notes"// A tool answers with text the assistant reads.const text = (value: string) => ({ content: [{ type: "text" as const, text: value }],})function buildServer() { const server = new McpServer({ name: "notes", version: "1.0.0" }) server.registerTool( "search_notes", { title: "Search notes", description: "Find notes whose title or body contains all the given words. Returns up to 10, newest first, as id, title and date.", inputSchema: { query: z.string().min(1).max(200) }, }, async ({ query }) => { const found = searchNotes(query) if (!found.length) return text("No notes match.") return text( found.map((n) => `#${n.id} ${n.title} (${n.createdAt})`).join("\n") ) } ) server.registerTool( "get_note", { title: "Read a note", description: "Read one note in full, by the id search_notes gives.", inputSchema: { id: z.number().int().positive() }, }, async ({ id }) => { const note = getNote(id) if (!note) return { ...text(`There is no note #${id}.`), isError: true } return text(`${note.title} (${note.createdAt})\n\n${note.body}`) } ) server.registerTool( "add_note", { title: "Add a note", description: "Save a new note with a short title and a body.", inputSchema: { title: z.string().min(1).max(120), body: z.string().max(5000), }, }, async ({ title, body }) => { const note = addNote(title, body) return text(`Saved note #${note.id}: ${note.title}`) } ) return server}// Only someone with the token may use the tools.function authorized(request: Request) { const expected = process.env.MCP_TOKEN if (!expected) return false const header = request.headers.get("authorization") ?? "" const given = header.replace(/^Bearer\s+/i, "") const a = Buffer.from(given) const b = Buffer.from(expected) return a.length === b.length && timingSafeEqual(a, b)}async function handle(request: Request) { if (!authorized(request)) { return Response.json( { error: "Missing or wrong token" }, { status: 401, headers: { "WWW-Authenticate": "Bearer" } } ) } const server = buildServer() const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true, }) await server.connect(transport) return transport.handleRequest(request)}export { handle as GET, handle as POST, handle as DELETE }

Here’s what each part does:

  • registerTool gives a tool its name, a title, a description and its inputs. The description is what the assistant reads to decide when to use the tool, so write it like you’d explain the tool to a new teammate: what it does and what it gives back.
  • inputSchema is a Zod shape. The SDK checks every call against it before your function runs, so query really is a string of 1 to 200 characters, and id really is a positive whole number. A call that doesn’t match never reaches your code.
  • isError: true tells the assistant the tool ran but couldn’t do what it asked, so it can try something else, like searching again.
  • WebStandardStreamableHTTPServerTransport speaks MCP over plain HTTP with web-standard Request and Response objects, which is exactly what a Next.js route handler has. sessionIdGenerator: undefined makes it stateless: every request stands alone, which is what serverless hosting needs. enableJsonResponse: true answers with plain JSON instead of opening a stream, which is all these quick tools need.
  • The last line uses the same function for GET, POST and DELETE, the three methods MCP clients send.

4. Protect it with a token

These tools read and write your data, so they must never be open to everyone. authorized compares the request’s Authorization: Bearer … header with a secret you choose, using timingSafeEqual so the comparison takes the same time whatever the guess. With no token set, every request is refused.

Make a long random token and save it in .env.local:

Terminalbash
echo "MCP_TOKEN=$(openssl rand -hex 32)" >> .env.local

.env.local is already in .gitignore, so the token never reaches your repository. Print it once, you’ll need it in step 6:

Terminalbash
grep MCP_TOKEN .env.local
On Windows without openssl, open .env.local in your editor and add a line MCP_TOKEN= followed by any long random string, at least 32 characters.

5. Call your tools from a script

Before you connect an assistant, see your server the way an assistant does. The SDK has a client too. Create scripts/try-mcp.mjs:

scripts/try-mcp.mjsjs
import { Client } from "@modelcontextprotocol/sdk/client/index.js"import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"const url = new URL("http://localhost:3000/api/mcp")const transport = new StreamableHTTPClientTransport(url, { requestInit: { headers: { Authorization: `Bearer ${process.env.MCP_TOKEN}` }, },})const client = new Client({ name: "try-mcp", version: "1.0.0" })await client.connect(transport)const { tools } = await client.listTools()console.log("Tools:", tools.map((t) => t.name).join(", "))const search = await client.callTool({ name: "search_notes", arguments: { query: "invoice" },})console.log("Search:", search.content[0].text)const added = await client.callTool({ name: "add_note", arguments: { title: "Call the accountant", body: "Ask about Q4." },})console.log("Add:", added.content[0].text)const bad = await client.callTool({ name: "get_note", arguments: { id: 99 } })console.log("Missing:", bad.content[0].text, bad.isError)await client.close()

Build the app and start it:

Terminalbash
npm run buildnpm run start

Leave it running. In a second terminal, in the same folder, run the script. --env-file hands it your token:

Terminalbash
node --env-file=.env.local scripts/try-mcp.mjs

You should see:

Outputtext
Tools: search_notes, get_note, add_noteSearch: #2 Client call: Studio Nord (2026-11-10)#1 Invoice template (2026-11-02)Add: Saved note #4: Call the accountantMissing: There is no note #99. true

That’s the whole conversation an assistant has with your server: it asks for the list of tools, then calls the ones it needs with the arguments it chose. Now check the lock. A request without the token gets nothing:

Terminalbash
curl -s -o /dev/null -w "%{http_code}\n" -X POST http://localhost:3000/api/mcp

It prints 401.

6. Connect Claude Code

With the app still running, add the server to Claude Code. Replace YOUR_TOKEN with the value from step 4:

Terminalbash
claude mcp add --transport http notes http://localhost:3000/api/mcp --header "Authorization: Bearer YOUR_TOKEN"

Then check that Claude Code can reach it:

Terminalbash
claude mcp list

The notes line ends with ✔ Connected. Start claude in any folder and ask something like “Search my notes for invoices and tell me what the template says.” Claude calls search_notes, then get_note with the id it found, and answers from your note. It asks your permission the first time it uses each tool.

claude mcp add stores the server in your own Claude Code settings for this folder, token included, not in your project. To remove it later, run claude mcp remove notes.

7. Put it online

The route is an ordinary Next.js route, so it deploys with the rest of your app. Two things to do when you do:

  • Set MCP_TOKEN on your host (on Vercel: Settings → Environment Variables), with a new random value. Never reuse your local one.
  • Swap the in-memory notes for your database. On a serverless host each request can land on a fresh copy of your app, so notes added in memory disappear. The Next.js 16 + Prisma 7 guide shows how to put them in Postgres; only lib/notes.ts changes.
  • Then point Claude Code at the new address: claude mcp add --transport http notes https://your-app.com/api/mcp --header "Authorization: Bearer …".

One token is right for tools only you use. If you want other people to connect their own assistants to their own data, each person needs their own access, which MCP does with OAuth sign-in. That’s a bigger job and its own guide.

If something goes wrong

  • 401 from the script. The token wasn’t sent or doesn’t match. Run the script with --env-file=.env.local, and restart npm run start after changing .env.local, because the server reads it once when it starts.
  • ECONNREFUSED from the script or ✘ Failed to connect in claude mcp list. The app isn’t running, or it’s on another port. Check the terminal running npm run start.
  • Cannot find module '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'. Your SDK is older than this guide. Run npm install @modelcontextprotocol/sdk@latest.
  • A tool call fails with “Invalid arguments”. The assistant sent something your Zod shape refuses, like text where you asked for a number. That’s the schema doing its job; make the description say clearly what each input is.
  • The note you added is gone. The notes are in memory and reset when the server restarts. That’s expected here; step 7 moves them to a database.

Questions people ask

What is an MCP server?

An MCP server is a program that offers tools to AI assistants through the Model Context Protocol. Each tool has a name, a description and typed inputs. An assistant like Claude Code reads the list, decides when a tool helps, and calls it, and the server runs your own code and sends the answer back.

Can I build an MCP server with Next.js?

Yes. The official MCP TypeScript SDK has a web-standard transport that takes a Request and returns a Response, which is exactly what a Next.js route handler works with. Build an McpServer, register your tools, connect the transport and return transport.handleRequest(request) from the route.

How do I secure an MCP server?

Never leave the endpoint open. Check an Authorization: Bearer token on every request, compare it with timingSafeEqual, and refuse everything when no token is set. Keep the token in an environment variable, and let Zod schemas check every tool input before your code runs.

Does an MCP server work with Cursor and Claude Desktop too?

Yes. MCP is a shared protocol, so the same server works with any client that supports remote servers over HTTP, including Claude Code, Claude Desktop, Cursor and VS Code. Each client has its own place to add the address and the Authorization header, but the server doesn’t change.

Where to go next

THE NEWSLETTER

Get the next guide in your inbox

One email when a new guide or free build is out, every step tested before it’s published. No spam, unsubscribe anytime.

Found this useful? Give it a heart, or share it with someone who’d use it.
WRITTEN BY
Ali Murtaza

I build SaaS products with Next.js and teach them start to finish, in full courses here and free builds on YouTube.

KEEP READING
FREE BUILDS ON THIS STACK