Skip to main content
Glama
tuliperis

SharkMCP

by tuliperis

stop_capture_session

Stop a network packet capture session and analyze captured data with customizable filters and output formats for security analysis and troubleshooting.

Instructions

Stop a running capture session and analyze packets. LLMs control all analysis parameters including display filters and output formats. Can use saved configurations.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sessionIdYesSession ID returned from start_capture_session
displayFilterNoWireshark display filter for analysis (e.g., "tls.handshake.type == 1")
outputFormatNoOutput format: json (-T json), fields (custom -e), or text (default wireshark output)text
customFieldsNoCustom tshark field list (only used with outputFormat=fields)
sslKeylogFileNoABSOLUTE path to SSL keylog file for TLS decryption
configNameNoName of saved configuration to use for analysis parameters

Implementation Reference

  • Main handler function for stopping the capture session: validates session, stops process if running, analyzes pcap with tshark, handles configs and SSL decryption, cleans up temp file, returns formatted analysis results.
    export async function stopCaptureSessionHandler(args: any, activeSessions: Map<string, CaptureSession>) {
      try {
        let { sessionId, displayFilter, outputFormat, customFields, sslKeylogFile, configName } = args;
        const session = activeSessions.get(sessionId);
        
        if (!session) {
          return {
            content: [{
              type: 'text' as const,
              text: `Error: No active session found with ID '${sessionId}'. Use 'list_capture_sessions' to see active sessions.`,
            }],
            isError: true
          };
        }
    
        // If configName is provided, load and use that configuration for analysis
        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 analysis parameters with saved config (saved config takes precedence)
          if (savedConfig.displayFilter) displayFilter = savedConfig.displayFilter;
          if (savedConfig.outputFormat) outputFormat = savedConfig.outputFormat;
          if (savedConfig.customFields) customFields = savedConfig.customFields;
          
          console.error(`Using saved configuration '${configName}' for analysis: ${JSON.stringify(savedConfig)}`);
        }
    
        console.error(`Stopping capture session: ${sessionId}`);
    
        // Check if the capture process has already completed naturally
        if (session.process && !session.process.killed && session.status === 'running') {
          console.error(`Terminating capture process for session ${sessionId}`);
          session.process.kill('SIGTERM');
          // Wait a moment for graceful termination
          await new Promise(resolve => setTimeout(resolve, 2000));
        } else if (session.status === 'completed') {
          console.error(`Capture session ${sessionId} already completed naturally`);
        } else {
          console.error(`Capture session ${sessionId} process already terminated`);
        }
    
        // Remove from active sessions
        activeSessions.delete(sessionId);
    
        try {
          // Check if file exists
          await fs.access(session.tempFile);
          
          // Wait a bit more to ensure file is fully written
          await new Promise(resolve => setTimeout(resolve, 1000));
          
          // Analyze captured file using the reusable function
          const output = await analyzePcap(
            session.tempFile,
            displayFilter,
            outputFormat,
            customFields,
            sslKeylogFile
          );
          
          const keylogToUse = sslKeylogFile || process.env.SSLKEYLOGFILE;
    
          // Clean up temporary file
          await fs.unlink(session.tempFile).catch(err => 
            console.error(`Failed to delete ${session.tempFile}: ${err.message}`)
          );
    
          const duration = new Date().getTime() - session.startTime.getTime();
          const durationSec = (duration / 1000).toFixed(1);
    
          // Trim output if too large
          const trimmedOutput = trimOutput(output, outputFormat);
    
          const configInfo = configName ? `\nUsing saved config: ${configName}` : '';
    
          return {
            content: [{
              type: 'text' as const,
              text: `Capture session '${sessionId}' completed!${configInfo}\nInterface: ${session.interface}\nDuration: ${durationSec}s\nDisplay Filter: ${displayFilter || 'none'}\nOutput Format: ${outputFormat}\nSSL Decryption: ${keylogToUse ? 'Enabled' : 'Disabled'}\n\nPacket Analysis Results:\n${trimmedOutput}`,
            }],
          };
    
        } catch (fileError: any) {
          console.error(`Error analyzing session ${sessionId}: ${fileError.message}`);
          return {
            content: [{
              type: 'text' as const,
              text: `Error analyzing session '${sessionId}': Capture file not found or unreadable. This could mean no packets were captured.\nDetails: ${fileError.message}`,
            }],
            isError: true,
          };
        }
      } catch (error: any) {
        console.error(`Error stopping capture session: ${error.message}`);
        return { 
          content: [{ type: 'text' as const, text: `Error: ${error.message}` }], 
          isError: true 
        };
      }
    } 
  • Zod schema defining input parameters for the stop_capture_session tool, including sessionId (required), optional analysis filters, formats, fields, SSL keylog, and config.
    export const stopCaptureSessionSchema = {
      sessionId: z.string().describe('Session ID returned from start_capture_session'),
      displayFilter: z.string().optional().describe('Wireshark display filter for analysis (e.g., "tls.handshake.type == 1")'),
      outputFormat: z.enum(['json', 'fields', 'text']).optional().default('text').describe('Output format: json (-T json), fields (custom -e), or text (default wireshark output)'),
      customFields: z.string().optional().describe('Custom tshark field list (only used with outputFormat=fields)'),
      sslKeylogFile: z.string().optional().describe('ABSOLUTE path to SSL keylog file for TLS decryption'),
      configName: z.string().optional().describe('Name of saved configuration to use for analysis parameters')
    };
  • src/index.ts:33-37 (registration)
    Registration of the stop_capture_session tool on the MCP server, using the schema and handler from stop-capture-session module.
      'stop_capture_session',
      'Stop a running capture session and analyze packets. LLMs control all analysis parameters including display filters and output formats. Can use saved configurations.',
      stopCaptureSessionSchema,
      async (args) => stopCaptureSessionHandler(args, activeSessions)
    );
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions that the tool stops a session and analyzes packets with LLM-controlled parameters, but lacks details on critical behaviors: whether stopping is reversible, if analysis occurs automatically upon stopping, error handling for invalid inputs, or performance implications. This is a significant gap for a tool with mutation and analysis functions.

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 concise with three sentences that are front-loaded: the first states the core action, the second adds control details, and the third mentions configuration use. Each sentence adds value without redundancy, though it could be slightly more structured by explicitly separating stopping and analysis aspects.

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 tool's complexity (stopping and analyzing packets with 6 parameters), no annotations, and no output schema, the description is incomplete. It doesn't explain what happens after stopping (e.g., session deletion, data retention), the analysis output format or structure, or error conditions. For a mutation tool with rich parameters, this leaves too many unknowns for effective agent 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 already documents all parameters thoroughly. The description adds minimal value beyond the schema by mentioning 'LLMs control all analysis parameters including display filters and output formats' and 'Can use saved configurations,' which loosely relates to parameters like 'displayFilter,' 'outputFormat,' and 'configName.' This meets the baseline of 3 when schema coverage is high.

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: 'Stop a running capture session and analyze packets.' It specifies the verb ('stop'), resource ('capture session'), and additional action ('analyze packets'), which distinguishes it from siblings like 'start_capture_session' (starting vs. stopping) and 'analyze_pcap_file' (live session vs. file analysis). However, it doesn't explicitly differentiate from 'manage_config' regarding configuration usage.

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

Usage Guidelines3/5

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

The description implies usage context by mentioning 'running capture session' and 'saved configurations,' suggesting it should be used after starting a session and potentially with configurations. It doesn't explicitly state when to use this tool vs. alternatives like 'analyze_pcap_file' for file-based analysis or 'manage_config' for configuration management, leaving some ambiguity.

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