Unverified Commit bb88ea52 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

[mcp] change the mcp endpoint response to JSON (#88911)

parent d1cf4e69
......@@ -51,7 +51,10 @@ export function registerGetErrorsTool(
content: [
{
type: 'text',
text: 'No browser sessions connected. Please open your application in a browser to retrieve error state.',
text: JSON.stringify({
error:
'No browser sessions connected. Please open your application in a browser to retrieve error state.',
}),
},
],
}
......@@ -83,10 +86,10 @@ export function registerGetErrorsTool(
content: [
{
type: 'text',
text:
responses.length === 0
? 'No browser sessions responded.'
: `No errors detected in ${responses.length} browser session(s).`,
text: JSON.stringify({
configErrors: [],
sessionErrors: [],
}),
},
],
}
......@@ -101,7 +104,7 @@ export function registerGetErrorsTool(
content: [
{
type: 'text',
text: output,
text: JSON.stringify(output),
},
],
}
......@@ -110,7 +113,9 @@ export function registerGetErrorsTool(
content: [
{
type: 'text',
text: `Error: ${error instanceof Error ? error.message : String(error)}`,
text: JSON.stringify({
error: error instanceof Error ? error.message : String(error),
}),
},
],
}
......
......@@ -31,7 +31,9 @@ export function registerGetLogsTool(server: McpServer, distDir: string) {
content: [
{
type: 'text',
text: `Log file not found at ${logFilePath}.`,
text: JSON.stringify({
error: `Log file not found at ${logFilePath}.`,
}),
},
],
}
......@@ -41,7 +43,9 @@ export function registerGetLogsTool(server: McpServer, distDir: string) {
content: [
{
type: 'text',
text: `Next.js log file path: ${logFilePath}`,
text: JSON.stringify({
logFilePath,
}),
},
],
}
......@@ -50,7 +54,9 @@ export function registerGetLogsTool(server: McpServer, distDir: string) {
content: [
{
type: 'text',
text: `Error getting log file path: ${error instanceof Error ? error.message : String(error)}`,
text: JSON.stringify({
error: `Error getting log file path: ${error instanceof Error ? error.message : String(error)}`,
}),
},
],
}
......
......@@ -39,7 +39,10 @@ export function registerGetPageMetadataTool(
content: [
{
type: 'text',
text: 'No browser sessions connected. Please open your application in a browser to retrieve page metadata.',
text: JSON.stringify({
error:
'No browser sessions connected. Please open your application in a browser to retrieve page metadata.',
}),
},
],
}
......@@ -57,7 +60,9 @@ export function registerGetPageMetadataTool(
content: [
{
type: 'text',
text: 'No browser sessions responded.',
text: JSON.stringify({
sessions: [],
}),
},
],
}
......@@ -78,7 +83,9 @@ export function registerGetPageMetadataTool(
content: [
{
type: 'text',
text: `No page metadata available from ${responses.length} browser session(s).`,
text: JSON.stringify({
sessions: [],
}),
},
],
}
......@@ -90,7 +97,7 @@ export function registerGetPageMetadataTool(
content: [
{
type: 'text',
text: output,
text: JSON.stringify(output),
},
],
}
......@@ -99,7 +106,9 @@ export function registerGetPageMetadataTool(
content: [
{
type: 'text',
text: `Error: ${error instanceof Error ? error.message : String(error)}`,
text: JSON.stringify({
error: error instanceof Error ? error.message : String(error),
}),
},
],
}
......@@ -150,10 +159,27 @@ function convertSegmentTrieToPageMetadata(data: SegmentTrieData): PageMetadata {
}
}
interface FormattedSegment {
path: string
type: string
isBoundary: boolean
isBuiltin: boolean
}
interface FormattedSession {
url: string
routerType: string
segments: FormattedSegment[]
}
interface FormattedPageMetadataOutput {
sessions: FormattedSession[]
}
function formatPageMetadata(
sessionMetadata: Array<{ url: string; metadata: PageMetadata }>
): string {
let output = `# Page metadata from ${sessionMetadata.length} browser session(s)\n\n`
): FormattedPageMetadataOutput {
const sessions: FormattedSession[] = []
for (const { url, metadata } of sessionMetadata) {
let displayUrl = url
......@@ -164,56 +190,50 @@ function formatPageMetadata(
// If URL parsing fails, use the original URL
}
output += `## Session: ${displayUrl}\n\n`
output += `**Router type:** ${metadata.routerType}\n\n`
if (metadata.segments.length === 0) {
output += '*No segments found*\n\n'
} else {
output += '### Files powering this page:\n\n'
// Ensure consistent output to avoid flaky tests
const sortedSegments = [...metadata.segments].sort((a, b) => {
const typeOrder = (segment: PageSegment): number => {
const type = segment.boundaryType || segment.type
if (type === 'layout') return 0
if (type.startsWith('boundary:')) return 1
if (type === 'page') return 2
return 3
}
const aOrder = typeOrder(a)
const bOrder = typeOrder(b)
if (aOrder !== bOrder) return aOrder - bOrder
return a.pagePath.localeCompare(b.pagePath)
})
for (const segment of sortedSegments) {
const path = segment.pagePath
const isBuiltin = path.startsWith('__next_builtin__')
// Ensure consistent output to avoid flaky tests
const sortedSegments = [...metadata.segments].sort((a, b) => {
const typeOrder = (segment: PageSegment): number => {
const type = segment.boundaryType || segment.type
const isBoundary = type.startsWith('boundary:')
let displayPath = path
.replace(/@boundary$/, '')
.replace(/^__next_builtin__/, '')
if (!isBuiltin && !displayPath.startsWith('app/')) {
displayPath = `app/${displayPath}`
}
const descriptors: string[] = []
if (isBoundary) descriptors.push('boundary')
if (isBuiltin) descriptors.push('builtin')
const descriptor =
descriptors.length > 0 ? ` (${descriptors.join(', ')})` : ''
output += `- ${displayPath}${descriptor}\n`
if (type === 'layout') return 0
if (type.startsWith('boundary:')) return 1
if (type === 'page') return 2
return 3
}
const aOrder = typeOrder(a)
const bOrder = typeOrder(b)
if (aOrder !== bOrder) return aOrder - bOrder
return a.pagePath.localeCompare(b.pagePath)
})
const formattedSegments: FormattedSegment[] = []
for (const segment of sortedSegments) {
const path = segment.pagePath
const isBuiltin = path.startsWith('__next_builtin__')
const type = segment.boundaryType || segment.type
const isBoundary = type.startsWith('boundary:')
let displayPath = path
.replace(/@boundary$/, '')
.replace(/^__next_builtin__/, '')
if (!isBuiltin && !displayPath.startsWith('app/')) {
displayPath = `app/${displayPath}`
}
output += '\n'
formattedSegments.push({
path: displayPath,
type,
isBoundary,
isBuiltin,
})
}
output += '---\n\n'
sessions.push({
url: displayUrl,
routerType: metadata.routerType,
segments: formattedSegments,
})
}
return output.trim()
return { sessions }
}
......@@ -23,7 +23,10 @@ export function registerGetProjectMetadataTool(
content: [
{
type: 'text',
text: 'Unable to determine the absolute path of the Next.js project.',
text: JSON.stringify({
error:
'Unable to determine the absolute path of the Next.js project.',
}),
},
],
}
......@@ -47,7 +50,9 @@ export function registerGetProjectMetadataTool(
content: [
{
type: 'text',
text: `Error: ${error instanceof Error ? error.message : String(error)}`,
text: JSON.stringify({
error: error instanceof Error ? error.message : String(error),
}),
},
],
}
......
......@@ -69,7 +69,9 @@ export function registerGetRoutesTool(
content: [
{
type: 'text',
text: 'No pages or app directory found in the project.',
text: JSON.stringify({
error: 'No pages or app directory found in the project.',
}),
},
],
}
......@@ -180,7 +182,10 @@ export function registerGetRoutesTool(
content: [
{
type: 'text',
text: 'No routes found in the project.',
text: JSON.stringify({
appRouter: [],
pagesRouter: [],
}),
},
],
}
......@@ -215,7 +220,9 @@ export function registerGetRoutesTool(
content: [
{
type: 'text',
text: `Error: ${error instanceof Error ? error.message : String(error)}`,
text: JSON.stringify({
error: error instanceof Error ? error.message : String(error),
}),
},
],
}
......
......@@ -41,7 +41,9 @@ export function registerGetActionByIdTool(server: McpServer, distDir: string) {
content: [
{
type: 'text',
text: 'Error: actionId parameter is required',
text: JSON.stringify({
error: 'actionId parameter is required',
}),
},
],
}
......@@ -61,7 +63,9 @@ export function registerGetActionByIdTool(server: McpServer, distDir: string) {
content: [
{
type: 'text',
text: `Error: Could not read server-reference-manifest.json at ${manifestPath}.`,
text: JSON.stringify({
error: `Could not read server-reference-manifest.json at ${manifestPath}.`,
}),
},
],
}
......@@ -129,7 +133,9 @@ export function registerGetActionByIdTool(server: McpServer, distDir: string) {
content: [
{
type: 'text',
text: `Error: Action ID "${actionId}" not found in server-reference-manifest.json`,
text: JSON.stringify({
error: `Action ID "${actionId}" not found in server-reference-manifest.json`,
}),
},
],
}
......@@ -138,7 +144,9 @@ export function registerGetActionByIdTool(server: McpServer, distDir: string) {
content: [
{
type: 'text',
text: `Error: ${error instanceof Error ? error.message : String(error)}`,
text: JSON.stringify({
error: error instanceof Error ? error.message : String(error),
}),
},
],
}
......
......@@ -35,25 +35,56 @@ async function resolveStackFrames(
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})`
interface StackFrame {
file: string
methodName: string
line: number | null
column: number | null
}
interface FormattedRuntimeError {
type: string
errorName: string
message: string
stack: StackFrame[]
}
interface FormattedSessionError {
url: string
buildError: string | null
runtimeErrors: FormattedRuntimeError[]
}
interface FormattedConfigError {
name: string
message: string
stack: string | null
}
const formatErrorFrames = async (
export interface FormattedErrorsOutput {
configErrors: FormattedConfigError[]
sessionErrors: FormattedSessionError[]
}
const formatStackFrameToObject = (
frame: StackFrameForFormatting
): StackFrame => {
return {
file: frame.file || '<unknown>',
methodName: frame.methodName || '<anonymous>',
line: frame.line1,
column: frame.column1,
}
}
const resolveErrorFrames = async (
frames: readonly StackFrameForFormatting[],
context: {
isServer: boolean
isEdgeServer: boolean
isAppDirectory: boolean
}
): Promise<string> => {
): Promise<StackFrame[]> => {
try {
const resolvedFrames = await resolveStackFrames({
frames: frames.map((frame) => ({
......@@ -68,132 +99,108 @@ const formatErrorFrames = async (
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'
)
return resolvedFrames
.filter(
(resolvedFrame) =>
!(
resolvedFrame.status === 'fulfilled' &&
resolvedFrame.value.originalStackFrame?.ignored
)
)
.map((resolvedFrame, j) =>
resolvedFrame.status === 'fulfilled' &&
resolvedFrame.value.originalStackFrame
? formatStackFrameToObject(resolvedFrame.value.originalStackFrame)
: formatStackFrameToObject(frames[j])
)
} catch {
return frames.map(formatStackFrame).join('\n') + '\n'
return frames.map(formatStackFrameToObject)
}
}
async function formatRuntimeError(
async function formatRuntimeErrorsToObjects(
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`
): Promise<FormattedRuntimeError[]> {
const formattedErrors: FormattedRuntimeError[] = []
for (const error of errors) {
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` : '')
)
let stack: StackFrame[] = []
if (error.frames?.length) {
const errorSource = getErrorSource(error.error)
stack = await resolveErrorFrames(error.frames, {
isServer: errorSource === 'server',
isEdgeServer: errorSource === 'edge-server',
isAppDirectory,
})
}
const errorSource = getErrorSource(error.error)
const frames = await formatErrorFrames(error.frames, {
isServer: errorSource === 'server',
isEdgeServer: errorSource === 'edge-server',
isAppDirectory,
formattedErrors.push({
type: error.type,
errorName,
message: errorMsg,
stack,
})
return errorHeader + errorMessage + `\`\`\`\n${frames}\`\`\`\n`
}
const formattedErrors = await Promise.all(errors.map(formatError))
return '### Runtime Errors\n' + formattedErrors.join('\n---\n')
return formattedErrors
}
export async function formatErrors(
errorsByUrl: Map<string, OverlayState>,
nextInstanceErrors: { nextConfig: unknown[] } = { nextConfig: [] }
): Promise<string> {
let output = ''
): Promise<FormattedErrorsOutput> {
const output: FormattedErrorsOutput = {
configErrors: [],
sessionErrors: [],
}
// Format Next.js instance errors first (e.g., next.config.js errors)
if (nextInstanceErrors.nextConfig.length > 0) {
output += `# Next.js Configuration Errors\n\n`
output += `**${nextInstanceErrors.nextConfig.length} error(s) found in next.config**\n\n`
nextInstanceErrors.nextConfig.forEach((error, index) => {
output += `## Error ${index + 1}\n\n`
output += '```\n'
if (error instanceof Error) {
output += `${error.name}: ${error.message}\n`
if (error.stack) {
output += error.stack
}
} else {
output += String(error)
}
output += '\n```\n\n'
})
output += '---\n\n'
for (const error of nextInstanceErrors.nextConfig) {
if (error instanceof Error) {
output.configErrors.push({
name: error.name,
message: error.message,
stack: error.stack || null,
})
} else {
output.configErrors.push({
name: 'Error',
message: String(error),
stack: null,
})
}
}
// Format browser session errors
if (errorsByUrl.size > 0) {
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'
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
}
const runtimeErrors = await formatRuntimeErrorsToObjects(
overlayState.errors,
overlayState.routerType === 'app'
)
output.sessionErrors.push({
url: displayUrl,
buildError: overlayState.buildError || null,
runtimeErrors,
})
}
return output.trim()
return output
}
......@@ -41,12 +41,12 @@ describe('get-logs MCP tool', () => {
await retry(async () => {
const sessionId = 'test-mcp-logs-' + Date.now()
const response = await callGetLogs(sessionId)
const responseText = await callGetLogs(sessionId)
const response = JSON.parse(responseText)
// Should return the log file path
expect(response).toContain('Next.js log file path:')
expect(response).toContain('logs/next-development.log')
expect(response).not.toContain('Log file not found at')
expect(response).toMatchObject({
logFilePath: expect.stringContaining('logs/next-development.log'),
})
})
})
})
......@@ -53,20 +53,21 @@ describe('mcp-server get_server_action_by_id tool', () => {
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 actionDetails = JSON.parse(content?.[0]?.text)
expect(callToolResult).toMatchObject({
jsonrpc: '2.0',
id: 'call-tool-1',
result: {
content: [{ type: 'text', text: expect.any(String) }],
},
})
// Verify the action details
expect(actionDetails.actionId).toBe(actionId)
expect(actionDetails.runtime).toBe('node')
expect(actionDetails.filename).toContain('app/actions.ts')
expect(actionDetails.functionName).toBeTruthy()
const actionDetails = JSON.parse(callToolResult.result.content[0].text)
expect(actionDetails).toMatchObject({
actionId,
runtime: 'node',
filename: expect.stringContaining('app/actions.ts'),
functionName: expect.any(String),
})
})
it('should return error for non-existent action ID', async () => {
......@@ -97,13 +98,18 @@ describe('mcp-server get_server_action_by_id tool', () => {
expect(callToolDataMatch).toBeTruthy()
const callToolResult = JSON.parse(callToolDataMatch![1])
expect(callToolResult.jsonrpc).toBe('2.0')
expect(callToolResult.id).toBe('call-tool-2')
expect(callToolResult).toMatchObject({
jsonrpc: '2.0',
id: 'call-tool-2',
result: {
content: [{ type: 'text', text: expect.any(String) }],
},
})
const content = callToolResult.result?.content
expect(content).toBeInstanceOf(Array)
expect(content?.[0]?.type).toBe('text')
expect(content?.[0]?.text).toContain('not found')
const errorResponse = JSON.parse(callToolResult.result.content[0].text)
expect(errorResponse).toMatchObject({
error: expect.stringContaining('not found'),
})
})
it('should return inline server action details', async () => {
......@@ -157,19 +163,20 @@ describe('mcp-server get_server_action_by_id tool', () => {
expect(callToolDataMatch).toBeTruthy()
const callToolResult = JSON.parse(callToolDataMatch![1])
expect(callToolResult.jsonrpc).toBe('2.0')
expect(callToolResult.id).toBe('call-tool-3')
const content = callToolResult.result?.content
expect(content).toBeInstanceOf(Array)
expect(content?.[0]?.type).toBe('text')
const actionDetails = JSON.parse(content?.[0]?.text)
expect(callToolResult).toMatchObject({
jsonrpc: '2.0',
id: 'call-tool-3',
result: {
content: [{ type: 'text', text: expect.any(String) }],
},
})
// Verify the inline action details
expect(actionDetails.actionId).toBe(inlineActionId)
expect(actionDetails.runtime).toBe('node')
expect(actionDetails.filename).toBeTruthy()
expect(actionDetails.functionName).toBe('inline server action')
const actionDetails = JSON.parse(callToolResult.result.content[0].text)
expect(actionDetails).toMatchObject({
actionId: inlineActionId,
runtime: 'node',
filename: expect.any(String),
functionName: 'inline server action',
})
})
})
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