Skip to main content
Glama

analyze_pcap

Extract and convert packet data from a PCAP file into JSON format using WireMCP for LLM-driven network analysis, enabling threat detection and diagnostics.

Instructions

Analyze a PCAP file and provide general packet data as JSON for LLM analysis

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pcapPathYesPath to the PCAP file to analyze (e.g., ./demo.pcap)

Implementation Reference

  • The handler function executes the analyze_pcap tool: parses PCAP with tshark, extracts IPs, URLs, protocols, packet JSON (trimmed if needed), and returns formatted text output.
    async (args) => {
      try {
        const tsharkPath = await findTshark();
        const { pcapPath } = args;
        console.error(`Analyzing PCAP file: ${pcapPath}`);
    
        // Check if file exists
        await fs.access(pcapPath);
    
        // Extract broad packet data
        const { stdout, stderr } = await execAsync(
          `${tsharkPath} -r "${pcapPath}" -T json -e frame.number -e ip.src -e ip.dst -e tcp.srcport -e tcp.dstport -e udp.srcport -e udp.dstport -e http.host -e http.request.uri -e frame.protocols`,
          { env: { ...process.env, PATH: `${process.env.PATH}:/usr/bin:/usr/local/bin:/opt/homebrew/bin` } }
        );
        if (stderr) console.error(`tshark stderr: ${stderr}`);
        const packets = JSON.parse(stdout);
    
        const ips = [...new Set(packets.flatMap(p => [
          p._source?.layers['ip.src']?.[0],
          p._source?.layers['ip.dst']?.[0]
        ]).filter(ip => ip))];
        console.error(`Found ${ips.length} unique IPs: ${ips.join(', ')}`);
    
        const urls = packets
          .filter(p => p._source?.layers['http.host'] && p._source?.layers['http.request.uri'])
          .map(p => `http://${p._source.layers['http.host'][0]}${p._source.layers['http.request.uri'][0]}`);
        console.error(`Found ${urls.length} URLs: ${urls.join(', ') || 'None'}`);
    
        const protocols = [...new Set(packets.map(p => p._source?.layers['frame.protocols']?.[0]))].filter(p => p);
        console.error(`Found protocols: ${protocols.join(', ') || 'None'}`);
    
        const maxChars = 720000;
        let jsonString = JSON.stringify(packets);
        if (jsonString.length > maxChars) {
          const trimFactor = maxChars / jsonString.length;
          const trimCount = Math.floor(packets.length * trimFactor);
          packets.splice(trimCount);
          jsonString = JSON.stringify(packets);
          console.error(`Trimmed packets from ${packets.length} to ${trimCount} to fit ${maxChars} chars`);
        }
    
        const outputText = `Analyzed PCAP: ${pcapPath}\n\n` +
          `Unique IPs:\n${ips.join('\n')}\n\n` +
          `URLs:\n${urls.length > 0 ? urls.join('\n') : 'None'}\n\n` +
          `Protocols:\n${protocols.join('\n') || 'None'}\n\n` +
          `Packet Data (JSON for LLM):\n${jsonString}`;
    
        return {
          content: [{ type: 'text', text: outputText }],
        };
      } catch (error) {
        console.error(`Error in analyze_pcap: ${error.message}`);
        return { content: [{ type: 'text', text: `Error: ${error.message}` }], isError: true };
      }
    }
  • Input schema using Zod: requires pcapPath string parameter.
    {
      pcapPath: z.string().describe('Path to the PCAP file to analyze (e.g., ./demo.pcap)'),
    },
  • index.js:301-362 (registration)
    Registers the analyze_pcap tool on the MCP server with name, description, schema, and handler.
    server.tool(
      'analyze_pcap',
      'Analyze a PCAP file and provide general packet data as JSON for LLM analysis',
      {
        pcapPath: z.string().describe('Path to the PCAP file to analyze (e.g., ./demo.pcap)'),
      },
      async (args) => {
        try {
          const tsharkPath = await findTshark();
          const { pcapPath } = args;
          console.error(`Analyzing PCAP file: ${pcapPath}`);
    
          // Check if file exists
          await fs.access(pcapPath);
    
          // Extract broad packet data
          const { stdout, stderr } = await execAsync(
            `${tsharkPath} -r "${pcapPath}" -T json -e frame.number -e ip.src -e ip.dst -e tcp.srcport -e tcp.dstport -e udp.srcport -e udp.dstport -e http.host -e http.request.uri -e frame.protocols`,
            { env: { ...process.env, PATH: `${process.env.PATH}:/usr/bin:/usr/local/bin:/opt/homebrew/bin` } }
          );
          if (stderr) console.error(`tshark stderr: ${stderr}`);
          const packets = JSON.parse(stdout);
    
          const ips = [...new Set(packets.flatMap(p => [
            p._source?.layers['ip.src']?.[0],
            p._source?.layers['ip.dst']?.[0]
          ]).filter(ip => ip))];
          console.error(`Found ${ips.length} unique IPs: ${ips.join(', ')}`);
    
          const urls = packets
            .filter(p => p._source?.layers['http.host'] && p._source?.layers['http.request.uri'])
            .map(p => `http://${p._source.layers['http.host'][0]}${p._source.layers['http.request.uri'][0]}`);
          console.error(`Found ${urls.length} URLs: ${urls.join(', ') || 'None'}`);
    
          const protocols = [...new Set(packets.map(p => p._source?.layers['frame.protocols']?.[0]))].filter(p => p);
          console.error(`Found protocols: ${protocols.join(', ') || 'None'}`);
    
          const maxChars = 720000;
          let jsonString = JSON.stringify(packets);
          if (jsonString.length > maxChars) {
            const trimFactor = maxChars / jsonString.length;
            const trimCount = Math.floor(packets.length * trimFactor);
            packets.splice(trimCount);
            jsonString = JSON.stringify(packets);
            console.error(`Trimmed packets from ${packets.length} to ${trimCount} to fit ${maxChars} chars`);
          }
    
          const outputText = `Analyzed PCAP: ${pcapPath}\n\n` +
            `Unique IPs:\n${ips.join('\n')}\n\n` +
            `URLs:\n${urls.length > 0 ? urls.join('\n') : 'None'}\n\n` +
            `Protocols:\n${protocols.join('\n') || 'None'}\n\n` +
            `Packet Data (JSON for LLM):\n${jsonString}`;
    
          return {
            content: [{ type: 'text', text: outputText }],
          };
        } catch (error) {
          console.error(`Error in analyze_pcap: ${error.message}`);
          return { content: [{ type: 'text', text: `Error: ${error.message}` }], isError: true };
        }
      }
    );
  • Associated prompt template for guiding LLM analysis after running analyze_pcap tool.
    server.prompt(
      'analyze_pcap_prompt',
      {
        pcapPath: z.string().describe('Path to the PCAP file'),
      },
      ({ pcapPath }) => ({
        messages: [{
          role: 'user',
          content: {
            type: 'text',
            text: `Please analyze the PCAP file at ${pcapPath} and provide insights about:
    1. Overall traffic patterns
    2. Unique IPs and their interactions
    3. Protocols and services used
    4. Notable events or anomalies
    5. Potential security concerns`
          }
        }]
      })
    );
  • Helper function to locate tshark binary, used by analyze_pcap handler.
    async function findTshark() {
      try {
        const tsharkPath = await which('tshark');
        console.error(`Found tshark at: ${tsharkPath}`);
        return tsharkPath;
      } catch (err) {
        console.error('which failed to find tshark:', err.message);
        const fallbacks = process.platform === 'win32'
          ? ['C:\\Program Files\\Wireshark\\tshark.exe', 'C:\\Program Files (x86)\\Wireshark\\tshark.exe']
          : ['/usr/bin/tshark', '/usr/local/bin/tshark', '/opt/homebrew/bin/tshark', '/Applications/Wireshark.app/Contents/MacOS/tshark'];
        
        for (const path of fallbacks) {
          try {
            await execAsync(`${path} -v`);
            console.error(`Found tshark at fallback: ${path}`);
            return path;
          } catch (e) {
            console.error(`Fallback ${path} failed: ${e.message}`);
          }
        }
        throw new Error('tshark not found. Please install Wireshark (https://www.wireshark.org/download.html) and ensure tshark is in your PATH.');
      }
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions the output format (JSON for LLM analysis) but doesn't cover critical aspects like whether this is a read-only operation, potential performance impacts, error handling, or what 'general packet data' entails. For a tool with no annotations, this is insufficient.

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

Conciseness4/5

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

The description is a single, efficient sentence that front-loads the core purpose. It avoids unnecessary details, but could be slightly more structured by explicitly separating input and output aspects. Overall, it's concise and well-sized for the tool's complexity.

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?

Given the lack of annotations and output schema, the description is incomplete. It doesn't explain what 'general packet data' includes, potential limitations, or how the JSON is structured for LLM analysis. For a tool with no structured support, more context is needed to guide 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?

The input schema has 100% description coverage, with 'pcapPath' clearly documented as the path to the PCAP file. The description adds no additional parameter semantics beyond what the schema provides, such as file format requirements or path validation. With high schema coverage, the baseline score of 3 is appropriate.

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 tool's purpose: 'Analyze a PCAP file and provide general packet data as JSON for LLM analysis.' It specifies the verb (analyze), resource (PCAP file), and output format (JSON for LLM analysis). However, it doesn't explicitly differentiate from sibling tools like 'capture_packets' or 'extract_credentials,' which prevents a score of 5.

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. It doesn't mention prerequisites (e.g., needing a PCAP file), exclusions, or comparisons to siblings like 'check_ip_threats' or 'get_summary_stats.' This lack of context leaves the agent without clear usage instructions.

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/0xKoda/WireMCP'

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