A Model Context Protocol (MCP) server that exposes the UniFi Network Controller API, enabling AI agents and applications to interact with UniFi network infrastructure in a standardized way.
Current Stable Release: v0.1.4
Note: v0.2.0 was published prematurely and should not be used. Please use v0.1.4, which contains the same code with the correct version number. The true v0.2.0 milestone release is planned for Q4 2025 and will include Zone-Based Firewall, Traffic Flow monitoring, and other major features. See DEVELOPMENT_PLAN.md for details.
The UniFi MCP Server supports three distinct API modes with different capabilities:
Full feature support - Direct access to your UniFi gateway.
- ✅ All Features Available: Device management, client control, network configuration, firewall rules, WiFi management
- ✅ Real-time Data: Access to live device/client statistics and detailed information
- ✅ Configuration Changes: Create, update, delete networks, VLANs, firewall rules, SSIDs
- 📍 Requirement: Local network access to your UniFi gateway (e.g., 192.168.1.1)
- ⚙️ Configuration:
UNIFI_API_TYPE=local+UNIFI_LOCAL_HOST=<gateway-ip>
Limited to aggregate statistics - UniFi cloud API in testing phase.
- ✅ Site Information: List sites with aggregate statistics (device counts, client counts, bandwidth)
⚠️ No Individual Device/Client Access: Cannot query specific devices or clients⚠️ No Configuration Changes: Cannot modify networks, firewall rules, or settings- ⚙️ Configuration:
UNIFI_API_TYPE=cloud-ea - 📊 Rate Limit: 100 requests/minute
Limited to aggregate statistics - UniFi stable v1 cloud API.
- ✅ Site Information: List sites with aggregate statistics (device counts, client counts, bandwidth)
⚠️ No Individual Device/Client Access: Cannot query specific devices or clients⚠️ No Configuration Changes: Cannot modify networks, firewall rules, or settings- ⚙️ Configuration:
UNIFI_API_TYPE=cloud-v1 - 📊 Rate Limit: 10,000 requests/minute
💡 Recommendation: Use Local Gateway API (UNIFI_API_TYPE=local) for full functionality. Cloud APIs are suitable only for high-level monitoring dashboards.
- Device Management: List, monitor, restart, locate, and upgrade UniFi devices (APs, switches, gateways)
- Network Configuration: Create, update, and delete networks, VLANs, and subnets with DHCP configuration
- Client Management: Query, block, unblock, and reconnect clients
- Firewall Rules: Create, update, and delete firewall rules with traffic filtering
- Zone-Based Firewall (ZBF): Modern zone-based security with zone management (create, read, update, delete zones and network assignments). Note: Zone policy matrix and application blocking endpoints do not exist in UniFi API v10.0.156 - requires UniFi Console UI configuration. See ZBF_STATUS.md for details.
- WiFi/SSID Management: Create and manage wireless networks with WPA2/WPA3, guest networks, and VLAN isolation
- Port Forwarding: Configure port forwarding rules for external access
- DPI Statistics: Deep Packet Inspection analytics for bandwidth usage by application and category
- Multi-Site Support: Work with multiple UniFi sites seamlessly
- Real-time Monitoring: Access device, network, client, and WiFi statistics
- Redis Caching: Optional Redis-based caching for improved performance (configurable TTL per resource type)
- Webhook Support: Real-time event processing with HMAC signature verification
- Automatic Cache Invalidation: Smart cache invalidation when configuration changes
- Event Handlers: Built-in handlers for device, client, and alert events
- Performance Tracking: Optional agnost.ai integration for monitoring MCP tool performance and usage analytics
- Confirmation Required: All mutating operations require explicit
confirm=Trueflag - Dry-Run Mode: Preview changes before applying them with
dry_run=True - Audit Logging: All operations logged to
audit.logfor compliance - Input Validation: Comprehensive parameter validation with detailed error messages
- Password Masking: Sensitive data automatically masked in logs
- Type-Safe: Full type hints and Pydantic validation throughout
- Security Scanners: CodeQL, Trivy, Bandit, Safety, and detect-secrets integration
- Async Support: Built with async/await for high performance and concurrency
- MCP Protocol: Standard Model Context Protocol for AI agent integration
- Comprehensive Testing: 213 unit tests with 37% coverage (target: 80%)
- CI/CD Pipelines: Automated testing, security scanning, and Docker builds
- Multi-Architecture: Docker images for amd64, arm64, arm/v7 (32-bit ARM), and arm64/v8
- Python 3.10 or higher
- A UniFi account at unifi.ui.com
- UniFi API key (obtain from Settings → Control Plane → Integrations)
- Access to UniFi Cloud API or local gateway
# Install uv if you haven't already
curl -LsSf https://astral.sh/uv/install.sh | sh
# Clone the repository
git clone https://github.com/enuno/unifi-mcp-server.git
cd unifi-mcp-server
# Create virtual environment and install dependencies
uv venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
uv pip install -e ".[dev]"# Clone the repository
git clone https://github.com/enuno/unifi-mcp-server.git
cd unifi-mcp-server
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install dependencies
pip install -e ".[dev]"The recommended way to run the UniFi MCP Server with full monitoring capabilities:
# 1. Copy and configure environment variables
cp .env.docker.example .env
# Edit .env with your UNIFI_API_KEY and AGNOST_ORG_ID
# 2. Start all services (MCP Server + Redis + MCP Toolbox)
docker-compose up -d
# 3. Check service status
docker-compose ps
# 4. View logs
docker-compose logs -f unifi-mcp
# 5. Access MCP Toolbox dashboard
open http://localhost:8080
# 6. Stop all services
docker-compose downIncluded Services:
- UniFi MCP Server: Main MCP server with 77 tools (69 functional, 8 deprecated)
- MCP Toolbox: Web-based analytics dashboard (port 8080)
- Redis: High-performance caching layer
See MCP_TOOLBOX.md for detailed Toolbox documentation.
For standalone Docker usage (not with MCP clients):
# Pull the image
docker pull ghcr.io/enuno/unifi-mcp-server:latest
# Run the container in background (Cloud API)
# Note: -i flag keeps stdin open for STDIO transport
docker run -i -d \
--name unifi-mcp \
-e UNIFI_API_KEY=your-api-key \
-e UNIFI_API_TYPE=cloud \
ghcr.io/enuno/unifi-mcp-server:latest
# OR run with local gateway proxy
docker run -i -d \
--name unifi-mcp \
-e UNIFI_API_KEY=your-api-key \
-e UNIFI_API_TYPE=local \
-e UNIFI_HOST=192.168.1.1 \
ghcr.io/enuno/unifi-mcp-server:latest
# Check container status
docker ps --filter name=unifi-mcp
# View logs
docker logs unifi-mcp
# Stop and remove
docker rm -f unifi-mcpNote: For MCP client integration (Claude Desktop, etc.), see the Usage section below for the correct configuration without -d flag.
- Log in to UniFi Site Manager
- Navigate to Settings → Control Plane → Integrations
- Click Create API Key
- Save the key immediately - it's only shown once!
- Store it securely in your
.envfile
Create a .env file in the project root:
# Required: Your UniFi API Key
UNIFI_API_KEY=your-api-key-here
# API Mode Selection (choose one):
# - 'local': Full access via local gateway (RECOMMENDED)
# - 'cloud-ea': Early Access cloud API (limited to statistics)
# - 'cloud-v1': Stable v1 cloud API (limited to statistics)
UNIFI_API_TYPE=local
# Local Gateway Configuration (for UNIFI_API_TYPE=local)
UNIFI_LOCAL_HOST=192.168.1.1
UNIFI_LOCAL_PORT=443
UNIFI_LOCAL_VERIFY_SSL=false
# Cloud API Configuration (for cloud-ea or cloud-v1)
# UNIFI_CLOUD_API_URL=https://api.ui.com
# Optional settings
UNIFI_DEFAULT_SITE=default
# Redis caching (optional - improves performance)
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_DB=0
# REDIS_PASSWORD=your-password # If Redis requires authentication
# Webhook support (optional - for real-time events)
WEBHOOK_SECRET=your-webhook-secret-here
# Performance tracking with agnost.ai (optional - for analytics)
# Get your Organization ID from https://app.agnost.ai
# AGNOST_ENABLED=true
# AGNOST_ORG_ID=your-organization-id-here
# AGNOST_ENDPOINT=https://api.agnost.ai
# AGNOST_DISABLE_INPUT=false # Set to true to disable input tracking
# AGNOST_DISABLE_OUTPUT=false # Set to true to disable output trackingSee .env.example for all available options.
# Development mode with MCP Inspector
uv run mcp dev src/main.py
# Production mode
uv run python src/main.pyThe MCP Inspector will be available at http://localhost:5173 for interactive testing.
Add to your Claude Desktop configuration (~/Library/Application Support/Claude/claude_desktop_config.json on macOS):
{
"mcpServers": {
"unifi": {
"command": "uv",
"args": [
"--directory",
"/path/to/unifi-mcp-server",
"run",
"mcp",
"run",
"src/main.py"
],
"env": {
"UNIFI_API_KEY": "your-api-key-here",
"UNIFI_API_TYPE": "cloud"
}
}
}
}{
"mcpServers": {
"unifi": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-e",
"UNIFI_API_KEY=your-api-key-here",
"-e",
"UNIFI_API_TYPE=cloud",
"ghcr.io/enuno/unifi-mcp-server:latest"
]
}
}
}Important: Do NOT use -d (detached mode) in MCP client configurations. The MCP client needs to maintain a persistent stdin/stdout connection to the container.
from mcp import MCP
import asyncio
async def main():
mcp = MCP("unifi-mcp-server")
# List all devices
devices = await mcp.call_tool("list_devices", {
"site_id": "default"
})
for device in devices:
print(f"{device['name']}: {device['status']}")
# Get network information via resource
networks = await mcp.read_resource("sites://default/networks")
print(f"Networks: {len(networks)}")
# Create a guest WiFi network with VLAN isolation
wifi = await mcp.call_tool("create_wlan", {
"site_id": "default",
"name": "Guest WiFi",
"security": "wpapsk",
"password": "GuestPass123!",
"is_guest": True,
"vlan_id": 100,
"confirm": True # Required for safety
})
print(f"Created WiFi: {wifi['name']}")
# Get DPI statistics for top bandwidth users
top_apps = await mcp.call_tool("list_top_applications", {
"site_id": "default",
"limit": 5,
"time_range": "24h"
})
for app in top_apps:
gb = app['total_bytes'] / 1024**3
print(f"{app['application']}: {gb:.2f} GB")
# Create Zone-Based Firewall zones (UniFi Network 9.0+)
lan_zone = await mcp.call_tool("create_firewall_zone", {
"site_id": "default",
"name": "LAN",
"description": "Trusted local network",
"confirm": True
})
iot_zone = await mcp.call_tool("create_firewall_zone", {
"site_id": "default",
"name": "IoT",
"description": "Internet of Things devices",
"confirm": True
})
# Set zone-to-zone policy (LAN can access IoT, but IoT cannot access LAN)
await mcp.call_tool("update_zbf_policy", {
"site_id": "default",
"source_zone_id": lan_zone["_id"],
"destination_zone_id": iot_zone["_id"],
"action": "accept",
"confirm": True
})
asyncio.run(main())See API.md for complete API documentation, including:
- Available MCP tools
- Resource URI schemes
- Request/response formats
- Error handling
- Examples
# Install development dependencies
uv pip install -e ".[dev]"
# Install pre-commit hooks
pre-commit install
pre-commit install --hook-type commit-msg# Run all tests
pytest tests/unit/
# Run with coverage report
pytest tests/unit/ --cov=src --cov-report=html --cov-report=term-missing
# Run specific test file
pytest tests/unit/test_zbf_tools.py -v
# Run tests for new v0.2.0 features
pytest tests/unit/test_new_models.py tests/unit/test_zbf_tools.py tests/unit/test_traffic_flow_tools.py
# Run only unit tests (fast)
pytest -m unit
# Run only integration tests (requires UniFi controller)
pytest -m integrationCurrent Test Coverage:
- Overall: 37.29% (213 tests passing)
- ZBF Tools: 84.13% (34 tests) - Zone management working, policy matrix/app blocking endpoints don't exist
- Traffic Flow Tools: 86.62% (16 tests)
- New v0.2.0 Models: 100% (36 tests)
- Existing Tools: 15-95% (varying coverage)
Note: ZBF unit tests validate tool logic, but 8 tools cannot function due to missing API endpoints (verified on v10.0.156)
See TESTING_PLAN.md for the comprehensive testing roadmap.
# Format code
black src/ tests/
isort src/ tests/
# Lint code
ruff check src/ tests/ --fix
# Type check
mypy src/
# Run all pre-commit checks
pre-commit run --all-files# Start development server with inspector
uv run mcp dev src/main.py
# Open http://localhost:5173 in your browserunifi-mcp-server/
├── .github/
│ └── workflows/ # CI/CD pipelines (CI, security, release)
├── .claude/
│ └── commands/ # Custom slash commands for development
├── src/
│ ├── main.py # MCP server entry point (77 tools registered)
│ ├── cache.py # Redis caching implementation
│ ├── config/ # Configuration management
│ ├── api/ # UniFi API client with rate limiting
│ ├── models/ # Pydantic data models
│ │ └── zbf.py # Zone-Based Firewall models
│ ├── tools/ # MCP tool definitions
│ │ ├── clients.py # Client query tools
│ │ ├── devices.py # Device query tools
│ │ ├── networks.py # Network query tools
│ │ ├── sites.py # Site query tools
│ │ ├── firewall.py # Firewall management (Phase 4)
│ │ ├── firewall_zones.py # Zone-Based Firewall zone management (v0.1.4)
│ │ ├── zbf_matrix.py # Zone-Based Firewall policy matrix (v0.1.4)
│ │ ├── network_config.py # Network configuration (Phase 4)
│ │ ├── device_control.py # Device control (Phase 4)
│ │ ├── client_management.py # Client management (Phase 4)
│ │ ├── wifi.py # WiFi/SSID management (Phase 5)
│ │ ├── port_forwarding.py # Port forwarding (Phase 5)
│ │ └── dpi.py # DPI statistics (Phase 5)
│ ├── resources/ # MCP resource definitions
│ ├── webhooks/ # Webhook receiver and handlers (Phase 5)
│ └── utils/ # Utility functions and validators
├── tests/
│ ├── unit/ # Unit tests (213 tests, 37% coverage)
│ ├── integration/ # Integration tests (planned)
│ └── performance/ # Performance benchmarks (planned)
├── docs/ # Additional documentation
│ └── AI-Coding/ # AI coding guidelines
├── .env.example # Environment variable template
├── pyproject.toml # Project configuration
├── README.md # This file
├── API.md # Complete API documentation
├── ZBF_STATUS.md # Zone-Based Firewall implementation status
├── TESTING_PLAN.md # Testing strategy and roadmap
├── DEVELOPMENT_PLAN.md # Development roadmap
├── CONTRIBUTING.md # Contribution guidelines
├── SECURITY.md # Security policy and best practices
├── AGENTS.md # AI agent guidelines
└── LICENSE # Apache 2.0 License
We welcome contributions from both human developers and AI coding assistants! Please see:
- CONTRIBUTING.md - Contribution guidelines
- AGENTS.md - AI agent-specific guidelines
- AI_CODING_ASSISTANT.md - AI coding standards
- AI_GIT_PRACTICES.md - AI Git practices
- Fork the repository
- Create a feature branch:
git checkout -b feature/your-feature-name - Make your changes
- Run tests and linting:
pytest && pre-commit run --all-files - Commit with conventional commits:
feat: add new feature - Push and create a pull request
Security is a top priority. Please see SECURITY.md for:
- Reporting vulnerabilities
- Security best practices
- Supported versions
Never commit credentials or sensitive data!
Phase 3: Read-Only Operations (16 tools)
- Device management (list, details, statistics, search by type)
- Client management (list, details, statistics, search)
- Network information (details, VLANs, subnets, statistics)
- Site management (list, details, statistics)
- MCP resources (sites, devices, clients, networks)
Phase 4: Mutating Operations with Safety (13 tools)
- Firewall rule management (create, update, delete)
- Network configuration (create, update, delete networks/VLANs)
- Device control (restart, locate, upgrade)
- Client management (block, unblock, reconnect)
- Safety mechanisms (confirmation, dry-run, audit logging)
Phase 5: Advanced Features (11 tools)
- WiFi/SSID management (create, update, delete, statistics)
- Port forwarding configuration (create, delete, list)
- DPI statistics (site-wide, top apps, per-client)
- Redis caching with automatic invalidation
- Webhook support for real-time events
Phase 6: Zone-Based Firewall (7 working tools, 8 non-functional)
- Zone management (create, update, delete, list, assign networks) - 7 tools ✅ WORKING
- Zone policy matrix (get matrix, update policies, delete policies) - 5 tools ❌ ENDPOINTS DO NOT EXIST
- Application blocking per zone (DPI-based blocking) - 2 tools ❌ ENDPOINTS DO NOT EXIST
- Zone statistics and monitoring - 1 tool ❌ ENDPOINT DOES NOT EXIST
- Type-safe Pydantic models for ZBF
- Comprehensive unit tests (84% coverage)
- Endpoint verification on U7 Express and UDM Pro (v10.0.156)
Phase 7: Traffic Flow Monitoring (15 tools) ✅ COMPLETE
- Real-time traffic flow monitoring and analysis
- Flow filtering by IP, protocol, application, time range
- Connection state tracking (active, closed, timed-out)
- Client traffic aggregation with top applications/destinations
- Bandwidth rate calculations for streaming flows
- Security quick-response capabilities (block suspicious IPs)
- Type-safe Pydantic models for traffic flows
- Comprehensive unit tests (86.62% coverage)
- Advanced analytics and reporting capabilities
ZBF API Limitations (Verified 2025-11-18):
- ✅ Zone CRUD operations work (local gateway API only)
- ❌ Zone policy matrix NOT available via API (configure in UniFi Console)
- ❌ Application blocking per zone NOT available via API
- ❌ Zone statistics NOT available via API
- See
tests/verification/PHASE2_FINDINGS.mdfor complete verification report
Total: 77 MCP tools (69 functional, 8 deprecated) + 4 MCP resources
- Unit tests for Phase 5 tools (target: 80% coverage)
- Integration tests for caching and webhooks
- Performance benchmarks and optimization
- Performance tracking with agnost.ai integration
- MCP Toolbox Docker integration for analytics dashboard
- Additional DPI analytics (historical trends)
- Backup and restore operations
- Complete UniFi API coverage (remaining endpoints)
- Advanced analytics dashboard
- VPN configuration management
- Alert and notification management
- Bulk operations for devices
- Traffic shaping and QoS management
This project is inspired by and builds upon:
- sirkirby/unifi-network-mcp - Reference implementation
- MakeWithData UniFi MCP Guide - Tutorial and guide
- Anthropic MCP - Model Context Protocol specification
- FastMCP - MCP server framework
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Documentation: See API.md and other docs in this repository
- Repository: https://github.com/enuno/unifi-mcp-server
- Docker Hub: https://ghcr.io/enuno/unifi-mcp-server
- Documentation: API.md
- UniFi Official: https://www.ui.com/
If you find this project useful, please consider starring it on GitHub to help others discover it!
Made with ❤️ for the UniFi and AI communities