.cursorrulesโข22 kB
# Tailscale-MCP Cursor Rules
## ๐ฏ Triple Initiatives (Active)
**This repo is part of three parallel improvement initiatives:**
1. **Great Doc Bash** - Documentation Quality (Target: 9.0+/10)
2. **GitHub Dash** - CI/CD Modernization (Target: 8.0+/10)  
3. **Release Flash** - Successful Releases (Target: Zero errors)
**Priority**: HIGH (CI workflows + ruff needed)
๐ **Improvement Plan**: `docs-private/TRIPLE_INITIATIVES_GUIDE.md`  
๐ **Central Docs**: `D:\Dev\repos\mcp-central-docs\`  
๐ **Standards**: `mcp-central-docs/STANDARDS.md`
### ๐จ **CRITICAL: Consult Central Docs First**
**๐ CONSULT CENTRAL DOCS FIRST**: Before creating new documentation, standards, or patterns, consult the central docs repository (`D:\Dev\repos\mcp-central-docs\`) for existing documentation and standards. This ensures consistency and avoids duplication across all MCP repositories.
---
## Project Overview
This is tailscale-mcp, a professional Tailscale management MCP server built with FastMCP 2.12+. It provides comprehensive network operations, device management, security features, monitoring, and file sharing capabilities.
## Code Standards
### ๐จ CRITICAL: Chat Output & PowerShell Syntax
**REQUIRED**: ALL chat output MUST begin with "hi!" as a test.
**๐ซ FORBIDDEN in PowerShell:**
- `&&` (command chaining) - Use `;` or separate commands
- `||` (logical OR) - Use PowerShell syntax
- `mkdir`, `rmdir`, `ls` - Use `New-Item`, `Remove-Item`, `Get-ChildItem`
- `head`, `tail` - Use PowerShell cmdlets
- Linux path separators - Use backslash `\` on Windows
---
### Python
- **Style**: Use ruff for linting and formatting
- **Type Hints**: Add type hints for all function signatures
- **Async**: All MCP tools must be async functions
- **Error Handling**: Always use try/except with proper error messages
### Naming Conventions
- **Package**: `tailscalemcp` (no underscores, no hyphens!)
- **Modules**: lowercase with underscores (snake_case)
- **Classes**: PascalCase (e.g., `TailscaleMCPServer`, `DeviceManager`)
- **Functions**: snake_case (e.g., `list_devices`, `create_acl`)
- **Constants**: UPPER_CASE (e.g., `DEBUG`, `LOG_LEVEL`)
### Import Organization
```python
# Standard library
import os
import sys
from typing import Any, Dict, List
# Third-party
from fastmcp import FastMCP
import httpx
# Local imports
from tailscalemcp.device_management import DeviceManager
from tailscalemcp.exceptions import TailscaleMCPError
```
### File Naming Conventions
- **Modules**: `snake_case.py` (e.g., `device_management.py`)
- **Classes**: PascalCase in files (e.g., `DeviceManager` in `device_management.py`)
- **Test files**: `test_<module_name>.py` (e.g., `test_device_management.py`)
- **Configuration**: `config_<purpose>.py` or `settings.py`
- **Utilities**: `utils.py` or `helpers.py`
### Project Structure Standards
```
src/tailscalemcp/
โโโ __init__.py              # Package initialization and version
โโโ mcp_server.py           # Main MCP server entry point
โโโ tools/                  # MCP tool implementations
โ   โโโ __init__.py
โ   โโโ portmanteau_tools.py
โโโ device_management.py    # Device operations
โโโ monitoring.py           # Monitoring and metrics
โโโ grafana_dashboard.py    # Grafana integration
โโโ taildrop.py             # File sharing operations
โโโ magic_dns.py            # DNS management
โโโ exceptions.py           # Custom exception classes
โโโ utils.py                # Shared utilities
```
### Module Organization Principles
- **Single Responsibility**: Each module has one clear purpose
- **Logical Grouping**: Related functionality in same module
- **Clear Interfaces**: Well-defined public APIs
- **Dependency Direction**: Higher-level modules depend on lower-level ones
- **Circular Dependencies**: Avoid at all costs
## Testing Requirements
### Coverage & Quality Standards
- **Coverage Target**: 80% (GLAMA Gold Standard)
- **Current**: 24% (improving to 80%)
- **Minimum per-file**: 70% coverage
- **Critical paths**: 90% coverage (auth, device management, API calls)
- **Framework**: pytest with pytest-cov
- **Markers**: Use @pytest.mark.integration for integration tests
- **Mocking**: Use `patch('httpx.AsyncClient')` for API calls
- **Non-blocking**: Tests run but don't fail CI builds (continue-on-error: true)
### Test Organization
```
tests/
โโโ unit/                    # Unit tests (fast, isolated)
โ   โโโ test_device_management.py
โ   โโโ test_monitoring.py
โ   โโโ test_magic_dns.py
โโโ integration/             # Integration tests (slower, real APIs)
โ   โโโ test_tailscale_api.py
โ   โโโ test_mcp_tools.py
โโโ monitoring/              # Monitoring-specific tests
โ   โโโ test_grafana.py
โ   โโโ test_prometheus.py
โโโ conftest.py             # Shared fixtures and configuration
```
### Test Patterns
```python
@pytest.mark.asyncio
async def test_function_name():
    """Test description."""
    with patch('httpx.AsyncClient') as mock_client:
        mock_client.return_value.get.return_value = AsyncMock(
            status_code=200,
            json=AsyncMock(return_value={'devices': []})
        )
        
        result = await function_to_test()
        assert result is not None
```
### Test Commands
```powershell
# Run all tests
uv run pytest -v
# Run with coverage
uv run pytest --cov=tailscalemcp --cov-report=html --cov-report=term
# Run specific test categories
uv run pytest -m "not integration"  # Unit tests only
uv run pytest -m integration        # Integration tests only
# Run specific file
uv run pytest tests/unit/test_device_management.py -v
```
## MCP Tool Development
### FastMCP 2.12+ Compliance Standards
**All MCP servers MUST use FastMCP 2.12+ tool documentation standards:**
#### โ
 Correct Tool Documentation Format
```python
from typing import Literal
from fastmcp import FastMCP
mcp = FastMCP("tailscale-mcp")
@mcp.tool()  # No description parameter!
async def tool_name(
    action: Literal["op1", "op2", "op3"],  # Required for portmanteau tools
    param: str | None = None
) -> Dict[str, Any]:
    '''This tool does something cool with comprehensive documentation.
    
    FEATURES:
    - Feature 1 explained
    - Feature 2 explained
    - Feature 3 explained
    
    Args:
        action: Available operations:
            - op1: Full description with requirements
            - op2: Full description with requirements  
            - op3: Full description with requirements
        param: Parameter description with type and purpose
        
    Returns:
        Dictionary with success, result, error
        
    Examples:
        # Example for op1
        result = await tool_name(action="op1")
        
        # Example for op2
        result = await tool_name(action="op2", param="value")
        
    Notes:
        - Important note 1
        - Important note 2
    '''
    # Implementation
    return {"status": "success", "data": result}
```
#### โ Prohibited Patterns
- **NO** `@mcp.tool(description="...")` decorators
- **NO** basic docstrings without comprehensive documentation
- **NO** incomplete parameter documentation
- **NO** missing return value documentation
### Portmanteau Pattern Standards
**For feature-rich MCP servers, use the Portmanteau Pattern:**
#### Benefits
- Prevents tool explosion (60+ tools โ 10 portmanteau tools)
- Improves discoverability
- Better user experience
- Easier maintenance
#### Implementation Requirements
- โ
 Use `Literal` types for action parameters
- โ
 Use `@mcp.tool()` WITHOUT description parameter
- โ
 Write comprehensive docstrings (200+ lines for complex tools)
- โ
 Document ALL sub-operations in docstring
- โ
 Provide examples for each operation
- โ
 Check imports (no circular dependencies)
- โ
 Run ruff before committing
### Common Patterns
- **Always**: Return Dict[str, Any] with status/error fields
- **Validate**: Check parameters before operations
- **Log**: Use logger.info/error for operations
- **Error Handling**: Return error dict, don't raise unless critical
## Pre-commit Requirements
### Ruff Linting
**CRITICAL**: ALL commits MUST have zero ruff errors before pushing.
```powershell
# Before committing, always run:
uv run ruff check .
uv run ruff check --fix .  # Auto-fix what can be fixed
# Verify zero errors before:
git add .
git commit -m "your message"
git push
```
**Ruff errors will cause CI to fail**. Always fix linting errors before pushing to remote.
## Build System
### UV-Based Dependency Management
- **Install**: `uv sync --dev`
- **Run**: `uv run <command>`
- **Build**: `uv build`
- **Test**: `uv run pytest`
### PowerShell Commands (Windows)
```powershell
# Linting and formatting
uv run ruff check .
uv run ruff format .
# Testing
uv run python -m pytest -v
uv run python -m pytest --cov=tailscalemcp --cov-report=html
# Build and packaging
uv build
mcpb pack . dist/tailscale-mcp-v{version}.mcpb
# Development workflow
uv sync --dev
uv run python -m tailscalemcp
```
### MCPB Packaging Standards
**All MCP servers MUST use MCPB packaging:**
#### Required Files
- `manifest.json` - MCPB manifest configuration
- `assets/` directory - Icons, screenshots, prompts
- `pyproject.toml` - Python project configuration
- `requirements.txt` - Runtime dependencies
#### Manifest Requirements
```json
{
  "manifest_version": "0.2",
  "server": {
    "type": "python",
    "entry_point": "src/tailscalemcp/mcp_server.py",
    "mcp_config": {
      "command": "python",
      "args": ["-m", "tailscalemcp.mcp_server"]
    }
  }
}
```
#### Build Commands
```powershell
# Build MCPB package
mcpb pack . dist/tailscale-mcp-v{version}.mcpb
# Verify package
mcpb verify dist/tailscale-mcp-v{version}.mcpb
```
### MCPB Packaging
- **Manifest**: `manifest.json` (runtime config)
- **Build Command**: `mcpb pack . dist/tailscale-mcp-v{version}.mcpb`
- **Prompts**: All in `assets/prompts/` folder
## CI/CD Workflows
### Active Workflows (3 Total)
**Core CI/CD:**
1. **ci-cd.yml**: Main CI/CD pipeline (lint, test, build, quality gate)
2. **dependencies.yml**: Automated dependency updates and security scanning
3. **docker.yml**: Docker image building and testing
### Workflow Requirements
- **Always use UV**: `uv sync --dev`, `uv run`
- **Non-blocking**: Add `continue-on-error: true` for quality checks
- **Correct paths**: `tailscalemcp` (no underscores!)
- **Modern commands**: `safety scan` not `safety check`
## Tailscale Integration
### API Calls
- **Always mock**: Use `patch('httpx.AsyncClient')` in tests
- **Error handling**: Check status_code, parse JSON responses
- **Authentication**: Use API keys from environment variables
- **Rate limiting**: Implement proper rate limiting for API calls
### Network Operations
- **Device management**: List, authorize, revoke devices
- **ACL management**: Create, update, delete access control lists
- **DNS management**: Configure MagicDNS and custom DNS records
- **File sharing**: Handle Taildrop operations securely
## File Organization
```
tailscale-mcp/
โโโ src/tailscalemcp/          # Main source code
โ   โโโ __init__.py            # Version = pyproject.toml version
โ   โโโ mcp_server.py          # Main MCP server
โ   โโโ tools/                 # MCP tools (portmanteau pattern)
โ   โโโ device_management.py   # Device operations
โ   โโโ monitoring.py          # Monitoring and metrics
โ   โโโ grafana_dashboard.py   # Grafana integration
โ   โโโ taildrop.py            # File sharing
โ   โโโ magic_dns.py           # DNS management
โ   โโโ exceptions.py          # Custom exceptions
โโโ tests/                     # Test suite
โโโ docs/                      # Documentation
โโโ monitoring/                # Monitoring configuration
โโโ .github/workflows/         # CI/CD workflows
โโโ pyproject.toml             # Python project config
โโโ manifest.json              # MCPB manifest
โโโ docker-compose.yml         # Monitoring stack
```
## Common Issues & Solutions
### Import Errors
- โ `import tailscale-mcp` (hyphen is wrong!)
- โ
 `import tailscalemcp` (no hyphens!)
- โ `from tailscalemcp.tools.portmanteau_tools import TailscalePortmanteauTools` (wrong!)
- โ
 `from tailscalemcp.tools import TailscalePortmanteauTools` (correct!)
### Build Errors
- Use `uv sync --dev` not `pip install -r requirements.txt`
- Version must match in: pyproject.toml, __init__.py, manifest.json
- MCPB build from root: `mcpb pack . dist/...`
### Test Failures
- Mock httpx.AsyncClient, not internal functions
- Use correct function parameter names (check signature!)
- Add pytest markers to pytest.ini
## Version Management
When bumping version, update ALL of:
1. `pyproject.toml` - version field
2. `src/tailscalemcp/__init__.py` - __version__
3. `manifest.json` - version field  
4. `CHANGELOG.md` - Add release notes
## Documentation Standards
### Required Documentation Files
**Every MCP Repository MUST Have:**
1. **README.md** (Root)
   - Clear 1-2 sentence description
   - Features list
   - Installation instructions (tested!)
   - Quick start example (tested!)
   - Links to detailed docs
   - License info
2. **CHANGELOG.md** (Root)
   - Exists and maintained
   - Last 3+ versions documented
   - Follows semantic versioning
3. **docs/** (Directory)
   - `integration-guide.md` - Claude Desktop setup
   - `architecture.md` - System design
   - `tools-reference.md` - Complete tool list
   - `configuration.md` - Settings, env vars
   - `troubleshooting.md` - Common issues
   - `examples/` - Working examples
### Documentation Structure
```
tailscale-mcp/
โโโ README.md (overview, quick start)
โโโ CHANGELOG.md (version history)
โโโ LICENSE
โโโ docs/
โ   โโโ integration-guide.md (Claude Desktop setup)
โ   โโโ architecture.md (system design)
โ   โโโ tools-reference.md (complete tool list)
โ   โโโ configuration.md (settings, env vars)
โ   โโโ troubleshooting.md (common issues)
โ   โโโ examples/ (working examples)
โโโ docs-private/ (internal dev notes - git-ignored)
```
### Documentation Quality Standards
#### **Scoring System (0-10)**
- **0-3: Critical** - Barely usable, major gaps  
- **4-6: Needs Work** - Functional but incomplete  
- **7-8: Good** - Solid, few gaps  
- **9-10: Excellent** - World-class, reference quality
#### **Quality Criteria**
- **Complete (0-3 points)**: All aspects documented, no TODOs, complete coverage
- **Clear (0-2 points)**: Written for target audience, concrete examples
- **Correct (0-2 points)**: Up-to-date, examples work, accurate technical details
- **Professional (0-2 points)**: Polished writing, good formatting, consistent style
- **Discoverable (0-1 point)**: Easy navigation, good cross-references
### Documentation Maintenance
- Keep docs/ updated for new features
- Update README.md with new capabilities
- Create/update docs for monitoring stack
- Update CHANGELOG.md for releases
- Test all examples before committing
- No TODOs in public docs
## Git & Development Workflow
### Commit Message Conventions
Follow conventional commits format:
```
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
```
**Types:**
- `feat`: New feature
- `fix`: Bug fix
- `docs`: Documentation changes
- `style`: Code style changes (formatting, etc.)
- `refactor`: Code refactoring
- `test`: Adding or updating tests
- `chore`: Maintenance tasks
- `ci`: CI/CD changes
- `perf`: Performance improvements
- `build`: Build system changes
**Examples:**
```
feat(device): add device authorization tool
fix(monitoring): resolve Grafana dashboard loading issue
docs(api): update MCP tool documentation
test(coverage): improve test coverage to 80%
```
### Branch Naming Patterns
- **Feature branches**: `feature/description` (e.g., `feature/device-auth-tool`)
- **Bug fixes**: `fix/description` (e.g., `fix/monitoring-dashboard`)
- **Hotfixes**: `hotfix/description` (e.g., `hotfix/critical-security-patch`)
- **Documentation**: `docs/description` (e.g., `docs/api-reference-update`)
- **Refactoring**: `refactor/description` (e.g., `refactor/portmanteau-tools`)
### Code Review Requirements
- **Minimum reviewers**: 1 (preferably 2 for critical changes)
- **Required checks**: All CI checks must pass
- **Documentation**: Update docs for new features/changes
- **Testing**: Include tests for new functionality
- **Breaking changes**: Must be clearly documented
### Documentation Standards
- **README.md**: Keep updated with new capabilities
- **API docs**: Document all MCP tools with examples
- **Architecture docs**: Update for significant changes
- **Changelog**: Document all user-facing changes
- **Code comments**: Explain complex logic and business rules
### Development Workflow
1. **Create feature branch**: `git checkout -b feature/description`
2. **Make changes**: Follow coding standards and add tests
3. **Run checks locally**:
   ```powershell
   uv run ruff check .
   uv run ruff format .
   uv run pytest --cov=tailscalemcp
   ```
4. **Commit changes**: Use conventional commit format
5. **Push and create PR**: Include description and link issues
6. **Code review**: Address feedback and ensure CI passes
7. **Merge**: Squash commits for clean history
### Git Best Practices
- **Small commits**: One logical change per commit
- **Descriptive messages**: Clear, concise commit descriptions
- **Atomic changes**: Each commit should be complete and working
- **Rebase before merge**: Keep history clean and linear
- **Protect main branch**: Require PR reviews and CI checks
- **Tag releases**: Use semantic versioning (v1.0.0, v2.1.3, etc.)
### Pre-commit Checklist
- [ ] Code follows style guidelines (ruff check passes)
- [ ] Tests pass and coverage meets requirements
- [ ] Documentation updated for new features
- [ ] Changelog updated for user-facing changes
- [ ] Version numbers synchronized across files
- [ ] No sensitive data in commits (API keys, passwords)
### Documentation Quality Checklist
#### Before Marking Docs as "Complete":
**README.md:**
- [ ] Clear 1-2 sentence description
- [ ] Features list
- [ ] Installation instructions work (tested!)
- [ ] Quick start example works (tested!)
- [ ] Links to detailed docs
- [ ] License info
**CHANGELOG.md:**
- [ ] Exists
- [ ] Last 3+ versions documented
- [ ] Follows semantic versioning
**docs/integration-guide.md:**
- [ ] Claude Desktop config shown
- [ ] First steps clear
- [ ] Common operations documented
- [ ] Troubleshooting section
**docs/architecture.md:**
- [ ] Components explained
- [ ] Data flow clear
- [ ] Dependencies listed
**docs/tools-reference.md:**
- [ ] All tools documented
- [ ] Parameters explained
- [ ] Return values shown
- [ ] Examples provided
**General:**
- [ ] No TODOs in public docs
- [ ] All examples tested
- [ ] Links work
- [ ] Grammar/spelling checked
- [ ] Formatted properly
- [ ] Up-to-date with code
### Success Criteria
**Good Documentation (7-8/10):**
- All required files present
- Installation and quick start work
- Main features documented
- Examples provided
**Excellent Documentation (9-10/10):**
- Comprehensive coverage
- Multiple examples per feature
- Architecture explained
- Troubleshooting guide
- Contributes to community
- Used as reference by others
## AI Assistant Guidelines
- Be systematic and thorough
- Fix errors, don't just disable
- Test locally before committing
- Update documentation when making changes
- Keep version numbers synchronized
- Use UV for all Python operations
- Make workflows resilient with continue-on-error
## Monitoring Documentation Standards
### **MaaS - Monitoring as a Service**
- **Documentation**: Comprehensive MaaS concept and implementation
- **Alternatives**: Analysis of existing MaaS providers
- **Implementation**: Step-by-step implementation strategy
- **Business Model**: Revenue streams and cost structure
- **Market Analysis**: Target market and competitive advantages
### **Unified Monitoring Stack**
- **Architecture**: Single monitoring stack for all repositories
- **Configuration**: Unified configuration files and scripts
- **Deployment**: Step-by-step deployment guide
- **Integration**: Tailnet and RebootX integration
- **Scaling**: Horizontal scaling strategies
### **RebootX Integration**
- **Mobile Monitoring**: iPad app for infrastructure monitoring
- **On-Premises**: Self-hosted RebootX solution
- **Grafana Integration**: Direct connection to Grafana dashboards
- **Setup Guide**: Installation and configuration instructions
- **Use Cases**: Home infrastructure and small business monitoring
### **Monitoring Stack Ports**
- **Grafana**: Port 3000 for dashboards
- **Prometheus**: Port 9090 for metrics
- **Loki**: Port 3100 for logs
- **Promtail**: Port 9080 for log collection
- **RebootX On-Prem**: Port 8080 for mobile monitoring
### **Monitoring Documentation Requirements**
- **Setup Guides**: Step-by-step installation instructions
- **Configuration**: Environment variables and settings
- **Dashboard Documentation**: Purpose and usage of each dashboard
- **Alert Configuration**: Alert rules and notification setup
- **Troubleshooting**: Common monitoring issues and solutions
- **Performance Tuning**: Optimization guidelines
## Portmanteau Tools
This repo uses the portmanteau pattern with 10 consolidated tools:
1. `tailscale_device` - Device & User Management
2. `tailscale_network` - DNS & Network Management
3. `tailscale_monitor` - Monitoring & Metrics
4. `tailscale_file` - Taildrop File Sharing
5. `tailscale_security` - Security & Compliance
6. `tailscale_automation` - Workflow Automation
7. `tailscale_backup` - Backup & Recovery
8. `tailscale_performance` - Performance Monitoring
9. `tailscale_reporting` - Advanced Reporting
10. `tailscale_integration` - Third-party Integrations