Skip to main content

Build an MCP Server in Next.js from Scratch

A complete beginner's walkthrough: expose your Next.js app's data to Claude and ChatGPT with mcp-handler, Zod schemas, tools, prompts, and a real local test.

Mustafa Tawab

Mustafa Tawab

•17 min read
#MCP#Next.js#TypeScript#AI#Tutorial
Build an MCP Server in Next.js from Scratch

This is the stack I used for the MCP server behind this portfolio. By the end of this article you will have a working endpoint at /api/mcp that Claude and ChatGPT can connect to, with two tools and one prompt.

No prior MCP experience needed. You should know basic TypeScript and have used Next.js once.


What We're Building#

A small notes server with three capabilities:

Type Name What it does
Tool notes_search Find notes by keyword, with pagination
Tool notes_get Read one note by id
Prompt summarize_topic Tell the model to search, read, and summarize

Everything is read-only. That keeps the first version safe and easy to reason about.

Here is the shape:

code
Claude / ChatGPT
      │  JSON-RPC over HTTPS
      ▼
POST /api/mcp
      ▼
src/app/api/mcp/route.ts   ← the door
      ▼
src/lib/mcp/server.ts      ← the menu
      ▼
src/lib/mcp/tools/notes.ts ← the kitchen
      ▼
src/lib/notes.ts           ← your data

Prerequisites#

  • Node.js 20 or newer
  • A Next.js 15 project using the App Router
  • Basic TypeScript

If you need a fresh project:

bash
npx create-next-app@latest notes-mcp --typescript --app --eslint --tailwind --src-dir
cd notes-mcp

The --src-dir flag matters because the paths below assume a src/ folder.


Step 1 — Install the Packages#

bash
npm install mcp-handler@2 @modelcontextprotocol/server@2 zod

Three packages, three jobs:

Package Job
@modelcontextprotocol/server The official toolkit that speaks MCP
mcp-handler An adapter that plugs that toolkit into a Next.js route
zod Describes and validates tool arguments

Think of the SDK as a phone and mcp-handler as the charger that fits your wall socket.


Step 2 — Create the Route#

Create src/app/api/mcp/route.ts:

typescript
import { createMcpHandler } from "mcp-handler"
import { registerServer } from "@/lib/mcp/server"

export const runtime = "nodejs"
export const dynamic = "force-dynamic"
export const maxDuration = 60

const handler = createMcpHandler(registerServer, {
    serverInfo: {
        name: "notes-mcp",
        version: "1.0.0",
    },
    instructions: [
        "Read-only notes server.",
        "Use notes_search to find notes by keyword.",
        "Use notes_get to read one note by id.",
        "Never invent a note that a tool did not return.",
    ].join(" "),
})

export { handler as GET, handler as POST }

That is the entire endpoint.

What each export does:

  • runtime = "nodejs" — MCP needs Node APIs, so do not use the Edge runtime.
  • dynamic = "force-dynamic" — every request must run fresh. Do not cache it.
  • maxDuration = 60 — gives slow tool calls room to finish on Vercel.
  • GET and POST — POST carries the messages. GET exists for clients that open a stream.

A note on GET: in stateless mode, GET /api/mcp returns 405 Method Not Allowed. That is correct, not a bug.

createMcpHandler calls registerServer once per request. That is why the server is stateless and safe to scale.


Step 3 — Create the Server Factory#

Create src/lib/mcp/server.ts:

typescript
import type { McpServer } from "@modelcontextprotocol/server"
import { registerNoteTools } from "./tools/notes"
import { registerNotePrompts } from "./prompts"

/**
 * Called once per HTTP request by createMcpHandler.
 * Everything must be registered on the instance passed in.
 */
export function registerServer(server: McpServer) {
    registerNoteTools(server)
    registerNotePrompts(server)
}

Two rules that matter:

  1. Register everything inside this function. Never on a module-level server.
  2. Do not create the server yourself. createMcpHandler owns the lifecycle.

A shared server instance would work in a single-user test and fail under real traffic, because two requests would mutate the same object at once.


Step 4 — Add Some Data#

Create src/lib/notes.ts:

typescript
export interface Note {
    id: string
    title: string
    body: string
    tags: string[]
}

export const notes: Note[] = [
    {
        id: "docker-compose",
        title: "Docker Compose basics",
        body: "Compose defines services, networks, and volumes in one YAML file. Use it when you have more than one container.",
        tags: ["docker", "devops"],
    },
    {
        id: "nextjs-routing",
        title: "Next.js App Router",
        body: "Folders define routes. A page.tsx file makes a route public. A route.ts file handles HTTP methods directly.",
        tags: ["nextjs", "react"],
    },
    {
        id: "mcp-intro",
        title: "MCP in one sentence",
        body: "MCP is a standard menu that lets an AI order from your software without entering the kitchen.",
        tags: ["mcp", "ai"],
    },
]

In a real app this would come from a database, a CMS, or the filesystem. The MCP layer does not care where the data lives. It only cares about the shape you return.


Step 5 — Write Your First Tool#

Create src/lib/mcp/tools/notes.ts:

typescript
import type { McpServer } from "@modelcontextprotocol/server"
import { z } from "zod"
import { notes } from "@/lib/notes"

const READ_ONLY = {
    readOnlyHint: true,
    destructiveHint: false,
    idempotentHint: true,
    openWorldHint: false,
} as const

const NoteSchema = z.object({
    id: z.string(),
    title: z.string(),
    body: z.string(),
    tags: z.array(z.string()),
})

const NoteListOutput = z.object({
    total: z.number(),
    count: z.number(),
    offset: z.number(),
    has_more: z.boolean(),
    next_offset: z.number().optional(),
    notes: z.array(NoteSchema),
})

export function registerNoteTools(server: McpServer) {
    server.registerTool(
        "notes_search",
        {
            title: "Search notes",
            description: `Use this when the user asks what they wrote about a topic.
Searches titles, bodies, and tags. Returns one page of matches with ids.
Call notes_get with an id to read the full note.`,
            inputSchema: z.object({
                query: z
                    .string()
                    .min(1)
                    .max(200)
                    .describe("Keywords to match, e.g. 'docker compose'."),
                limit: z
                    .number()
                    .int()
                    .min(1)
                    .max(50)
                    .default(10)
                    .describe("Maximum number of notes to return."),
                offset: z
                    .number()
                    .int()
                    .min(0)
                    .default(0)
                    .describe("Number of matches to skip, for pagination."),
            }),
            outputSchema: NoteListOutput,
            annotations: READ_ONLY,
        },
        async ({ query, limit, offset }) => {
            const tokens = query
                .toLowerCase()
                .split(/\s+/)
                .filter((token) => token.length > 1)

            const matches = notes.filter((note) => {
                const haystack =
                    `${note.title} ${note.body} ${note.tags.join(" ")}`.toLowerCase()
                return tokens.some((token) => haystack.includes(token))
            })

            const page = matches.slice(offset, offset + limit)
            const nextOffset = offset + page.length
            const hasMore = nextOffset < matches.length

            const payload = NoteListOutput.parse({
                total: matches.length,
                count: page.length,
                offset,
                has_more: hasMore,
                ...(hasMore ? { next_offset: nextOffset } : {}),
                notes: page,
            })

            const text =
                payload.notes.length === 0
                    ? "No notes matched that query. Try fewer or different keywords."
                    : [
                          `# Notes`,
                          `Showing ${payload.count} of ${payload.total}.`,
                          ...payload.notes.map(
                              (note) =>
                                  `## ${note.title}\n${note.body}\n\nID: \`${note.id}\``
                          ),
                      ].join("\n\n")

            return {
                structuredContent: payload,
                content: [{ type: "text", text }],
            }
        }
    )

    server.registerTool(
        "notes_get",
        {
            title: "Get note",
            description: `Use this when you have a note id from notes_search and need the full text.
Call notes_search first if you do not know the id.`,
            inputSchema: z.object({
                id: z
                    .string()
                    .min(1)
                    .max(40)
                    .describe(
                        "Note id from notes_search, e.g. 'docker-compose'."
                    ),
            }),
            outputSchema: NoteSchema,
            annotations: READ_ONLY,
        },
        async ({ id }) => {
            const note = notes.find((entry) => entry.id === id)

            if (!note) {
                return {
                    isError: true,
                    content: [
                        {
                            type: "text",
                            text: `No note found for "${id}". Call notes_search to see valid ids.`,
                        },
                    ],
                }
            }

            const payload = NoteSchema.parse(note)

            return {
                structuredContent: payload,
                content: [
                    {
                        type: "text",
                        text: `# ${payload.title}\n\n${payload.body}\n\nTags: ${payload.tags.join(", ")}`,
                    },
                ],
            }
        }
    )
}

That is the core of the whole server. Everything else is wiring.


Step 6 — The Six Parts of a Tool#

Every tool has the same six pieces. Learn them once and you can read any MCP codebase.

Part What it is Why it matters
Name notes_search The model calls it by this exact string
Title "Search notes" A human-readable label for UIs
Description "Use this when..." The model chooses tools by reading this
Input schema z.object({...}) Defines and validates allowed arguments
Output schema NoteListOutput Describes the structured result
Annotations readOnlyHint: true Tells clients this tool is safe to run

The description is the most important field. The model cannot see your code. It sees only the name, description, and schema.

Compare:

code
❌ "Searches notes."
✅ "Use this when the user asks what they wrote about a topic. Searches titles,
    bodies, and tags. Returns one page of matches with ids. Call notes_get with
    an id to read the full note."

The second one tells the model when to use it and what to do next. That is what makes an agent feel competent.


Step 7 — Input Schemas and Validation#

Zod does three jobs at once:

  1. Describes the arguments to the client as JSON Schema.
  2. Validates arguments before your handler runs.
  3. Infers TypeScript types, so you do not annotate the handler.
typescript
inputSchema: z.object({
    query: z.string().min(1).max(200).describe("Keywords to match."),
    limit: z.number().int().min(1).max(50).default(10),
})

If the model sends { "limit": 999 }, the request is rejected before your code executes. The model receives a validation error it can read and correct.

Use .describe() on every argument. That text becomes the only documentation the model gets for that field.


Step 8 — Return Two Kinds of Answer#

Every tool returns content, and optionally structuredContent.

typescript
return {
    structuredContent: payload, // JSON for programs
    content: [
        { type: "text", text }, // Markdown for the model
    ],
}
  • content is what the model reads and quotes.
  • structuredContent is the same facts as JSON, for clients that want to render or process them.

Think of a receipt with a printed summary and a barcode: a human reads the summary, a machine scans the barcode.

If you declare an outputSchema, every successful result must include structuredContent that matches it. Build the payload by parsing through the schema:

typescript
const payload = NoteListOutput.parse({ ... })

That guarantees the JSON you advertise and the JSON you send cannot drift apart.


Step 9 — Add a Prompt#

Tools are buttons the model presses. Prompts are recipes the user picks.

Create src/lib/mcp/prompts.ts:

typescript
import type { McpServer } from "@modelcontextprotocol/server"
import { z } from "zod"

export function registerNotePrompts(server: McpServer) {
    server.registerPrompt(
        "summarize_topic",
        {
            title: "Summarize a topic",
            description:
                "Summarize what the user's notes say about a topic, with citations.",
            argsSchema: z.object({
                topic: z
                    .string()
                    .min(1)
                    .max(80)
                    .describe("Topic to summarize, e.g. 'docker'."),
            }),
        },
        async ({ topic }) => ({
            messages: [
                {
                    role: "user",
                    content: {
                        type: "text",
                        text: [
                            `Summarize what my notes say about ${topic}.`,
                            "Call notes_search first.",
                            "Then call notes_get for the two most relevant notes.",
                            "Use only facts returned by the tools. Do not invent notes.",
                            "Return three bullet points and list the note ids you used.",
                        ].join(" "),
                    },
                },
            ],
        })
    )
}

A prompt contains instructions, not facts. It tells the model which tools to call and how to format the answer. That keeps one source of truth: the data stays in the tools.


Step 10 — Run It#

bash
npm run dev

Watch the banner for the port:

code
- Local: http://localhost:3000

If port 3000 is busy, Next picks 3001. Use whatever it prints.

Test with curl#

First, the handshake. Note that initialize does not send an MCP-Protocol-Version header:

bash
curl -sN -X POST http://localhost:3000/api/mcp \
  -H 'content-type: application/json' \
  -H 'accept: application/json, text/event-stream' \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
      "protocolVersion": "2025-11-25",
      "capabilities": {},
      "clientInfo": { "name": "curl", "version": "0" }
    }
  }'

You should get a Server-Sent Events response:

code
event: message
data: {"result":{"protocolVersion":"2025-11-25","capabilities":{...},"serverInfo":{"name":"notes-mcp","version":"1.0.0"}}}

Then list the tools, this time with the negotiated header:

bash
curl -s -X POST http://localhost:3000/api/mcp \
  -H 'content-type: application/json' \
  -H 'accept: application/json, text/event-stream' \
  -H 'mcp-protocol-version: 2025-11-25' \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}'

Test with the Inspector#

The Inspector is the best way to click around:

bash
npx @modelcontextprotocol/inspector@latest

Open the URL it prints, then connect with:

Field Value
Transport Streamable HTTP
URL http://localhost:3000/api/mcp

You should see both tools. Call notes_search with {"query":"docker"} and check the result.

For a terminal-only check:

bash
npx @modelcontextprotocol/inspector@latest --cli \
  http://localhost:3000/api/mcp \
  --transport http \
  --method tools/list --strict

--cli must come before the URL.


Step 11 — Write a Smoke Test#

A smoke test catches wiring mistakes before a real client does. Save this as scripts/mcp-smoke.mjs:

javascript
const URL = process.env.MCP_URL ?? "http://localhost:3000/api/mcp"

async function rpc(method, params = {}, protocol) {
    const headers = {
        "content-type": "application/json",
        accept: "application/json, text/event-stream",
    }
    if (protocol) headers["mcp-protocol-version"] = protocol

    const response = await fetch(URL, {
        method: "POST",
        headers,
        body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
    })

    const text = await response.text()
    const data = text
        .split("\n")
        .filter((line) => line.startsWith("data:"))
        .map((line) => line.slice(5).trim())
        .join("\n")

    return JSON.parse(data || text).result
}

const init = await rpc("initialize", {
    protocolVersion: "2025-11-25",
    capabilities: {},
    clientInfo: { name: "smoke", version: "0" },
})

console.log("server:", init.serverInfo)

const { tools } = await rpc("tools/list", {}, init.protocolVersion)
console.log(
    "tools:",
    tools.map((tool) => tool.name)
)

const result = await rpc(
    "tools/call",
    { name: "notes_search", arguments: { query: "docker" } },
    init.protocolVersion
)
console.log("first result:", result.content[0].text.slice(0, 120))

Run it:

bash
node scripts/mcp-smoke.mjs

If it prints your server name and both tools, the wiring is correct.


Step 12 — Deploy to Vercel#

Push the branch and let Vercel build it. Then do three things.

1. Set the site URL#

code
NEXT_PUBLIC_SITE_URL=https://your-project.vercel.app

Use this for absolute URLs in tool results. Never hardcode localhost in a tool.

2. Include runtime files#

If your tools read files from disk, tell the bundler to include them:

typescript
// next.config.ts
const nextConfig = {
    outputFileTracingIncludes: {
        "/api/mcp": ["./content/blog/**/*"],
    },
}

Without this, the files exist in your repo but not in the deployed function bundle. The tool works locally and returns empty results in production.

3. Turn off Deployment Protection for /api/mcp#

Vercel's Deployment Protection puts a login wall in front of preview deployments. Claude and ChatGPT cannot log in, so the connector fails. Either disable protection or exclude /api/mcp.

Then verify from the outside:

bash
curl -s -o /dev/null -w '%{http_code}\n' \
  -X POST https://your-project.vercel.app/api/mcp \
  -H 'content-type: application/json' \
  -H 'accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'

200 is what you want.


Step 13 — Connect Claude and ChatGPT#

Claude: Settings → Connectors → Add custom connector. Paste the URL:

code
https://your-project.vercel.app/api/mcp

No trailing slash. Leave the OAuth fields blank. A trailing slash returns a redirect, and some clients treat that as a failed connection.

ChatGPT: chatgpt.com/plugins → + → Add custom MCP server. Same URL.

For ChatGPT's company-knowledge features, add two extra tools named exactly search and fetch. They have a strict contract, which is covered in the MCP docs and in the portfolio's own implementation.


Common Mistakes#

Symptom Likely cause Fix
405 on GET /api/mcp Stateless mode Expected. Use POST.
400 "headers and body disagree" Sent MCP-Protocol-Version on initialize Omit the header on the handshake
406 Not Acceptable Missing text/event-stream in Accept Send accept: application/json, text/event-stream
Tool works locally, empty in production Files not bundled Add outputFileTracingIncludes
Claude says "Couldn't register with sign-in service" Wrong URL or trailing slash Re-add with the exact URL, no /
Tools not showing up Server factory registers nothing Check registerServer calls each registrar
Type errors on registerTool @modelcontextprotocol/server v1 vs v2 Use v2 and zod v4

What You Just Built#

A read-only MCP server with:

  • a stateless Streamable HTTP endpoint at /api/mcp
  • two tools with validated inputs and structured outputs
  • pagination and actionable errors
  • one prompt that teaches the model a workflow
  • a smoke test and a deployment checklist

That is a real, shippable server. The portfolio version adds more tools, a blog reader, and a ChatGPT compatibility layer, but the skeleton is identical.

Next: build the same thing in Node.js with Express or in Python.

Tags:#MCP#Next.js#TypeScript#AI#Tutorial
Mustafa Tawab

Author

Mustafa Tawab

Software Engineer & Product Builder focused on scalable SaaS architectures, AI agents, and resilient cloud systems.

Chat on WhatsApp