Skip to main content
Glama

find_unused_javascript

Identify and eliminate unused JavaScript code to optimize website performance and reduce bundle size. Analyze URLs, specify device emulation, and set minimum unused byte thresholds for targeted improvements.

Instructions

Find unused JavaScript code to reduce bundle size

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
deviceNoDevice to emulate (default: desktop)desktop
minBytesNoMinimum unused bytes to report (default: 2048)
urlYesURL to audit

Implementation Reference

  • Core handler function that runs a Lighthouse performance audit, extracts unused JavaScript from the 'unused-javascript' audit, filters items by minimum byte threshold, computes totals, and returns structured results including URL, device, total unused bytes, filtered items, and fetch time.
    export async function findUnusedJavaScript(
      url: string,
      device: "desktop" | "mobile" = "desktop",
      minBytes = DEFAULTS.MIN_UNUSED_JS_BYTES,
    ) {
      const runnerResult = await runRawLighthouseAudit(url, ["performance"], device);
      const { lhr } = runnerResult;
    
      const unusedJsAudit = lhr.audits["unused-javascript"];
    
      if (!unusedJsAudit || !unusedJsAudit.details) {
        return {
          url: lhr.finalDisplayedUrl,
          device,
          totalUnusedBytes: 0,
          items: [],
          fetchTime: lhr.fetchTime,
        };
      }
    
      // Filter items by minimum bytes
      const items = (unusedJsAudit.details.items || [])
        .filter((item: Record<string, unknown>) => (item.wastedBytes as number) >= minBytes)
        .map((item: Record<string, unknown>) => ({
          url: item.url as string,
          totalBytes: item.totalBytes as number,
          wastedBytes: item.wastedBytes as number,
          wastedPercent: Math.round(((item.wastedBytes as number) / (item.totalBytes as number)) * 100),
        }));
    
      const totalUnusedBytes = items.reduce((sum: number, item: { wastedBytes: number }) => sum + item.wastedBytes, 0);
    
      return {
        url: lhr.finalDisplayedUrl,
        device,
        totalUnusedBytes,
        items,
        fetchTime: lhr.fetchTime,
      };
    }
  • Zod schema defining input parameters for the tool: URL (validated HTTP/HTTPS), device (desktop/mobile), minBytes (minimum wasted bytes threshold, default 2048).
    export const unusedJavaScriptSchema = {
      url: baseSchemas.url,
      device: baseSchemas.device,
      minBytes: z.number().min(0).default(2048).describe("Minimum unused bytes to report (default: 2048)"),
    };
  • MCP server tool registration for 'find_unused_javascript', providing description, input schema, and async handler that calls the core findUnusedJavaScript function, processes results into AI-friendly structured data with summaries and recommendations, handles errors, and returns formatted content.
    server.tool(
      "find_unused_javascript",
      "Find unused JavaScript code to reduce bundle size",
      unusedJavaScriptSchema,
      async ({ url, device, minBytes }) => {
        try {
          const result = await findUnusedJavaScript(url, device, minBytes);
    
          // Create structured, AI-friendly response
          const analysisData = {
            url: result.url,
            device: result.device,
            timestamp: result.fetchTime,
            thresholdBytes: minBytes,
            summary: {
              totalUnusedKB: Math.round((result.totalUnusedBytes / 1024) * 100) / 100,
              totalFilesAnalyzed: result.items.length,
              hasUnusedCode: result.items.length > 0,
            },
            unusedFiles: result.items.map((item) => ({
              filename: item.url.split("/").pop() || item.url,
              totalKB: Math.round((item.totalBytes / 1024) * 100) / 100,
              unusedKB: Math.round((item.wastedBytes / 1024) * 100) / 100,
              unusedPercent: item.wastedPercent,
              url: item.url,
            })),
            recommendations:
              result.items.length > 0
                ? [
                    "Remove unused JavaScript code",
                    "Implement code splitting",
                    "Use tree shaking",
                    "Add lazy loading for non-critical scripts",
                  ]
                : ["No optimization needed - minimal unused code detected"],
          };
    
          const summary =
            result.items.length > 0
              ? `Found ${result.items.length} files with unused JavaScript (${analysisData.summary.totalUnusedKB}KB total)`
              : `No significant unused JavaScript found above ${minBytes} byte threshold`;
    
          return {
            content: createStructuredAnalysis("Unused JavaScript Analysis", analysisData, summary),
          };
        } catch (error: unknown) {
          const errorMessage = error instanceof Error ? error.message : String(error);
          return {
            content: [
              {
                type: "text" as const,
                text: `Analysis failed: ${errorMessage}`,
              },
              {
                type: "text" as const,
                text: JSON.stringify(
                  {
                    error: true,
                    url,
                    device,
                    message: errorMessage,
                    timestamp: new Date().toISOString(),
                  },
                  null,
                  2,
                ),
              },
            ],
            isError: true,
          };
        }
      },
    );
  • src/index.ts:27-27 (registration)
    Top-level call to register all analysis tools, including find_unused_javascript, on the MCP server.
    registerAnalysisTools(server);
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden but only states the high-level goal without disclosing behavioral traits. It doesn't mention whether this is a read-only analysis, requires network access, has rate limits, returns specific formats, or what 'unused' means operationally (e.g., static vs. runtime analysis).

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence with zero waste—every word contributes to the purpose. It's appropriately sized and front-loaded with the core action and goal.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a 3-parameter analysis tool with no annotations and no output schema, the description is incomplete. It lacks details on what the tool actually returns (e.g., list of files, byte counts, recommendations), how 'unused' is determined, or any behavioral context needed for effective use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema fully documents all parameters. The description adds no additional meaning about parameters beyond implying URL analysis for JavaScript, which is already covered by the schema's 'url' parameter description. Baseline 3 is appropriate when schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('find') and resource ('unused JavaScript code') with a specific goal ('to reduce bundle size'). It distinguishes itself from siblings like 'analyze_resources' or 'check_performance_budget' by focusing specifically on JavaScript code usage analysis, though it doesn't explicitly name alternatives.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives like 'analyze_resources' or 'run_audit', nor does it mention prerequisites or exclusions. It implies usage for bundle optimization but lacks explicit context about when this specific analysis is preferred.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/danielsogl/lighthouse-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server