unifi-mcp-server / rules
Cursor rule294 starsChanged 18 days agoApache-2.0View on GitHub
UniFi API integration guidelines and patterns
- Reads credentials
We split this unifi-api.mdc into the rules it gives an agent
7 rules. About 0 are common, 5 are distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈5
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 15
Use UNIFI_API_KEY environment variable for authentication
- Distinctive: line 17
No session management or cookies required (stateless authentication)
- Distinctive: line 78
Document that write operations are not yet available
- Distinctive: line 80
Consider implementing a "preview" mode that shows what would be created
- Very specific: line 97
Use configurable rate limits via UNIFI_RATE_LIMIT environment variable
- Distinctive: line 167
Keep all API interactions in dedicated modules:
- Distinctive: line 189
Always reference the official UniFi API documentation:
≈ “Common” is an estimate: at least 1 in 5 of the 6,350 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
---
description: UniFi API integration guidelines and patterns
globs: ["src/api/**/*.py", "src/tools/**/*.py"]
alwaysApply: true
---
# UniFi API Guidelines
## Authentication with API Keys
This project uses the **official UniFi Cloud API** with API key authentication.
**Authentication Method:**
- Use `UNIFI_API_KEY` environment variable for authentication
- API key is passed via the `X-API-Key` HTTP header
- No session management or cookies required (stateless authentication)
**NEVER hardcode API keys:**
```python
# ❌ BAD - Hardcoded API key
headers = {
"X-API-Key": "abc123def456..."
}
# ✅ GOOD - Load from environment
from src.config.config import Settings
settings = Settings()
headers = {
"X-API-Key": settings.api_key
}
```
## API Access Modes
Support both cloud and local gateway access modes:
**Cloud API (Default):**
```python
# Base URL: https://api.ui.com/v1/
settings.api_type = "cloud"
settings.cloud_api_url = "https://api.ui.com"
```
**Local Gateway Proxy:**
```python
# Base URL: https://{gateway-ip}/proxy/network/integration/v1/
settings.api_type = "local"
settings.local_host = "192.168.2.1"
settings.local_port = 443
```
## Read-Only Limitation
**IMPORTANT:** The Early Access API is currently **read-only**.
```python
# ✅ ALLOWED - Read operations
async def list_devices(site_id: str):
"""List all devices - read operation."""
devices = await client.get(f"/v1/sites/{site_id}/devices")
return devices
# ❌ NOT AVAILABLE - Write operations (will fail)
async def create_network(name: str, vlan_id: int):
"""Create network - not yet supported in EA API."""
# This will return 403 Forbidden in current API version
raise NotImplementedError(
"Write operations are not available in the Early Access API. "
"This feature will be available in v1 Stable release."
)
```
**Handling write requests:**
- Document that write operations are not yet available
- Return clear error messages to users
- Consider implementing a "preview" mode that shows what would be created
- Monitor UniFi API release notes for v1 Stable availability
## Rate Limiting Considerations
Implement proper rate limiting to respect API limits:
**Current Limits:**
- Early Access: 100 requests/minute
- v1 Stable (future): 10,000 requests/minute
**Best Practices:**
- Cache frequently accessed data (devices, sites, networks)
- Batch operations when possible
- Implement exponential backoff for 429 errors
- Use configurable rate limits via `UNIFI_RATE_LIMIT` environment variable
- Log rate limit warnings for monitoring
## API Error Handling
Handle UniFi API-specific errors gracefully:
```python
import httpx
from typing import Dict, Any
class UniFiAPIError(Exception):
"""Base exception for UniFi API errors."""
pass
class UniFiAuthenticationError(UniFiAPIError):
"""Authentication failed - invalid API key."""
pass
class UniFiRateLimitError(UniFiAPIError):
"""Rate limit exceeded."""
pass
async def safe_api_request(
client: httpx.AsyncClient,
method: str,
endpoint: str,
**kwargs
) -> Dict[str, Any]:
"""
Make a safe API request with proper error handling.
Args:
client: HTTP client
method: HTTP method (GET, POST, etc.)
endpoint: API endpoint
**kwargs: Additional request parameters
Returns:
Response data as dictionary
Raises:
UniFiAuthenticationError: Invalid API key
UniFiRateLimitError: Rate limit exceeded
UniFiAPIError: Other API errors
"""
try:
response = await client.request(method, endpoint, **kwargs)
response.raise_for_status()
return response.json()
except httpx.HTTPStatusError as e:
if e.response.status_code == 401:
raise UniFiAuthenticationError(
"Invalid API key. Please check your UNIFI_API_KEY."
)
elif e.response.status_code == 429:
retry_after = e.response.headers.get("Retry-After", 60)
raise UniFiRateLimitError(
f"Rate limit exceeded. Retry after {retry_after} seconds."
)
else:
raise UniFiAPIError(f"API error: {e.response.status_code}")
except httpx.RequestError as e:
raise UniFiAPIError(f"Request failed: {str(e)}")
```
## Centralize API Calls
Keep all API interactions in dedicated modules:
```python
# src/api/client.py
class UniFiClient:
async def request(
self,
method: str,
endpoint: str,
**kwargs
) -> Dict[str, Any]:
"""
Make authenticated request to UniFi API.
Handles authentication, retries, and error handling.
"""
# Centralized implementation
pass
```
## Official API Documentation
Always reference the official UniFi API documentation:
- **Getting Started**: https://developer.ui.com/site-manager-api/gettingstarted
- **Project Reference**: `docs/UNIFI_API.md` (comprehensive guide)
- **API Tutorial**: https://www.makewithdata.tech/p/build-a-mcp-server-for-ai-access
Where files are headingNew Cursor rule files have more rules about planning and tracking tasks, and fewer about code style.
Of the Cursor rule files we read, the 3,978 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository52 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .agents/skills/fastmcp/CLAUDE.mdCLAUDE.md
- CLAUDE.mdCLAUDE.md
- .claude/skills/fastmcp/CLAUDE.mdCLAUDE.md
- .cursor/rules/common-mistakes.mdcCursor rule
- .cursor/rules/core-principles.mdcCursor rule
- .cursor/rules/environment-setup.mdcCursor rule
- .cursor/rules/mcp-tools.mdcCursor rule
- .cursor/rules/project-context.mdcCursor rule
- .cursor/rules/README.mdCursor rule
- .cursor/rules/workflow.mdcCursor rule
- FastMCP DevelopmentSkill
- mcp-builderSkill
- source-command-build-dockerSkill
- source-command-check-depsSkill
- source-command-cleanSkill
- source-command-docsSkill
- source-command-formatSkill
- source-command-lintSkill
- source-command-prSkill
- source-command-securitySkill
- source-command-setupSkill
- source-command-testSkill
- source-command-unifi-api-docs-update-2Skill
- source-command-unifi-api-docs-updateSkill
- source-command-unifi-mcp-add-toolSkill
- source-command-unifi-mcp-release-prepSkill
- source-command-unifi-mcp-test-coverageSkill
- source-command-unifi-mcp-update-docsSkill
- unifi-cloud-fleet-toolsSkill
- unifi-mcp-tool-builderSkill
- unifi-network-config-toolsSkill
- unifi-protect-toolsSkill
- unifi-security-toolsSkill
- FastMCP DevelopmentSkill
- mcp-builderSkill
- unifi-cloud-fleet-toolsSkill
- unifi-mcp-tool-builderSkill
- unifi-network-config-toolsSkill
- unifi-protect-toolsSkill
- unifi-security-toolsSkill
- unifiSkill
- unifi-channel-planningSkill
- unifi-cloud-fleet-toolsSkill
- unifi-devicesSkill
- unifi-mcp-tool-builderSkill
- unifi-network-config-toolsSkill
- unifi-networkSkill
- unifi-protect-toolsSkill
- unifi-securitySkill
- unifi-security-toolsSkill
- unifi-systemSkill
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

