Commit 1aa43b92 authored by Jude Gao's avatar Jude Gao

Feat: Add resolve_stack_frames MCP tool

parent 1fffbcac
...@@ -818,5 +818,7 @@ ...@@ -818,5 +818,7 @@
"817": "`cacheLifeProfiles` should always be provided.", "817": "`cacheLifeProfiles` should always be provided.",
"818": "`cacheLife()` can only be called inside a \"use cache\" function.", "818": "`cacheLife()` can only be called inside a \"use cache\" function.",
"819": "`cacheTag()` 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." "820": "`cacheLife()` can only be called during App Router rendering at the moment.",
"821": "Stack frame resolver not available. This is a bug in Next.js.",
"822": "Failed to resolve stack frames: %s"
} }
...@@ -30,6 +30,7 @@ import { BLOCKED_PAGES } from '../../shared/lib/constants' ...@@ -30,6 +30,7 @@ import { BLOCKED_PAGES } from '../../shared/lib/constants'
import { import {
getOverlayMiddleware, getOverlayMiddleware,
getSourceMapMiddleware, getSourceMapMiddleware,
getOriginalStackFrames,
} from './middleware-turbopack' } from './middleware-turbopack'
import { PageNotFoundError } from '../../shared/lib/utils' import { PageNotFoundError } from '../../shared/lib/utils'
import { debounce } from '../utils' import { debounce } from '../utils'
...@@ -112,6 +113,7 @@ import { ...@@ -112,6 +113,7 @@ import {
matchNextPageBundleRequest, matchNextPageBundleRequest,
} from './hot-reloader-shared-utils' } from './hot-reloader-shared-utils'
import { getMcpMiddleware } from '../mcp/get-mcp-middleware' import { getMcpMiddleware } from '../mcp/get-mcp-middleware'
import { setStackFrameResolver } from '../mcp/tools/resolve-stack-frames'
const wsServer = new ws.Server({ noServer: true }) const wsServer = new ws.Server({ noServer: true })
const isTestMode = !!( const isTestMode = !!(
...@@ -738,6 +740,19 @@ export async function createHotReloaderTurbopack( ...@@ -738,6 +740,19 @@ export async function createHotReloaderTurbopack(
: []), : []),
] ]
if (nextConfig.experimental.mcpServer) {
setStackFrameResolver(async (request) => {
return getOriginalStackFrames({
project,
projectPath,
frames: request.frames,
isServer: request.isServer,
isEdgeServer: request.isEdgeServer,
isAppDirectory: request.isAppDirectory,
})
})
}
let versionInfoCached: ReturnType<typeof getVersionInfo> | undefined let versionInfoCached: ReturnType<typeof getVersionInfo> | undefined
// This fetch, even though not awaited, is not kicked off eagerly because the first `fetch()` in // 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 // Node.js adds roughly 20ms main-thread blocking to load the SSL certificate cache
......
...@@ -10,6 +10,7 @@ import { type webpack, StringXor } from 'next/dist/compiled/webpack/webpack' ...@@ -10,6 +10,7 @@ import { type webpack, StringXor } from 'next/dist/compiled/webpack/webpack'
import { import {
getOverlayMiddleware, getOverlayMiddleware,
getSourceMapMiddleware, getSourceMapMiddleware,
getOriginalStackFrames,
} from './middleware-webpack' } from './middleware-webpack'
import { WebpackHotMiddleware } from './hot-middleware' import { WebpackHotMiddleware } from './hot-middleware'
import { join, relative, isAbsolute, posix, dirname } from 'path' import { join, relative, isAbsolute, posix, dirname } from 'path'
...@@ -105,6 +106,7 @@ import { ...@@ -105,6 +106,7 @@ import {
matchNextPageBundleRequest, matchNextPageBundleRequest,
} from './hot-reloader-shared-utils' } from './hot-reloader-shared-utils'
import { getMcpMiddleware } from '../mcp/get-mcp-middleware' import { getMcpMiddleware } from '../mcp/get-mcp-middleware'
import { setStackFrameResolver } from '../mcp/tools/resolve-stack-frames'
const MILLISECONDS_IN_NANOSECOND = BigInt(1_000_000) const MILLISECONDS_IN_NANOSECOND = BigInt(1_000_000)
...@@ -1625,6 +1627,21 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -1625,6 +1627,21 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
? [getMcpMiddleware(this.dir)] ? [getMcpMiddleware(this.dir)]
: []), : []),
] ]
if (this.config.experimental.mcpServer) {
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( public invalidate(
......
import { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp' import { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'
import { registerGetProjectPathTool } from './tools/get-project-path'
import { registerResolveStackFramesTool } from './tools/resolve-stack-frames'
let mcpServer: McpServer | undefined let mcpServer: McpServer | undefined
...@@ -12,46 +14,8 @@ export const getOrCreateMcpServer = (projectPath: string) => { ...@@ -12,46 +14,8 @@ export const getOrCreateMcpServer = (projectPath: string) => {
version: '0.1.0', version: '0.1.0',
}) })
mcpServer.registerTool( registerGetProjectPathTool(mcpServer, projectPath)
'get_project_path', registerResolveStackFramesTool(mcpServer)
{
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)}`,
},
],
}
}
}
)
return mcpServer return mcpServer
} }
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 { z } from 'next/dist/compiled/zod'
import type { McpServer } from 'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp'
import type {
OriginalStackFramesRequest,
OriginalStackFramesResponse,
} from '../../../next-devtools/server/shared'
let stackFrameResolver:
| ((
request: OriginalStackFramesRequest
) => Promise<OriginalStackFramesResponse>)
| undefined
export function setStackFrameResolver(resolver: typeof stackFrameResolver) {
stackFrameResolver = resolver
}
export async function getOriginalSourceFromBundled(
bundledStackFrames: OriginalStackFramesRequest['frames'],
context: {
isServer: boolean
isEdgeServer: boolean
isAppDirectory: boolean
}
): Promise<OriginalStackFramesResponse> {
if (!stackFrameResolver) {
throw new Error(
'Stack frame resolver not available. This is a bug in Next.js.'
)
}
const request: OriginalStackFramesRequest = {
frames: bundledStackFrames,
isServer: context.isServer,
isEdgeServer: context.isEdgeServer,
isAppDirectory: context.isAppDirectory,
}
return stackFrameResolver(request)
}
export function registerResolveStackFramesTool(server: McpServer) {
server.registerTool(
'resolve_stack_frames',
{
description:
'Resolve bundled/minified stack frames to original source locations using source maps',
inputSchema: {
frames: z
.array(
z.object({
file: z
.union([z.string(), z.null()])
.describe('File path or URL (e.g., webpack-internal://...)'),
methodName: z.string().describe('Method/function name'),
arguments: z.array(z.string()).describe('Method arguments'),
line1: z
.union([z.number(), z.null()])
.describe('1-based line number in bundled code'),
column1: z
.union([z.number(), z.null()])
.describe('1-based column number in bundled code'),
})
)
.describe('Stack frames from error.stack or console trace'),
isServer: z
.boolean()
.describe('Whether error occurred during server-side rendering'),
isEdgeServer: z
.boolean()
.describe('Whether error occurred in edge runtime'),
isAppDirectory: z
.boolean()
.describe('Whether using Next.js app directory structure'),
},
},
async (request) => {
try {
const { frames, isServer, isEdgeServer, isAppDirectory } = request as {
frames: OriginalStackFramesRequest['frames']
isServer: boolean
isEdgeServer: boolean
isAppDirectory: boolean
}
const resolvedFrames = await getOriginalSourceFromBundled(frames, {
isServer,
isEdgeServer,
isAppDirectory,
})
return {
content: [
{
type: 'text' as const,
text: JSON.stringify(resolvedFrames, null, 2),
},
],
}
} catch (error) {
throw new Error(
`Failed to resolve stack frames: ${error instanceof Error ? error.message : String(error)}`
)
}
}
)
}
'use client'
import { useState } from 'react'
export default function ErrorTestButtonPage() {
const [shouldError, setShouldError] = useState(false)
if (shouldError) {
throw new Error('Test error for stack frame resolution triggered by button')
}
return (
<div>
<h1>Click to trigger error</h1>
<button id="trigger-error-button" onClick={() => setShouldError(true)}>
Trigger Error
</button>
</div>
)
}
'use client'
export default function ErrorTestPage() {
// This will throw an error when the component renders
if (typeof window !== 'undefined') {
throw new Error('Test error for stack frame resolution')
}
return <div>This page will throw an error</div>
}
import { FileRef, nextTestSetup } from 'e2e-utils' import { FileRef, nextTestSetup } from 'e2e-utils'
import path from 'path' import path from 'path'
import { initializeMCPSession } from './utils/mcp-test-utils'
describe('mcp-server', () => { describe('mcp-server get_project_path tool', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')), files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
}) })
async function initializeMCPSession( it('should list get_project_path tool in available tools', async () => {
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` const mcpEndpoint = `${next.url}/_next/mcp`
// Initialize MCP session // Initialize MCP session
const initResult = await initializeMCPSession(mcpEndpoint, 'init-1') 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 // List available tools
const listToolsResponse = await fetch(mcpEndpoint, { const listToolsResponse = await fetch(mcpEndpoint, {
...@@ -72,29 +30,34 @@ describe('mcp-server', () => { ...@@ -72,29 +30,34 @@ describe('mcp-server', () => {
const listToolsText = await listToolsResponse.text() const listToolsText = await listToolsResponse.text()
const listToolsDataMatch = listToolsText.match(/data: ({.*})/s) const listToolsDataMatch = listToolsText.match(/data: ({.*})/s)
if (!listToolsDataMatch) { expect(listToolsDataMatch).toBeTruthy()
throw new Error(`Unexpected response format: ${listToolsText}`)
}
const listToolsResult = JSON.parse(listToolsDataMatch[1])
const listToolsResult = JSON.parse(listToolsDataMatch![1])
expect(listToolsResult.result?.tools).toBeInstanceOf(Array) expect(listToolsResult.result?.tools).toBeInstanceOf(Array)
const projectDirTool = listToolsResult.result?.tools?.find( const projectDirTool = listToolsResult.result?.tools?.find(
(tool: { name: string }) => tool.name === 'get_project_path' (tool: { name: string }) => tool.name === 'get_project_path'
) )
expect(projectDirTool).toBeDefined() expect(projectDirTool).toBeDefined()
expect(projectDirTool?.description).toBe( expect(projectDirTool?.description).toBe(
'Returns the absolute path of the root directory for this Next.js project.' 'Returns the absolute path of the root directory for this Next.js project.'
) )
// Input schema should be an empty object schema
expect(projectDirTool?.inputSchema).toMatchObject({
type: 'object',
properties: {},
})
}) })
it('should return exact absolute path for get_project_path tool', async () => { it('should return correct project path via get_project_path tool', async () => {
const mcpEndpoint = `${next.url}/_next/mcp` const mcpEndpoint = `${next.url}/_next/mcp`
// Initialize MCP session (required before calling tools) // Initialize MCP session
await initializeMCPSession(mcpEndpoint, 'init-2') await initializeMCPSession(mcpEndpoint, 'init-2')
// Call get_project_path tool and verify response // Call get_project_path tool
const callToolResponse = await fetch(mcpEndpoint, { const callToolResponse = await fetch(mcpEndpoint, {
method: 'POST', method: 'POST',
headers: { headers: {
...@@ -114,11 +77,9 @@ describe('mcp-server', () => { ...@@ -114,11 +77,9 @@ describe('mcp-server', () => {
const callToolText = await callToolResponse.text() const callToolText = await callToolResponse.text()
const callToolDataMatch = callToolText.match(/data: ({.*})/s) const callToolDataMatch = callToolText.match(/data: ({.*})/s)
if (!callToolDataMatch) { expect(callToolDataMatch).toBeTruthy()
throw new Error(`Unexpected response format: ${callToolText}`)
}
const callToolResult = JSON.parse(callToolDataMatch[1])
const callToolResult = JSON.parse(callToolDataMatch![1])
expect(callToolResult.jsonrpc).toBe('2.0') expect(callToolResult.jsonrpc).toBe('2.0')
expect(callToolResult.id).toBe('call-tool-1') expect(callToolResult.id).toBe('call-tool-1')
...@@ -126,10 +87,12 @@ describe('mcp-server', () => { ...@@ -126,10 +87,12 @@ describe('mcp-server', () => {
expect(content).toBeInstanceOf(Array) expect(content).toBeInstanceOf(Array)
expect(content?.[0]?.type).toBe('text') expect(content?.[0]?.type).toBe('text')
// Get the actual project path from the response
const actualProjectPath = content?.[0]?.text const actualProjectPath = content?.[0]?.text
// Project directory should match the test directory from the test harness // Verify it's an absolute path
expect(path.isAbsolute(actualProjectPath)).toBe(true)
// Should match the test directory
expect(actualProjectPath).toBe(next.testDir) expect(actualProjectPath).toBe(next.testDir)
}) })
}) })
import { FileRef, nextTestSetup } from 'e2e-utils'
import path from 'path'
import { retry } from 'next-test-utils'
import { initializeMCPSession } from './utils/mcp-test-utils'
describe('mcp-server stack frames resolution', () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
})
it('should capture real error stack frames and resolve them via MCP', async () => {
const browser = await next.browser('/error-test-button')
await browser.waitForElementByCss('#trigger-error-button')
// Intercept the overlay's stack frame resolution request
await browser.eval(() => {
;(window as any).interceptedRequest = null
const originalFetch = window.fetch
window.fetch = function (...args) {
const [url, options] = args
if (
typeof url === 'string' &&
url.includes('__nextjs_original-stack-frames')
) {
if (options?.body) {
try {
;(window as any).interceptedRequest = JSON.parse(
options.body as string
)
} catch (e) {}
}
}
return originalFetch.apply(this, args)
}
})
// Trigger the error
await browser.elementByCss('#trigger-error-button').click()
// Wait for error overlay
await retry(async () => {
const hasOverlay = await browser.eval(
() => document.querySelector('nextjs-portal') !== null
)
expect(hasOverlay).toBe(true)
})
// Get the intercepted request with real bundled frames
await retry(async () => {
const req = await browser.eval(() => (window as any).interceptedRequest)
expect(req).toBeTruthy()
})
const interceptedRequest = await browser.eval(
() => (window as any).interceptedRequest
)
expect(interceptedRequest).toBeTruthy()
expect(interceptedRequest.frames).toBeTruthy()
expect(interceptedRequest.frames.length).toBeGreaterThan(0)
// Verify we have real bundled paths
const firstFrame = interceptedRequest.frames[0]
expect(firstFrame.file).toMatch(
/webpack-internal:\/\/|turbopack:\/\/|file:\/\/.*\/.next\//
)
// Test MCP resolution with real frames
const mcpEndpoint = `${next.url}/_next/mcp`
// Initialize MCP
await initializeMCPSession(mcpEndpoint, 'init')
// Call resolve_stack_frames with real intercepted frames
const resolveResponse = await fetch(mcpEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 'resolve',
method: 'tools/call',
params: {
name: 'resolve_stack_frames',
arguments: interceptedRequest,
},
}),
})
const resolveText = await resolveResponse.text()
const match = resolveText.match(/data: ({.*})/s)
expect(match).toBeTruthy()
const result = JSON.parse(match![1])
if (result.error) {
throw new Error(`MCP error: ${JSON.stringify(result.error)}`)
}
const content = result.result?.content
expect(content).toBeInstanceOf(Array)
expect(content.length).toBeGreaterThan(0)
expect(content[0].type).toBe('text')
// Parse the JSON response
const resolvedFrames = JSON.parse(content[0].text)
expect(resolvedFrames).toBeInstanceOf(Array)
expect(resolvedFrames.length).toBeGreaterThan(0)
// Verify resolution worked
const resolved = resolvedFrames[0]
if (resolved.status === 'fulfilled') {
const { originalStackFrame, originalCodeFrame } = resolved.value
expect(originalStackFrame).toBeTruthy()
expect(originalStackFrame.file).toContain('error-test-button/page.tsx')
expect(originalStackFrame.methodName).toContain('ErrorTestButtonPage')
if (originalCodeFrame) {
expect(originalCodeFrame).toContain('throw new Error')
}
}
await browser.close()
})
})
export 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
}
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