Loading...
Loading...
Pattern for building MCP servers in Next.js with mcp-handler, shared Zod schemas, and reusable server actions.
npx skill4agent add gocallum/nextjs16-agent-skills mcp-server-skillsapp/
api/[transport]/route.ts # One handler for all transports (e.g., /api/mcp)
actions/mcp-actions.ts # Server actions reusing the same logic/schemas
lib/
dice.ts | tools.ts # Zod schemas, tool definitions, pure logic
components/ # UI that calls server actions for web testingroute.tslib/*// lib/dice.ts
import { z } from "zod";
export const diceSchema = z.number().int().min(2);
export function rollDice(sides: number) {
const validated = diceSchema.parse(sides);
const value = 1 + Math.floor(Math.random() * validated);
return { type: "text" as const, text: `🎲 You rolled a ${value}!` };
}
export const rollDiceTool = {
name: "roll_dice",
description: "Rolls an N-sided die",
schema: { sides: diceSchema },
} as const;// app/actions/mcp-actions.ts
"use server";
import { rollDice as rollDiceCore, rollDiceTool } from "@/lib/dice";
export async function rollDice(sides: number) {
try {
const result = rollDiceCore(sides);
return { success: true, result: { content: [result] } };
} catch {
return {
success: false,
error: { code: -32602, message: "Invalid parameters: sides must be >= 2" },
};
}
}
export async function listTools() {
return {
success: true,
result: {
tools: [
{
name: rollDiceTool.name,
description: rollDiceTool.description,
inputSchema: {
type: "object",
properties: { sides: { type: "number", minimum: 2 } },
required: ["sides"],
},
},
],
},
};
}// app/api/[transport]/route.ts
import { createMcpHandler } from "mcp-handler";
import { rollDice, rollDiceTool } from "@/lib/dice";
const handler = createMcpHandler(
(server) => {
server.tool(
rollDiceTool.name,
rollDiceTool.description,
rollDiceTool.schema,
async ({ sides }) => ({ content: [rollDice(sides)] }),
);
},
{}, // server options
{
basePath: "/api", // must match folder path
maxDuration: 60,
verboseLogs: true,
},
);
export { handler as GET, handler as POST };createMcpHandlerserver.toolbasePath/api/[transport]{
"mcpServers": {
"rolldice": {
"command": "npx",
"args": ["-y", "mcp-remote", "http://localhost:3000/api/mcp"]
}
}
}lib/*{ success, result | error }maxDurationruntime/api/[transport]