Commit 49f5e798 authored by Jiachi Liu's avatar Jiachi Liu

[mcp] get_routes mcp tool (#85773)

parent 65361361
......@@ -781,6 +781,9 @@ export async function createHotReloaderTurbopack(
getMcpMiddleware({
projectPath,
distDir,
nextConfig,
pagesDir: opts.pagesDir,
appDir: opts.appDir,
sendHmrMessage: (message) => hotReloader.send(message),
getActiveConnectionCount: () =>
clientsWithoutHtmlRequestId.size + clientsByHtmlRequestId.size,
......
......@@ -1674,6 +1674,9 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
getMcpMiddleware({
projectPath: this.dir,
distDir: this.distDir,
nextConfig: this.config,
pagesDir: this.pagesDir,
appDir: this.appDir,
sendHmrMessage: (message) => this.send(message),
getActiveConnectionCount: () =>
this.webpackHotMiddleware?.getClientCount() ?? 0,
......
......@@ -4,11 +4,16 @@ import { registerGetErrorsTool } from './tools/get-errors'
import { registerGetPageMetadataTool } from './tools/get-page-metadata'
import { registerGetLogsTool } from './tools/get-logs'
import { registerGetActionByIdTool } from './tools/get-server-action-by-id'
import { registerGetRoutesTool } from './tools/get-routes'
import type { HmrMessageSentToBrowser } from '../dev/hot-reloader-types'
import type { NextConfigComplete } from '../config-shared'
export interface McpServerOptions {
projectPath: string
distDir: string
nextConfig: NextConfigComplete
pagesDir: string | undefined
appDir: string | undefined
sendHmrMessage: (message: HmrMessageSentToBrowser) => void
getActiveConnectionCount: () => number
getDevServerUrl: () => string | undefined
......@@ -23,7 +28,7 @@ export const getOrCreateMcpServer = (options: McpServerOptions) => {
mcpServer = new McpServer({
name: 'Next.js MCP Server',
version: '0.1.0',
version: '0.2.0',
})
registerGetProjectMetadataTool(
......@@ -43,6 +48,12 @@ export const getOrCreateMcpServer = (options: McpServerOptions) => {
)
registerGetLogsTool(mcpServer, options.distDir)
registerGetActionByIdTool(mcpServer, options.distDir)
registerGetRoutesTool(mcpServer, {
projectPath: options.projectPath,
nextConfig: options.nextConfig,
pagesDir: options.pagesDir,
appDir: options.appDir,
})
return mcpServer
}
/**
* MCP tool for getting all routes that become entry points in a Next.js application.
*
* This tool discovers routes by scanning the filesystem directly. It finds all route
* files in the app/ and pages/ directories and converts them to route paths.
*
* Returns routes grouped by router type:
* - appRouter: App Router pages and route handlers
* - pagesRouter: Pages Router pages and API routes
*
* Dynamic route segments appear as [id], [slug], or [...slug] patterns. This tool
* does NOT expand getStaticParams - it only shows the route patterns as defined in
* the filesystem.
*/
import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'
import { mcpTelemetryTracker } from '../mcp-telemetry-tracker'
import {
collectAppFiles,
collectPagesFiles,
processAppRoutes,
processPageRoutes,
createPagesMapping,
} from '../../../build/entries'
import { createValidFileMatcher } from '../../lib/find-page-file'
import { PAGE_TYPES } from '../../../lib/page-types'
import type { NextConfigComplete } from '../../../server/config-shared'
import z from 'next/dist/compiled/zod'
interface RouteInfo {
route: string
type: 'app' | 'page' | 'api'
}
export function registerGetRoutesTool(
server: McpServer,
options: {
projectPath: string
nextConfig: NextConfigComplete
pagesDir: string | undefined
appDir: string | undefined
}
) {
server.registerTool(
'get_routes',
{
description:
'Get all routes that will become entry points in the Next.js application by scanning the filesystem. Returns routes grouped by router type (appRouter, pagesRouter). Dynamic segments appear as [param] or [...slug] patterns. API routes are included in their respective routers (e.g., /api/* routes from pages/ are in pagesRouter). Optional parameter: routerType ("app" | "pages") - filter by specific router type, omit to get all routes.',
inputSchema: {
routerType: z.union([z.literal('app'), z.literal('pages')]).optional(),
},
},
async (request) => {
// Track telemetry
mcpTelemetryTracker.recordToolCall('mcp/get_routes')
try {
const routerType =
request.routerType === 'app' || request.routerType === 'pages'
? request.routerType
: undefined
const routes: RouteInfo[] = []
const { projectPath, nextConfig, pagesDir, appDir } = options
// Check if we have any directories to scan
if (!pagesDir && !appDir) {
return {
content: [
{
type: 'text',
text: 'No pages or app directory found in the project.',
},
],
}
}
const isSrcDir =
(pagesDir && pagesDir.includes('/src/')) ||
(appDir && appDir.includes('/src/'))
// Create valid file matcher for filtering
const validFileMatcher = createValidFileMatcher(
nextConfig.pageExtensions,
appDir
)
// Collect and process App Router routes if requested
if (appDir && (!routerType || routerType === 'app')) {
try {
const { appPaths } = await collectAppFiles(appDir, validFileMatcher)
if (appPaths.length > 0) {
const mappedAppPages = await createPagesMapping({
pagePaths: appPaths,
isDev: true,
pagesType: PAGE_TYPES.APP,
pageExtensions: nextConfig.pageExtensions,
pagesDir,
appDir,
appDirOnly: pagesDir ? false : true,
})
const { appRoutes, appRouteHandlers } = processAppRoutes(
mappedAppPages,
validFileMatcher,
projectPath,
isSrcDir || false
)
// Add app page routes
for (const { route } of appRoutes) {
routes.push({
route,
type: 'app',
})
}
// Add app route handlers
for (const { route } of appRouteHandlers) {
routes.push({
route,
type: 'app',
})
}
}
} catch (error) {
// Error collecting app routes - continue anyway
}
}
// Collect and process Pages Router routes if requested
if (pagesDir && (!routerType || routerType === 'pages')) {
try {
const pagePaths = await collectPagesFiles(
pagesDir,
validFileMatcher
)
if (pagePaths.length > 0) {
const mappedPages = await createPagesMapping({
pagePaths,
isDev: true,
pagesType: PAGE_TYPES.PAGES,
pageExtensions: nextConfig.pageExtensions,
pagesDir,
appDir,
appDirOnly: false,
})
const { pageRoutes, pageApiRoutes } = processPageRoutes(
mappedPages,
projectPath,
isSrcDir || false
)
// Add page routes
for (const { route } of pageRoutes) {
routes.push({
route,
type: 'page',
})
}
// Add API routes (always included as part of pages router)
for (const { route } of pageApiRoutes) {
routes.push({
route,
type: 'api',
})
}
}
} catch (error) {
// Error collecting pages routes - continue anyway
}
}
if (routes.length === 0) {
return {
content: [
{
type: 'text',
text: 'No routes found in the project.',
},
],
}
}
// Group routes by router type
const appRoutes = routes
.filter((r) => r.type === 'app')
.map((r) => r.route)
.sort()
const pageRoutes = routes
.filter((r) => r.type === 'page' || r.type === 'api')
.map((r) => r.route)
.sort()
// Format the output with grouped routes
const output = {
appRouter: appRoutes.length > 0 ? appRoutes : undefined,
pagesRouter: pageRoutes.length > 0 ? pageRoutes : undefined,
}
return {
content: [
{
type: 'text',
text: JSON.stringify(output, null, 2),
},
],
}
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error: ${error instanceof Error ? error.message : String(error)}`,
},
],
}
}
}
)
}
......@@ -237,6 +237,7 @@ export type McpToolName =
| 'mcp/get_logs'
| 'mcp/get_page_metadata'
| 'mcp/get_project_metadata'
| 'mcp/get_routes'
| 'mcp/get_server_action_by_id'
export type EventMcpToolUsage = {
......
export async function GET(
request: Request,
{ params }: { params: { id: string } }
) {
return Response.json({ id: params.id })
}
export default function BlogPost({ params }: { params: { slug: string } }) {
return <div>Blog post: {params.slug}</div>
}
export default function Docs({ params }: { params: { slug: string[] } }) {
return <div>Docs: {params.slug.join('/')}</div>
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function HomePage() {
return <div>Home</div>
}
export default function Product({ params }: { params: { id: string } }) {
return <div>Product: {params.id}</div>
}
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
mcpServer: true,
},
}
module.exports = nextConfig
export default function About() {
return <div>About Page</div>
}
import type { NextApiRequest, NextApiResponse } from 'next'
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ name: 'Legacy API' })
}
export default function Post({ id }: { id: string }) {
return <div>Post {id}</div>
}
export async function getServerSideProps(context: any) {
return {
props: { id: context.params.id },
}
}
import path from 'path'
import { nextTestSetup } from 'e2e-utils'
describe('get_routes MCP tool', () => {
const { next, skipped } = nextTestSetup({
files: path.join(__dirname, 'fixtures', 'dynamic-routes-app'),
skipDeployment: true,
})
if (skipped) {
return
}
async function callGetRoutes(
id: string,
args: Record<string, unknown> = {}
): Promise<string> {
const response = await fetch(`${next.url}/_next/mcp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({
jsonrpc: '2.0',
id,
method: 'tools/call',
params: { name: 'get_routes', arguments: args },
}),
})
const text = await response.text()
const match = text.match(/data: ({.*})/s)
const result = JSON.parse(match![1])
return result.result?.content?.[0]?.text
}
it('should return all routes via MCP get_routes tool without visiting pages', async () => {
// The tool should discover all routes by scanning the filesystem,
// without needing to visit/compile any pages first
const sessionId = 'test-mcp-routes-' + Date.now()
const responseText = await callGetRoutes(sessionId)
expect(responseText).toBeTruthy()
const response = JSON.parse(responseText)
// Snapshot the discovered routes grouped by router type
// Note: Dynamic routes show parameter patterns like [id], [slug], [...slug]
expect(response).toMatchInlineSnapshot(`
{
"appRouter": [
"/",
"/api/users/[id]",
"/blog/[slug]",
"/docs/[...slug]",
"/products/[id]",
],
"pagesRouter": [
"/about",
"/api/legacy",
"/posts/[id]",
],
}
`)
})
it('should filter routes by routerType parameter', async () => {
// Test app-only filter
const appOnlyResponse = JSON.parse(
await callGetRoutes('test-app-only', { routerType: 'app' })
)
expect(appOnlyResponse).toMatchInlineSnapshot(`
{
"appRouter": [
"/",
"/api/users/[id]",
"/blog/[slug]",
"/docs/[...slug]",
"/products/[id]",
],
}
`)
// Test pages-only filter
const pagesOnlyResponse = JSON.parse(
await callGetRoutes('test-pages-only', { routerType: 'pages' })
)
expect(pagesOnlyResponse).toMatchInlineSnapshot(`
{
"pagesRouter": [
"/about",
"/api/legacy",
"/posts/[id]",
],
}
`)
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment