AI8 min read
Build an MCP Server in Next.js with TypeScript (SDK v2)
Build an MCP server in a Next.js route handler with TypeScript: MCP SDK v2, mcp-handler, a zod-typed search tool, MCP Inspector testing and bearer-token auth.
To build an MCP server in a Next.js app, install mcp-handler, @modelcontextprotocol/server (v2 of the official TypeScript SDK) and zod, then create app/api/mcp/route.ts. Inside createMcpHandler, register tools with server.registerTool(name, config, handler) using a z.object(...) input schema, and export the handler as GET and POST. Any MCP client that speaks Streamable HTTP can then call your tools at /api/mcp.
Most tutorials you will find still use the v1 package @modelcontextprotocol/sdk and server.tool(...). The SDK moved to v2 and the code looks different now, so here is a working example built against the current packages.
Key takeaways
- The Model Context Protocol (MCP) lets AI apps like Claude, ChatGPT, Cursor or VS Code call tools and read data from your server through one standard interface.
- Use
@modelcontextprotocol/server2.x for new servers. It implements the 2026-07-28 MCP spec and replaces@modelcontextprotocol/sdk1.x. - In Next.js, Vercel's
mcp-handler2.x wraps the SDK into a Web-standard(Request) => Responsehandler you can drop into a route. - Tool inputs are a full zod schema (
z.object({...})). The raw-shape form is deprecated, and the variadicserver.tool()call is gone inmcp-handler2.x. - Test with the MCP Inspector before connecting a real client, and put
withMcpAuthin front of anything that is not public and read-only.
What MCP is, briefly
MCP is an open protocol built on JSON-RPC. A host (an AI app) runs a client that connects to your server, and your server offers three kinds of things: tools the model can call, resources it can read, and prompts users can pick. The spec defines two standard transports: stdio for local processes, and Streamable HTTP, where "each message is an HTTP POST to a single MCP endpoint" (transports spec).
The 2026-07-28 revision made the base protocol stateless: requests are self-contained and capabilities are negotiated per request. That matters for serverless hosting, because you no longer need sticky sessions or Redis to keep an MCP connection alive.
Support is broad. When Anthropic moved MCP to the Agentic AI Foundation under the Linux Foundation in December 2025, it noted that MCP had been adopted by ChatGPT, Cursor, Gemini, Microsoft Copilot and Visual Studio Code (Anthropic announcement).
Which packages to install
I checked npm on 2026-11-18. The current versions are:
| Package | Version | Role |
|---|---|---|
@modelcontextprotocol/server |
2.4.0 | Official TypeScript server SDK, v2 |
mcp-handler |
2.4.0 | Vercel's adapter that turns the SDK into a route handler |
zod |
4.x | Tool input and output schemas |
@modelcontextprotocol/sdk |
1.32.2 | The v1 single package, only for existing servers |
mcp-handler 2.x needs the v2 SDK, zod 4.2 or newer, and Node.js 20+. If older posts import @vercel/mcp-adapter, that is the earlier package name for this adapter; its npm description still reads "Vercel MCP Adapter".
npm install mcp-handler@^2 @modelcontextprotocol/server@^2 zod@^4The SDK README also notes that TypeScript 6 no longer auto-includes @types/*, so add "types": ["node"] to compilerOptions if the compiler complains about Buffer.
Example: a "search blog posts" tool
Here is a small, real use case: let an AI assistant search the posts on a Next.js blog and get back titles and URLs. First, a plain data function. In a real app this would query your CMS or database.
// lib/posts.ts
export type Post = {
slug: string
title: string
description: string
tags: string[]
}
const posts: Post[] = [
{
slug: 'nextjs-caching-explained',
title: 'Next.js Caching Explained',
description: "use cache, cacheLife, cacheTag and revalidateTag in Next.js 16.",
tags: ['nextjs', 'caching'],
},
// ...more posts, or load them from your CMS
]
export function searchPosts(query: string, limit: number): Post[] {
const q = query.toLowerCase()
return posts
.filter((p) =>
[p.title, p.description, ...p.tags].join(' ').toLowerCase().includes(q),
)
.slice(0, limit)
}Now the MCP route. This follows the registerTool shape from the SDK v2 tools guide and the mcp-handler README.
// app/api/mcp/route.ts
import { createMcpHandler } from 'mcp-handler'
import { z } from 'zod'
import { searchPosts } from '@/lib/posts'
const SITE_URL = 'https://example.com'
const handler = createMcpHandler(
(server) => {
server.registerTool(
'search_posts',
{
title: 'Search blog posts',
description:
'Search published blog posts by keyword. Returns each match with its title, URL and summary.',
inputSchema: z.object({
query: z.string().min(2).describe('Words to find in titles, summaries and tags'),
limit: z.number().int().min(1).max(10).default(5),
}),
outputSchema: z.object({
results: z.array(
z.object({ title: z.string(), url: z.string(), description: z.string() }),
),
}),
annotations: { readOnlyHint: true },
},
async ({ query, limit }) => {
const results = searchPosts(query, limit).map((p) => ({
title: p.title,
url: `${SITE_URL}/blog/${p.slug}/`,
description: p.description,
}))
return {
content: [
{
type: 'text',
text: results.length
? results.map((r) => `${r.title}\n${r.url}`).join('\n\n')
: `No posts match "${query}".`,
},
],
structuredContent: { results },
}
},
)
},
{ serverInfo: { name: 'blog', version: '1.0.0' } },
)
export { handler as GET, handler as POST }A few details worth knowing:
inputSchemais a fullz.object. The SDK converts it to JSON Schema for clients, validates incoming arguments, and infers the handler's argument types. If the arguments fail validation, the client gets a tool result withisError: trueand your handler never runs.outputSchemaplusstructuredContentgives clients typed JSON alongside the text. The SDK validatesstructuredContentagainst the schema before it leaves the server.annotationslikereadOnlyHintare hints. The SDK docs say they do not change how the tool runs; clients use them to decide things like approval prompts.- The path is up to you.
mcp-handlerdoes not read the URL, so/api/mcpis only a convention.
Without mcp-handler
The v2 SDK ships its own createMcpHandler, which takes a factory that returns a fresh McpServer per request and gives you a fetch function (serving over HTTP). In a route handler that looks like this:
// app/api/mcp/route.ts (SDK only)
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server'
const mcp = createMcpHandler(() => {
const server = new McpServer({ name: 'blog', version: '1.0.0' })
// server.registerTool('search_posts', ...) exactly as above
return server
})
export const GET = (req: Request) => mcp.fetch(req)
export const POST = (req: Request) => mcp.fetch(req)In Next.js I would still pick mcp-handler, because it adds the auth helpers below and OpenTelemetry spans that Vercel's MCP observability reads.
Test it with the MCP Inspector
Start npm run dev, then in a second terminal:
npx @modelcontextprotocol/inspector@latestFollowing Vercel's guide:
- Open
http://127.0.0.1:6274. - Choose Streamable HTTP and enter
http://localhost:3000/api/mcp. - Under Configuration, paste the proxy session token printed in the inspector's terminal.
- Click Connect, then List Tools, pick
search_postsand run it with a query.
For quick checks in a script or CI, the inspector has a CLI mode. Because the URL ends in /mcp, it infers the transport (CLI docs):
npx @modelcontextprotocol/inspector --cli http://localhost:3000/api/mcp --method tools/list
npx @modelcontextprotocol/inspector --cli http://localhost:3000/api/mcp \
--method tools/call --tool-name search_posts --tool-arg query=cachingOne warning from the inspector's own README: the session token is embedded in the page, so it is not real access control. Keep the inspector on localhost.
Connect a real client
Once it is deployed, give clients the full URL. In Claude Code (docs):
claude mcp add --transport http blog https://example.com/api/mcpIn Cursor, add it to .cursor/mcp.json:
{
"mcpServers": {
"blog": { "url": "https://example.com/api/mcp" }
}
}If you are building your own chat UI, the AI SDK can consume the same server with createMCPClient from @ai-sdk/mcp, which plugs into the streaming setup from my Next.js AI chatbot guide.
Auth and security
The SDK is explicit about this: its HTTP handler "trusts its caller" and validates no Host header, no Origin header and no token. Whatever sits in front of it has to do that work.
For a Next.js route, mcp-handler provides withMcpAuth. This is the pattern from Vercel's docs, with a static token for local testing:
// app/api/mcp/route.ts (with auth)
import type { AuthInfo } from '@modelcontextprotocol/server'
import { createMcpHandler, withMcpAuth } from 'mcp-handler'
const handler = createMcpHandler((server) => {
// registerTool calls from above
})
const verifyToken = async (
_req: Request,
bearerToken?: string,
): Promise<AuthInfo | undefined> => {
if (!bearerToken || bearerToken !== process.env.MCP_DEMO_TOKEN) return undefined
return { token: bearerToken, scopes: ['read:posts'], clientId: 'demo-client' }
}
const authHandler = withMcpAuth(handler, verifyToken, {
required: true,
requiredScopes: ['read:posts'],
resourceMetadataPath: '/.well-known/oauth-protected-resource',
})
export { authHandler as GET, authHandler as POST }Requests without a valid token get a 401, and tokens missing a required scope get a 403. Tool handlers can read the verified identity from ctx.http?.authInfo. For production, swap the comparison for real verification against your authorization server (issuer, audience, expiry, scopes) and serve the OAuth metadata from app/.well-known/oauth-protected-resource/route.ts with protectedResourceHandler. The 2026-07-28 spec moved client registration toward Client ID Metadata Documents; that is your authorization server's job, not the route's.
The rest is common sense, backed by the spec's security principles:
- Start read-only. The spec calls tools "arbitrary code execution". A search tool is low risk; a "delete post" tool needs auth, scopes and a human approval step.
- Treat everything the model sends as untrusted. Zod validation helps, but still check ownership on every database call.
- Treat what you return as data, not instructions. If a tool returns user-generated content, that content can contain prompt injection aimed at the model reading it.
- Rate limit the route. Vercel suggests a WAF rate limiting rule for the MCP path, and Deployment Protection for previews.
- Never put secrets in tool output or descriptions. Models repeat what they see.
If you generate MCP code with an assistant, apply the checklist from my AI coding assistant workflow: check every API against the installed versions, because most examples online still show v1. And if you need AI without any server at all, the opposite approach is to run a local LLM in the browser.
FAQ
Which npm package do I use to build an MCP server in TypeScript?
For new servers, use @modelcontextprotocol/server, which is v2 of the official TypeScript SDK and implements the 2026-07-28 spec. It replaces the single @modelcontextprotocol/sdk package from v1. In a Next.js app, add mcp-handler on top to get a route handler.
Do I still need Redis or SSE endpoints for an MCP server on Vercel?
No. mcp-handler 2.x removed the old HTTP+SSE transport and the Redis configuration. It serves the stateless 2026-07-28 protocol and falls back to stateless Streamable HTTP for 2025-era clients from the same route.
How do I define tool inputs with zod in MCP SDK v2?
Pass a full schema such as z.object({ query: z.string() }) as inputSchema in registerTool. The raw shape form, a plain object of zod fields, is deprecated in v2. The SDK turns the schema into JSON Schema for clients and validates arguments before your handler runs.
How do I test an MCP server locally?
Run your Next.js dev server, then run npx @modelcontextprotocol/inspector. Open the web UI on port 6274, choose Streamable HTTP, enter http://localhost:3000/api/mcp, paste the session token from the terminal and connect. The inspector also has a --cli mode for scripted checks.
Is a public MCP server safe without authentication?
Only if every tool is read-only and returns public data. The SDK's HTTP handler validates no token on its own. Wrap the route with withMcpAuth from mcp-handler, verify tokens properly, and add rate limiting before you expose anything private or anything that writes data.
Wrapping up
An MCP server in Next.js is now one route file: createMcpHandler from mcp-handler, tools registered with registerTool and a z.object schema, exported as GET and POST. Test it with the MCP Inspector, add withMcpAuth before anything private goes live, and keep tools small and read-only until you have a reason not to. The SDK v2 docs and the mcp-handler repo are the references to check, because this ecosystem moves fast.
- #ai
- #mcp
- #nextjs
- #typescript
- #ai-sdk
Keep reading
AI7 min read
Build an AI Chatbot in Next.js with Streaming (AI SDK 7)
Build an AI chatbot in Next.js with streaming responses using AI SDK 7: a streamText route handler, useChat on the client, tools, persistence, any provider.
Read articleAI7 min read
Remove Background From Image Free, Without Uploading
Remove the background from a photo for free in your browser: how AI cutouts work, PNG vs JPG, clean edges on hair and products, and keeping your photos private.
Read articleAI8 min read
AI Coding Assistants for React Developers: A Workflow
A practical AI coding assistant workflow for React developers: how to prompt, review AI-generated code, test it, and where AI helps or quietly hurts.
Read article