### Quick Start: Setup and Configuration for OPNsense MCP Server Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/README.md This bash script guides users through cloning the repository, setting up a Python virtual environment, installing dependencies, configuring OPNsense credentials, and setting up the Claude Desktop client for natural language firewall management. It emphasizes local storage of sensitive credentials. ```bash # 1. đŸ“Ĩ Clone & Enter git clone https://github.com/floriangrousset/opnsense-mcp-server && cd opnsense-mcp-server # 2. đŸ› ī¸ Setup Environment curl -LsSf https://astral.sh/uv/install.sh | sh uv venv && source .venv/bin/activate uv pip install -r requirements.txt # 3. 🔐 Configure Your OPNsense Credentials (Secure - Local Only!) opnsense-mcp setup # Enter your OPNsense URL, API key, and secret interactively # 🔒 Credentials stored locally ONLY - never sent to AI models! # 4. âš™ī¸ Configure Claude Desktop (Automatic!) ./setup-claude.sh # 🎉 Magic happens here! # 5. 🚀 Start Managing! # Open Claude Desktop and say: "Configure OPNsense connection" ``` -------------------------------- ### Clone and Setup Project - Bash Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/CONTRIBUTING.md Commands to clone the OPNsense MCP Server repository, set up a virtual environment, and install development dependencies. ```bash git clone https://github.com/YOUR_USERNAME/opnsense-mcp-server cd opnsense-mcp-server uv venv && source .venv/bin/activate uv pip install -e ".[dev]" ``` -------------------------------- ### Install Dependencies with uv Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/CLAUDE.md This snippet demonstrates how to set up a Python development environment using 'uv', a fast Python package installer and virtual environment manager. It covers installing uv, creating a virtual environment, and installing project dependencies from requirements.txt. ```bash # Install uv (Python package manager) curl -LsSf https://astral.sh/uv/install.sh | sh # Create virtual environment uv venv source .venv/bin/activate # Linux/macOS # .venv\Scripts\activate # Windows # Install dependencies uv pip install -r requirements.txt ``` -------------------------------- ### Install jq Package Manager Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/README.md This snippet provides commands to install `jq`, a lightweight and flexible command-line JSON processor. It's a prerequisite for the automated Claude Desktop setup script. ```bash # Install jq if needed brew install jq # 🍎 macOS sudo apt install jq # 🐧 Ubuntu/Debian sudo yum install jq # 🎩 RHEL/CentOS ``` -------------------------------- ### OPNSense MCP CLI Setup and Management Commands Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/SECURITY.md These bash commands illustrate how to set up and manage OPNsense MCP Server configurations using its command-line interface. This includes interactive setup, profile-specific setup, listing profiles, testing connections, and deleting profiles. ```bash # Setup using interactive CLI opnsense-mcp setup # Or setup specific profile opnsense-mcp setup --profile production # List all configured profiles opnsense-mcp list-profiles # Show profile details (credentials NOT shown) opnsense-mcp list-profiles --verbose # Test connection without exposing credentials opnsense-mcp test-connection --profile production # Delete unused profiles opnsense-mcp delete-profile staging # Multi-environment setup examples opnsense-mcp setup --profile dev opnsense-mcp setup --profile staging opnsense-mcp setup --profile production ``` -------------------------------- ### Install Development Dependencies (Bash) Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/CLAUDE.md Installs the project in editable mode with development dependencies using uv pip. This command is typically used for setting up the development environment. ```bash uv pip install -e ".[dev]" ``` -------------------------------- ### Bash Command for Installing Test Dependencies Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/tests/README.md This bash command installs the necessary Python dependencies for testing the OPNsense MCP Server project. It assumes you are in the project's root directory and uses `uv pip install` to manage the virtual environment. Ensure `requirements.txt` is present and `uv` is installed. ```bash # Ensure you're in the project root cd /path/to/opnsense-mcp-server # Install test dependencies uv pip install -r requirements.txt ``` -------------------------------- ### Install uv (Ultra-Fast Python Manager) Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/README.md Instructions for installing the `uv` package manager, which is used for its speed in managing Python environments and dependencies. It provides commands for macOS/Linux and Windows. ```bash # 🍎 macOS/Linux - One command install curl -LsSf https://astral.sh/uv/install.sh | sh ``` ```powershell # đŸĒŸ Windows (PowerShell) curl -LsSf https://astral.sh/uv/install.ps1 | powershell -c - ``` -------------------------------- ### Install Python Dependencies with uv Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/README.md After setting up the virtual environment, this command uses `uv` to install all the necessary Python packages listed in the `requirements.txt` file. This ensures the project has all its required libraries. ```bash # Install all required packages (super fast with uv!) uv pip install -r requirements.txt ``` -------------------------------- ### Run Claude Desktop Auto-Magic Setup Script Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/README.md This command executes the `setup-claude.sh` script, which automates the configuration of Claude Desktop by finding its configuration, detecting the Python virtual environment, and safely updating settings. ```bash # Run the magic setup script ./setup-claude.sh ``` -------------------------------- ### Run OPNsense MCP Server Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/CLAUDE.md This section provides instructions for running the OPNsense MCP Server. It shows how to execute the server as a Python module, via its entry point if installed, and using a backward compatibility wrapper script. ```bash # Run as Python module (recommended) python -m src.opnsense_mcp.main # Or run via entry point (if installed) opnsense-mcp-server # Or use backward compatibility wrapper python opnsense-mcp-server.py ``` -------------------------------- ### Commit Message Examples Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/CONTRIBUTING.md Provides concrete examples of how to apply the semantic commit message conventions. These examples cover various types of changes commonly found in software development. ```markdown ``` feat: add support for WireGuard configuration in VPN domain fix: correct DHCP lease parsing in dns_dhcp module docs: update README with new certificate management tools test: add unit tests for firewall rule validation ``` ``` -------------------------------- ### Run Tests with pytest Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/CLAUDE.md Instructions for running the project's tests using pytest. It includes steps for installing development dependencies and executing tests, including running tests with code coverage reporting. ```bash # Install dev dependencies uv pip install -e ".[dev]" # Run tests pytest # Run with coverage pytest --cov=src/opnsense_mcp ``` -------------------------------- ### Docker Support - Build and Run Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/CLAUDE.md Commands for managing the Docker image and container for the OPNsense MCP Server. 'docker build' creates the image, and 'docker-compose up -d' starts the server in detached mode using docker-compose. ```bash # Build image docker build -t opnsense-mcp-server . # Run with docker-compose docker-compose up -d ``` -------------------------------- ### Create and Activate Python Virtual Environment with uv Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/README.md This section shows how to create an isolated Python virtual environment using `uv` and then how to activate it. Activating the environment ensures that project-specific dependencies are installed and used correctly. ```bash # Create isolated Python environment uv venv # Activate it source .venv/bin/activate # 🐧 Linux/macOS # .venv\Scripts\activate # đŸĒŸ Windows ``` -------------------------------- ### Commit Changes - Bash Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/CONTRIBUTING.md Example of how to commit changes with a conventional commit message. ```bash git commit -m "feat: add support for XYZ feature" ``` -------------------------------- ### Make Scripts Executable (Linux/macOS) Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/README.md On Linux and macOS, this command uses `chmod` to make the Python script and setup script executable. This is necessary to run them directly from the terminal. ```bash chmod +x opnsense-mcp-server.py setup-claude.sh ``` -------------------------------- ### Install Ollama and Pull Model (Bash) Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/README.md This snippet demonstrates how to install Ollama, a tool for running local LLMs, and then pull a specific language model (e.g., llama3.2). Ollama is recommended for enhanced privacy and control when using AI with OPNsense. ```bash # Install Ollama curl -fsSL https://ollama.ai/install.sh | sh # Pull a model (e.g., llama3.2) ollama pull llama3.2 ``` -------------------------------- ### Define Tools with Decorators - Python Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/CLAUDE.md An example of how to define a tool using the '@mcp.tool' decorator in Python. This pattern is used for registering functions as callable tools within the MCP server, specifying their name, description, parameters, and return types. ```python from ..core.client import get_opnsense_client from ..core.exceptions import OPNsenseClientError from ..shared.constants import API_ENDPOINTS from ..main import mcp @mcp.tool(name="tool_name", description="Tool description") async def tool_name(param: str) -> dict: client = get_opnsense_client() result = await client.request("GET", API_ENDPOINTS["endpoint"]) return result ``` -------------------------------- ### Manage OPNsense Firewall Rules with Python Source: https://context7.com/floriangrousset/opnsense-mcp-server/llms.txt This section covers the management of OPNsense firewall rules, including creation, listing, modification, and deletion. It uses a Python client to interact with the OPNsense API. The examples show how to add a rule, apply changes, search for existing rules, toggle their state (enable/disable), and delete them. Comprehensive validation is applied. ```python # Tool: firewall_add_rule # File: src/opnsense_mcp/domains/firewall.py:184 # Natural language: "Block all SSH traffic from the internet" # API call structure: client = await get_opnsense_client() response = await client.request( "POST", "/api/firewall/filter/addRule", data={ "rule": { "action": "block", "interface": "wan", "protocol": "tcp", "destination_port": "22", "description": "Block SSH from WAN", "enabled": "1", "direction": "in", "source": "any", "destination": "any" } }, operation="add_firewall_rule" ) # Response: # { # "result": "saved", # "uuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" # } # Apply the rule: await client.request("POST", "/api/firewall/filter/apply") # {"status": "ok"} # List all rules with filtering: response = await client.request( "POST", "/api/firewall/filter/searchRule", data={ "current": 1, "rowCount": 100, "searchPhrase": "SSH" } ) # Returns: # { # "rows": [ # { # "uuid": "a1b2c3d4- āŽŽāŽ°ā¯", # "enabled": "1", # "action": "block", # "interface": "wan", # "protocol": "tcp", # "destination_port": "22", # "description": "Block SSH from WAN" # } # ], # "rowCount": 1, # "total": 1, # "current": 1 # } # Toggle rule (enable/disable): await client.request("POST", "/api/firewall/filter/toggleRule/a1b2c3d4- āŽŽāŽ°ā¯") # {"changed": true} # Delete rule: await client.request("POST", "/api/firewall/filter/delRule/a1b2c3d4- āŽŽāŽ°ā¯") await client.request("POST", "/api/firewall/filter/apply") ``` -------------------------------- ### Execute Custom API Calls and Utilities on OPNsense Source: https://context7.com/floriangrousset/opnsense-mcp-server/llms.txt Performs arbitrary GET or POST API requests to the OPNsense server for advanced control and data retrieval, including backing up the configuration. Requires an initialized OPNsense client. Responses vary based on the API endpoint. ```python # Execute custom API call: response = await client.request( "GET", "/api/diagnostics/interface/getArp", operation="custom_api_call" ) # Custom POST with data: custom_response = await client.request( "POST", "/api/custom/endpoint/action", data={"param1": "value1", "param2": "value2"}, operation="custom_operation" ) # Backup configuration to file: backup = await client.request( "GET", "/api/core/backup/download", operation="backup_config" ) # Save to disk: import json with open("/tmp/opnsense-backup.xml", "w") as f: f.write(backup) ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/README.md This snippet demonstrates how to clone the project repository using git and then navigate into the newly created directory. It's a standard first step for setting up any project from a remote source. ```bash git clone https://github.com/floriangrousset/opnsense-mcp-server cd opnsense-mcp-server ``` -------------------------------- ### Audit Python Packages for Vulnerabilities Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/SECURITY.md This command audits installed Python packages to detect known vulnerabilities. It requires the 'pip-audit' tool to be installed separately. This helps in proactively identifying and mitigating security risks. ```bash pip-audit # If installed ``` -------------------------------- ### Development Testing and Code Quality for OPNsense MCP Server Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/README.md Commands for setting up development dependencies, running tests with detailed output, filtering tests, and checking code quality using tools like black, ruff, and mypy. Essential for contributing to the project. ```bash # Install development dependencies uv pip install -e ".[dev]" # Run tests with detailed output pytest -vv --tb=short # Run only fast tests (exclude integration) pytest -m "not integration" # Run failed tests from last run pytest --lf # Check code quality black src/ tests/ # Format code ruff check src/ tests/ # Lint code mypy src/ # Type checking ``` -------------------------------- ### Get OPNsense DNS Resolver Settings Source: https://context7.com/floriangrousset/opnsense-mcp-server/llms.txt Retrieves the current configuration settings for the OPNsense Unbound DNS resolver. This API call returns a JSON object containing details such as whether DNSSEC is enabled, the listening port, forwarder status, and the network interfaces the resolver is listening on. No specific input data is required for this GET request. ```python settings = await client.request( "GET", "/api/unbound/settings/get" ) ``` -------------------------------- ### Securely Setting Up OPNsense Credentials Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/SECURITY.md Demonstrates the secure method for setting up OPNsense credentials using the opnsense-mcp CLI tool. It contrasts with the old, insecure method of passing credentials directly. This method ensures interactive and secure password input and automatic credential loading in client applications. ```bash # One-time setup (local machine) opnsense-mcp setup # Enter your credentials interactively (secure password input) # Then in Claude Desktop User: "Configure OPNsense connection" # Credentials loaded from local storage automatically ``` -------------------------------- ### Create OPNsense User, Group, and Assign Privileges Source: https://context7.com/floriangrousset/opnsense-mcp-server/llms.txt This snippet demonstrates how to create a new user, establish a read-only group, add the user to the group, and assign specific privileges to the group. It also shows how to retrieve user privileges and reset a user's password. The code assumes an initialized 'client' object for API interaction. ```python user_response = await client.request( "POST", "/api/access/user/addItem", data={ "user": { "disabled": "0", "username": "monitoring", "password": "SecureP@ssw0rd!", "descr": "Monitoring System Account", "email": "monitoring@example.com", "full_name": "Monitoring System", "scope": "user", "uid": "", # Auto-assign "authorizedkeys": "" # SSH keys if needed } } ) user_uuid = user_response["uuid"] group_response = await client.request( "POST", "/api/access/group/addItem", data={ "group": { "name": "readonly", "description": "Read-Only Users", "scope": "local", "gid": "" # Auto-assign } } ) group_uuid = group_response["uuid"] await client.request( "POST", f"/api/access/group/addMember/{group_uuid}", data={"member": user_uuid} ) privileges = [ "page-all-readonly", # Read-only access to all pages "page-dashboard-all", # Dashboard access "page-diagnostics-log-firewall" # Firewall log access ] for privilege in privileges: await client.request( "POST", f"/api/access/group/addPrivilege/{group_uuid}", data={"privilege": privilege} ) user_privs = await client.request( "GET", f"/api/access/user/getPrivileges/{user_uuid}" ) await client.request( "POST", f"/api/access/user/setItem/{user_uuid}", data={ "user": { "password": "NewSecureP@ssw0rd!", "password_confirm": "NewSecureP@ssw0rd!" } } ) ``` -------------------------------- ### Run Quality Checks - Bash Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/CONTRIBUTING.md Commands to format code using Black, lint code using Ruff, perform type checking with mypy, and run tests with pytest. ```bash # Format code black src/ tests/ # Lint code ruff check src/ tests/ # Type check mypy src/ # Run tests pytest tests/ ``` -------------------------------- ### Check for Outdated Python Dependencies Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/SECURITY.md This command checks for outdated Python packages in your environment. It's a crucial step for identifying potential security vulnerabilities introduced by unpatched libraries. Ensure you have Python and pip installed. ```bash # Check for security updates quarterly pip list --outdated ``` -------------------------------- ### Error Handling Best Practices Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/CONTRIBUTING.md Outlines key principles for robust error handling within the project. This includes using custom exceptions, verifying client initialization, providing clear messages, and logging errors effectively. ```markdown - Use custom exceptions from `core/exceptions.py` - All tools should check for initialized client via `get_opnsense_client()` - Provide clear, actionable error messages to users - Log errors with appropriate context for debugging ``` -------------------------------- ### Add New Tool Definition - Python Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/CONTRIBUTING.md Python code demonstrating how to define a new tool within a domain module using the @mcp.tool decorator, including imports, arguments, return types, and docstrings. ```python from ..core.client import get_opnsense_client from ..core.exceptions import OPNsenseClientError from ..shared.constants import API_ENDPOINTS from ..main import mcp @mcp.tool(name="your_tool_name", description="Clear description") async def your_tool_name(param: str) -> dict: """ Comprehensive docstring explaining what the tool does. Args: param: Description of parameter Returns: dict: Description of return value Raises: OPNsenseClientError: When connection fails """ client = get_opnsense_client() result = await client.request("GET", API_ENDPOINTS["your_endpoint"]) return result ``` -------------------------------- ### Run Specific Pytest Test Categories Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/tests/README.md Allows running tests categorized by module or type. Examples include running only core module tests, domain tests, integration tests (marked with 'integration'), or unit tests (marked with 'unit'). ```bash # Core module tests only pytest tests/test_core/ # Domain tests only pytest tests/test_domains/ # Integration tests only pytest tests/test_integration.py -m integration # Unit tests only (fast) pytest -m unit ``` -------------------------------- ### Retrieve OPNsense API Access Logs Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/SECURITY.md This command retrieves core system access logs from the OPNsense firewall via its API. It's used to monitor who is accessing the system and when, which is vital for detecting unauthorized activity. Requires 'opnsense-mcp' to be installed and configured. ```bash # Check OPNsense API access logs opnsense-mcp exec_api_call GET "/api/diagnostics/log/core/system" ``` -------------------------------- ### Run Tests - Bash Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/CONTRIBUTING.md Bash commands to execute all tests, run tests with coverage reporting, and run a specific test module. ```bash # Run all tests pytest # Run with coverage pytest --cov=src/opnsense_mcp --cov-report=html # Run specific test module pytest tests/test_core/test_client.py ``` -------------------------------- ### Resetting OPNsense Credentials After Compromise Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/SECURITY.md Provides instructions for updating local OPNsense MCP server configuration with new credentials after existing ones have been compromised. This involves revoking old keys, generating new ones in OPNsense, and re-running the setup command. ```bash opnsense-mcp setup --profile default # Enter new credentials ``` -------------------------------- ### Manage OPNsense Firewall Aliases with Python Source: https://context7.com/floriangrousset/opnsense-mcp-server/llms.txt This snippet focuses on managing firewall aliases in OPNsense, which are used for grouping IP addresses and networks. The provided example shows how to add multiple IP addresses to an existing alias named 'BlockedIPs' using the `opnsense_mcp` library. ```python # Tool: add_to_alias # File: src/opnsense_mcp/domains/firewall.py:371 # Natural language: "Add 192.168.100.50 and 10.0.0.200 to the BlockedIPs alias" ``` -------------------------------- ### Run All Pytest Tests Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/tests/README.md Executes all tests defined in the project using the pytest framework. This is the standard command to run the entire test suite. ```bash pytest ``` -------------------------------- ### Bash Command for Running Tests with Coverage Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/tests/README.md This bash command clears the previous coverage data and runs tests with coverage enabled for the OPNsense MCP Server project. It uses `pytest` with the `--cov` flag to generate a coverage report for the `src/opnsense_mcp` module. Requires `pytest` and `coverage.py` to be installed. ```bash # Clear coverage cache rm -rf .coverage htmlcov/ # Run tests with coverage pytest --cov=src/opnsense_mcp ``` -------------------------------- ### Custom API Calls and Utilities Source: https://context7.com/floriangrousset/opnsense-mcp-server/llms.txt Execute arbitrary API calls for advanced customization and utility functions like backing up the configuration. ```APIDOC ## GET /api/diagnostics/interface/getArp ### Description Retrieves the ARP table from the OPNSense device. ### Method GET ### Endpoint /api/diagnostics/interface/getArp ### Parameters This endpoint does not require any parameters. ### Response #### Success Response (200) - **ARP table** (array) - An array of objects, where each object represents an ARP entry. - **ip** (string) - The IP address of the ARP entry. - **mac** (string) - The MAC address associated with the IP address. - **interface** (string) - The network interface on which the ARP entry was observed. - **hostname** (string) - The hostname resolved for the IP address, if available. #### Response Example ```json [ { "ip": "192.168.1.10", "mac": "aa:bb:cc:dd:ee:ff", "interface": "em0", "hostname": "laptop" } ] ``` --- ## POST /api/custom/endpoint/action ### Description Executes a custom API call on a specified endpoint with provided data. ### Method POST ### Endpoint /api/custom/endpoint/action ### Parameters #### Request Body - **param1** (string) - Example parameter for the custom endpoint. - **param2** (string) - Another example parameter for the custom endpoint. ### Request Example ```json { "param1": "value1", "param2": "value2" } ``` ### Response #### Success Response (200) - The response structure depends entirely on the custom API endpoint being called. --- ## GET /api/core/backup/download ### Description Downloads the current OPNSense configuration backup file. ### Method GET ### Endpoint /api/core/backup/download ### Parameters This endpoint does not require any parameters. ### Response #### Success Response (200) - **backup** (file) - The configuration backup file in XML format. ### Response Example ```xml ``` ``` -------------------------------- ### Export Certificate Authority Certificate from OPNsense Source: https://context7.com/floriangrousset/opnsense-mcp-server/llms.txt Exports the public certificate of a specified Certificate Authority (CA) from OPNsense. This allows the CA certificate to be shared or imported into other systems or clients that need to trust certificates issued by this CA. The export is done via a GET request, specifying the CA's UUID. ```python # Export CA certificate: ca_export = await client.request( "GET", f"/api/trust/ca/export/{ca_uuid}" ) ``` -------------------------------- ### Code Quality Tools - black, ruff, mypy Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/CLAUDE.md A set of commands for maintaining code quality. 'black' is used for code formatting, 'ruff' for linting to enforce style and detect errors, and 'mypy' for static type checking to catch type-related bugs. ```bash # Format code with black black src/ tests/ # Lint with ruff ruff check src/ tests/ # Type checking with mypy mypy src/ ``` -------------------------------- ### Validate Port Specification - Python Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/SECURITY.md The validate_port_specification function in Python ensures that port numbers and ranges used in firewall rules are valid. It checks if ports are within the 1-65535 range, if port range start is less than end, and supports single ports, ranges, and lists. This prevents firewall misconfigurations due to invalid port inputs. ```python validate_port_specification("80", "firewall_add_rule") # ✅ Valid validate_port_specification("80-443", "firewall_add_rule") # ✅ Valid validate_port_specification("80,443,8080", "firewall_add_rule") # ✅ Valid validate_port_specification("70000", "firewall_add_rule") # ❌ Invalid - out of range validate_port_specification("443-80", "firewall_add_rule") # ❌ Invalid - end < start validate_port_specification("abc", "firewall_add_rule") # ❌ Invalid - non-numeric ``` -------------------------------- ### Configure OPNsense Connection Securely with Python Source: https://context7.com/floriangrousset/opnsense-mcp-server/llms.txt This snippet demonstrates how to securely configure a connection to an OPNsense firewall using locally stored credentials. It utilizes the `ConfigLoader` and `ServerState` from the `opnsense_mcp` library. The credentials are never exposed to the LLM, ensuring enhanced security. Prerequisites include setting up credentials via the CLI. ```python from opnsense_mcp.core.config_loader import ConfigLoader from opnsense_mcp.core.state import ServerState # Load credentials securely (never logged) config = ConfigLoader.load(profile="production") # Returns: OPNsenseConfig(url='https://192.168.1.1', # api_key='[REDACTED]', # api_secret='[REDACTED]', # verify_ssl=True) # Initialize server state await server_state.initialize(config) # Connection established with retry logic and connection pooling ``` -------------------------------- ### Setup OPNsense VoIP Priority Traffic Shaping Source: https://context7.com/floriangrousset/opnsense-mcp-server/llms.txt This Python snippet configures hierarchical Quality of Service (QoS) for OPNsense, prioritizing VoIP traffic. It creates a main pipe, a high-priority queue for VoIP, a normal queue for other traffic, and a rule to classify VoIP traffic (SIP/RTP ports). Finally, it reconfigures the traffic shaper and retrieves its status. This requires an active OPNsense API client connection. ```python # Tool: traffic_shaper_prioritize_voip # File: src/opnsense_mcp/domains/traffic_shaping.py:635 # Natural language: "Setup VoIP priority with 5 Mbps guaranteed bandwidth" client = await get_opnsense_client() # Create pipe (hard bandwidth limit): pipe_response = await client.request( "POST", "/api/trafficshaper/settings/addPipe", data={ "pipe": { "enabled": "1", "description": "WAN Uplink 100Mbps", "bandwidth": "100", "bandwidthMetric": "Mbit", "queue": "100", "mask": "none", "scheduler": "fq_codel" # Fair Queue CoDel recommended } } ) pipe_uuid = pipe_response["uuid"] # Create high-priority queue for VoIP: voip_queue = await client.request( "POST", "/api/trafficshaper/settings/addQueue", data={ "queue": { "enabled": "1", "description": "VoIP Priority Queue", "pipe": pipe_uuid, "weight": "90", # High priority (0-100) "mask": "none" } } ) voip_queue_uuid = voip_queue["uuid"] # Create normal queue for other traffic: normal_queue = await client.request( "POST", "/api/trafficshaper/settings/addQueue", data={ "queue": { "enabled": "1", "description": "Normal Traffic Queue", "pipe": pipe_uuid, "weight": "50", "mask": "none" } } ) normal_queue_uuid = normal_queue["uuid"] # Create rule to classify VoIP traffic (SIP/RTP ports): voip_rule = await client.request( "POST", "/api/trafficshaper/settings/addRule", data={ "rule": { "enabled": "1", "description": "VoIP Traffic Classification", "interface": "wan", "direction": "out", "protocol": "udp", "source_port": "", "destination_port": "5060-5061,10000-20000", # SIP + RTP range "target": voip_queue_uuid, "sequence": "1" # Process first } } ) # Apply traffic shaper configuration: await client.request("POST", "/api/trafficshaper/settings/reconfigure") # Get traffic shaper status: status = await client.request( "GET", "/api/trafficshaper/service/show" ) ``` -------------------------------- ### Test File Structure Convention Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/CONTRIBUTING.md Illustrates the expected directory structure for test files, which should mirror the source code's structure. This ensures organization and discoverability of tests. ```tree tests/ ├── test_core/ │ ├── test_client.py │ ├── test_connection.py │ └── test_exceptions.py ├── test_domains/ │ ├── test_configuration.py │ ├── test_system.py │ └── ... (one per domain) └── test_shared/ └── test_constants.py ``` -------------------------------- ### Run OPNsense MCP Server Tests Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/README.md Commands to execute the project's test suite using pytest. Supports running all tests, verbose output, coverage reports, and specific test files. Ensures code quality before contributing. ```bash # Run all tests pytest # Run with verbose output pytest -v # Run with coverage report pytest --cov=src/opnsense_mcp --cov-report=html # Run specific test file pytest tests/test_core/test_client_basic.py ``` -------------------------------- ### Basic Diagnostic Commands for OPNsense MCP Server Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/README.md A collection of diagnostic commands intended for troubleshooting the OPNsense MCP Server and its integration with the firewall. These commands cover connection testing, permission verification, API call logging, and service status checks. ```text Test my connection to OPNsense and show me any errors ``` ```text Show me the current API user permissions and privileges ``` ```text Display the last 10 API calls and their results ``` ```text Check if all required services are running on the firewall ``` -------------------------------- ### Configure Network Interfaces with OPNsense API Source: https://context7.com/floriangrousset/opnsense-mcp-server/llms.txt This snippet demonstrates how to configure various network elements using the OPNsense API. It covers creating VLANs, bridges, Link Aggregation (LAGG), and Virtual IP addresses (CARP) for high availability. It also shows how to retrieve the status of all network interfaces. Dependencies include an OPNsense client library. ```python client = await get_opnsense_client() # Create VLAN: vlan_response = await client.request( "POST", "/api/interfaces/vlan_settings/addItem", data={ "vlan": { "if": "em0", # Parent interface "tag": "100", # VLAN ID (1-4094) "descr": "Guest Network", "pcp": "0", # Priority Code Point "vlanif": "" # Auto-generate (vlan0100) } } ) vlan_uuid = vlan_response["uuid"] # Reconfigure to create interface: await client.request("POST", "/api/interfaces/vlan_settings/reconfigure") # Create bridge between interfaces: bridge_response = await client.request( "POST", "/api/interfaces/bridge_settings/addItem", data={ "bridge": { "members": ["em1", "em2"], # Bridge LAN ports "description": "LAN Bridge", "stp": "1", # Enable Spanning Tree Protocol "maxage": "20", "fwdelay": "15", "bridgeif": "" # Auto-generate (bridge0) } } ) # Create LAGG (Link Aggregation) for redundancy: lagg_response = await client.request( "POST", "/api/interfaces/lagg_settings/addItem", data={ "lagg": { "members": ["em3", "em4"], "description": "WAN Link Aggregation", "proto": "lacp", # LACP for dynamic bonding "laggif": "" # Auto-generate (lagg0) } } ) await client.request("POST", "/api/interfaces/lagg_settings/reconfigure") # Create virtual IP (CARP for HA): vip_response = await client.request( "POST", "/api/interfaces/vip_settings/addItem", data={ "vip": { "mode": "carp", "interface": "lan", "vhid": "1", # Virtual Host ID (1-255) "advskew": "0", # Advertisement skew (0=master) "password": "CarpP@ss123", "address": "192.168.1.200", "subnet": "24", "descr": "LAN CARP VIP" } } ) await client.request("POST", "/api/interfaces/vip_settings/reconfigure") # Get all interfaces status: interfaces = await client.request("GET", "/api/interfaces/overview/export") ``` -------------------------------- ### API Interaction Patterns Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/CONTRIBUTING.md Details standard patterns for interacting with the OPNsense API. This covers defining endpoints, using the client's request method, handling configuration changes, and implementing retry logic. ```markdown - Define API endpoints in `shared/constants.py` - Use consistent request/response handling via `OPNsenseClient.request()` - POST requests for configuration changes should be followed by "apply" calls where needed - Leverage retry logic with exponential backoff from `core/retry.py` ``` -------------------------------- ### Push to Fork - Bash Source: https://github.com/floriangrousset/opnsense-mcp-server/blob/main/CONTRIBUTING.md Command to push local commits to a remote fork repository. ```bash git push origin feat/your-feature-name ```