# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
This is a Firewalla MCP (Model Context Protocol) server that provides tools for interacting with Firewalla network security devices. The server exposes network monitoring and device management capabilities through MCP tools.
## Build and Development Commands
- `npm run build` - Compile TypeScript to JavaScript in the `dist/` directory
- `npm run start` - Run the compiled server from `dist/server.js`
- `npm run dev` - Build and immediately run the server (equivalent to build + start)
- `npm test` - Run tests with Vitest
- `npm run test:watch` - Run tests in watch mode
- `npm run test:coverage` - Run tests with coverage report
## Architecture
### Core Components
**FirewallaAPI Class** (`server.ts:149-196`)
- Handles HTTP communication with Firewalla devices
- Manages authentication with bearer tokens and device IDs
- Provides methods for querying flows and device information
**FirewallaMCPServer Class** (`server.ts:198-712`)
- Main MCP server implementation using `@modelcontextprotocol/sdk`
- Registers and handles MCP tool requests
- Provides traffic analysis and device management capabilities
### Available MCP Tools (13 tools)
1. **configure_firewalla** - Set up API connection credentials (or use env vars)
2. **get_config_status** - Check configuration status and source
3. **query_network_flows** - Retrieve network flow data with time range filters
4. **list_devices** - Get all network devices
5. **get_device_details** - Detailed device information by MAC address
6. **analyze_network_traffic** - Traffic analysis (summary, top talkers, blocked traffic, security events)
7. **get_device_traffic** - Device-specific traffic analysis
8. **get_network_overview** - Comprehensive network overview
9. **get_cloud_rules** - Active cloud security rules
10. **get_traffic_trends** - Traffic trends (24h/7d/30d)
11. **get_firewalla_status** - Firewalla device status
12. **search_devices** - Search devices by name/IP/MAC
13. **update_device_rules** - Allow/block/deny categories, apps, or specific targets for devices
### Key Data Types
- **FlowRecord** (`server.ts:19-69`) - Network flow data structure
- **Device** (`server.ts:201-224`) - Network device information
- **DevicePolicy** (`server.ts:76-100`) - Device security and network policies
- **FirewallaConfig** (`server.ts:13-17`) - API connection configuration
- **DeviceRule** (`server.ts:154-172`) - Security rule configuration for devices
- **RuleUpdateRequest** (`server.ts:174-177`) - Rule update API request structure
## TypeScript Configuration
- Target: ES2022 with ESNext modules
- Strict mode enabled
- Output directory: `./dist`
- Single source file: `server.ts`
## Configuration
The server can be configured in two ways:
### Option 1: Environment Variables (Recommended)
Set these environment variables before starting the server:
```bash
export FIREWALLA_URL="https://my.firewalla.com"
export FIREWALLA_TOKEN="your-bearer-token"
export FIREWALLA_ID="your-firewalla-device-id"
```
### Option 2: Runtime Configuration
Use the `configure_firewalla` MCP tool after the server starts.
### Checking Configuration Status
Use the `get_config_status` tool to verify the current configuration state.
## Server Communication
The server uses stdio transport for MCP communication.
### Structured Logging
The server uses structured JSON logging to stderr (stdout reserved for MCP):
**Log Format:**
```json
{
"service": "firewalla-mcp",
"timestamp": "2024-01-01T00:00:00.000Z",
"level": "info",
"message": "Server started",
"context": { "transport": "stdio" }
}
```
**Log Levels** (configurable via `LOG_LEVEL` env var):
- `debug` - Verbose debugging information
- `info` - General operational messages (default)
- `warn` - Warning conditions (retries, partial config)
- `error` - Error conditions
**Example:**
```bash
LOG_LEVEL=debug npm run start
```
### Error Recovery
The API client includes robust error handling with automatic retry:
**Retry Behavior:**
- Retries on 5xx server errors (500, 502, 503, etc.)
- Retries on rate limits (429) with Retry-After header support
- Retries on network failures (connection errors, timeouts)
- Does NOT retry on 4xx client errors (400, 401, 403, 404)
**Retry Configuration (defaults):**
- `maxRetries: 3` - Maximum retry attempts
- `baseDelayMs: 1000` - Initial delay before first retry
- `maxDelayMs: 10000` - Maximum delay between retries
- `timeoutMs: 30000` - Request timeout
**Custom Error Classes:**
- `FirewallaAPIError` - Base API error with status code and endpoint
- `FirewallaAuthError` - Authentication failures (401/403)
- `FirewallaNetworkError` - Network/timeout errors (retryable)
- `FirewallaRateLimitError` - Rate limiting (429) with retry-after
### Graceful Shutdown
The server handles shutdown signals gracefully:
- **SIGINT** (Ctrl+C) - Closes MCP connection and exits cleanly
- **SIGTERM** - Same graceful shutdown behavior
- **Uncaught exceptions** - Logs error and shuts down gracefully
- **Unhandled rejections** - Logs reason and shuts down gracefully
A second signal during shutdown will force immediate exit.
## Traffic Analysis Features
The server includes sophisticated network analysis capabilities:
- Traffic volume and protocol distribution
- Top talking devices and destinations
- Security event detection and blocked traffic analysis
- Country-based traffic categorization
- Suspicious port activity monitoring
## API Samples Directory
The `api_samples/` directory contains real Firewalla API request examples and response data for development reference:
### Flow Data (`api_samples/flows/`)
- **query** - Flow query API with POST request showing network traffic records including blocked connections, threat intel events, and detailed flow metadata
- **trend** - Dashboard trend API showing 24-hour traffic patterns with upload/download statistics and blocking percentages by hour
### Policy and Network Information (`api_samples/policies_and_network_info/`)
- **active_rules** - Cloud rule listings showing security policies like YouTube blocking with DNS-level filtering
- **device_and_network_info_and_policies** - Comprehensive device inventory including network interfaces, device policies, WireGuard VPN clients, and network group configurations
- **firewalla_device_info** - Firewalla device status and configuration information
These samples demonstrate the actual data structures used by the MCP server and provide examples of real network environments with multiple LANs, VPN clients, and security policies.