Unverified Commit 943d76ba authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Add bundle source MCP queries

Co-authored-by: 's avatarWill Binns-Smith <755844+wbinnssmith@users.noreply.github.com>
parent bcacea1a
......@@ -8,11 +8,35 @@ const { McpServer } =
const DEFAULT_LIMIT = 50
const MAX_LIMIT = 100
const MAX_CHUNKS = 100
const COMPRESSED_CAVEAT =
'Compressed source sizes are estimates because attributed parts are compressed independently.'
type Environment = 'total' | 'client'
type Environment = 'total' | 'client' | 'server'
type Metric = 'raw' | 'compressed'
type FileType = 'js' | 'css' | 'json' | 'asset'
interface Pagination {
offset: number
limit: number
total: number
returned: number
truncated: boolean
}
interface SourceRow {
key: string
sourcePath?: string
packageName?: string
rawSize: number
compressedSize: number
client: boolean
server: boolean
traced: boolean
chunks: string[]
chunkCount: number
chunksTruncated: boolean
}
interface OverviewArgs {
snapshot?: string
......@@ -23,6 +47,18 @@ interface OverviewArgs {
limit?: number
}
interface SourcesArgs {
route: string
snapshot?: string
search?: string
environment?: Environment
fileTypes?: FileType[]
groupBy?: 'source' | 'package'
metric?: Metric
offset?: number
limit?: number
}
function jsonResult(value: unknown, isError = false) {
return {
...(isError ? { isError: true } : {}),
......@@ -34,6 +70,7 @@ function publicError(error: unknown): string {
if (!(error instanceof Error)) return 'Unable to query analyzer data'
if (error.message.startsWith('Unknown snapshot')) return 'Unknown snapshot'
if (error.message.startsWith('Unknown route')) return 'Unknown route'
if (error.message.startsWith('Unknown source')) return 'Unknown source'
if (/^Invalid /.test(error.message)) {
return error.message
}
......@@ -50,17 +87,20 @@ function safeTool<T, R>(fn: (args: T) => Promise<R>) {
}
}
function pagination(offset: number, limit: number, total: number): Pagination {
return {
offset,
limit,
total,
returned: Math.max(0, Math.min(limit, total - offset)),
truncated: offset + limit < total,
}
}
function page<T>(values: T[], offset: number, limit: number) {
const result = values.slice(offset, offset + limit)
return {
values: result,
pagination: {
offset,
limit,
total: values.length,
returned: result.length,
truncated: offset + limit < values.length,
},
values: values.slice(offset, offset + limit),
pagination: pagination(offset, limit, values.length),
}
}
......@@ -75,6 +115,10 @@ function metricValue(
return metric === 'compressed' ? value.compressedSize : value.rawSize
}
function outputEnvironment(filename: string): 'client' | 'server' {
return filename.startsWith('[client-fs]/') ? 'client' : 'server'
}
function sourceSizes(
data: AnalyzeData,
sourceIndex: number,
......@@ -88,8 +132,7 @@ function sourceSizes(
if (!part || !output) continue
if (
environment !== 'total' &&
(output.filename.startsWith('[client-fs]/') ? 'client' : 'server') !==
environment
outputEnvironment(output.filename) !== environment
) {
continue
}
......@@ -110,6 +153,100 @@ function routeSizes(data: AnalyzeData, environment: Environment) {
return { rawSize, compressedSize }
}
function packageNameFromPath(sourcePath: string): string | undefined {
const marker = 'node_modules/'
const start = sourcePath.lastIndexOf(marker)
if (start === -1) return undefined
const parts = sourcePath.slice(start + marker.length).split('/')
if (!parts[0] || parts[0] === '.pnpm') return undefined
return parts[0].startsWith('@') && parts[1]
? `${parts[0]}/${parts[1]}`
: parts[0]
}
function hasFileType(
flags: ReturnType<AnalyzeData['getSourceFlags']>,
types: FileType[] | undefined
): boolean {
return !types?.length || types.some((type) => flags[type])
}
function collectSources(
data: AnalyzeData,
options: {
search?: string
environment: Environment
fileTypes?: FileType[]
groupBy: 'source' | 'package'
}
): SourceRow[] {
const search = options.search?.toLocaleLowerCase()
const rows = new Map<string, SourceRow>()
for (let index = 0; index < data.sourceCount(); index++) {
if (data.sourceChunkParts(index).length === 0) continue
const sourcePath = data.getFullSourcePath(index)
if (
!sourcePath ||
(search && !sourcePath.toLocaleLowerCase().includes(search))
) {
continue
}
const flags = data.getSourceFlags(index)
if (
(options.environment === 'client' && !flags.client) ||
(options.environment === 'server' && !flags.server) ||
!hasFileType(flags, options.fileTypes)
) {
continue
}
const sizes = sourceSizes(data, index, options.environment)
if (sizes.rawSize === 0 && sizes.compressedSize === 0) continue
const packageName = packageNameFromPath(sourcePath)
const key =
options.groupBy === 'package' && packageName ? packageName : sourcePath
const existing = rows.get(key)
if (existing) {
existing.rawSize += sizes.rawSize
existing.compressedSize += sizes.compressedSize
existing.client ||= flags.client
existing.server ||= flags.server
existing.traced ||= flags.traced
existing.chunks.push(...data.sourceChunks(index))
} else {
rows.set(key, {
key,
...(options.groupBy === 'package' && packageName
? { packageName }
: { sourcePath }),
...sizes,
client: flags.client,
server: flags.server,
traced: flags.traced,
chunks: data.sourceChunks(index),
chunkCount: 0,
chunksTruncated: false,
})
}
}
return [...rows.values()].map((row) => {
const chunks = [...new Set(row.chunks)].sort(compareText)
return {
...row,
chunks: chunks.slice(0, MAX_CHUNKS),
chunkCount: chunks.length,
chunksTruncated: chunks.length > MAX_CHUNKS,
}
})
}
function sortBySize(rows: SourceRow[], metric: Metric): SourceRow[] {
return rows.sort(
(a, b) =>
metricValue(b, metric) - metricValue(a, metric) ||
compareText(a.key, b.key)
)
}
function provenance(metadata: SnapshotMetadata) {
return {
id: metadata.id,
......@@ -146,6 +283,7 @@ const snapshotSchema = z
.optional()
.describe('`current` (default) or an exact historical snapshot ID.')
const metricSchema = z.enum(['raw', 'compressed']).optional()
const environmentSchema = z.enum(['total', 'client', 'server']).optional()
export function createAnalyzeMcpServer(repository: AnalyzeRepository) {
const server = new McpServer({
......@@ -206,5 +344,52 @@ export function createAnalyzeMcpServer(repository: AnalyzeRepository) {
})
)
server.registerTool(
'query_bundle_sources',
{
description:
'Query and rank source or npm-package contributions for one analyzed route.',
inputSchema: {
route: z.string().max(4096),
snapshot: snapshotSchema,
search: z.string().max(1000).optional(),
environment: environmentSchema,
fileTypes: z
.array(z.enum(['js', 'css', 'json', 'asset']))
.max(4)
.optional(),
groupBy: z.enum(['source', 'package']).optional(),
metric: metricSchema,
...pagingSchema,
},
},
safeTool(async (args: SourcesArgs) => {
const environment = args.environment ?? 'total'
const metric = args.metric ?? 'raw'
const rows = sortBySize(
collectSources(await repository.loadRoute(args.snapshot, args.route), {
search: args.search,
environment,
fileTypes: args.fileTypes,
groupBy: args.groupBy ?? 'source',
}),
metric
)
const paged = page(rows, args.offset ?? 0, args.limit ?? DEFAULT_LIMIT)
return {
route: args.route,
snapshot: provenance(
(await repository.getSnapshot(args.snapshot)).metadata
),
environment,
metric,
groupBy: args.groupBy ?? 'source',
sources: paged.values,
pagination: paged.pagination,
caveats: [COMPRESSED_CAVEAT],
}
})
)
return server
}
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { AnalyzeRepository } from './repository'
const directories: string[] = []
afterEach(async () => {
await Promise.all(
directories.splice(0).map((directory) => rm(directory, { recursive: true }))
)
})
async function fixture(): Promise<AnalyzeRepository> {
const directory = await mkdtemp(
path.join(tmpdir(), 'next-analyze-repository-')
)
directories.push(directory)
await mkdir(path.join(directory, 'data'), { recursive: true })
await mkdir(path.join(directory, 'history'), { recursive: true })
const metadata = {
id: '20250101-000000-local',
createdAt: '2025-01-01T00:00:00.000Z',
routeCount: 1,
}
await writeFile(
path.join(directory, 'data', 'metadata.json'),
JSON.stringify(metadata)
)
await writeFile(
path.join(directory, 'data', 'routes.json'),
JSON.stringify(['/'])
)
await writeFile(
path.join(directory, 'history', 'history.json'),
JSON.stringify({ snapshots: [] })
)
return new AnalyzeRepository(directory)
}
describe('AnalyzeRepository path validation', () => {
it.each(['/../secret', '/%2e%2e/secret', '/foo\\..\\secret', 'relative'])(
'rejects unsafe route %s',
async (route) => {
const repository = await fixture()
await expect(repository.loadRoute('current', route)).rejects.toThrow(
'Invalid route'
)
}
)
it('rejects unknown routes before reading a dataset', async () => {
const repository = await fixture()
await expect(repository.loadRoute('current', '/unknown')).rejects.toThrow(
'Unknown route'
)
})
it('rejects malformed and unknown snapshot identifiers', async () => {
const repository = await fixture()
await expect(repository.getSnapshot('../data')).rejects.toThrow(
'Invalid snapshot identifier'
)
await expect(
repository.getSnapshot('20250101-000001-local')
).rejects.toThrow('Unknown snapshot')
})
})
......@@ -121,7 +121,7 @@ describe('next experimental-analyze', () => {
const toolList = await callMcp(mcpUrl, 'tools/list', {})
expect(toolList.tools.map((tool: { name: string }) => tool.name)).toEqual(
['get_bundle_overview']
['get_bundle_overview', 'query_bundle_sources']
)
const overview = await callMcpTool(mcpUrl, 'get_bundle_overview', {
......@@ -142,6 +142,39 @@ describe('next experimental-analyze', () => {
})
).toEqual(overview)
const concurrent = await Promise.all([
callMcpTool(mcpUrl, 'get_bundle_overview', { routeFilter: 'NOT' }, 101),
callMcpTool(mcpUrl, 'get_bundle_overview', { routeFilter: '/' }, 102),
callMcpTool(
mcpUrl,
'query_bundle_sources',
{ route: '/', limit: 1 },
103
),
])
expect(concurrent[0].routes[0].route).toBe('/_not-found')
expect(concurrent[1].routes).toHaveLength(2)
expect(concurrent[2].sources).toHaveLength(1)
const sources = await callMcpTool(mcpUrl, 'query_bundle_sources', {
route: '/',
search: 'project',
limit: 1,
})
expect(sources.pagination).toMatchObject({ limit: 1, returned: 1 })
expect(sources.sources[0]).toMatchObject({
sourcePath: expect.any(String),
rawSize: expect.any(Number),
compressedSize: expect.any(Number),
})
const packages = await callMcpTool(mcpUrl, 'query_bundle_sources', {
route: '/',
groupBy: 'package',
limit: 1,
})
expect(packages.groupBy).toBe('package')
expect(packages.sources).toHaveLength(1)
} finally {
serveProcess?.kill()
await exit.catch(() => {})
......
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