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