← Back to Blog
DevOps2026-05-12Β·58 min read

Talk to Your Firewall: Query OPNsense from tools like Claude Code with MCP

By blizzy

Operationalizing Firewall Telemetry: Integrating OPNsense with AI Agents via MCP

Current Situation Analysis

Network infrastructure management often suffers from a "context tax." Engineers managing OPNsense deployments frequently interrupt their primary workflow to retrieve telemetry data. The standard ritual involves leaving the IDE or terminal, initiating an SSH session, executing commands like pfctl -sr or tcpdump, parsing raw output, and returning to the task. This friction is not merely inconvenient; it introduces latency in incident response and increases the cognitive load required to correlate data across disparate sources.

While OPNsense provides a robust REST API, this interface is typically consumed by custom scripts or monitoring dashboards rather than interactive tools. The gap between unstructured operational intent (e.g., "Why is this host unreachable?") and structured API calls remains wide. Developers lack a standardized mechanism to expose firewall state directly to the tools they use daily, such as AI coding assistants or terminal-based agents.

Model Context Protocol (MCP) addresses this by creating a universal bridge between AI clients and external data sources. By wrapping the OPNsense REST API in an MCP server, firewall telemetry becomes a set of callable tools. This allows agents to query DHCP leases, inspect firewall logs, and analyze ARP tables without human intervention, effectively eliminating context switching and enabling automated network diagnostics.

WOW Moment: Key Findings

Integrating firewall telemetry via MCP fundamentally alters the operational loop. The following comparison highlights the efficiency gains when moving from manual CLI interaction to an MCP-driven agent workflow.

Metric Manual CLI/SSH Workflow MCP-Integrated Agent Delta
Context Switches 3-5 per query (IDE β†’ SSH β†’ Web UI β†’ IDE) 0 -100%
Query Construction Manual syntax recall (pfctl, grep) Natural language intent High reliability
Data Correlation Manual cross-referencing of outputs Automated tool chaining Immediate
Error Rate Medium (typos, wrong flags) Low (schema-validated calls) Reduced
Time to Insight 45–90 seconds <5 seconds ~90% faster

Why this matters: The MCP layer transforms the firewall from a static appliance into an active participant in the development and operations workflow. Agents can autonomously validate network states, correlate blocked connections with DHCP leases, and generate remediation steps, allowing engineers to focus on architecture and policy rather than data retrieval.

Core Solution

The architecture relies on a lightweight MCP server that translates tool calls into authenticated requests against the OPNsense REST API. The server supports two transport modes: STDIO for local development and SSE for shared team access.

Architecture Decisions

  1. Read-First Design: The server exposes read-only tools by default. Write operations are gated behind explicit tool calls to prevent accidental configuration drift.
  2. Credential Isolation: API secrets are never hardcoded. The server requires environment variables, ensuring compatibility with secret managers and .env files.
  3. Transport Flexibility: STDIO is used for single-user, local scenarios where the agent runs on the same host. SSE allows multiple clients to connect to a centralized firewall bridge, useful for lab environments or team collaboration.

Implementation Steps

1. Generate OPNsense API Credentials Navigate to System β†’ Access β†’ API in the OPNsense web interface. Create a new key with the minimum required privileges. For telemetry queries, read-only access is sufficient.

2. Deploy the MCP Bridge The server is a Python application. We recommend using a virtual environment to isolate dependencies.

# Clone the bridge repository
git clone https://github.com/coreyhines/opnsense-mcp
cd opnsense-mcp

# Create isolated environment
python3 -m venv .venv
source .venv/bin/activate

# Install dependencies
pip install -r requirements.txt

3. Configure Environment Create a .env file with your credentials. Use distinct variable names to avoid conflicts with other services.

# .env
FIREWALL_HOST=https://192.168.1.1
FIREWALL_API_TOKEN=your_api_key_here
FIREWALL_API_SECRET=your_api_secret_here
VERIFY_SSL=false

4. Client Configuration Configure your MCP client to recognize the bridge. Below is a TypeScript example of an agent loop that utilizes the firewall tools. This demonstrates how the MCP server integrates into a custom application.

import { MCPClient, ToolCall } from '@anthropic/mcp-client';

interface NetworkAuditResult {
  activeHosts: number;
  recentBlocks: string[];
  status: 'ok' | 'investigation_needed';
}

class NetworkAuditorAgent {
  private client: MCPClient;

  constructor(config: { serverName: string }) {
    this.client = new MCPClient({ server: config.serverName });
  }

  async performAudit(): Promise<NetworkAuditResult> {
    try {
      // Tool 1: Retrieve active DHCP leases
      const leaseCall: ToolCall = {
        name: 'fetch_dhcp_leases',
        arguments: { status: 'active' }
      };
      const leases = await this.client.execute(leaseCall);

      // Tool 2: Query recent firewall blocks
      const logCall: ToolCall = {
        name: 'query_firewall_events',
        arguments: { 
          action: 'block', 
          timeframe: '10m',
          limit: 20 
        }
      };
      const blocks = await this.client.execute(logCall);

      return {
        activeHosts: leases.data.length,
        recentBlocks: blocks.data.map((b: any) => b.source_ip),
        status: blocks.data.length > 5 ? 'investigation_needed' : 'ok'
      };
    } catch (error) {
      console.error('Audit failed:', error);
      throw error;
    }
  }
}

// Usage
const auditor = new NetworkAuditorAgent({ serverName: 'firewall-telemetry' });
auditor.performAudit().then(console.log);

5. Transport Selection

  • STDIO (Local): Ideal for Claude Code or Cursor running on your workstation.

    {
      "mcpServers": {
        "firewall-telemetry": {
          "command": "/bin/bash",
          "args": ["/path/to/opnsense-mcp/mcp_start.sh"],
          "cwd": "/path/to/opnsense-mcp"
        }
      }
    }
    
  • SSE (Shared): For team access, deploy the server with TLS termination.

    # Deploy using Podman and Caddy for secure access
    sudo bash deploy/install.sh
    # Clients connect via https://your-host/sse
    

Pitfall Guide

1. Credential Sprawl

  • Explanation: Storing API secrets in version control or sharing them via insecure channels.
  • Fix: Enforce .env usage and add .env to .gitignore. Use a secret manager in production deployments. Rotate keys immediately if exposure is suspected.

2. Over-Privileged API Keys

  • Explanation: Generating API keys with full administrative access when only telemetry is required.
  • Fix: Create dedicated API keys with read-only scopes. If write capabilities are needed, use a separate key with restricted permissions and audit all write calls.

3. SSE Exposure Risks

  • Explanation: Exposing the SSE endpoint to the public internet without authentication or TLS.
  • Fix: Always use HTTPS. Place the SSE endpoint behind a reverse proxy with authentication. Restrict access via firewall rules to trusted IP ranges.

4. Rate Limiting and API Throttling

  • Explanation: Agents making rapid, repetitive calls can overwhelm the OPNsense API, causing timeouts.
  • Fix: Implement client-side caching for static data like firewall rules. Add delays between calls in agent loops. Monitor OPNsense logs for API abuse.

5. Stale Data Assumptions

  • Explanation: Assuming data is real-time when the agent may be using cached responses or when the firewall state changes rapidly.
  • Fix: Explicitly request fresh data for time-sensitive queries. Implement a "refresh" tool call in the agent workflow before critical decisions.

6. Tool Schema Drift

  • Explanation: Updates to the MCP server may change tool names or arguments, breaking agent integrations.
  • Fix: Pin the MCP server version in your deployment. Validate tool schemas during agent initialization. Implement error handling for unknown tools.

7. Log Noise in Production

  • Explanation: High-frequency queries can generate excessive logs on the OPNsense device, obscuring real security events.
  • Fix: Configure the MCP server to suppress verbose logging. Use log aggregation tools to filter MCP-related entries.

Production Bundle

Action Checklist

  • Generate Read-Only Key: Create an API key in OPNsense with minimal privileges for telemetry access.
  • Secure Secrets: Store credentials in a .env file and ensure it is excluded from version control.
  • Validate STDIO: Test the local connection using a simple query before deploying shared services.
  • Deploy SSE Securely: If using SSE, ensure TLS is configured and access is restricted to trusted networks.
  • Configure Agent Permissions: Review the tools exposed to the AI client and disable any unnecessary capabilities.
  • Monitor API Usage: Set up alerts for unusual API request patterns or authentication failures.
  • Test Error Handling: Verify that the agent gracefully handles network timeouts and API errors.

Decision Matrix

Scenario Recommended Approach Why Cost Impact
Solo Development STDIO Transport Zero infrastructure overhead; runs locally with the editor. Free
Team Lab SSE with Auth Centralized access allows multiple engineers to query the firewall. Low (Container/VM)
Production Audit SSE + RBAC Audit trails and role-based access control ensure compliance. Medium
Automated Remediation SSE + Write Keys Agents can execute corrective actions based on telemetry. Medium

Configuration Template

MCP Client Configuration (mcp.json)

{
  "mcpServers": {
    "firewall-telemetry": {
      "command": "/bin/bash",
      "args": ["/opt/mcp-servers/opnsense-bridge/mcp_start.sh"],
      "cwd": "/opt/mcp-servers/opnsense-bridge",
      "env": {
        "FIREWALL_HOST": "https://firewall.internal",
        "FIREWALL_API_TOKEN": "${FIREWALL_TOKEN}",
        "FIREWALL_API_SECRET": "${FIREWALL_SECRET}"
      }
    }
  }
}

Environment Template (.env.example)

# Firewall Connection
FIREWALL_HOST=https://<your-opnsense-ip>
FIREWALL_API_TOKEN=<your-api-key>
FIREWALL_API_SECRET=<your-api-secret>

# SSL Verification (set to false for self-signed certs in lab)
VERIFY_SSL=true

# Logging Level
LOG_LEVEL=info

Quick Start Guide

  1. Create API Key: Log into OPNsense, go to System β†’ Access β†’ API, and generate a new key.
  2. Install Bridge: Clone the repository and install dependencies using pip or uv.
  3. Configure: Copy .env.example to .env and populate with your credentials.
  4. Connect: Add the server configuration to your MCP client and run a test query like "Show active DHCP leases."
  5. Iterate: Expand your agent workflows to include log analysis and packet capture automation.