Skip to main content
Glama
tuliperis

SharkMCP

by tuliperis

start_capture_session

Start a background packet capture session with configurable filters, interfaces, and packet limits for network analysis and troubleshooting.

Instructions

Start a background packet capture session. LLMs control all capture parameters including filters, interfaces, and packet limits. Can use saved configurations.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
interfaceNoNetwork interface to capture from (e.g., eth0, en0, lo0)lo0
captureFilterNoOptional BPF capture filter to apply while capturing (e.g., "port 443")
timeoutNoTimeout in seconds before auto-stopping capture (default: 60s to prevent orphaned sessions)
maxPacketsNoMaximum number of packets to capture (safety limit, default: 100,000)
sessionNameNoOptional session name for easier identification
configNameNoName of saved configuration to use (will override other parameters)

Implementation Reference

  • The main handler function that starts a background tshark packet capture process, manages sessions, handles configurations, and sets up timeouts and limits.
    export async function startCaptureSessionHandler(args: any, activeSessions: Map<string, CaptureSession>) {
      try {
        const tsharkPath = await findTshark();
        let { interface: networkInterface, captureFilter, timeout, maxPackets, sessionName, configName } = args;
        
        // If configName is provided, load and use that configuration
        if (configName) {
          const savedConfig = await loadFilterConfig(configName);
          if (!savedConfig) {
            return {
              content: [{
                type: 'text' as const,
                text: `Error: Configuration '${configName}' not found. Use manage_config with action 'list' to see available configurations.`,
              }],
              isError: true
            };
          }
          
          // Override parameters with saved config (saved config takes precedence)
          if (savedConfig.interface) networkInterface = savedConfig.interface;
          if (savedConfig.captureFilter) captureFilter = savedConfig.captureFilter;
          if (savedConfig.timeout) timeout = savedConfig.timeout;
          if (savedConfig.maxPackets) maxPackets = savedConfig.maxPackets;
          
          console.error(`Using saved configuration '${configName}': ${JSON.stringify(savedConfig)}`);
        }
        
        // Generate unique session ID
        const sessionId = sessionName || `capture_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
        
        // Check if session already exists
        if (activeSessions.has(sessionId)) {
          return {
            content: [{
              type: 'text' as const,
              text: `Error: Session '${sessionId}' already exists. Use a different session name or stop the existing session.`,
            }],
            isError: true
          };
        }
    
        const tempFile = `/tmp/shark_${sessionId}.pcap`;
        console.error(`Starting capture session: ${sessionId} on ${networkInterface}`);
    
        // Build comprehensive tshark command for background capture
        // Use timeout as primary stopping mechanism, with maxPackets as safety limit
        const args_array = [
          '-i', networkInterface,
          '-a', `duration:${timeout}`,  // Auto-stop after timeout seconds
          '-c', maxPackets.toString(),  // Safety limit to prevent excessive capture
          '-w', tempFile
        ];
        
        // Add capture filter if provided (as a single argument to -f)
        if (captureFilter) {
          args_array.push('-f', captureFilter);
        }
    
        // Set up basic environment
        const captureEnv: Record<string, string> = {
          ...process.env,
          PATH: `${process.env.PATH}:/usr/bin:/usr/local/bin:/opt/homebrew/bin`
        };
        
        // Log the command with proper quoting for copy-paste debugging
        const quotedArgs = args_array.map(arg => {
          // Quote arguments that contain spaces or special characters
          if (arg.includes(' ') || arg.includes('|') || arg.includes('&') || arg.includes('(') || arg.includes(')')) {
            return `"${arg}"`;
          }
          return arg;
        });
        console.error(`Running background command: ${tsharkPath} ${quotedArgs.join(' ')}`);
    
        // Start background capture process with stderr logging
        const captureProcess = spawn(tsharkPath, args_array, {
          env: captureEnv,
          stdio: ['ignore', 'ignore', 'pipe'], // Capture stderr for error logging
          detached: true   // Fully detach the process
        });
        
        // Log any errors from tshark
        if (captureProcess.stderr) {
          captureProcess.stderr.on('data', (data) => {
            console.error(`tshark stderr [${sessionId}]: ${data.toString().trim()}`);
          });
        }
        
        // Unref the process so the parent can exit independently
        captureProcess.unref();
    
        // Store session info
        const session: CaptureSession = {
          id: sessionId,
          process: captureProcess,
          interface: networkInterface,
          captureFilter,
          timeout,
          maxPackets,
          startTime: new Date(),
          tempFile,
          status: 'running'
        };
        
        activeSessions.set(sessionId, session);
    
        // Handle process completion - KEEP SESSION ALIVE for result retrieval
        captureProcess.on('exit', (code) => {
          console.error(`Capture session ${sessionId} exited with code: ${code}`);
          if (activeSessions.has(sessionId)) {
            const session = activeSessions.get(sessionId)!;
            session.process = null;
            session.status = code === 0 ? 'completed' : 'error';
            session.endTime = new Date();
            if (code !== null) {
              session.exitCode = code;
            }
            console.error(`Session ${sessionId} marked as ${session.status}, file: ${session.tempFile}`);
          }
        });
    
        captureProcess.on('error', (error) => {
          console.error(`Capture session ${sessionId} error: ${error.message}`);
          if (activeSessions.has(sessionId)) {
            const session = activeSessions.get(sessionId)!;
            session.process = null;
            session.status = 'error';
            session.endTime = new Date();
          }
        });
    
        const configInfo = configName ? `\nUsing saved config: ${configName}` : '';
        
        return {
          content: [{
            type: 'text' as const,
            text: `Capture session started successfully!${configInfo}\nSession ID: ${sessionId}\nInterface: ${networkInterface}\nCapture Filter: ${captureFilter || 'none'}\nTimeout: ${timeout}s (auto-stop)\nMax Packets: ${maxPackets} (safety limit)\n\nCapture will auto-stop after ${timeout} seconds or use 'stop_capture_session' with session ID '${sessionId}' to stop manually and retrieve results.`,
          }],
        };
      } catch (error: any) {
        console.error(`Error starting capture session: ${error.message}`);
        return { 
          content: [{ type: 'text' as const, text: `Error: ${error.message}` }], 
          isError: true 
        };
      }
    } 
  • Zod schema defining the input parameters for the start_capture_session tool, including interface, filters, timeouts, and config options.
    export const startCaptureSessionSchema = {
      interface: z.string().optional().default('lo0').describe('Network interface to capture from (e.g., eth0, en0, lo0)'),
      captureFilter: z.string().optional().describe('Optional BPF capture filter to apply while capturing (e.g., "port 443")'),
      timeout: z.number().optional().default(60).describe('Timeout in seconds before auto-stopping capture (default: 60s to prevent orphaned sessions)'),
      maxPackets: z.number().optional().default(100000).describe('Maximum number of packets to capture (safety limit, default: 100,000)'),
      sessionName: z.string().optional().describe('Optional session name for easier identification'),
      configName: z.string().optional().describe('Name of saved configuration to use (will override other parameters)')
    };
  • src/index.ts:24-29 (registration)
    Registration of the start_capture_session tool with the MCP server, including name, description, schema, and handler reference.
    server.tool(
      'start_capture_session',
      'Start a background packet capture session. LLMs control all capture parameters including filters, interfaces, and packet limits. Can use saved configurations.',
      startCaptureSessionSchema,
      async (args) => startCaptureSessionHandler(args, activeSessions)
    );
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses that this starts a 'background' session (implying asynchronous operation) and mentions 'safety limits' like packet maximums, but it doesn't cover critical behavioral aspects such as authentication requirements, rate limits, error conditions, or what happens to existing sessions.

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 front-loaded with the core purpose in the first sentence, followed by supporting details. Both sentences earn their place by clarifying scope and capabilities without redundancy, making it efficient and well-structured.

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

Completeness3/5

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

Given the tool's complexity (starting a background capture with 6 parameters) and no annotations or output schema, the description is moderately complete. It covers the purpose and key features but lacks details on behavioral traits, error handling, and output expectations, which are important for such an operation.

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 6 parameters. The description adds minimal value beyond the schema by mentioning 'filters, interfaces, and packet limits' and 'saved configurations,' but it doesn't provide additional semantic context or usage examples for the parameters.

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

Purpose5/5

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

The description clearly states the specific action ('Start a background packet capture session') and resource ('packet capture session'), distinguishing it from sibling tools like 'analyze_pcap_file' (analysis) and 'stop_capture_session' (termination). It also mentions key capabilities like controlling parameters and using saved configurations.

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

Usage Guidelines4/5

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

The description provides clear context for when to use this tool (starting captures with parameter control), but it doesn't explicitly state when not to use it or name alternatives. For example, it doesn't contrast with 'manage_config' for configuration tasks or specify prerequisites.

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

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/tuliperis/SharkMCP'

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