Skip to main content
Glama
chadkunsman

NetBox MCP Server

by chadkunsman
README.md
# NetBox MCP Server

A comprehensive read-only FastMCP server that exposes NetBox API functionality to AI systems via the Model Context Protocol (MCP).

## Overview

This project implements a read-only MCP server that provides comprehensive tools to interact with NetBox infrastructure data. It enables natural language queries about network devices, sites, circuits, VLANs, IP prefixes, and individual IP addresses, making it easier for AI assistants to retrieve and present network infrastructure information without allowing any modifications to the NetBox data.

## Features

### Device Management
- Query NetBox devices using structured filters
- Search for devices by specific name
- Use natural language to ask about devices
- Support for filtering by site, role, status, manufacturer, and more

### Site Operations
- List all available sites with status and region information
- Get comprehensive site details including device and rack counts
- Site-based filtering across all resource types

### Circuit Management
- Query circuits by provider, type, status, and termination sites
- Search circuits using natural language
- Track circuit terminations (A-side and Z-side)
- Filter by circuit ID patterns

### IP Prefix Management
- Query IP prefixes by site, VRF, tenant, status, and role
- Support for both IPv4 and IPv6 address families
- VLAN association and filtering
- Prefix pool management
- CIDR notation pattern matching

### VLAN Management
- Query VLANs by name, VID (VLAN ID), site, group, tenant, role, and status
- True substring matching for VLAN names and descriptions
- Cross-field search across VLAN properties
- Support for VLAN group and tenant organization

### IP Address Management
- Query individual IP addresses by address, device, interface, VRF, and status
- Track IP assignments to devices and interfaces
- Filter by IP role (loopback, VIP, secondary, anycast)
- DNS hostname search and parent-prefix filtering
- IPv4 and IPv6 support

> **Prefixes vs. IP addresses:** use the **prefix** tools for subnets/address
> pools/VLAN-to-subnet mapping, and the **IP address** tools for individual IPs
> assigned to devices/interfaces, DNS lookups, and IP-role filtering.

### Natural Language Processing
- Intelligent parsing of natural language queries into structured API calls
- Fuzzy matching for sites, roles, providers, and circuit types
- Cross-field search capabilities
- User-friendly error messages and suggestions

## Example Queries

### Device Queries
- "Show me all devices at site SF1"
- "List all active firewalls"
- "Tell me about device sf1.as1"
- "Find all ION devices"
- "Show switches at NYC location"

### Site Queries
- "List all available sites"
- "Tell me about site SF1"
- "Show site information for Denver"

### Circuit Queries
- "Show me circuits from Zayo"
- "List Internet circuits at SF1"
- "Find circuit CID-12345"
- "Show active MPLS circuits"

### IP Prefix Queries
- "Show IPv4 prefixes at SF1"
- "List all /24 subnets"
- "Find prefixes in VLAN 100"
- "Show prefix pools"

### VLAN Queries
- "Show me VLAN 100"
- "List all VLANs at site SF1"
- "Find VLANs with '90' in the name"
- "Show active VLANs for tenant ABC"
- "Get all production VLANs"

### IP Address Queries
- "Show me IP addresses on device switch01"
- "Find all loopback addresses"
- "What IPs are assigned to firewall01?"
- "Show IPs with hostname containing ntp"
- "List IPv4 addresses in VRF production"

## Deployment

### Runlayer Deployment (Recommended)

This project is crafted to support Runlayer deployment using streamable HTTP transport. Deploy to Runlayer's managed infrastructure with automatic scaling, monitoring, and HTTPS endpoints.

**Prerequisites:**
- Docker (or Colima) running locally
- Runlayer CLI (`uvx runlayer`)
- Admin API key from your Runlayer instance

**Deploy:**

```bash
# Initialize deployment (creates runlayer.yaml)
uvx runlayer deploy init --secret <api-key> --host <runlayer-url>

# Configure runlayer.yaml with your environment variables, then deploy
uvx runlayer deploy --config runlayer.yaml --secret <api-key> --host <runlayer-url>
```

**For Colima users**, prefix the deploy command with:
```bash
DOCKER_HOST=unix://${HOME}/.colima/docker.sock uvx runlayer deploy ...
```

After deployment, register the service as an MCP server in the Runlayer dashboard to make it available in the MCP catalog.

**Configuration:** The `runlayer.yaml` is pre-configured for:
- ARM64 architecture (cost-optimized)
- Port 8000 with `/mcp` endpoint path
- Streamable HTTP transport

**Per-user authentication:** In a hosted Runlayer deployment, each user
authenticates with their own NetBox API token. `NETBOX_TOKEN` is therefore **not**
set in `runlayer.yaml` — it is a Runlayer **Placeholder**, injected per request as
the `x-rl-env-NETBOX_TOKEN` header and resolved by the server for that request.
Only `NETBOX_URL` and `NETBOX_SSL_VERIFY` are deployment-wide env vars.

To configure it, in the connector's **Headers** field (Runlayer dashboard) map:

```json
{ "x-rl-env-NETBOX_TOKEN": "{NETBOX_TOKEN}" }
```

and mark the `NETBOX_TOKEN` placeholder as required + secret. (When running locally
over STDIO, the token comes from the `NETBOX_TOKEN` environment variable instead.)

## Installation

### Running Locally (STDIO)

For local use (e.g. with an MCP client like Claude Desktop), run the server over
STDIO transport with `uv`. The server uses in-package imports, so it must be run
from the `src` directory via `--directory`:

```bash
MCP_TRANSPORT=stdio \
NETBOX_URL=https://your-netbox.example.com \
NETBOX_TOKEN=your_api_token \
NETBOX_SSL_VERIFY=true \
uv run --directory src python server.py
```

> There is no console-script entry point; the server is launched directly via
> `python server.py` (locally over STDIO) or as an HTTP service (hosted — see
> [Deployment](#deployment)).

### Development Setup

For development and testing:

1. Clone the repository:
   ```bash
   git clone https://github.com/chadkunsman/netbox_mcp.git
   cd netbox_mcp
   ```

2. Install in development mode:
   ```bash
   uv venv
   source .venv/bin/activate  # On Windows: .venv\Scripts\activate
   uv pip install -e .
   ```

3. Set environment variables:
   ```bash
   export NETBOX_URL=https://your-netbox.example.com
   export NETBOX_TOKEN=your_api_token
   export NETBOX_SSL_VERIFY=true
   ```

### Claude Desktop Configuration

Add this to your Claude Desktop MCP configuration (`~/Library/Application
Support/Claude/claude_desktop_config.json` on macOS), replacing the path with your
local clone:

```json
{
  "mcpServers": {
    "netbox": {
      "command": "uv",
      "args": [
        "run", "--directory",
        "/absolute/path/to/netbox_mcp/src",
        "python", "server.py"
      ],
      "env": {
        "MCP_TRANSPORT": "stdio",
        "NETBOX_URL": "https://your-netbox.example.com",
        "NETBOX_TOKEN": "your_api_token",
        "NETBOX_SSL_VERIFY": "true"
      }
    }
  }
}
```

> **Notes:** `MCP_TRANSPORT=stdio` is required (the server defaults to HTTP).
> Claude Desktop launches with a minimal `PATH`, so if `uv` isn't found, use its
> absolute path for `command` (e.g. `/opt/homebrew/bin/uv`). Restart Claude Desktop
> after editing the config.

### Automated Testing

Run the pytest test suite (integration tests query a real NetBox instance, so
`NETBOX_URL`/`NETBOX_TOKEN` must be set, e.g. via a local `.env`):

```bash
# Run the full suite
uv run pytest tests/ -v

# Run only the integration tests
uv run pytest tests/test_mcp_tools.py -v

# Run with coverage
uv run pytest tests/ --cov=src
```

### Manual Testing with MCPTools

For interactive exploration and debugging:

```bash
# List all available tools
mcp tools uv run --directory src python server.py

# Call a specific tool with parameters
mcp call get_device --params '{"name":"my-device-01"}' uv run --directory src python server.py

# Start interactive testing shell
mcp shell uv run --directory src python server.py

# View server logs during testing
mcp tools --server-logs uv run --directory src python server.py
```

## Configuration

The server reads the following environment variables:

**NetBox connection:**
- `NETBOX_URL`: URL of your NetBox instance (e.g., https://netbox.example.com) — required
- `NETBOX_TOKEN`: API token with read permissions. Required for local/STDIO use; in a hosted Runlayer deployment it is supplied per user via the `x-rl-env-NETBOX_TOKEN` header instead (see [Deployment](#deployment))
- `NETBOX_SSL_VERIFY`: Whether to verify SSL certificates (true/false, default true)

**Transport** (used when launching the server):
- `MCP_TRANSPORT`: `stdio` for local use, or `http` (streamable HTTP) for hosted/Runlayer. Defaults to `http`
- `MCP_HOST`: Bind host for HTTP transport (default `0.0.0.0`)
- `MCP_PORT`: Bind port for HTTP transport (default `8000`)

## Project Structure

```
netbox_mcp/
├── src/
│   ├── server.py          # Main MCP server implementation
│   ├── tools/             # Tool definitions
│   │   ├── devices.py     # Device-related tools
│   │   ├── sites.py       # Site-related tools
│   │   ├── circuits.py    # Circuit-related tools
│   │   ├── prefixes.py    # IP prefix-related tools
│   │   ├── vlans.py       # VLAN-related tools
│   │   └── ip_addresses.py # IP address-related tools
│   ├── models/            # Pydantic models
│   ├── utils/             # Shared utility functions
│   └── config/            # Configuration
│       └── netbox.py      # NetBox client configuration
├── tests/                 # Pytest test suite
│   ├── test_mcp_tools.py  # Integration tests
│   └── conftest.py        # Test fixtures
└── docs/                  # NetBox-specific documentation
```

## License

[MIT License](LICENSE)

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.