[
  {
    "path": ".gitignore",
    "content": "# Dependencies\nnode_modules/\nnpm-debug.log\nyarn-debug.log\nyarn-error.log\npackage-lock.json\nyarn.lock\n.pcap\n*.cap\n\n# Environment variables\n.env\n.env.local\n.env.*.local\n\n# PCAP files (usually large and contain sensitive data)\n*.pcap\n*.pcapng\ncaptures/\n\n# Operating System\n.DS_Store\n.DS_Store?\n._*\n.Spotlight-V100\n.Trashes\nehthumbs.db\nThumbs.db\n\n# IDE and Editor files\n.idea/\n.vscode/\n*.swp\n*.swo\n*~\n\n# Logs\nlogs/\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n\n# Build output\ndist/\nbuild/\nout/\n\n# Test coverage\ncoverage/\n\n# Temporary files\ntmp/\ntemp/\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2024 WireMCP\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE. "
  },
  {
    "path": "README.md",
    "content": "![Wire-MCP Banner](Wire-MCP.png)\n\n\n# WireMCP\nWireMCP is a Model Context Protocol (MCP) server designed to empower Large Language Models (LLMs) with real-time network traffic analysis capabilities. By leveraging tools built on top of Wireshark's `tshark`, WireMCP captures and processes live network data, providing LLMs with structured context to assist in tasks like threat hunting, network diagnostics, and anomaly detection.\n\n# Features\nWireMCP exposes the following tools to MCP clients, enhancing LLM understanding of network activity:\n\n- **`capture_packets`**: Captures live traffic and returns raw packet data as JSON, enabling LLMs to analyze packet-level details (e.g., IP addresses, ports, HTTP methods).\n- **`get_summary_stats`**: Provides protocol hierarchy statistics, giving LLMs an overview of traffic composition (e.g., TCP vs. UDP usage).\n- **`get_conversations`**: Delivers TCP/UDP conversation statistics, allowing LLMs to track communication flows between endpoints.\n- **`check_threats`**: Captures IPs and checks them against the URLhaus blacklist, equipping LLMs with threat intelligence context for identifying malicious activity.\n- **`check_ip_threats`**: Performs targeted threat intelligence lookups for specific IP addresses against multiple threat feeds, providing detailed reputation and threat data.\n- **`analyze_pcap`**: Analyzes PCAP files to provide comprehensive packet data in JSON format, enabling detailed post-capture analysis of network traffic.\n- **`extract_credentials`**: Scans PCAP files for potential credentials from various protocols (HTTP Basic Auth, FTP, Telnet), aiding in security audits and forensic analysis.\n\n\n## How It Helps LLMs\nWireMCP bridges the gap between raw network data and LLM comprehension by:\n- **Contextualizing Traffic**: Converts live packet captures into structured outputs (JSON, stats) that LLMs can parse and reason about.\n- **Threat Detection**: Integrates IOCs (currently URLhaus) to flag suspicious IPs, enhancing LLM-driven security analysis.\n- **Diagnostics**: Offers detailed traffic insights, enabling LLMs to assist with troubleshooting or identifying anomalies.\n- **Narrative Generation**: LLM's can Transform complex packet captures into coherent stories, making network analysis accessible to non-technical users.\n\n# Installation\n\n## Prerequisites\n- Mac / Windows / Linux\n- [Wireshark](https://www.wireshark.org/download.html) (with `tshark` installed and accessible in PATH)\n- Node.js (v16+ recommended)\n- npm (for dependency installation)\n\n## Setup\n1. Clone the repository:\n   ```bash\n   git clone https://github.com/0xkoda/WireMCP.git\n   cd WireMCP\n   ```\n\n2. Install dependencies:\n   ```bash\n   npm install\n   ```\n\n3. Run the MCP server:\n   ```bash\n   node index.js\n   ```\n\n> **Note**: Ensure `tshark` is in your PATH. WireMCP will auto-detect it or fall back to common install locations (e.g., `/Applications/Wireshark.app/Contents/MacOS/tshark` on macOS).\n\n# Usage with MCP Clients\n\nWireMCP works with any MCP-compliant client. Below are examples for popular clients:\n\n## Example 1: Cursor\n\nEdit `mcp.json` in Cursor -> Settings -> MCP :\n\n```json\n{\n  \"mcpServers\": {\n    \"wiremcp\": {\n      \"command\": \"node\",\n      \"args\": [\n        \"/ABSOLUTE_PATH_TO/WireMCP/index.js\"\n      ]\n    }\n  }\n}\n```\n\n**Location (macOS)**: `/Users/YOUR_USER/Library/Application Support/Claude/claude_desktop_config.json`\n\n## Other Clients\n\nThis MCP will work well with any client. Use the command `node /path/to/WireMCP/index.js` in their MCP server settings.\n\n# Example Output\n\nRunning `check_threats` might yield:\n\n```\nCaptured IPs:\n174.67.0.227\n52.196.136.253\n\nThreat check against URLhaus blacklist:\nNo threats detected in URLhaus blacklist.\n```\n\nRunning `analyze_pcap` on a capture file:\n\n```json\n{\n  \"content\": [{\n    \"type\": \"text\",\n    \"text\": \"Analyzed PCAP: ./capture.pcap\\n\\nUnique IPs:\\n192.168.0.2\\n192.168.0.1\\n\\nProtocols:\\neth:ethertype:ip:tcp\\neth:ethertype:ip:tcp:telnet\\n\\nPacket Data:\\n[{\\\"layers\\\":{\\\"frame.number\\\":[\\\"1\\\"],\\\"ip.src\\\":[\\\"192.168.0.2\\\"],\\\"ip.dst\\\":[\\\"192.168.0.1\\\"],\\\"tcp.srcport\\\":[\\\"1550\\\"],\\\"tcp.dstport\\\":[\\\"23\\\"]}}]\"\n  }]\n}\n```\n\n\nLLMs can use these outputs to:\n- Provide natural language explanations of network activity\n- Identify patterns and potential security concerns\n- Offer context-aware recommendations\n- Generate human-readable reports\n\n# Roadmap\n\n- **Expand IOC Providers**: Currently uses URLhaus for threat checks. Future updates will integrate additional sources (e.g., IPsum, Emerging Threats) for broader coverage.\n\n\n# Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.\n\n# License\n\n[MIT](LICENSE)\n\n# Acknowledgments\n\n- Wireshark/tshark team for their excellent packet analysis tools\n- Model Context Protocol community for the framework and specifications\n- URLhaus for providing threat intelligence data"
  },
  {
    "path": "index.js",
    "content": "// index.js - WireMCP Server\nconst axios = require('axios');\nconst { exec } = require('child_process');\nconst { promisify } = require('util');\nconst which = require('which');\nconst fs = require('fs').promises;\nconst execAsync = promisify(exec);\nconst { McpServer } = require('@modelcontextprotocol/sdk/server/mcp.js');\nconst { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');\nconst { z } = require('zod');\n\n// Redirect console.log to stderr\nconst originalConsoleLog = console.log;\nconsole.log = (...args) => console.error(...args);\n\n// Dynamically locate tshark\nasync function findTshark() {\n  try {\n    const tsharkPath = await which('tshark');\n    console.error(`Found tshark at: ${tsharkPath}`);\n    return tsharkPath;\n  } catch (err) {\n    console.error('which failed to find tshark:', err.message);\n    const fallbacks = process.platform === 'win32'\n      ? ['C:\\\\Program Files\\\\Wireshark\\\\tshark.exe', 'C:\\\\Program Files (x86)\\\\Wireshark\\\\tshark.exe']\n      : ['/usr/bin/tshark', '/usr/local/bin/tshark', '/opt/homebrew/bin/tshark', '/Applications/Wireshark.app/Contents/MacOS/tshark'];\n    \n    for (const path of fallbacks) {\n      try {\n        await execAsync(`${path} -v`);\n        console.error(`Found tshark at fallback: ${path}`);\n        return path;\n      } catch (e) {\n        console.error(`Fallback ${path} failed: ${e.message}`);\n      }\n    }\n    throw new Error('tshark not found. Please install Wireshark (https://www.wireshark.org/download.html) and ensure tshark is in your PATH.');\n  }\n}\n\n// Initialize MCP server\nconst server = new McpServer({\n  name: 'wiremcp',\n  version: '1.0.0',\n});\n\n// Tool 1: Capture live packet data\nserver.tool(\n  'capture_packets',\n  'Capture live traffic and provide raw packet data as JSON for LLM analysis',\n  {\n    interface: z.string().optional().default('en0').describe('Network interface to capture from (e.g., eth0, en0)'),\n    duration: z.number().optional().default(5).describe('Capture duration in seconds'),\n  },\n  async (args) => {\n    try {\n      const tsharkPath = await findTshark();\n      const { interface, duration } = args;\n      const tempPcap = 'temp_capture.pcap';\n      console.error(`Capturing packets on ${interface} for ${duration}s`);\n\n      await execAsync(\n        `${tsharkPath} -i ${interface} -w ${tempPcap} -a duration:${duration}`,\n        { env: { ...process.env, PATH: `${process.env.PATH}:/usr/bin:/usr/local/bin:/opt/homebrew/bin` } }\n      );\n\n      const { stdout, stderr } = await execAsync(\n        `${tsharkPath} -r \"${tempPcap}\" -T json -e frame.number -e ip.src -e ip.dst -e tcp.srcport -e tcp.dstport -e tcp.flags -e frame.time -e http.request.method -e http.response.code`,\n        { env: { ...process.env, PATH: `${process.env.PATH}:/usr/bin:/usr/local/bin:/opt/homebrew/bin` } }\n      );\n      if (stderr) console.error(`tshark stderr: ${stderr}`);\n      let packets = JSON.parse(stdout);\n\n      const maxChars = 720000;\n      let jsonString = JSON.stringify(packets);\n      if (jsonString.length > maxChars) {\n        const trimFactor = maxChars / jsonString.length;\n        const trimCount = Math.floor(packets.length * trimFactor);\n        packets = packets.slice(0, trimCount);\n        jsonString = JSON.stringify(packets);\n        console.error(`Trimmed packets from ${packets.length} to ${trimCount} to fit ${maxChars} chars`);\n      }\n\n      await fs.unlink(tempPcap).catch(err => console.error(`Failed to delete ${tempPcap}: ${err.message}`));\n\n      return {\n        content: [{\n          type: 'text',\n          text: `Captured packet data (JSON for LLM analysis):\\n${jsonString}`,\n        }],\n      };\n    } catch (error) {\n      console.error(`Error in capture_packets: ${error.message}`);\n      return { content: [{ type: 'text', text: `Error: ${error.message}` }], isError: true };\n    }\n  }\n);\n\n// Tool 2: Capture and provide summary statistics\nserver.tool(\n  'get_summary_stats',\n  'Capture live traffic and provide protocol hierarchy statistics for LLM analysis',\n  {\n    interface: z.string().optional().default('en0').describe('Network interface to capture from (e.g., eth0, en0)'),\n    duration: z.number().optional().default(5).describe('Capture duration in seconds'),\n  },\n  async (args) => {\n    try {\n      const tsharkPath = await findTshark();\n      const { interface, duration } = args;\n      const tempPcap = 'temp_capture.pcap';\n      console.error(`Capturing summary stats on ${interface} for ${duration}s`);\n\n      await execAsync(\n        `${tsharkPath} -i ${interface} -w ${tempPcap} -a duration:${duration}`,\n        { env: { ...process.env, PATH: `${process.env.PATH}:/usr/bin:/usr/local/bin:/opt/homebrew/bin` } }\n      );\n\n      const { stdout, stderr } = await execAsync(\n        `${tsharkPath} -r \"${tempPcap}\" -qz io,phs`,\n        { env: { ...process.env, PATH: `${process.env.PATH}:/usr/bin:/usr/local/bin:/opt/homebrew/bin` } }\n      );\n      if (stderr) console.error(`tshark stderr: ${stderr}`);\n\n      await fs.unlink(tempPcap).catch(err => console.error(`Failed to delete ${tempPcap}: ${err.message}`));\n\n      return {\n        content: [{\n          type: 'text',\n          text: `Protocol hierarchy statistics for LLM analysis:\\n${stdout}`,\n        }],\n      };\n    } catch (error) {\n      console.error(`Error in get_summary_stats: ${error.message}`);\n      return { content: [{ type: 'text', text: `Error: ${error.message}` }], isError: true };\n    }\n  }\n);\n\n// Tool 3: Capture and provide conversation stats\nserver.tool(\n  'get_conversations',\n  'Capture live traffic and provide TCP/UDP conversation statistics for LLM analysis',\n  {\n    interface: z.string().optional().default('en0').describe('Network interface to capture from (e.g., eth0, en0)'),\n    duration: z.number().optional().default(5).describe('Capture duration in seconds'),\n  },\n  async (args) => {\n    try {\n      const tsharkPath = await findTshark();\n      const { interface, duration } = args;\n      const tempPcap = 'temp_capture.pcap';\n      console.error(`Capturing conversations on ${interface} for ${duration}s`);\n\n      await execAsync(\n        `${tsharkPath} -i ${interface} -w ${tempPcap} -a duration:${duration}`,\n        { env: { ...process.env, PATH: `${process.env.PATH}:/usr/bin:/usr/local/bin:/opt/homebrew/bin` } }\n      );\n\n      const { stdout, stderr } = await execAsync(\n        `${tsharkPath} -r \"${tempPcap}\" -qz conv,tcp`,\n        { env: { ...process.env, PATH: `${process.env.PATH}:/usr/bin:/usr/local/bin:/opt/homebrew/bin` } }\n      );\n      if (stderr) console.error(`tshark stderr: ${stderr}`);\n\n      await fs.unlink(tempPcap).catch(err => console.error(`Failed to delete ${tempPcap}: ${err.message}`));\n\n      return {\n        content: [{\n          type: 'text',\n          text: `TCP/UDP conversation statistics for LLM analysis:\\n${stdout}`,\n        }],\n      };\n    } catch (error) {\n      console.error(`Error in get_conversations: ${error.message}`);\n      return { content: [{ type: 'text', text: `Error: ${error.message}` }], isError: true };\n    }\n  }\n);\n\n// Tool 4: Capture traffic and check threats against URLhaus\nserver.tool(\n  'check_threats',\n  'Capture live traffic and check IPs against URLhaus blacklist',\n  {\n    interface: z.string().optional().default('en0').describe('Network interface to capture from (e.g., eth0, en0)'),\n    duration: z.number().optional().default(5).describe('Capture duration in seconds'),\n  },\n  async (args) => {\n    try {\n      const tsharkPath = await findTshark();\n      const { interface, duration } = args;\n      const tempPcap = 'temp_capture.pcap';\n      console.error(`Capturing traffic on ${interface} for ${duration}s to check threats`);\n\n      await execAsync(\n        `${tsharkPath} -i ${interface} -w ${tempPcap} -a duration:${duration}`,\n        { env: { ...process.env, PATH: `${process.env.PATH}:/usr/bin:/usr/local/bin:/opt/homebrew/bin` } }\n      );\n\n      const { stdout } = await execAsync(\n        `${tsharkPath} -r \"${tempPcap}\" -T fields -e ip.src -e ip.dst`,\n        { env: { ...process.env, PATH: `${process.env.PATH}:/usr/bin:/usr/local/bin:/opt/homebrew/bin` } }\n      );\n      const ips = [...new Set(stdout.split('\\n').flatMap(line => line.split('\\t')).filter(ip => ip && ip !== 'unknown'))];\n      console.error(`Captured ${ips.length} unique IPs: ${ips.join(', ')}`);\n\n      const urlhausUrl = 'https://urlhaus.abuse.ch/downloads/text/';\n      console.error(`Fetching URLhaus blacklist from ${urlhausUrl}`);\n      let urlhausData;\n      let urlhausThreats = [];\n      try {\n        const response = await axios.get(urlhausUrl);\n        console.error(`URLhaus response status: ${response.status}, length: ${response.data.length} chars`);\n        console.error(`URLhaus raw data (first 200 chars): ${response.data.slice(0, 200)}`);\n        const ipRegex = /\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b/;\n        urlhausData = [...new Set(response.data.split('\\n')\n          .map(line => {\n            const match = line.match(ipRegex);\n            return match ? match[0] : null;\n          })\n          .filter(ip => ip))];\n        console.error(`URLhaus lookup successful: ${urlhausData.length} blacklist IPs fetched`);\n        console.error(`Sample URLhaus IPs: ${urlhausData.slice(0, 5).join(', ') || 'None'}`);\n        urlhausThreats = ips.filter(ip => urlhausData.includes(ip));\n        console.error(`Checked IPs against URLhaus: ${urlhausThreats.length} threats found - ${urlhausThreats.join(', ') || 'None'}`);\n      } catch (e) {\n        console.error(`Failed to fetch URLhaus data: ${e.message}`);\n        urlhausData = [];\n      }\n\n      const outputText = `Captured IPs:\\n${ips.join('\\n')}\\n\\n` +\n        `Threat check against URLhaus blacklist:\\n${\n          urlhausThreats.length > 0 ? `Potential threats: ${urlhausThreats.join(', ')}` : 'No threats detected in URLhaus blacklist.'\n        }`;\n\n      await fs.unlink(tempPcap).catch(err => console.error(`Failed to delete ${tempPcap}: ${err.message}`));\n\n      return {\n        content: [{ type: 'text', text: outputText }],\n      };\n    } catch (error) {\n      console.error(`Error in check_threats: ${error.message}`);\n      return { content: [{ type: 'text', text: `Error: ${error.message}` }], isError: true };\n    }\n  }\n);\n\n// Tool 5: Check a specific IP against URLhaus IOCs\nserver.tool(\n  'check_ip_threats',\n  'Check a given IP address against URLhaus blacklist for IOCs',\n  {\n    ip: z.string().regex(/\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b/).describe('IP address to check (e.g., 192.168.1.1)'),\n  },\n  async (args) => {\n    try {\n      const { ip } = args;\n      console.error(`Checking IP ${ip} against URLhaus blacklist`);\n\n      const urlhausUrl = 'https://urlhaus.abuse.ch/downloads/text/';\n      console.error(`Fetching URLhaus blacklist from ${urlhausUrl}`);\n      let urlhausData;\n      let isThreat = false;\n      try {\n        const response = await axios.get(urlhausUrl);\n        console.error(`URLhaus response status: ${response.status}, length: ${response.data.length} chars`);\n        console.error(`URLhaus raw data (first 200 chars): ${response.data.slice(0, 200)}`);\n        const ipRegex = /\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b/;\n        urlhausData = [...new Set(response.data.split('\\n')\n          .map(line => {\n            const match = line.match(ipRegex);\n            return match ? match[0] : null;\n          })\n          .filter(ip => ip))];\n        console.error(`URLhaus lookup successful: ${urlhausData.length} blacklist IPs fetched`);\n        console.error(`Sample URLhaus IPs: ${urlhausData.slice(0, 5).join(', ') || 'None'}`);\n        isThreat = urlhausData.includes(ip);\n        console.error(`IP ${ip} checked against URLhaus: ${isThreat ? 'Threat found' : 'No threat found'}`);\n      } catch (e) {\n        console.error(`Failed to fetch URLhaus data: ${e.message}`);\n        urlhausData = [];\n      }\n\n      const outputText = `IP checked: ${ip}\\n\\n` +\n        `Threat check against URLhaus blacklist:\\n${\n          isThreat ? 'Potential threat detected in URLhaus blacklist.' : 'No threat detected in URLhaus blacklist.'\n        }`;\n\n      return {\n        content: [{ type: 'text', text: outputText }],\n      };\n    } catch (error) {\n      console.error(`Error in check_ip_threats: ${error.message}`);\n      return { content: [{ type: 'text', text: `Error: ${error.message}` }], isError: true };\n    }\n  }\n);\n\n// Tool 6: Analyze an existing PCAP file for general context\nserver.tool(\n  'analyze_pcap',\n  'Analyze a PCAP file and provide general packet data as JSON for LLM analysis',\n  {\n    pcapPath: z.string().describe('Path to the PCAP file to analyze (e.g., ./demo.pcap)'),\n  },\n  async (args) => {\n    try {\n      const tsharkPath = await findTshark();\n      const { pcapPath } = args;\n      console.error(`Analyzing PCAP file: ${pcapPath}`);\n\n      // Check if file exists\n      await fs.access(pcapPath);\n\n      // Extract broad packet data\n      const { stdout, stderr } = await execAsync(\n        `${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`,\n        { env: { ...process.env, PATH: `${process.env.PATH}:/usr/bin:/usr/local/bin:/opt/homebrew/bin` } }\n      );\n      if (stderr) console.error(`tshark stderr: ${stderr}`);\n      const packets = JSON.parse(stdout);\n\n      const ips = [...new Set(packets.flatMap(p => [\n        p._source?.layers['ip.src']?.[0],\n        p._source?.layers['ip.dst']?.[0]\n      ]).filter(ip => ip))];\n      console.error(`Found ${ips.length} unique IPs: ${ips.join(', ')}`);\n\n      const urls = packets\n        .filter(p => p._source?.layers['http.host'] && p._source?.layers['http.request.uri'])\n        .map(p => `http://${p._source.layers['http.host'][0]}${p._source.layers['http.request.uri'][0]}`);\n      console.error(`Found ${urls.length} URLs: ${urls.join(', ') || 'None'}`);\n\n      const protocols = [...new Set(packets.map(p => p._source?.layers['frame.protocols']?.[0]))].filter(p => p);\n      console.error(`Found protocols: ${protocols.join(', ') || 'None'}`);\n\n      const maxChars = 720000;\n      let jsonString = JSON.stringify(packets);\n      if (jsonString.length > maxChars) {\n        const trimFactor = maxChars / jsonString.length;\n        const trimCount = Math.floor(packets.length * trimFactor);\n        packets.splice(trimCount);\n        jsonString = JSON.stringify(packets);\n        console.error(`Trimmed packets from ${packets.length} to ${trimCount} to fit ${maxChars} chars`);\n      }\n\n      const outputText = `Analyzed PCAP: ${pcapPath}\\n\\n` +\n        `Unique IPs:\\n${ips.join('\\n')}\\n\\n` +\n        `URLs:\\n${urls.length > 0 ? urls.join('\\n') : 'None'}\\n\\n` +\n        `Protocols:\\n${protocols.join('\\n') || 'None'}\\n\\n` +\n        `Packet Data (JSON for LLM):\\n${jsonString}`;\n\n      return {\n        content: [{ type: 'text', text: outputText }],\n      };\n    } catch (error) {\n      console.error(`Error in analyze_pcap: ${error.message}`);\n      return { content: [{ type: 'text', text: `Error: ${error.message}` }], isError: true };\n    }\n  }\n);\n\n// Tool 7: Extract credentials from a PCAP file\nserver.tool(\n    'extract_credentials',\n    'Extract potential credentials (HTTP Basic Auth, FTP, Telnet) from a PCAP file for LLM analysis',\n    {\n      pcapPath: z.string().describe('Path to the PCAP file to analyze (e.g., ./demo.pcap)'),\n    },\n    async (args) => {\n      try {\n        const tsharkPath = await findTshark();\n        const { pcapPath } = args;\n        console.error(`Extracting credentials from PCAP file: ${pcapPath}`);\n  \n        await fs.access(pcapPath);\n  \n        // Extract plaintext credentials\n        const { stdout: plaintextOut } = await execAsync(\n          `${tsharkPath} -r \"${pcapPath}\" -T fields -e http.authbasic -e ftp.request.command -e ftp.request.arg -e telnet.data -e frame.number`,\n          { env: { ...process.env, PATH: `${process.env.PATH}:/usr/bin:/usr/local/bin:/opt/homebrew/bin` } }\n        );\n\n        // Extract Kerberos credentials\n        const { stdout: kerberosOut } = await execAsync(\n          `${tsharkPath} -r \"${pcapPath}\" -T fields -e kerberos.CNameString -e kerberos.realm -e kerberos.cipher -e kerberos.type -e kerberos.msg_type -e frame.number`,\n          { env: { ...process.env, PATH: `${process.env.PATH}:/usr/bin:/usr/local/bin:/opt/homebrew/bin` } }\n        );\n\n        const lines = plaintextOut.split('\\n').filter(line => line.trim());\n        const packets = lines.map(line => {\n          const [authBasic, ftpCmd, ftpArg, telnetData, frameNumber] = line.split('\\t');\n          return {\n            authBasic: authBasic || '',\n            ftpCmd: ftpCmd || '',\n            ftpArg: ftpArg || '',\n            telnetData: telnetData || '',\n            frameNumber: frameNumber || ''\n          };\n        });\n  \n        const credentials = {\n          plaintext: [],\n          encrypted: []\n        };\n  \n        // Process HTTP Basic Auth\n        packets.forEach(p => {\n          if (p.authBasic) {\n            const [username, password] = Buffer.from(p.authBasic, 'base64').toString().split(':');\n            credentials.plaintext.push({ type: 'HTTP Basic Auth', username, password, frame: p.frameNumber });\n          }\n        });\n  \n        // Process FTP\n        packets.forEach(p => {\n          if (p.ftpCmd === 'USER') {\n            credentials.plaintext.push({ type: 'FTP', username: p.ftpArg, password: '', frame: p.frameNumber });\n          }\n          if (p.ftpCmd === 'PASS') {\n            const lastUser = credentials.plaintext.findLast(c => c.type === 'FTP' && !c.password);\n            if (lastUser) lastUser.password = p.ftpArg;\n          }\n        });\n  \n        // Process Telnet\n        packets.forEach(p => {\n          if (p.telnetData) {\n            const telnetStr = p.telnetData.trim();\n            if (telnetStr.toLowerCase().includes('login:') || telnetStr.toLowerCase().includes('password:')) {\n              credentials.plaintext.push({ type: 'Telnet Prompt', data: telnetStr, frame: p.frameNumber });\n            } else if (telnetStr && !telnetStr.match(/[A-Z][a-z]+:/) && !telnetStr.includes(' ')) {\n              const lastPrompt = credentials.plaintext.findLast(c => c.type === 'Telnet Prompt');\n              if (lastPrompt && lastPrompt.data.toLowerCase().includes('login:')) {\n                credentials.plaintext.push({ type: 'Telnet', username: telnetStr, password: '', frame: p.frameNumber });\n              } else if (lastPrompt && lastPrompt.data.toLowerCase().includes('password:')) {\n                const lastUser = credentials.plaintext.findLast(c => c.type === 'Telnet' && !c.password);\n                if (lastUser) lastUser.password = telnetStr;\n                else credentials.plaintext.push({ type: 'Telnet', username: '', password: telnetStr, frame: p.frameNumber });\n              }\n            }\n          }\n        });\n\n        // Process Kerberos credentials\n        const kerberosLines = kerberosOut.split('\\n').filter(line => line.trim());\n        kerberosLines.forEach(line => {\n          const [cname, realm, cipher, type, msgType, frameNumber] = line.split('\\t');\n          \n          if (cipher && type) {\n            let hashFormat = '';\n            // Format hash based on message type\n            if (msgType === '10' || msgType === '30') { // AS-REQ or TGS-REQ\n              hashFormat = '$krb5pa$23$';\n              if (cname) hashFormat += `${cname}$`;\n              if (realm) hashFormat += `${realm}$`;\n              hashFormat += cipher;\n            } else if (msgType === '11') { // AS-REP\n              hashFormat = '$krb5asrep$23$';\n              if (cname) hashFormat += `${cname}@`;\n              if (realm) hashFormat += `${realm}$`;\n              hashFormat += cipher;\n            }\n\n            if (hashFormat) {\n              credentials.encrypted.push({\n                type: 'Kerberos',\n                hash: hashFormat,\n                username: cname || 'unknown',\n                realm: realm || 'unknown',\n                frame: frameNumber,\n                crackingMode: msgType === '11' ? 'hashcat -m 18200' : 'hashcat -m 7500'\n              });\n            }\n          }\n        });\n\n        console.error(`Found ${credentials.plaintext.length} plaintext and ${credentials.encrypted.length} encrypted credentials`);\n  \n        const outputText = `Analyzed PCAP: ${pcapPath}\\n\\n` +\n          `Plaintext Credentials:\\n${credentials.plaintext.length > 0 ? \n            credentials.plaintext.map(c => \n              c.type === 'Telnet Prompt' ? \n                `${c.type}: ${c.data} (Frame ${c.frame})` : \n                `${c.type}: ${c.username}:${c.password} (Frame ${c.frame})`\n            ).join('\\n') : \n            'None'}\\n\\n` +\n          `Encrypted/Hashed Credentials:\\n${credentials.encrypted.length > 0 ?\n            credentials.encrypted.map(c =>\n              `${c.type}: User=${c.username} Realm=${c.realm} (Frame ${c.frame})\\n` +\n              `Hash=${c.hash}\\n` +\n              `Cracking Command: ${c.crackingMode}\\n`\n            ).join('\\n') :\n            'None'}\\n\\n` +\n          `Note: Encrypted credentials can be cracked using tools like John the Ripper or hashcat.\\n` +\n          `For Kerberos hashes:\\n` +\n          `- AS-REQ/TGS-REQ: hashcat -m 7500 or john --format=krb5pa-md5\\n` +\n          `- AS-REP: hashcat -m 18200 or john --format=krb5asrep`;\n  \n        return {\n          content: [{ type: 'text', text: outputText }],\n        };\n      } catch (error) {\n        console.error(`Error in extract_credentials: ${error.message}`);\n        return { content: [{ type: 'text', text: `Error: ${error.message}` }], isError: true };\n      }\n    }\n  );\n\n// Add prompts for each tool\nserver.prompt(\n  'capture_packets_prompt',\n  {\n    interface: z.string().optional().describe('Network interface to capture from'),\n    duration: z.number().optional().describe('Duration in seconds to capture'),\n  },\n  ({ interface = 'en0', duration = 5 }) => ({\n    messages: [{\n      role: 'user',\n      content: {\n        type: 'text',\n        text: `Please analyze the network traffic on interface ${interface} for ${duration} seconds and provide insights about:\n1. The types of traffic observed\n2. Any notable patterns or anomalies\n3. Key IP addresses and ports involved\n4. Potential security concerns`\n      }\n    }]\n  })\n);\n\nserver.prompt(\n  'summary_stats_prompt',\n  {\n    interface: z.string().optional().describe('Network interface to capture from'),\n    duration: z.number().optional().describe('Duration in seconds to capture'),\n  },\n  ({ interface = 'en0', duration = 5 }) => ({\n    messages: [{\n      role: 'user',\n      content: {\n        type: 'text',\n        text: `Please provide a summary of network traffic statistics from interface ${interface} over ${duration} seconds, focusing on:\n1. Protocol distribution\n2. Traffic volume by protocol\n3. Notable patterns in protocol usage\n4. Potential network health indicators`\n      }\n    }]\n  })\n);\n\nserver.prompt(\n  'conversations_prompt',\n  {\n    interface: z.string().optional().describe('Network interface to capture from'),\n    duration: z.number().optional().describe('Duration in seconds to capture'),\n  },\n  ({ interface = 'en0', duration = 5 }) => ({\n    messages: [{\n      role: 'user',\n      content: {\n        type: 'text',\n        text: `Please analyze network conversations on interface ${interface} for ${duration} seconds and identify:\n1. Most active IP pairs\n2. Conversation durations and data volumes\n3. Unusual communication patterns\n4. Potential indicators of network issues`\n      }\n    }]\n  })\n);\n\nserver.prompt(\n  'check_threats_prompt',\n  {\n    interface: z.string().optional().describe('Network interface to capture from'),\n    duration: z.number().optional().describe('Duration in seconds to capture'),\n  },\n  ({ interface = 'en0', duration = 5 }) => ({\n    messages: [{\n      role: 'user',\n      content: {\n        type: 'text',\n        text: `Please analyze traffic on interface ${interface} for ${duration} seconds and check for security threats:\n1. Compare captured IPs against URLhaus blacklist\n2. Identify potential malicious activity\n3. Highlight any concerning patterns\n4. Provide security recommendations`\n      }\n    }]\n  })\n);\n\nserver.prompt(\n  'check_ip_threats_prompt',\n  {\n    ip: z.string().describe('IP address to check'),\n  },\n  ({ ip }) => ({\n    messages: [{\n      role: 'user',\n      content: {\n        type: 'text',\n        text: `Please analyze the following IP address (${ip}) for potential security threats:\n1. Check against URLhaus blacklist\n2. Evaluate the IP's reputation\n3. Identify any known malicious activity\n4. Provide security recommendations`\n      }\n    }]\n  })\n);\n\nserver.prompt(\n  'analyze_pcap_prompt',\n  {\n    pcapPath: z.string().describe('Path to the PCAP file'),\n  },\n  ({ pcapPath }) => ({\n    messages: [{\n      role: 'user',\n      content: {\n        type: 'text',\n        text: `Please analyze the PCAP file at ${pcapPath} and provide insights about:\n1. Overall traffic patterns\n2. Unique IPs and their interactions\n3. Protocols and services used\n4. Notable events or anomalies\n5. Potential security concerns`\n      }\n    }]\n  })\n);\n\nserver.prompt(\n  'extract_credentials_prompt',\n  {\n    pcapPath: z.string().describe('Path to the PCAP file'),\n  },\n  ({ pcapPath }) => ({\n    messages: [{\n      role: 'user',\n      content: {\n        type: 'text',\n        text: `Please analyze the PCAP file at ${pcapPath} for potential credential exposure:\n1. Look for plaintext credentials (HTTP Basic Auth, FTP, Telnet)\n2. Identify Kerberos authentication attempts\n3. Extract any hashed credentials\n4. Provide security recommendations for credential handling`\n      }\n    }]\n  })\n);\n\n// Start the server\nserver.connect(new StdioServerTransport())\n  .then(() => console.error('WireMCP Server is running...'))\n  .catch(err => {\n    console.error('Failed to start WireMCP:', err);\n    process.exit(1);\n  });"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"wiremcp\",\n  \"version\": \"1.0.0\",\n  \"description\": \"An MCP for network sleuthing\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"author\": \"0xKoda\",\n  \"license\": \"MIT\",\n  \"dependencies\": {\n    \"@modelcontextprotocol/sdk\": \"^1.8.0\",\n    \"axios\": \"^1.8.4\",\n    \"child_process\": \"^1.0.2\",\n    \"util\": \"^0.12.5\",\n    \"which\": \"^5.0.0\",\n    \"zod\": \"^3.24.2\"\n  }\n}\n"
  }
]