A comprehensive Model Context Protocol (MCP) server for UniFi Network API integration, supporting both legacy firewall rules and the new Zone-Based Firewall (ZBF) system introduced in UniFi Network 9.0+.
- Dual Firewall Support: Legacy firewall rules and Zone-Based Firewall (ZBF)
- Automatic Version Detection: Detects UniFi controller capabilities
- Comprehensive Device Management: Gateways, switches, access points, and clients
- Network Administration: VLANs, networks, and IP groups
- Real-time Monitoring: Statistics, events, and health monitoring
- Automation Tools: Scheduling, bulk operations, and emergency lockdown
- TypeScript Implementation: Full type safety and IntelliSense support
- Robust Error Handling: Structured error recovery and retry mechanisms
- Rate Limiting: Built-in API rate limiting to prevent controller overload
- Caching System: Configurable caching for performance optimization
- Health Monitoring: Continuous health checks and metrics collection
- SSL Support: Handles self-signed certificates common in UniFi deployments
- Node.js 18+
- UniFi Network Application 6.0+ (9.0+ for ZBF features)
- UniFi Gateway with API access enabled
- Valid API key
Global Installation:
# Install globally to use as a CLI tool
npm install -g @thelord/unifi-mcp-server
# Run the server
unifi-mcp-serverLocal Installation:
# Install in your project
npm install @thelord/unifi-mcp-server
# Run with npx
npx @thelord/unifi-mcp-serverDirect Execution:
# Run without installing
npx @thelord/unifi-mcp-server-
Clone and Install
git clone <repository> cd unifi-mcp-server npm install
-
Configure Environment
cp .env.example .env
Edit
.envwith your UniFi settings:UNIFI_GATEWAY_IP=192.168.1.1 UNIFI_API_KEY=your_api_key_here UNIFI_SITE_ID=default UNIFI_VERIFY_SSL=false
-
Build and Run
npm run build npm start
npm run devTo use this MCP server with Claude Desktop, add the following configuration to your Claude Desktop config file:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
Windows: %APPDATA%/Claude/claude_desktop_config.json
{
"mcpServers": {
"unifi-network": {
"command": "npx",
"args": ["@thelord/unifi-mcp-server"],
"env": {
"UNIFI_GATEWAY_IP": "192.168.1.1",
"UNIFI_API_KEY": "your_api_key_here",
"UNIFI_SITE_ID": "default",
"UNIFI_VERIFY_SSL": "false"
}
}
}
}{
"mcpServers": {
"unifi-network": {
"command": "unifi-mcp-server",
"env": {
"UNIFI_GATEWAY_IP": "192.168.1.1",
"UNIFI_API_KEY": "your_api_key_here",
"UNIFI_SITE_ID": "default",
"UNIFI_VERIFY_SSL": "false"
}
}
}
}{
"mcpServers": {
"unifi-network": {
"command": "node",
"args": ["/path/to/unifi-mcp-server/dist/index.js"],
"env": {
"UNIFI_GATEWAY_IP": "192.168.1.1",
"UNIFI_API_KEY": "your_api_key_here",
"UNIFI_SITE_ID": "default",
"UNIFI_VERIFY_SSL": "false"
}
}
}
}You can configure the server using environment variables in the MCP client configuration:
{
"mcpServers": {
"unifi-network": {
"command": "npx",
"args": ["@thelord/unifi-mcp-server"],
"env": {
"UNIFI_GATEWAY_IP": "10.0.1.1",
"UNIFI_API_KEY": "your_32_char_api_key",
"UNIFI_SITE_ID": "default",
"UNIFI_VERIFY_SSL": "false",
"UNIFI_TIMEOUT": "30000",
"LOG_LEVEL": "info",
"ENABLE_ZBF_TOOLS": "true",
"ENABLE_LEGACY_FIREWALL": "true",
"API_RATE_LIMIT_PER_MINUTE": "60"
}
}
}
}For other MCP clients, use the appropriate command based on your installation method:
npm/npx:
npx @thelord/unifi-mcp-serverGlobal installation:
unifi-mcp-serverSource installation:
node /path/to/dist/index.jsAfter configuring your MCP client:
- Restart Claude Desktop (or your MCP client)
- Test the connection by asking Claude: "Can you connect to my UniFi network and show me the devices?"
- Verify tools are loaded by asking: "What UniFi tools are available?"
Claude Desktop not detecting the server:
- Verify the JSON syntax is correct
- Check file path:
~/Library/Application Support/Claude/claude_desktop_config.json - Restart Claude Desktop completely
- Check Claude Desktop logs for errors
Connection issues:
- Verify
UNIFI_GATEWAY_IPis correct and accessible - Ensure
UNIFI_API_KEYis valid and has proper permissions - Set
UNIFI_VERIFY_SSL=falseif using self-signed certificates - Check network connectivity to the UniFi controller
UNIFI_GATEWAY_IP: IP address of your UniFi controller/gatewayUNIFI_API_KEY: API key for authenticationUNIFI_SITE_ID: Site identifier (default: "default")UNIFI_VERIFY_SSL: Verify SSL certificates (default: false)UNIFI_TIMEOUT: Request timeout in milliseconds (default: 30000)UNIFI_MAX_RETRIES: Maximum retry attempts (default: 3)
ENABLE_ZBF_TOOLS: Enable Zone-Based Firewall tools (default: true)ENABLE_LEGACY_FIREWALL: Enable legacy firewall tools (default: true)ENABLE_MONITORING: Enable monitoring tools (default: true)ENABLE_AUTOMATION: Enable automation tools (default: true)
API_RATE_LIMIT_PER_MINUTE: API requests per minute (default: 60)CONCURRENT_REQUESTS_LIMIT: Concurrent requests (default: 5)CACHE_TTL_SECONDS: Cache time-to-live (default: 300)
LOG_LEVEL: Logging level (error, warn, info, debug, trace)LOG_FILE: Log file path (optional)LOG_FORMAT: Log format (json, simple, combined)
unifi_connect: Establish connection to UniFi controllerunifi_test_connection: Test connectivity and authenticationunifi_get_system_info: Retrieve system information and versionunifi_disconnect: Disconnect from controllerunifi_get_connection_status: Get detailed connection status
unifi_get_devices: List all UniFi devicesunifi_get_device_details: Get detailed device informationunifi_restart_device: Restart specific deviceunifi_adopt_device: Adopt pending deviceunifi_get_device_stats: Get device performance statistics
unifi_get_clients: List connected clientsunifi_get_client_details: Get detailed client informationunifi_block_client: Block client accessunifi_unblock_client: Unblock client accessunifi_get_client_stats: Get client usage statistics
unifi_get_firewall_rules: Get traditional firewall rulesunifi_create_firewall_rule: Create new firewall ruleunifi_update_firewall_rule: Update existing ruleunifi_delete_firewall_rule: Delete firewall ruleunifi_toggle_firewall_rule: Enable/disable rule
unifi_get_zones: List firewall zonesunifi_create_zone: Create custom zoneunifi_update_zone: Update zone configurationunifi_delete_zone: Delete custom zoneunifi_get_zone_policies: Get policies between zonesunifi_create_zone_policy: Create zone-to-zone policyunifi_update_zone_policy: Update existing policyunifi_delete_zone_policy: Delete zone policyunifi_get_zone_matrix: Get visual policy matrixunifi_block_app_in_zone: Simple application blocking
unifi_get_networks: List configured networks/VLANsunifi_create_network: Create new network/VLANunifi_update_network: Update network configurationunifi_delete_network: Delete network/VLANunifi_get_network_stats: Get network usage statistics
unifi_get_ip_groups: Get IP/MAC address groupsunifi_create_ip_group: Create address groupunifi_update_ip_group: Update group configurationunifi_delete_ip_group: Delete address groupunifi_add_to_ip_group: Add address to groupunifi_remove_from_ip_group: Remove address from group
unifi_get_site_stats: Get general site statisticsunifi_get_bandwidth_usage: Get bandwidth usage by client/deviceunifi_get_events: Get system events and logsunifi_get_alerts: Get active system alertsunifi_get_topology: Get network topologyunifi_get_interference: Get WiFi interference data
unifi_schedule_device_block: Schedule device blockingunifi_emergency_lockdown: Activate emergency network lockdownunifi_bulk_device_management: Perform bulk operations on devicesunifi_auto_backup_config: Backup configuration automaticallyunifi_health_check: Perform comprehensive health check
// Connect to UniFi controller
await mcp.callTool("unifi_connect", {
gatewayIp: "192.168.1.1",
apiKey: "your-api-key",
siteId: "default",
});
// Test connection
const status = await mcp.callTool("unifi_test_connection", {});
console.log("Connection status:", status.data.status);// Get all devices
const devices = await mcp.callTool("unifi_get_devices", {});
// Get specific device details
const device = await mcp.callTool("unifi_get_device_details", {
deviceId: "device-mac-address",
});
// Restart a device
await mcp.callTool("unifi_restart_device", {
deviceId: "device-mac-address",
});// Create IoT zone
await mcp.callTool("unifi_create_zone", {
name: "iot_zone",
description: "IoT devices zone",
networks: ["iot_network_id"],
});
// Create policy: IoT zone cannot access Internal zone
await mcp.callTool("unifi_create_zone_policy", {
sourceZone: "iot_zone",
targetZone: "internal",
action: "deny",
logging: true,
});
// Allow IoT zone to access external (internet)
await mcp.callTool("unifi_create_zone_policy", {
sourceZone: "iot_zone",
targetZone: "external",
action: "allow",
});// Create firewall rule
await mcp.callTool("unifi_create_firewall_rule", {
name: "Block_SSH_External",
action: "deny",
protocol: "tcp",
source: "any",
destination: "192.168.1.0/24",
destinationPort: "22",
priority: 2000,
});// Create guest network
await mcp.callTool("unifi_create_network", {
name: "Guest_Network",
purpose: "guest",
vlanId: 100,
subnet: "192.168.100.0/24",
gateway: "192.168.100.1",
dhcpEnabled: true,
dhcpRange: {
start: "192.168.100.10",
end: "192.168.100.100",
},
});// Get site statistics
const stats = await mcp.callTool("unifi_get_site_stats", {
timeframe: "day",
});
// Get bandwidth usage for specific client
const usage = await mcp.callTool("unifi_get_bandwidth_usage", {
entityType: "client",
entityId: "client-mac-address",
timeframe: "hour",
});// Schedule device blocking during school hours
await mcp.callTool("unifi_schedule_device_block", {
deviceId: "kid-device-mac",
schedule: {
days: ["monday", "tuesday", "wednesday", "thursday", "friday"],
startTime: "08:00",
endTime: "15:00",
},
});
// Emergency lockdown
await mcp.callTool("unifi_emergency_lockdown", {
blockAllClients: true,
allowedDevices: ["admin-device-mac"],
autoDisableAfter: 60, // minutes
});| Version | Legacy Firewall | Zone-Based Firewall | Advanced Stats | Notes |
|---|---|---|---|---|
| 6.0-8.5 | ✅ Full | ❌ Not Available | Basic functionality | |
| 9.0+ | ✅ Full | ✅ Full | ZBF recommended |
| Device | Legacy Firewall | Zone-Based Firewall | Advanced Features |
|---|---|---|---|
| UCG-Ultra | ✅ | ✅ | ✅ |
| UCG-Max | ✅ | ✅ | ✅ |
| UDM-Pro | ✅ | ✅ | |
| UDM-Base | ✅ | ✅ | |
| USG-Pro-4 | ✅ | ❌ | ❌ |
| USG-3P | ✅ | ❌ | ❌ |
The server provides comprehensive error handling with structured error responses:
// Example error response
{
"success": false,
"error": {
"code": "FEATURE_NOT_SUPPORTED",
"message": "Zone-Based Firewall requires UniFi Network 9.0+",
"details": {
"feature": "zbf",
"currentVersion": "8.5.6",
"requiredVersion": "9.0.0"
}
}
}CONNECTION_FAILED: Unable to connect to UniFi controllerAUTHENTICATION_FAILED: Invalid API key or permissionsFEATURE_NOT_SUPPORTED: Feature not available in current versionHARDWARE_INCOMPATIBLE: Feature requires different hardwareVALIDATION_ERROR: Invalid input parametersRATE_LIMIT_EXCEEDED: API rate limit exceeded
src/
├── index.ts # Main entry point
├── server/ # MCP server implementation
│ ├── mcpServer.ts # Main server class
│ ├── toolRegistry.ts # Tool management
│ └── types.ts # Server types
├── unifi/ # UniFi API client
│ ├── client.ts # HTTP client
│ ├── versionDetector.ts # Version detection
│ └── types.ts # UniFi types
├── tools/ # Tool implementations
│ ├── connection/ # Connection tools
│ ├── devices/ # Device management
│ ├── firewall/ # Firewall tools
│ ├── networks/ # Network management
│ ├── monitoring/ # Statistics and monitoring
│ └── automation/ # Automation tools
├── utils/ # Utilities
│ ├── errors.ts # Error handling
│ ├── validators.ts # Input validation
│ ├── logger.ts # Logging system
│ └── helpers.ts # Helper functions
└── config/ # Configuration
├── environment.ts # Environment config
└── constants.ts # System constants
npm run buildnpm test
npm run test:watch
npm run test:coveragenpm run lint
npm run lint:fix- Certificate Errors: Set
UNIFI_VERIFY_SSL=falsefor self-signed certificates - Network Timeout: Increase
UNIFI_TIMEOUTvalue - API Key Invalid: Verify API key is correct and has proper permissions
- ZBF Tools Unavailable: Check UniFi version is 9.0+ and hardware supports ZBF
- Legacy Tools Deprecated: Consider migrating to ZBF for new UniFi versions
- Limited Statistics: Advanced stats require UniFi 8.5+
- Rate Limiting: Reduce
API_RATE_LIMIT_PER_MINUTEif needed - Slow Responses: Enable caching with appropriate
CACHE_TTL_SECONDS - Memory Usage: Monitor and adjust cache settings
Enable debug logging:
LOG_LEVEL=debug npm startThe server provides health check endpoints for monitoring:
# Check server status
curl http://localhost:9090/health
# Get detailed debug info
curl http://localhost:9090/debug- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Follow TypeScript best practices
- Add comprehensive tests for new features
- Update documentation for API changes
- Use conventional commit messages
- Ensure all tests pass before submitting
This project is licensed under the MIT License - see the LICENSE file for details.
- Issues: GitHub Issues
- Documentation: This README and inline code documentation
- Examples: See
examples/directory for complete usage examples
- Initial release
- Full UniFi Network API support
- Zone-Based Firewall integration
- Comprehensive tool set
- Production-ready error handling and logging