Skip to main content
Glama
mcpcap

mcpacket

by mcpcap

analyze_tcp_connections

Analyze TCP connection states from PCAP files to detect problems and summarize connection statistics.

Instructions

Analyze TCP connection states and lifecycle.

This is the core tool for TCP connection analysis, solving 80% of TCP-related issues.

FILE UPLOAD LIMITATION: This MCP tool cannot process files uploaded through Claude's web interface. Files must be accessible via URL or local file path.

SUPPORTED INPUT FORMATS:

  • Remote files: "https://example.com/capture.pcap"

  • Local files: "/absolute/path/to/capture.pcap"

UNSUPPORTED:

  • Files uploaded through Claude's file upload feature

  • Base64 file content

  • Relative file paths

Args: pcap_file: HTTP URL or absolute local file path to PCAP file server_ip: Optional filter for server IP address server_port: Optional filter for server port detailed: Whether to return detailed connection information

Returns: A structured dictionary containing TCP connection analysis results including: - summary: Overall connection statistics - connections: List of individual connections with states - issues: Detected problems

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pcap_fileYes
server_ipNo
server_portNo
detailedNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The main function that executes the 'analyze_tcp_connections' tool logic. It delegates to analyze_packets() which routes to _analyze_connections() for the actual connection analysis, then to _analyze_single_connection() for per-connection details.
    def analyze_tcp_connections(
        self,
        pcap_file: str,
        server_ip: str | None = None,
        server_port: int | None = None,
        detailed: bool = False,
    ) -> dict[str, Any]:
        """
        Analyze TCP connection states and lifecycle.
    
        This is the core tool for TCP connection analysis, solving 80% of TCP-related issues.
    
        FILE UPLOAD LIMITATION: This MCP tool cannot process files uploaded through
        Claude's web interface. Files must be accessible via URL or local file path.
    
        SUPPORTED INPUT FORMATS:
        - Remote files: "https://example.com/capture.pcap"
        - Local files: "/absolute/path/to/capture.pcap"
    
        UNSUPPORTED:
        - Files uploaded through Claude's file upload feature
        - Base64 file content
        - Relative file paths
    
        Args:
            pcap_file: HTTP URL or absolute local file path to PCAP file
            server_ip: Optional filter for server IP address
            server_port: Optional filter for server port
            detailed: Whether to return detailed connection information
    
        Returns:
            A structured dictionary containing TCP connection analysis results including:
            - summary: Overall connection statistics
            - connections: List of individual connections with states
            - issues: Detected problems
        """
        return self.analyze_packets(
            pcap_file,
            analysis_type="connections",
            server_ip=server_ip,
            server_port=server_port,
            detailed=detailed,
        )
  • _analyze_connections() performs the core TCP connection analysis: groups packets by connection (4-tuple), calls _analyze_single_connection() per connection, and aggregates summary statistics (handshakes, resets, normal closes, issues).
    def _analyze_connections(
        self, pcap_file: str, tcp_packets: list, all_packets: list
    ) -> dict[str, Any]:
        """Analyze TCP connections."""
        # Group packets by connection (4-tuple)
        connections = defaultdict(list)
        for pkt in tcp_packets:
            conn_key = self._get_connection_key(pkt)
            connections[conn_key].append(pkt)
    
        # Analyze each connection
        connection_details = []
        successful_handshakes = 0
        failed_handshakes = 0
        reset_connections = 0
        normal_close = 0
        issues = []
    
        for conn_key, pkts in connections.items():
            conn_info = self._analyze_single_connection(conn_key, pkts)
            connection_details.append(conn_info)
    
            if conn_info["handshake_completed"]:
                successful_handshakes += 1
            else:
                failed_handshakes += 1
    
            if conn_info["close_reason"] == "reset":
                reset_connections += 1
            elif conn_info["close_reason"] == "normal":
                normal_close += 1
    
        # Detect issues
        total_retrans = sum(c["retransmissions"] for c in connection_details)
    
        if reset_connections > 0:
            issues.append(f"{reset_connections} connections terminated by RST")
        if total_retrans > 0:
            issues.append(f"{total_retrans} retransmissions detected")
        if failed_handshakes > 0:
            issues.append(f"{failed_handshakes} failed handshakes")
    
        return {
            "file": pcap_file,
            "analysis_timestamp": datetime.now().isoformat(),
            "total_packets": len(all_packets),
            "tcp_packets_found": len(tcp_packets),
            "filter": {
                "server_ip": self._analysis_kwargs.get("server_ip"),
                "server_port": self._analysis_kwargs.get("server_port"),
            },
            "summary": {
                "total_connections": len(connections),
                "successful_handshakes": successful_handshakes,
                "failed_handshakes": failed_handshakes,
                "established_connections": successful_handshakes,
                "reset_connections": reset_connections,
                "normal_close": normal_close,
                "active_connections": len(connections)
                - reset_connections
                - normal_close,
            },
            "connections": connection_details
            if self._analysis_kwargs.get("detailed", False)
            else connection_details[:10],
            "issues": issues,
        }
  • _analyze_single_connection() analyzes an individual TCP connection: counts SYN/SYN-ACK/ACK/RST/FIN flags, detects retransmissions, determines handshake completion and close reason.
    def _analyze_single_connection(
        self, conn_key: tuple, packets: list
    ) -> dict[str, Any]:
        """Analyze a single TCP connection."""
        client, server = self._identify_connection_roles(packets)
    
        syn_count = 0
        syn_ack_count = 0
        ack_count = 0
        rst_count = 0
        fin_count = 0
        data_packets = 0
        retransmissions = 0
    
        seen_seqs_by_sender: dict[tuple[str, int], set[int]] = defaultdict(set)
        handshake_completed = False
    
        for pkt in packets:
            src_ip, _ = self._extract_ips(pkt)
            tcp = pkt[TCP]
            flags = tcp.flags
    
            # Count flags
            if flags & 0x02:  # SYN
                syn_count += 1
            if flags & 0x12 == 0x12:  # SYN-ACK
                syn_ack_count += 1
            if flags & 0x10:  # ACK
                ack_count += 1
            if flags & 0x04:  # RST
                rst_count += 1
            if flags & 0x01:  # FIN
                fin_count += 1
    
            # Check for data
            if len(tcp.payload) > 0:
                data_packets += 1
    
            # Detect retransmissions (simplified)
            seq = tcp.seq
            sender = (src_ip, tcp.sport)
            if seq in seen_seqs_by_sender[sender] and len(tcp.payload) > 0:
                retransmissions += 1
            seen_seqs_by_sender[sender].add(seq)
    
        # Determine handshake completion
        if syn_count > 0 and syn_ack_count > 0 and ack_count > 0:
            handshake_completed = True
    
        # Determine close reason
        close_reason = "unknown"
        if rst_count > 0:
            close_reason = "reset"
        elif fin_count >= 2:
            close_reason = "normal"
        elif len(packets) > 3:
            close_reason = "active"
    
        return {
            "client": f"{client[0]}:{client[1]}",
            "server": f"{server[0]}:{server[1]}",
            "state": "closed" if close_reason in ["reset", "normal"] else "active",
            "handshake_completed": handshake_completed,
            "syn_count": syn_count,
            "syn_ack_count": syn_ack_count,
            "ack_count": ack_count,
            "rst_count": rst_count,
            "fin_count": fin_count,
            "data_packets": data_packets,
            "retransmissions": retransmissions,
            "close_reason": close_reason,
            "packet_count": len(packets),
        }
  • The tool is registered with the MCP server in _register_tools() via self.mcp.tool(module.analyze_tcp_connections) when the 'tcp' module is enabled.
    def _register_tools(self) -> None:
        """Register all available tools with the MCP server."""
        # Register tools for each loaded module
        for module_name, module in self.modules.items():
            if module_name == "dns":
                self.mcp.tool(module.analyze_dns_packets)
            elif module_name == "dhcp":
                self.mcp.tool(module.analyze_dhcp_packets)
            elif module_name == "icmp":
                self.mcp.tool(module.analyze_icmp_packets)
            elif module_name == "capinfos":
                self.mcp.tool(module.analyze_capinfos)
            elif module_name == "tcp":
                self.mcp.tool(module.analyze_tcp_connections)
                self.mcp.tool(module.analyze_tcp_anomalies)
                self.mcp.tool(module.analyze_tcp_retransmissions)
                self.mcp.tool(module.analyze_traffic_flow)
            elif module_name == "sip":
                self.mcp.tool(module.analyze_sip_packets)
  • The analyze_tcp_connections function signature and docstring define the input schema: pcap_file (str), server_ip (optional str), server_port (optional int), detailed (bool). Returns a dict with summary, connections, and issues.
    def analyze_tcp_connections(
        self,
        pcap_file: str,
        server_ip: str | None = None,
        server_port: int | None = None,
        detailed: bool = False,
    ) -> dict[str, Any]:
        """
        Analyze TCP connection states and lifecycle.
    
        This is the core tool for TCP connection analysis, solving 80% of TCP-related issues.
    
        FILE UPLOAD LIMITATION: This MCP tool cannot process files uploaded through
        Claude's web interface. Files must be accessible via URL or local file path.
    
        SUPPORTED INPUT FORMATS:
        - Remote files: "https://example.com/capture.pcap"
        - Local files: "/absolute/path/to/capture.pcap"
    
        UNSUPPORTED:
        - Files uploaded through Claude's file upload feature
        - Base64 file content
        - Relative file paths
    
        Args:
            pcap_file: HTTP URL or absolute local file path to PCAP file
            server_ip: Optional filter for server IP address
            server_port: Optional filter for server port
            detailed: Whether to return detailed connection information
    
        Returns:
            A structured dictionary containing TCP connection analysis results including:
            - summary: Overall connection statistics
            - connections: List of individual connections with states
            - issues: Detected problems
        """
        return self.analyze_packets(
            pcap_file,
            analysis_type="connections",
            server_ip=server_ip,
            server_port=server_port,
            detailed=detailed,
        )
Behavior4/5

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

With no annotations, the description must disclose behavioral traits. It effectively does so by detailing input file format limitations (unsupported Claude uploads, base64, relative paths) and the structure of the output. However, it does not mention potential performance constraints or if the tool modifies any state.

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 well-structured with clear sections (purpose, limitation, formats, args). While verbose, every sentence adds value. Minor redundancy in the 'FILE UPLOAD LIMITATION' heading, but it aids clarity. It could be slightly more concise, but overall efficient.

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

Completeness5/5

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

Given the tool's complexity (4 parameters, output schema presence), the description covers all critical aspects: input constraints, parameter semantics, return structure, and intended use case. It differentiates from siblings and handles common user misunderstandings (file upload limitation). Complete and informative.

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

Parameters5/5

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

The input schema has 0% description coverage, leaving the description to explain parameters fully. The Arg descriptions add substantial meaning: pcap_file is clarified as 'HTTP URL or absolute local file path', server_ip and server_port are optional filters, and detailed is a boolean for detail level. This fully compensates for the schema's lack of descriptions.

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 tool's purpose: 'Analyze TCP connection states and lifecycle.' It further positions itself as the core TCP tool solving 80% of TCP issues, effectively distinguishing it from sibling tools like analyze_tcp_anomalies and analyze_tcp_retransmissions.

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 the tool by stating it is the primary TCP analysis tool. However, it does not explicitly mention when not to use it or provide direct comparisons with sibling tools, though the sibling list offers indirect differentiation.

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/mcpcap/mcpacket'

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