Wonsuk Choi
← blog

How to Build an MCP Server in Next.js (and What Running One in Production Taught Me)

To build an MCP server: serve one endpoint over Streamable HTTP, register tools with typed schemas, then add auth and rate limits. Here is how mine is wired in Next.js.

To build an MCP server, expose one HTTP endpoint that speaks the Model Context Protocol, register each tool with a name, a plain-language description and a typed input schema, and put authentication and rate limits in front of it before anyone outside your team connects. In Next.js that is one route file, the open-source mcp-handler adapter, a Zod schema per tool, and a bearer-token check.

I run an MCP server like this in production for Expert Sapiens and Seoul Homes. Agents can search experts and property listings, and signed-in users can save listings or contact an expert. This post walks through how it is built, in the order I would do it again.

1. Pick the transport#

The MCP specification defines two standard transports: stdio, for a server that runs as a local process, and Streamable HTTP, for a server that lives at a URL (transports). The older HTTP+SSE transport was replaced by Streamable HTTP in protocol revision 2025-03-26, and newer revisions of the specification mark it deprecated.

If you want ChatGPT, Claude or Cursor to reach your server over the internet, use Streamable HTTP. My endpoint is https://expertsapiens.com/api/mcp. When I moved to mcp-handler 2, the old SSE paths went away and now answer 404. A client that only speaks stdio can still connect through the mcp-remote bridge:

{ "command": "npx", "args": ["-y", "mcp-remote", "https://expertsapiens.com/api/mcp"] }

2. One route file#

With the Next.js App Router, the server is a route handler. This is a simplified version of mine:

// app/api/mcp/route.ts
import { createMcpHandler } from "mcp-handler";
import { z } from "zod";

const handler = createMcpHandler((server) => {
  server.registerTool(
    "search_experts",
    {
      title: "Search Experts",
      description:
        "Search verified experts by keyword, category, country or language. Returns a ranked list with profile URLs.",
      inputSchema: z.object({
        q: z.string().optional().describe("Keyword, e.g. 'immigration attorney'"),
        limit: z.number().int().min(1).max(20).optional().describe("Number of results. Default 10, max 20."),
      }),
    },
    async ({ q, limit }) => {
      const experts = await searchExperts({ q, limit });
      return { content: [{ type: "text", text: JSON.stringify({ experts, count: experts.length }) }] };
    },
  );
});

export { handler as GET, handler as POST };

The path is a convention, not a requirement. Mine lives in a [transport] catch-all route and returns 404 for any other path under /api, so a typo does not reach a tool. I use mcp-handler 2, @modelcontextprotocol/server 2 and Zod 4. Tools return plain results; I wrap errors in a small helper so a failure comes back as a tool error the agent can read instead of a crashed request.

3. Write tools for a model, not for a developer#

A tool is a function an agent decides to call from its description alone, so the description and the parameter notes are the interface. What I do:

  • Describe what the tool returns and when to use it, in one or two sentences.
  • Give every parameter a .describe() with valid values and an example. My category filter lists the allowed slugs, the country filter says "ISO 3166-1 alpha-2, e.g. 'US', 'KR'".
  • Bound everything. limit has a maximum of 20, so an agent cannot ask for the whole table.
  • Return a useful empty result. "No experts found. Try broader filters." tells the agent what to do next; an empty array does not.

The public endpoint has eight tools today: search and detail for experts, search and detail for property listings, and four account tools. Keep the list short. Every tool you add is one more description the agent has to read and choose between.

4. Auth: make the 401 do the work#

Read-only tools on my public endpoint need no credential. Anything that acts on an account does, so I run a second endpoint, /api/account/mcp, which answers 401 with a WWW-Authenticate header when no valid token is sent. That is what the specification asks for (authorization), and it is how an OAuth-capable client learns where to start the sign-in flow. You can see it yourself:

POST https://expertsapiens.com/api/account/mcp
HTTP/2 401
www-authenticate: Bearer error="invalid_token", error_description="No authorization provided",
  resource_metadata="https://expertsapiens.com/.well-known/oauth-protected-resource/api/account/mcp"

The resource_metadata URL serves an OAuth 2.0 Protected Resource Metadata document (RFC 9728) that names the authorization server. The specification builds on OAuth 2.1, and mine is Supabase Auth.

In code, mcp-handler's withMcpAuth wraps the handler and calls a function I write to verify the bearer token:

const authHandler = withMcpAuth(handler, verifyBearer, {
  required: true,
  resourceMetadataPath: "/.well-known/oauth-protected-resource/api/account/mcp",
});

My verifyBearer accepts two kinds of credential: an es_live_ API key, and a Supabase OAuth access token issued to an MCP client. It returns the caller's id, and the tools use that id, never an argument the model supplies, to decide whose data to touch.

5. Rate limits belong in front of auth#

Two limits matter, and the order matters too:

  1. Per IP, before auth. A flood of made-up bearer tokens should not turn into a flood of database lookups, so a per-IP limit (600 requests a minute) runs before token verification. The ceiling is high on purpose, because hosted connectors share IP addresses.
  2. Per account, inside the tool. Tools that act on an account allow 30 actions a minute per account. When the limit is hit, the tool returns an error result that says how long to wait, so the agent can back off instead of retrying blindly.

On top of that, the "contact an expert" tool caps inquiries at 5 per expert and 20 in total per 24 hours per account. An agent with write access should have limits on what it can do for you at scale, not only on how fast it calls.

6. Test the parts that can hurt you#

I have six test files for the MCP layer. They cover the route rate limit, OAuth token verification, and the account tools. I would test these first:

  • A request with no token gets 401, not 200 and not 500.
  • A fake token is rejected without a database lookup.
  • A tool never reads the account id from its arguments.
  • The per-account limit returns a tool error, not an exception.

Frequently asked questions#

Which transport should a new MCP server use?#

Streamable HTTP if it will be reached over the network, stdio if it runs on the same machine as the client. HTTP+SSE is deprecated in the specification, so do not start with it.

Can I build an MCP server in Next.js?#

Yes. With the App Router, an adapter such as mcp-handler turns your tool definitions into a standard Request-to-Response handler you export as GET and POST. I run mine that way.

Do I need OAuth?#

Not for read-only public tools. You need it once a tool acts on someone's account. The specification expects a 401 with a WWW-Authenticate header and a protected-resource metadata document, so an OAuth-capable client can sign the user in.

How do I stop an agent from calling a tool too often?#

Limit per IP in front of auth, limit per account inside the tool, and return the limit as a tool error with a retry time. For tools that write, add a daily cap as well.

If you want an MCP server built for your own API or product, see MCP server development. For how I connect these agents to my own data, read how I built a knowledge-base chat with Supabase and Claude and llms.txt and AI SEO. The row-level security behind the account tools is in Supabase RLS patterns I use in production.

Related posts

Freelance

Need help with this?

I help startups and businesses ship web projects: migrations, new products, and performance fixes.

Get in touch →