Skip to main content
Glama
perfonext-profiler-mcp

perfonext-profiler-mcp

perfonext-profiler-mcp

Analyze V8 and Chrome CPU profiles to find hotspots in Next.js servers and scripts.

npm npm downloads license website

perfonext-profiler-mcp is a Model Context Protocol (MCP) server that gives GitHub Copilot, Claude Desktop, Claude Code, and other MCP clients structured CPU profiling data for Next.js performance work. It loads V8 and Chrome CPU profiles and turns them into hotspot rankings, per-package costs, and source-annotated hot lines — evidence agents can reason over instead of ingesting multi-megabyte profile dumps.

Quick Start

perfonext-profiler-mcp is a standard MCP stdio server, so it works with any MCP-compatible client (GitHub Copilot in VS Code, Claude Desktop, Claude Code, Cursor, and others). Run it directly with npx:

npx -y @perfonext/profiler-mcp

Or install globally:

npm install -g @perfonext/profiler-mcp

The executable command remains perfonext-profiler-mcp after installation.

VS Code

Add the server to .vscode/mcp.json (the workspace MCP configuration file):

{
  "servers": {
    "perfonext-profiler": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@perfonext/profiler-mcp"]
    }
  }
}

Reload the VS Code window and run MCP: List Servers to start it, or accept the trust prompt when it appears.

Claude Desktop

Add the server to claude_desktop_config.json:

{
  "mcpServers": {
    "perfonext-profiler": {
      "command": "npx",
      "args": ["-y", "@perfonext/profiler-mcp"]
    }
  }
}

Restart Claude Desktop to pick up the new server.

Claude Code

Add the server with the CLI:

claude mcp add perfonext-profiler -- npx -y @perfonext/profiler-mcp

Or add the same mcpServers entry to .mcp.json.

Other MCP clients

Any client that supports stdio MCP servers can launch npx -y @perfonext/profiler-mcp. Consult your client's documentation for its MCP server configuration format.

For a locally-built checkout, point command/args at node and the repo's dist/index.js instead.

Related MCP server: Debugger MCP Server

Troubleshooting

spawn npx ENOENT / spawn node ENOENT on macOS with nvm

If the server fails to start with this error, your GUI MCP client likely cannot see nvm. GUI apps on macOS do not load shell config (.zshrc/.bashrc), so nvm-installed npx/node are not on PATH. Use an absolute npx path and include the same Node directory in PATH:

{
  "servers": {
    "perfonext-profiler": {
      "type": "stdio",
      "command": "/Users/YOU/.nvm/versions/node/v<version>/bin/npx",
      "args": ["-y", "@perfonext/profiler-mcp"],
      "env": {
        "PATH": "/Users/YOU/.nvm/versions/node/v<version>/bin:/usr/bin:/bin"
      }
    }
  }
}

Merge these fields into your client's server entry, under servers for VS Code or mcpServers for Claude Desktop/Code. Then ask your assistant: "How do I capture a CPU profile of my Next.js server?"

What It Does

  • loads .cpuprofile files and Chrome trace exports that contain CPU profile data

  • identifies the hottest functions by self time, annotated with the originating npm package

  • explains caller and callee relationships for a selected function

  • reads actual source code for hot functions and annotates each line with V8 sample counts (v0.2.0)

  • aggregates CPU self-time per npm package to find expensive third-party dependencies (v0.3.0)

  • compares two profiles to surface regressions and improvements

  • returns deterministic optimization suggestions for common hotspots

  • summarizes loaded profiles so an MCP client can keep context tight

Tools

Tool

Description

how_to_collect

Return a ready-to-run command and step-by-step recipe for capturing a .cpuprofile, then loading it. Use this when you don't have a profile yet

load_profile

Parse and load a .cpuprofile file or Chrome trace export from disk

get_hotspots

Find top functions by self-time. Each entry includes a package field identifying the npm package or (user code)

explain_function

Explain a function's timing, callers, and callees. Pass includeSource: true to attach annotated source lines

read_source_context

Read the actual source file for a hot function and annotate each line with tick counts from positionTicks

get_package_costs

Aggregate CPU self-time by npm package — shows which dependencies are most expensive

compare_profiles

Compare two profiles and highlight regressions

suggest_optimizations

Generate structured, multi-pattern optimization suggestions for hot functions. Detects high fan-in, recursion, dominant callers, and V8-specific patterns. Deduplicates functions split across multiple call sites

get_profile_summary

Summarize one profile or list all loaded profiles

Every tool result carries a nextStep breadcrumb pointing at the natural follow-up call, so an MCP client can walk the collect → analyze → fix loop without guessing.

Example Prompts

  • "How do I capture a CPU profile of my Next.js server?"

  • "Load the CPU profile at ./profile.cpuprofile and show me the top hotspots."

  • "Which npm packages are consuming the most CPU in this profile?"

  • "Explain why processData is expensive in the loaded profile."

  • "Show me the actual source lines for processData and mark which lines are hottest."

  • "Explain transformResult and include the annotated source code."

  • "Compare my baseline and current CPU profiles and tell me what got slower."

  • "Suggest optimizations for the top three hotspots."

Deep Tool Reference

how_to_collect details

// Input
{ "scenario": "next-server" } // or "script"; defaults to "next-server"

// Output
{
  "scenario": "next-server",
  "summary": "Profile a production Next.js server while it handles a single request. ...",
  "command": "node --cpu-prof --cpu-prof-dir=./.perf-profiles ./node_modules/next/dist/bin/next start",
  "steps": [ "...", "load_profile({ filePath: \"./.perf-profiles/<file>.cpuprofile\" })" ],
  "outputDir": "./.perf-profiles",
  "nextStep": "After stopping the server, call load_profile with the .cpuprofile ..."
}

next-server profiles a production Next.js server while it serves a single request. If next start says standalone output is unsupported, use the script scenario with .next/standalone/server.js. script profiles that standalone server (or another Node entry). Keep the scenario to one route and one hit. Node writes one .cpuprofile per process/worker thread into the output directory. The Next server command uses Node CLI flags (not NODE_OPTIONS) so it is the same on Unix and Windows.

read_source_context details

// Input
{ "profileId": "<id>", "functionName": "myFn", "contextLines": 10 }

// Output (per line)
{
  "lineNumber": 42,
  "content": "  for (let i = 0; i < items.length; i++) {",
  "ticks": 18,      // V8 samples that landed on this line
  "isHot": true     // true when ticks >= 50% of peak ticks for this function
}

The returned window is sized to cover the function's actual hot lines, not just a fixed radius around its declaration — a function's real bottleneck is often well past its function line. contextLines (default 10) sets the minimum padding around both the declaration and the hot lines; if any ticks still fall outside the returned window, the top-level result includes hiddenTicks (a count) and a warning telling you to retry with a larger contextLines. explain_function also accepts contextLines when called with includeSource: true.

Only files inside the current working directory can be read. file:// URLs and absolute paths are both handled; http://, node: builtins, and paths outside the project root are rejected.

suggest_optimizations details

// Input
{ "profileId": "<id>", "limit": 5 }

// Output (per function)
{
  "function": "processData",
  "file": "file:///app/src/processor.js",
  "line": 10,
  "selfPercent": "18.2%",
  "patterns": [
    {
      "pattern": "high-fan-in",
      "detail": "Called from 6 distinct call sites (e.g. renderRow, buildTree, …)",
      "suggestion": "This function is a shared hot path. Ensure it is well-optimised and monomorphic …"
    },
    {
      "pattern": "hot-caller",
      "detail": "84% of calls come from \"renderRow\"",
      "suggestion": "Focus optimisation effort on \"renderRow\" rather than this function …"
    }
  ],
  "topSuggestion": "This function is a shared hot path …"
}

Patterns detected (multiple can fire for the same function):

Pattern

Trigger

gc-pressure

Function name matches GC/Scavenge/MarkCompact

json-serialization

JSON.parse / JSON.stringify

regex-cost

RegExp / exec / test calls

v8-deopt

Compile / Recompile / Optimize / Deoptimize

high-fan-in

≥ 3 distinct parent call sites

recursion

Function appears in its own descendant sub-tree

hot-caller

One caller accounts for ≥ 80% of call-site occurrences

cpu-bound

Fallback when no other pattern matches

Functions that appear at multiple call sites are automatically merged before ranking so the same logical function is only reported once.

get_package_costs details

// Input
{ "profileId": "<id>", "limit": 10 }

// Output (per package)
{
  "rank": 1,
  "package": "lodash",
  "selfTime": "42.3ms",
  "selfPercent": "14.1%",
  "totalTimeIncludingCallbacks": "58.0ms",
  "totalPercentIncludingCallbacks": "19.3%",
  "topFunctions": [
    { "function": "chunk", "file": "lodash/chunk.js", "line": 41, "selfTime": "28.0ms", "selfPercent": "9.3%" }
  ]
}

selfTime is the time spent inside the package's own code. totalTimeIncludingCallbacks also counts everything the package called into — including your own callbacks handed back to it — so it can exceed what removing the package would actually save.

Scoped packages (@babel/core, @next/env, etc.) are handled correctly. User code and native builtins (no node_modules in the path) are excluded.

Generating a CPU Profile

Ask Copilot to call how_to_collect for a ready-to-run recipe, or generate one manually:

Next.js production server (profile a single request):

node --cpu-prof --cpu-prof-dir=./.perf-profiles ./node_modules/next/dist/bin/next start
# hit the route once, then stop the process so it can exit and write the profile

If next start reports that standalone output is unsupported:

node --cpu-prof --cpu-prof-dir=./.perf-profiles .next/standalone/server.js

Chrome DevTools:

  1. Open DevTools and go to the Performance tab.

  2. Record the scenario you want to inspect.

  3. Stop recording and save the result as a .cpuprofile export.

Development

npm install
npm run build
npm test

The repository already includes sample fixtures under tests/fixtures/ for local validation.

License

MIT

Available Tools

9 tools
compare_profilesCompare ProfilesA

Compare two loaded CPU profiles side-by-side. Shows functions that got slower/faster and new/removed hotspots.

Inputs: baseProfileId (required), compareProfileId (required), limit.

explain_functionExplain FunctionA

Returns detailed timing info for a specific function: self-time, total-time, callers, and callees. Use this to understand why a function is slow.

Inputs: profileId (required), functionName (required), contextLines, includeSource.

get_hotspotsGet HotspotsA

Returns the top N functions by self-time (CPU time spent directly in the function, not its callees). Use this to find performance bottlenecks.

Inputs: profileId (required), limit.

get_package_costsGet Package CostsA

Aggregate CPU self-time by npm package. Identifies which third-party dependencies are consuming the most CPU, by parsing node_modules paths from the profile. Useful for deciding which packages to replace, lazy-load, or avoid. Scoped packages (e.g. @babel/core) are handled correctly.

Inputs: profileId (required), limit.

get_profile_summaryGet Profile SummaryA

Returns an overview of a loaded profile: duration, sample count, top-level call tree (filtered to functions >0.1% of total time), and idle time percentage. For large profiles, the call tree is limited to depth 2 and top 20 children per node to keep output manageable. Also lists all loaded profiles if no ID is given.

Inputs: profileId, treeDepth.

how_to_collectHow To Collect a CPU ProfileA

Returns a ready-to-run command and step-by-step recipe for capturing a V8 CPU profile, then loading it with load_profile. Use this when you do not yet have a .cpuprofile file. Choose the scenario that matches how the code runs.

Inputs: scenario.

load_profileLoad CPU ProfileA

Parse and load a V8/Chrome CPU profile from disk. Supports both .cpuprofile files and Chrome DevTools Trace JSON exports. Returns a profile ID for use with other tools.

Inputs: filePath (required).

read_source_contextRead Source ContextA

Read the actual source code for a hot function and annotate each line with sampled tick counts from positionTicks. The returned window is sized to cover the function's actual hot lines, not just the area around its declaration; if any ticks still fall outside it, a warning field reports how many and suggests a larger contextLines. Only reads files within the project root.

Inputs: profileId (required), functionName (required), contextLines.

suggest_optimizationsSuggest OptimizationsA

Analyzes the profile and returns structured optimization suggestions for the hottest functions. Detects high fan-in, recursion, dominant callers, V8-specific patterns, always reports CPU self-time cost for expensive functions, and deduplicates functions split across multiple call sites.

Inputs: profileId (required), limit.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.2/5.0

    Scored across 9 tools

    Disambiguation5/5

    Each tool maps to a distinct part of the profiling workflow: loading, summarizing, hotspot analysis, per-function detail, comparison, optimization, source inspection, package aggregation, and collection guidance. There is no meaningful overlap that would make an agent choose the wrong tool.

    Naming Consistency4/5

    Most tools follow a clear snake_case verb_noun pattern such as load_profile, get_hotspots, and compare_profiles. A few names like explain_function and how_to_collect deviate slightly from the predominant get_ style, but the naming is still predictable and readable.

    Tool Count5/5

    Nine tools is an ideal size for a profiler-analysis server: each tool serves a distinct analytical purpose and the set is neither bloated nor thin. The count feels appropriately scoped to the domain.

    Completeness5/5

    The tool surface covers the full workflow from capturing/loading profiles to summarizing, exploring hotspots, comparing profiles, reading source context, and identifying expensive packages. There are no obvious dead ends or missing operations that would prevent an agent from completing a typical profiling analysis.

    Maintenance

    ActivitySlowing
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      MCP server for Polar Signals Cloud continuous profiling platform, enabling AI assistants to analyze CPU performance, memory usage, and identify optimization opportunities in production systems.
      9
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides real-time debugging, code quality monitoring, and performance insights for React/Next.js applications with features including Chrome DevTools integration, breakpoint management, complexity analysis, and live error streaming.
      1
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      Live .NET runtime diagnostics for AI assistants. Ask Claude to diagnose memory leaks, GC pressure, LOH fragmentation, and thread starvation in any running .NET process — no code changes required.
      7
      2
      MIT