> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mcp-use.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Next.js

> Run mcp-use inside a Next.js route or beside a Next.js application as a standalone server.

mcp-use supports two intentionally separate Next.js topologies:

| Topology   | HTTP owner            | Choose it when                                                  |
| ---------- | --------------------- | --------------------------------------------------------------- |
| Embedded   | Next.js Route Handler | The website and MCP endpoint should deploy as one application.  |
| Standalone | `mcp-use dev/start`   | MCP needs its own process, port, deployment, or scaling policy. |

Both use the same V2 `MCPServer`, tool, and view APIs. Neither requires an MCP configuration file.

## Embedded in Next.js

The Next.js adapter mounts MCP at a Route Handler. `withMcpUse` integrates view compilation, public assets, output tracing, and CORS with the Next.js build; `createNextHandler` exposes the server over HTTP. Restart `next dev` after changing the MCP server or a view so its startup build runs again.

<Steps>
  <Step title="Install mcp-use">
    ```bash theme={null}
    pnpm add mcp-use zod
    ```
  </Step>

  <Step title="Export the MCP server">
    ```typescript mcp-server.ts theme={null}
    import { MCPServer } from "mcp-use";
    import { z } from "zod";

    const server = new MCPServer({
      name: "my-next-app",
      version: "1.0.0",
      basePath: "/api/mcp",
    });

    server.tool(
      {
        name: "greet",
        description: "Greet a person",
        inputSchema: z.object({ name: z.string() }),
      },
      async ({ name }) => ({
        content: [{ type: "text", text: `Hello, ${name}!` }],
      }),
    );

    export default server;
    ```

    Export the server without calling `listen()`. Next.js owns the HTTP listener.
  </Step>

  <Step title="Enable the Next.js integration">
    ```typescript next.config.ts theme={null}
    import type { NextConfig } from "next";
    import { withMcpUse } from "mcp-use/next";

    const nextConfig: NextConfig = {};

    export default withMcpUse(nextConfig, {
      entry: "./mcp-server.ts",
      basePath: "/api/mcp",
    });
    ```
  </Step>

  <Step title="Add the Route Handler">
    Use an optional catch-all because mcp-use serves the MCP endpoint and nested view assets from the same subtree:

    ```typescript app/api/mcp/[[...path]]/route.ts theme={null}
    import server from "@/mcp-server";
    import { createNextHandler } from "mcp-use/next";

    export const { GET, POST, DELETE, OPTIONS } = createNextHandler(server);
    ```

    If the server is at the project root and your `@/*` alias only maps `src/*`, use the appropriate relative import or move the server under `src/`.
  </Step>
</Steps>

Use normal Next.js scripts:

```json package.json theme={null}
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  }
}
```

Run `pnpm dev`, open the Next.js page, and connect an MCP client to `http://localhost:3000/api/mcp`.

The complete example at [`packages/server/examples/nextjs`](https://github.com/mcp-use/mcp-use/tree/beta/libraries/typescript/packages/server/examples/nextjs) also shows a view that imports a component used by the Next.js landing page and an image from the application's `public` directory.

## Standalone beside Next.js

The generic standalone CLI can run inside any TypeScript project, including a Next.js monorepo. It uses the project `tsconfig.json`, so the MCP server and its views can reuse project aliases, ordinary services, and browser-safe components.

<Steps>
  <Step title="Create an MCP source directory">
    ```text theme={null}
    src/
    ├── app/
    ├── components/
    ├── lib/
    └── mcp/
        ├── server.ts
        └── views/
            └── status-card/
                └── view.tsx
    ```
  </Step>

  <Step title="Export the server">
    ```typescript src/mcp/server.ts theme={null}
    import { MCPServer } from "mcp-use";
    import { getStatus } from "@/lib/status-service";

    const server = new MCPServer({
      name: "my-next-app",
      version: "1.0.0",
    });

    // Register tools and views. Tool code may call ordinary shared services.

    export default server;
    ```

    Do not call `listen()`. The mcp-use CLI owns the standalone listener.
  </Step>

  <Step title="Add separate scripts">
    ```json package.json theme={null}
    {
      "scripts": {
        "next:dev": "next dev --port 3000",
        "next:build": "next build",
        "next:start": "next start --port 3000",
        "mcp:dev": "mcp-use dev --mcp-dir src/mcp --port 3001",
        "mcp:build": "mcp-use build --mcp-dir src/mcp",
        "mcp:start": "mcp-use start"
      }
    }
    ```
  </Step>
</Steps>

Run `pnpm next:dev` and `pnpm mcp:dev` in separate terminals. The website is available at `http://localhost:3000`; the independent MCP endpoint is available at `http://localhost:3001/mcp`.

### Split monorepo

When the MCP source is outside the Next.js package, select the host project explicitly:

```bash theme={null}
mcp-use dev \
  --path apps/web \
  --entry ../mcp/src/server.ts \
  --views-dir ../mcp/src/views \
  --port 3001
```

`--path` selects the project root used for `package.json`, `.env`, and `tsconfig.json`. `--entry` and `--views-dir` are resolved relative to that root. The same flags work with `mcp-use build`; start the generated production server with `mcp-use start --path apps/web`.

The complete example is at [`packages/server/examples/nextjs-standalone`](https://github.com/mcp-use/mcp-use/tree/beta/libraries/typescript/packages/server/examples/nextjs-standalone).

## Sharing code safely

When the standalone CLI detects a Next.js host project, it loads the Next.js environment cascade and provides compatibility shims for common server-only imports. Shared services that import `server-only`, `next/cache`, or `next/headers` can load, but the shims do not invent a website request: `headers()` and `cookies()` are empty, and cache invalidation is a no-op. Pass required identity or request data through MCP authentication and request context.

MCP App views run in a browser iframe. A view may import browser-safe components from the Next.js project, but it must not import Server Components or modules that depend on `server-only`, `next/headers`, a database client, the filesystem, or other server-only APIs. Fetch data in the tool and return it to the view as `structuredContent`.

## CLI discovery

`--mcp-dir src/mcp` discovers the first supported server entry in that directory and uses `src/mcp/views` for views. An explicit `--entry` overrides entry discovery; `--views-dir` overrides the view directory. The project does not need `mcp.config.ts`.

## Verification

For either topology, verify the complete contract rather than only checking that a port is open:

1. Build the project in production mode.
2. Initialize an MCP session with `@mcp-use/client`.
3. List tools and confirm the expected names and schemas.
4. Call every example tool and assert its text and `structuredContent`.
5. Read each view URI from tool metadata and assert that its HTML resource loads.
6. Load every generated JavaScript, stylesheet, and public asset referenced by the view.
7. For embedded mode, also request the Next.js landing page and verify browser CORS preflight against `/api/mcp`.

Both repository examples expose `pnpm verify`, which performs their MCP assertions with the mcp-use client. The embedded example additionally verifies its Next.js landing page and nested public asset route; the standalone example should also pass `pnpm next:build`.
