Can I integrate this in an existing Next.js codebase?

main
470cc51publish clerk plugin gh workflow
This post might have stale content, as main is 110 commits ahead.

can i integrate this in an existing next.js codebase? and share code (such as a connection to the database)?

Avatar of anthropic/claude-opus-4.5
Claude Opus 4.5
commented

Now I have a comprehensive view. Let me summarize what I've found:


##Yes, you can integrate xmcp into an existing Next.js codebase!

###How to integrate

The easiest way is to run the init command in your existing project:

npx init-xmcp@latest

This will set up xmcp in your project. Once initialized, the integration works like this:

###Key Files

  1. xmcp.config.ts (at project root):
import { XmcpConfig } from "xmcp";

const config: XmcpConfig = {
  http: true,
  experimental: {
    adapter: "nextjs",
  },
  paths: {
    tools: "src/tools",       // where your tools live
    prompts: false,           // disable if not using
    resources: false,         // disable if not using
  },
};

export default config;
  1. Route handler at src/app/mcp/route.ts:
import { xmcpHandler } from "@xmcp/adapter";

export { xmcpHandler as GET, xmcpHandler as POST };
  1. Tools live in src/tools/ (file-system routing)

###Sharing Code (Database, Utils, etc.)

Yes, you can absolutely share code! The tools are just regular TypeScript files. Looking at the examples:

  • examples/with-nextjs imports shared utilities:

    // src/tools/get-weather.ts
    import { AlertsResponse, formatAlert, makeNWSRequest } from "@/utils";
    
  • examples/better-auth-nextjs shows database integration with a shared auth module:

    // src/lib/auth.ts
    import { Pool } from "pg";
    
    export const auth = betterAuth({
      database: new Pool({
        connectionString: process.env.DATABASE_URL,
      }),
      // ...
    });
    

So if you have a database connection (e.g., Prisma, Drizzle, raw pg pool), you can simply import it in your tools:

// src/tools/get-users.ts
import { db } from "@/lib/db";  // your existing database connection
import { z } from "zod";
import { type ToolMetadata } from "xmcp";

export const schema = {
  limit: z.number().optional().describe("Max users to return"),
};

export const metadata: ToolMetadata = {
  name: "get-users",
  description: "Get users from the database",
};

export default async function getUsers({ limit = 10 }) {
  const users = await db.user.findMany({ take: limit });
  
  return {
    content: [{ type: "text", text: JSON.stringify(users) }],
  };
}

###Dev & Build Scripts

Update your package.json:

{
  "scripts": {
    "dev": "xmcp dev & next dev --turbopack",
    "build": "xmcp build && next build"
  }
}

The xmcp CLI handles bundling your tools and generating the adapter code, which Next.js then serves via the route handler.


END OF POST

Can I integrate this in an existing Next.js codebase? — basementstudio/xmcp