Unverified Commit f9ee7a1a authored by Jude Gao's avatar Jude Gao Committed by GitHub

Feat: `get_errors` MCP endpoint (#84161)

Enables AI agents to programmatically access the runtime/build errors
from the current devtool overlay of a dev session. The errors are
pretty-printed by default with source-mapped stack frames. In
particular, it supports pulling error information from multiple browser
tabs.
parent e8a1342e
......@@ -43,6 +43,7 @@ bench/heavy-npm-deps/**
packages/next-bundle-analyzer/index.d.ts
examples/with-typescript-graphql/lib/gql/
test/development/basic/hmr/components/parse-error.js
test/development/mcp-server/fixtures/default-template/app/build-error/page.tsx
packages/next-swc/docs/assets/**/*
test/lib/amp-validator-wasm.js
test/production/pages-dir/production/fixture/amp-validator-wasm.js
......
......@@ -55,6 +55,7 @@ test/e2e/app-dir/server-source-maps/fixtures/default/internal-pkg/ignored.js
test/e2e/app-dir/server-source-maps/fixtures/default/internal-pkg/sourcemapped.js
test/e2e/app-dir/server-source-maps/fixtures/default/external-pkg/sourcemapped.js
test/e2e/async-modules/amp-validator-wasm.js
test/development/mcp-server/fixtures/default-template/app/build-error/page.tsx
# turbopack crates, disable for some tests and precompiled dependencies.
/turbopack/crates/*/js/src/compiled
......
......@@ -819,5 +819,8 @@
"818": "`cacheLife()` can only be called inside a \"use cache\" function.",
"819": "`cacheTag()` can only be called inside a \"use cache\" function.",
"820": "`cacheLife()` can only be called during App Router rendering at the moment.",
"821": "Unprocessable request"
"821": "Unprocessable request",
"822": "Stack frame resolver not initialized. This is a bug in Next.js.",
"823": "Timeout waiting for error state from frontend. The browser may not be responding to HMR messages.",
"824": "URL is required in MCP error state response. This is a bug in Next.js."
}
......@@ -8,17 +8,24 @@ import {
REACT_REFRESH_FULL_RELOAD,
REACT_REFRESH_FULL_RELOAD_FROM_ERROR,
} from '../shared'
import { dispatcher } from 'next/dist/compiled/next-devtools'
import {
dispatcher,
getSerializedOverlayState,
} from 'next/dist/compiled/next-devtools'
import { ReplaySsrOnlyErrors } from '../../../../next-devtools/userspace/app/errors/replay-ssr-only-errors'
import { AppDevOverlayErrorBoundary } from '../../../../next-devtools/userspace/app/app-dev-overlay-error-boundary'
import { useErrorHandler } from '../../../../next-devtools/userspace/app/errors/use-error-handler'
import { RuntimeErrorHandler } from '../../runtime-error-handler'
import { useWebSocketPing } from './web-socket'
import { HMR_MESSAGE_SENT_TO_BROWSER } from '../../../../server/dev/hot-reloader-types'
import {
HMR_MESSAGE_SENT_TO_BROWSER,
HMR_MESSAGE_SENT_TO_SERVER,
} from '../../../../server/dev/hot-reloader-types'
import type {
HmrMessageSentToBrowser,
TurbopackMessageSentToBrowser,
} from '../../../../server/dev/hot-reloader-types'
import type { McpErrorStateResponse } from '../../../../shared/lib/mcp-error-types'
import { useUntrackedPathname } from '../../../components/navigation-untracked'
import reportHmrLatency from '../../report-hmr-latency'
import { TurbopackHmr } from '../turbopack-hot-reloader-common'
......@@ -469,6 +476,17 @@ export function processMessage(
return
}
case HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_CURRENT_ERROR_STATE: {
const errorState = getSerializedOverlayState()
const response: McpErrorStateResponse = {
event: HMR_MESSAGE_SENT_TO_SERVER.MCP_ERROR_STATE_RESPONSE,
requestId: message.requestId,
errorState,
url: window.location.href,
}
sendMessage(JSON.stringify(response))
return
}
case HMR_MESSAGE_SENT_TO_BROWSER.MIDDLEWARE_CHANGES:
case HMR_MESSAGE_SENT_TO_BROWSER.CLIENT_CHANGES:
case HMR_MESSAGE_SENT_TO_BROWSER.SERVER_ONLY_CHANGES:
......
......@@ -32,12 +32,18 @@
/// <reference types="webpack/module.d.ts" />
import { dispatcher } from 'next/dist/compiled/next-devtools'
import {
dispatcher,
getSerializedOverlayState,
} from 'next/dist/compiled/next-devtools'
import { register } from '../../../../next-devtools/userspace/pages/pages-dev-overlay-setup'
import stripAnsi from 'next/dist/compiled/strip-ansi'
import { addMessageListener, sendMessage } from './websocket'
import formatWebpackMessages from '../../../../shared/lib/format-webpack-messages'
import { HMR_MESSAGE_SENT_TO_BROWSER } from '../../../../server/dev/hot-reloader-types'
import {
HMR_MESSAGE_SENT_TO_BROWSER,
HMR_MESSAGE_SENT_TO_SERVER,
} from '../../../../server/dev/hot-reloader-types'
import type {
AddedPageMessage,
DevPagesManifestUpdateMessage,
......@@ -393,6 +399,17 @@ function processMessage(message: HmrMessageSentToBrowser) {
case HMR_MESSAGE_SENT_TO_BROWSER.SERVER_ONLY_CHANGES:
// These action types are handled in src/client/page-bootstrap.ts
break
case HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_CURRENT_ERROR_STATE: {
const errorState = getSerializedOverlayState()
const response = {
event: HMR_MESSAGE_SENT_TO_SERVER.MCP_ERROR_STATE_RESPONSE,
requestId: message.requestId,
errorState,
url: window.location.href,
}
sendMessage(JSON.stringify(response))
break
}
default:
message satisfies never
}
......
......@@ -121,6 +121,7 @@ export function pageBootstrap(assetPrefix: string) {
case HMR_MESSAGE_SENT_TO_BROWSER.ISR_MANIFEST:
case HMR_MESSAGE_SENT_TO_BROWSER.DEVTOOLS_CONFIG:
case HMR_MESSAGE_SENT_TO_BROWSER.REACT_DEBUG_CHUNK:
case HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_CURRENT_ERROR_STATE:
// Most of these action types are handled in
// src/client/dev/hot-reloader/pages/hot-reloader-pages.ts and
// src/client/dev/hot-reloader/app/hot-reloader-app.tsx
......
......@@ -27,6 +27,7 @@ import {
createContext,
startTransition,
useContext,
useEffect,
useInsertionEffect,
useLayoutEffect,
type ActionDispatch,
......@@ -73,6 +74,35 @@ type Dispatch = ReturnType<typeof useErrorOverlayReducer>[1]
let maybeDispatch: Dispatch | null = null
const queue: Array<(dispatch: Dispatch) => void> = []
// Global state store for accessing current overlay state from outside React context
type OverlayStateWithRouter = OverlayState & { routerType: 'pages' | 'app' }
let currentOverlayState: OverlayStateWithRouter | null = null
export function getCurrentOverlayState(): OverlayStateWithRouter | null {
return currentOverlayState
}
export function getSerializedOverlayState(): OverlayStateWithRouter | null {
// Serialize error objects properly since Error properties are non-enumerable
// This is used when sending state via HMR/JSON.stringify
if (!currentOverlayState) return null
return {
...currentOverlayState,
errors: currentOverlayState.errors.map((errorEvent: any) => ({
...errorEvent,
error: errorEvent.error
? {
name: errorEvent.error.name,
message: errorEvent.error.message,
stack: errorEvent.error.stack,
}
: null,
})),
}
}
// Events might be dispatched before we get a `dispatch` from React (e.g. console.error during module eval).
// We need to queue them until we have a `dispatch` function available.
function createQueuable<Args extends any[]>(
......@@ -204,6 +234,10 @@ function DevOverlayRoot({
isRecoverableError
)
useEffect(() => {
currentOverlayState = { ...state, routerType }
}, [state, routerType])
useLayoutEffect(() => {
const portalNode = shadowRoot.host
if (state.theme === 'dark') {
......
......@@ -289,4 +289,12 @@ export class WebpackHotMiddleware {
this.clientsByRequestId.delete(requestId)
}
}
hasClients = () => {
return this.clients.size > 0
}
getClientCount = () => {
return this.clients.size
}
}
......@@ -30,6 +30,7 @@ import { BLOCKED_PAGES } from '../../shared/lib/constants'
import {
getOverlayMiddleware,
getSourceMapMiddleware,
getOriginalStackFrames,
} from './middleware-turbopack'
import { PageNotFoundError } from '../../shared/lib/utils'
import { debounce } from '../utils'
......@@ -112,6 +113,8 @@ import {
matchNextPageBundleRequest,
} from './hot-reloader-shared-utils'
import { getMcpMiddleware } from '../mcp/get-mcp-middleware'
import { handleErrorStateResponse } from '../mcp/tools/get-errors'
import { setStackFrameResolver } from '../mcp/tools/utils/format-errors'
const wsServer = new ws.Server({ noServer: true })
const isTestMode = !!(
......@@ -734,10 +737,27 @@ export async function createHotReloaderTurbopack(
},
}),
...(nextConfig.experimental.mcpServer
? [getMcpMiddleware(projectPath)]
? [
getMcpMiddleware(
projectPath,
(message) => hotReloader.send(message),
() => clients.size
),
]
: []),
]
setStackFrameResolver(async (request) => {
return getOriginalStackFrames({
project,
projectPath,
isServer: request.isServer,
isEdgeServer: request.isEdgeServer,
isAppDirectory: request.isAppDirectory,
frames: request.frames,
})
})
let versionInfoCached: ReturnType<typeof getVersionInfo> | undefined
// This fetch, even though not awaited, is not kicked off eagerly because the first `fetch()` in
// Node.js adds roughly 20ms main-thread blocking to load the SSL certificate cache
......@@ -919,6 +939,15 @@ export async function createHotReloaderTurbopack(
break
}
case 'mcp-error-state-response': {
handleErrorStateResponse(
parsedData.requestId,
parsedData.errorState,
parsedData.url
)
break
}
default:
// Might be a Turbopack message...
if (!parsedData.type) {
......
......@@ -30,11 +30,18 @@ export const enum HMR_MESSAGE_SENT_TO_BROWSER {
ISR_MANIFEST = 'isrManifest',
DEV_INDICATOR = 'devIndicator',
DEVTOOLS_CONFIG = 'devtoolsConfig',
REQUEST_CURRENT_ERROR_STATE = 'requestCurrentErrorState',
// Binary messages:
REACT_DEBUG_CHUNK = 0,
}
export const enum HMR_MESSAGE_SENT_TO_SERVER {
// JSON messages:
MCP_ERROR_STATE_RESPONSE = 'mcp-error-state-response',
PING = 'ping',
}
export interface ServerErrorMessage {
type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_ERROR
errorJSON: string
......@@ -143,6 +150,11 @@ export interface ReactDebugChunkMessage {
chunk: Uint8Array | null
}
export interface RequestCurrentErrorStateMessage {
type: HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_CURRENT_ERROR_STATE
requestId: string
}
export type HmrMessageSentToBrowser =
| TurbopackMessage
| TurbopackConnectedMessage
......@@ -161,6 +173,7 @@ export type HmrMessageSentToBrowser =
| AppIsrManifestMessage
| DevToolsConfigMessage
| ReactDebugChunkMessage
| RequestCurrentErrorStateMessage
export type BinaryHmrMessageSentToBrowser = Extract<
HmrMessageSentToBrowser,
......
......@@ -10,6 +10,7 @@ import { type webpack, StringXor } from 'next/dist/compiled/webpack/webpack'
import {
getOverlayMiddleware,
getSourceMapMiddleware,
getOriginalStackFrames,
} from './middleware-webpack'
import { WebpackHotMiddleware } from './hot-middleware'
import { join, relative, isAbsolute, posix, dirname } from 'path'
......@@ -105,6 +106,7 @@ import {
matchNextPageBundleRequest,
} from './hot-reloader-shared-utils'
import { getMcpMiddleware } from '../mcp/get-mcp-middleware'
import { setStackFrameResolver } from '../mcp/tools/utils/format-errors'
const MILLISECONDS_IN_NANOSECOND = BigInt(1_000_000)
......@@ -1622,9 +1624,28 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
},
}),
...(this.config.experimental.mcpServer
? [getMcpMiddleware(this.dir)]
? [
getMcpMiddleware(
this.dir,
(message) => this.send(message),
() => this.webpackHotMiddleware?.getClientCount() ?? 0
),
]
: []),
]
setStackFrameResolver(async (request) => {
return getOriginalStackFrames({
isServer: request.isServer,
isEdgeServer: request.isEdgeServer,
isAppDirectory: request.isAppDirectory,
frames: request.frames,
clientStats: () => this.clientStats,
serverStats: () => this.serverStats,
edgeServerStats: () => this.edgeServerStats,
rootDirectory: this.dir,
})
})
}
public invalidate(
......
......@@ -36,13 +36,17 @@ import {
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
} from '../../shared/lib/constants'
import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment'
import { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'
import {
HMR_MESSAGE_SENT_TO_BROWSER,
HMR_MESSAGE_SENT_TO_SERVER,
} from './hot-reloader-types'
import { isAppPageRouteDefinition } from '../route-definitions/app-page-route-definition'
import { scheduleOnNextTick } from '../../lib/scheduler'
import { Batcher } from '../../lib/batcher'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { PAGE_TYPES } from '../../lib/page-types'
import { getNextFlightSegmentPath } from '../../client/flight-data-helpers'
import { handleErrorStateResponse } from '../mcp/tools/get-errors'
const debug = createDebug('next:on-demand-entry-handler')
......@@ -992,12 +996,21 @@ export function onDemandEntryHandler({
typeof data !== 'string' ? data.toString() : data
)
if (parsedData.event === 'ping') {
if (parsedData.event === HMR_MESSAGE_SENT_TO_SERVER.PING) {
if (parsedData.appDirRoute) {
handleAppDirPing(parsedData.tree)
} else {
handlePing(parsedData.page)
}
} else if (
parsedData.event ===
HMR_MESSAGE_SENT_TO_SERVER.MCP_ERROR_STATE_RESPONSE
) {
handleErrorStateResponse(
parsedData.requestId,
parsedData.errorState,
parsedData.url
)
}
} catch {}
})
......
......@@ -2,8 +2,13 @@ import type { ServerResponse, IncomingMessage } from 'http'
import { getOrCreateMcpServer } from './get-or-create-mcp-server'
import { parseBody } from '../api-utils/node/parse-body'
import { StreamableHTTPServerTransport } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/streamableHttp'
import type { HmrMessageSentToBrowser } from '../dev/hot-reloader-types'
export function getMcpMiddleware(projectPath: string) {
export function getMcpMiddleware(
projectPath: string,
sendHmrMessage: (message: HmrMessageSentToBrowser) => void,
getActiveConnectionCount: () => number
) {
return async function (
req: IncomingMessage,
res: ServerResponse,
......@@ -13,7 +18,11 @@ export function getMcpMiddleware(projectPath: string) {
if (!pathname.startsWith('/_next/mcp')) {
return next()
}
const mcpServer = getOrCreateMcpServer(projectPath)
const mcpServer = getOrCreateMcpServer(
projectPath,
sendHmrMessage,
getActiveConnectionCount
)
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined,
})
......
import { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'
import { registerGetProjectPathTool } from './tools/get-project-path'
import { registerGetErrorsTool } from './tools/get-errors'
import type { HmrMessageSentToBrowser } from '../dev/hot-reloader-types'
let mcpServer: McpServer | undefined
export const getOrCreateMcpServer = (projectPath: string) => {
export const getOrCreateMcpServer = (
projectPath: string,
sendHmrMessage: (message: HmrMessageSentToBrowser) => void,
getActiveConnectionCount: () => number
) => {
if (mcpServer) {
return mcpServer
}
......@@ -12,46 +19,8 @@ export const getOrCreateMcpServer = (projectPath: string) => {
version: '0.1.0',
})
mcpServer.registerTool(
'get_project_path',
{
description:
'Returns the absolute path of the root directory for this Next.js project.',
inputSchema: {},
},
async (_request) => {
try {
if (!projectPath) {
return {
content: [
{
type: 'text',
text: 'Unable to determine the absolute path of the Next.js project.',
},
],
}
}
return {
content: [
{
type: 'text',
text: projectPath,
},
],
}
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error: ${error instanceof Error ? error.message : String(error)}`,
},
],
}
}
}
)
registerGetProjectPathTool(mcpServer, projectPath)
registerGetErrorsTool(mcpServer, sendHmrMessage, getActiveConnectionCount)
return mcpServer
}
/**
* MCP tool for retrieving browser error state.
*
* This tool demonstrates server-to-browser communication in Next.js dev mode.
* It leverages the existing HMR infrastructure rather than creating new channels.
*
* Flow:
* MCP client → server generates request ID → HMR message to browser →
* browser queries error overlay state → HMR response back → server performs source mapping →
* formatted output.
*/
import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'
import type { OverlayState } from '../../../next-devtools/dev-overlay/shared'
import {
HMR_MESSAGE_SENT_TO_BROWSER,
type HmrMessageSentToBrowser,
} from '../../dev/hot-reloader-types'
import { nanoid } from 'next/dist/compiled/nanoid'
import type { OverlayStateWithUrl } from '../../../shared/lib/mcp-error-types'
import { formatErrors } from './utils/format-errors'
// These promises are created when the MCP endpoint is called but before the browser has responded
// with its error state. They are resolved when the browser has responded with its error state
// or when the timeout is reached.
const pendingRequests = new Map<
string,
{
responses: OverlayStateWithUrl[]
expectedCount: number
resolve: (value: OverlayStateWithUrl[]) => void
reject: (reason?: any) => void
timeout: NodeJS.Timeout
}
>()
export function registerGetErrorsTool(
server: McpServer,
sendHmrMessage: (message: HmrMessageSentToBrowser) => void,
getActiveConnectionCount: () => number
) {
server.registerTool(
'get_errors',
{
description:
'Get the current error state of the app when rendered in the browser, including any build or runtime errors with source-mapped stack traces',
inputSchema: {},
},
async (_request) => {
try {
const connectionCount = getActiveConnectionCount()
if (connectionCount === 0) {
return {
content: [
{
type: 'text',
text: 'No browser sessions connected. Please open your application in a browser to retrieve error state.',
},
],
}
}
const requestId = `mcp-error-state-${nanoid()}`
// The promise will be resolved when all active browser sessions have responded
// with their respective error states. We will resolve the promise after 5 seconds
// with whatever responses we have received so far.
const responsePromise = new Promise<OverlayStateWithUrl[]>(
(resolve, reject) => {
const timeout = setTimeout(() => {
const pending = pendingRequests.get(requestId)
if (pending && pending.responses.length > 0) {
resolve(pending.responses)
} else {
reject(
new Error(
'Timeout waiting for error state from frontend. The browser may not be responding to HMR messages.'
)
)
}
pendingRequests.delete(requestId)
}, 5000)
pendingRequests.set(requestId, {
responses: [],
expectedCount: connectionCount,
resolve,
reject,
timeout,
})
}
)
// When browser receives this HMR message, it will send back a response with
// its client-side error state, which will be handled by `handleErrorStateResponse`.
sendHmrMessage({
type: HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_CURRENT_ERROR_STATE,
requestId,
})
const clientStates = await responsePromise
const errorsByUrl = new Map<string, OverlayState>()
for (const state of clientStates) {
if (state.errorState) {
errorsByUrl.set(state.url, state.errorState)
}
}
const hasErrors = Array.from(errorsByUrl.values()).some(
(state) => state.errors.length > 0 || !!state.buildError
)
if (!hasErrors) {
return {
content: [
{
type: 'text',
text:
clientStates.length === 0
? 'No browser sessions responded.'
: `No errors detected in ${clientStates.length} browser session(s).`,
},
],
}
}
const output = await formatErrors(errorsByUrl)
return {
content: [
{
type: 'text',
text: output,
},
],
}
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error: ${error instanceof Error ? error.message : String(error)}`,
},
],
}
}
}
)
}
// Browser will first receive an HMR message from server to send back its error state.
// The actual state is sent back in a subsequent HMR message, which is handled by this function
// on the server.
export function handleErrorStateResponse(
requestId: string,
errorState: OverlayState | null,
url: string | undefined
) {
if (!url) {
throw new Error(
'URL is required in MCP error state response. This is a bug in Next.js.'
)
}
const pending = pendingRequests.get(requestId)
if (pending) {
pending.responses.push({ url, errorState })
if (pending.responses.length >= pending.expectedCount) {
clearTimeout(pending.timeout)
pending.resolve(pending.responses)
pendingRequests.delete(requestId)
}
}
}
import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'
export function registerGetProjectPathTool(
server: McpServer,
projectPath: string
) {
server.registerTool(
'get_project_path',
{
description:
'Returns the absolute path of the root directory for this Next.js project.',
inputSchema: {},
},
async (_request) => {
try {
if (!projectPath) {
return {
content: [
{
type: 'text',
text: 'Unable to determine the absolute path of the Next.js project.',
},
],
}
}
return {
content: [
{
type: 'text',
text: projectPath,
},
],
}
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error: ${error instanceof Error ? error.message : String(error)}`,
},
],
}
}
}
)
}
import type { OverlayState } from '../../../../next-devtools/dev-overlay/shared'
import type { SupportedErrorEvent } from '../../../../next-devtools/dev-overlay/container/runtime-error/render-error'
import { getErrorSource } from '../../../../shared/lib/error-source'
import type {
OriginalStackFramesRequest,
OriginalStackFramesResponse,
} from '../../../../next-devtools/server/shared'
type StackFrameForFormatting = {
file: string | null
methodName: string
line1: number | null
column1: number | null
}
type StackFrameResolver = (
request: OriginalStackFramesRequest
) => Promise<OriginalStackFramesResponse>
// Dependency injection for stack frame resolver
let stackFrameResolver: StackFrameResolver | undefined
export function setStackFrameResolver(fn: StackFrameResolver) {
stackFrameResolver = fn
}
async function resolveStackFrames(
request: OriginalStackFramesRequest
): Promise<OriginalStackFramesResponse> {
if (!stackFrameResolver) {
throw new Error(
'Stack frame resolver not initialized. This is a bug in Next.js.'
)
}
return stackFrameResolver(request)
}
const formatStackFrame = (frame: StackFrameForFormatting): string => {
const file = frame.file || '<unknown>'
const method = frame.methodName || '<anonymous>'
const { line1: line, column1: column } = frame
return line && column
? ` at ${method} (${file}:${line}:${column})`
: line
? ` at ${method} (${file}:${line})`
: ` at ${method} (${file})`
}
const formatErrorFrames = async (
frames: readonly StackFrameForFormatting[],
context: {
isServer: boolean
isEdgeServer: boolean
isAppDirectory: boolean
}
): Promise<string> => {
try {
const resolvedFrames = await resolveStackFrames({
frames: frames.map((frame) => ({
file: frame.file || null,
methodName: frame.methodName || '<anonymous>',
arguments: [],
line1: frame.line1 || null,
column1: frame.column1 || null,
})),
isServer: context.isServer,
isEdgeServer: context.isEdgeServer,
isAppDirectory: context.isAppDirectory,
})
return (
resolvedFrames
.filter(
(resolvedFrame) =>
!(
resolvedFrame.status === 'fulfilled' &&
resolvedFrame.value.originalStackFrame?.ignored
)
)
.map((resolvedFrame, j) =>
resolvedFrame.status === 'fulfilled' &&
resolvedFrame.value.originalStackFrame
? formatStackFrame(resolvedFrame.value.originalStackFrame)
: formatStackFrame(frames[j])
)
.join('\n') + '\n'
)
} catch {
return frames.map(formatStackFrame).join('\n') + '\n'
}
}
async function formatRuntimeError(
errors: readonly SupportedErrorEvent[],
isAppDirectory: boolean
): Promise<string> {
const formatError = async (
error: SupportedErrorEvent,
index: number
): Promise<string> => {
const errorHeader = `\n#### Error ${index + 1} (Type: ${error.type})\n\n`
const errorName = error.error?.name || 'Error'
const errorMsg = error.error?.message || 'Unknown error'
const errorMessage = `**${errorName}**: ${errorMsg}\n\n`
if (!error.frames?.length) {
const stack = error.error?.stack || ''
return (
errorHeader + errorMessage + (stack ? `\`\`\`\n${stack}\n\`\`\`\n` : '')
)
}
const errorSource = getErrorSource(error.error)
const frames = await formatErrorFrames(error.frames, {
isServer: errorSource === 'server',
isEdgeServer: errorSource === 'edge-server',
isAppDirectory,
})
return errorHeader + errorMessage + `\`\`\`\n${frames}\`\`\`\n`
}
const formattedErrors = await Promise.all(errors.map(formatError))
return '### Runtime Errors\n' + formattedErrors.join('\n---\n')
}
export async function formatErrors(
errorsByUrl: Map<string, OverlayState>
): Promise<string> {
let output = `# Found errors in ${errorsByUrl.size} browser session(s)\n\n`
for (const [url, overlayState] of errorsByUrl) {
const totalErrorCount =
overlayState.errors.length + (overlayState.buildError ? 1 : 0)
if (totalErrorCount === 0) continue
let displayUrl = url
try {
const urlObj = new URL(url)
displayUrl = urlObj.pathname + urlObj.search + urlObj.hash
} catch {
// If URL parsing fails, use the original URL
}
output += `## Session: ${displayUrl}\n\n`
output += `**${totalErrorCount} error(s) found**\n\n`
// Build errors
if (overlayState.buildError) {
output += '### Build Error\n\n'
output += '```\n'
output += overlayState.buildError
output += '\n```\n\n'
}
// Runtime errors with source-mapped stack traces
if (overlayState.errors.length > 0) {
const runtimeErrors = await formatRuntimeError(
overlayState.errors,
overlayState.routerType === 'app'
)
output += runtimeErrors
output += '\n'
}
output += '---\n\n'
}
return output.trim()
}
import type { OverlayState } from '../../next-devtools/dev-overlay/shared'
export interface OverlayStateWithUrl {
url: string
errorState: OverlayState | null
}
export interface McpErrorStateResponse {
event: string
requestId: string
errorState: OverlayState | null
url: string
}
export default function BuildErrorPage() {
// Syntax error - missing closing brace
return <div>Page
}
\ No newline at end of file
import Link from 'next/link'
export default function Page() {
return <h1>Test MCP Server Page</h1>
return (
<div>
<h1>Home Page</h1>
<nav>
<Link href="/runtime-error">Go to Runtime Error</Link>
<br />
<Link href="/build-error">Go to Build Error</Link>
</nav>
</div>
)
}
export default function RuntimeErrorPage() {
throw new Error('Test runtime error 2')
}
export default function RuntimeErrorPage() {
throw new Error('Test runtime error')
}
import { FileRef, nextTestSetup } from 'e2e-utils'
import path from 'path'
import { retry, debugPrint, getFullUrl } from 'next-test-utils'
import stripAnsi from 'strip-ansi'
import { chromium, firefox, webkit } from 'playwright'
import type { Browser } from 'playwright'
describe('mcp-server get_errors tool', () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
})
async function callGetErrors(id: 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_errors', arguments: {} },
}),
})
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 handle no browser sessions gracefully', async () => {
const errors = await callGetErrors('test-no-session')
expect(stripAnsi(errors)).toMatchInlineSnapshot(
`"No browser sessions connected. Please open your application in a browser to retrieve error state."`
)
})
it('should return no errors for clean page', async () => {
await next.browser('/')
const errors = await callGetErrors('test-1')
expect(stripAnsi(errors)).toMatchInlineSnapshot(
`"No errors detected in 1 browser session(s)."`
)
})
it('should capture runtime errors with source-mapped stack frames', async () => {
const browser = await next.browser('/')
await browser.elementByCss('a[href="/runtime-error"]').click()
let errors: string = ''
await retry(async () => {
const sessionId = 'test-2-' + Date.now()
errors = await callGetErrors(sessionId)
expect(errors).toContain('Runtime Errors')
expect(errors).toContain('Found errors in 1 browser session')
})
const strippedErrors = stripAnsi(errors)
// Replace dynamic port with placeholder
.replace(/localhost:\d+/g, 'localhost:PORT')
// Verify proper URL display in session header (now shows pathname only)
expect(strippedErrors).toContain('Session: /runtime-error')
expect(strippedErrors).toMatchInlineSnapshot(`
"# Found errors in 1 browser session(s)
## Session: /runtime-error
**1 error(s) found**
### Runtime Errors
#### Error 1 (Type: runtime)
**Error**: Test runtime error
\`\`\`
at RuntimeErrorPage (app/runtime-error/page.tsx:2:9)
\`\`\`
---"
`)
})
it('should capture build errors when directly visiting error page', async () => {
await next.browser('/build-error')
let errors: string = ''
await retry(async () => {
const sessionId = 'test-4-' + Date.now()
errors = await callGetErrors(sessionId)
expect(errors).toContain('Build Error')
expect(errors).toContain('Found errors in 1 browser session')
})
let strippedErrors = stripAnsi(errors)
// Replace dynamic port with placeholder
.replace(/localhost:\d+/g, 'localhost:PORT')
// Verify proper URL display in session header (now shows pathname only)
expect(strippedErrors).toContain('Session: /build-error')
const isTurbopack = process.env.IS_TURBOPACK_TEST === '1'
// Normalize paths in turbopack output to remove temp directory prefix
if (isTurbopack) {
strippedErrors = strippedErrors.replace(/\.\/test\/tmp\/[^/]+\//g, './')
}
if (isTurbopack) {
// Turbopack output
expect(strippedErrors).toMatchInlineSnapshot(`
"# Found errors in 1 browser session(s)
## Session: /build-error
**2 error(s) found**
### Build Error
\`\`\`
./app/build-error/page.tsx:4:1
Parsing ecmascript source code failed
2 | // Syntax error - missing closing brace
3 | return <div>Page
> 4 | }
| ^
Unexpected token. Did you mean \`{'}'}\` or \`&rbrace;\`?
\`\`\`
### Runtime Errors
#### Error 1 (Type: runtime)
**Error**: ./app/build-error/page.tsx:4:1
Parsing ecmascript source code failed
2 | // Syntax error - missing closing brace
3 | return <div>Page
> 4 | }
| ^
Unexpected token. Did you mean \`{'}'}\` or \`&rbrace;\`?
\`\`\`
at <unknown> (Error: ./app/build-error/page.tsx:4:1)
at <unknown> (Error: (./app/build-error/page.tsx:4:1)
\`\`\`
---"
`)
} else {
// Webpack output
expect(strippedErrors).toMatchInlineSnapshot(`
"# Found errors in 1 browser session(s)
## Session: /build-error
**1 error(s) found**
### Build Error
\`\`\`
./app/build-error/page.tsx
Error: x Unexpected token. Did you mean \`{'}'}\` or \`&rbrace;\`?
,-[4:1]
1 | export default function BuildErrorPage() {
2 | // Syntax error - missing closing brace
3 | return <div>Page
4 | }
: ^
\`----
x Expected '</', got '<eof>'
,-[4:1]
1 | export default function BuildErrorPage() {
2 | // Syntax error - missing closing brace
3 | return <div>Page
4 | }
\`----
Caused by:
Syntax Error
\`\`\`
---"
`)
}
})
it('should capture errors from multiple browser sessions', async () => {
// Restart the server
await next.stop()
await next.start()
// Open two independent browser sessions concurrently
const [s1, s2] = await Promise.all([
launchStandaloneSession(next.url, '/runtime-error'),
launchStandaloneSession(next.url, '/runtime-error-2'),
])
try {
// Wait for server to be ready
await new Promise((resolve) => setTimeout(resolve, 1000))
let errors: string = ''
await retry(async () => {
const sessionId = 'test-multi-' + Date.now()
errors = await callGetErrors(sessionId)
// Check that we have at least the 2 sessions we created
expect(errors).toMatch(/Found errors in \d+ browser session/)
// Ensure both our sessions are present
expect(errors).toContain('/runtime-error')
expect(errors).toContain('/runtime-error-2')
})
const strippedErrors = stripAnsi(errors).replace(
/localhost:\d+/g,
'localhost:PORT'
)
// Extract each session's content to check them independently
const session1Match = strippedErrors.match(
/## Session: \/runtime-error\n[\s\S]*?(?=---)/
)
const session2Match = strippedErrors.match(
/## Session: \/runtime-error-2\n[\s\S]*?(?=---)/
)
expect(session1Match).toBeTruthy()
expect(session2Match).toBeTruthy()
expect(session1Match?.[0]).toMatchInlineSnapshot(`
"## Session: /runtime-error
**1 error(s) found**
### Runtime Errors
#### Error 1 (Type: runtime)
**Error**: Test runtime error
\`\`\`
at RuntimeErrorPage (app/runtime-error/page.tsx:2:9)
\`\`\`
"
`)
expect(session2Match?.[0]).toMatchInlineSnapshot(`
"## Session: /runtime-error-2
**1 error(s) found**
### Runtime Errors
#### Error 1 (Type: runtime)
**Error**: Test runtime error 2
\`\`\`
at RuntimeErrorPage (app/runtime-error-2/page.tsx:2:9)
\`\`\`
"
`)
} finally {
await s1.close()
await s2.close()
}
})
})
/**
* Minimal standalone browser session launcher for testing multiple concurrent browser tabs.
* The standard test harness (next.browser) uses a singleton browser instance which doesn't
* support concurrent tabs needed for testing errors across multiple browser sessions.
*/
async function launchStandaloneSession(
appPortOrUrl: string | number,
url: string
) {
const headless = !!process.env.HEADLESS
const browserName = (process.env.BROWSER_NAME || 'chrome').toLowerCase()
let browser: Browser
if (browserName === 'safari') {
browser = await webkit.launch({ headless })
} else if (browserName === 'firefox') {
browser = await firefox.launch({ headless })
} else {
browser = await chromium.launch({ headless })
}
const context = await browser.newContext()
const page = await context.newPage()
const fullUrl = getFullUrl(appPortOrUrl, url)
debugPrint(`Loading standalone browser with ${fullUrl}`)
page.on('pageerror', (error) => debugPrint('Standalone page error', error))
await page.goto(fullUrl, { waitUntil: 'load' })
debugPrint(`Loaded standalone browser with ${fullUrl}`)
return {
page,
close: async () => {
await page.close().catch(() => {})
await context.close().catch(() => {})
await browser.close().catch(() => {})
},
}
}
import { FileRef, nextTestSetup } from 'e2e-utils'
import path from 'path'
describe('mcp-server get_project_path tool', () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
})
it('should return correct project path via get_project_path tool', async () => {
const mcpEndpoint = `${next.url}/_next/mcp`
// Call get_project_path tool
const callToolResponse = await fetch(mcpEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 'call-tool-1',
method: 'tools/call',
params: {
name: 'get_project_path',
arguments: {},
},
}),
})
const callToolText = await callToolResponse.text()
const callToolDataMatch = callToolText.match(/data: ({.*})/s)
expect(callToolDataMatch).toBeTruthy()
const callToolResult = JSON.parse(callToolDataMatch![1])
expect(callToolResult.jsonrpc).toBe('2.0')
expect(callToolResult.id).toBe('call-tool-1')
const content = callToolResult.result?.content
expect(content).toBeInstanceOf(Array)
expect(content?.[0]?.type).toBe('text')
const actualProjectPath = content?.[0]?.text
// Verify it's an absolute path
expect(path.isAbsolute(actualProjectPath)).toBe(true)
// Should match the test directory
expect(actualProjectPath).toBe(next.testDir)
})
})
import { FileRef, nextTestSetup } from 'e2e-utils'
import path from 'path'
describe('mcp-server', () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
})
async function initializeMCPSession(
mcpEndpoint: string,
id: string
): Promise<any> {
const initResponse = await fetch(mcpEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({
jsonrpc: '2.0',
id,
method: 'initialize',
params: {
protocolVersion: '1.0.0',
capabilities: {},
clientInfo: {
name: 'test-client',
version: '1.0.0',
},
},
}),
})
const initText = await initResponse.text()
const dataMatch = initText.match(/data: ({.*})/s)
if (!dataMatch) {
throw new Error(`Unexpected response format: ${initText}`)
}
const initResult = JSON.parse(dataMatch[1])
if (initResult.error) {
throw new Error(`MCP error: ${JSON.stringify(initResult.error)}`)
}
return initResult
}
it('should initialize MCP server and list available tools', async () => {
const mcpEndpoint = `${next.url}/_next/mcp`
// Initialize MCP session
const initResult = await initializeMCPSession(mcpEndpoint, 'init-1')
expect(initResult.jsonrpc).toBe('2.0')
expect(initResult.id).toBe('init-1')
expect(initResult.result?.serverInfo?.name).toBe('Next.js MCP Server')
// List available tools
const listToolsResponse = await fetch(mcpEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 'list-tools-1',
method: 'tools/list',
params: {},
}),
})
const listToolsText = await listToolsResponse.text()
const listToolsDataMatch = listToolsText.match(/data: ({.*})/s)
if (!listToolsDataMatch) {
throw new Error(`Unexpected response format: ${listToolsText}`)
}
const listToolsResult = JSON.parse(listToolsDataMatch[1])
expect(listToolsResult.result?.tools).toBeInstanceOf(Array)
const projectDirTool = listToolsResult.result?.tools?.find(
(tool: { name: string }) => tool.name === 'get_project_path'
)
expect(projectDirTool).toBeDefined()
expect(projectDirTool?.description).toBe(
'Returns the absolute path of the root directory for this Next.js project.'
)
})
it('should return exact absolute path for get_project_path tool', async () => {
const mcpEndpoint = `${next.url}/_next/mcp`
// Initialize MCP session (required before calling tools)
await initializeMCPSession(mcpEndpoint, 'init-2')
// Call get_project_path tool and verify response
const callToolResponse = await fetch(mcpEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 'call-tool-1',
method: 'tools/call',
params: {
name: 'get_project_path',
arguments: {},
},
}),
})
const callToolText = await callToolResponse.text()
const callToolDataMatch = callToolText.match(/data: ({.*})/s)
if (!callToolDataMatch) {
throw new Error(`Unexpected response format: ${callToolText}`)
}
const callToolResult = JSON.parse(callToolDataMatch[1])
expect(callToolResult.jsonrpc).toBe('2.0')
expect(callToolResult.id).toBe('call-tool-1')
const content = callToolResult.result?.content
expect(content).toBeInstanceOf(Array)
expect(content?.[0]?.type).toBe('text')
// Get the actual project path from the response
const actualProjectPath = content?.[0]?.text
// Project directory should match the test directory from the test harness
expect(actualProjectPath).toBe(next.testDir)
})
})
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