Skip to main content
Glama
nakad-pixel

GitHub MCP Control Plane

by nakad-pixel
README.md
# GitHub MCP Control Plane

A production-ready, enterprise-grade GitHub MCP (Model Context Protocol) server deployed on Cloudflare Workers with zero-idle cost, comprehensive security validation, and full audit trails.

## Overview

This MCP server provides secure, controlled access to GitHub operations through the Model Context Protocol. It implements a stateless request/response model with enterprise-grade security features including:

- **Multi-layer Security**: Secret detection, vulnerability scanning, RBAC, and policy enforcement
- **Full Audit Trail**: Every action logged with correlation IDs for complete traceability
- **Rate Limiting**: Distributed rate limiting using Cloudflare KV
- **Batch Operations**: Handle 100+ files in a single commit
- **Delegation**: Heavy tasks delegated to GitHub Actions for optimal performance
- **Idempotent Operations**: Built-in retry logic with exponential backoff

## Architecture

```
┌─────────────┐
│   Client    │
└──────┬──────┘
       │ MCP Request
       ▼
┌─────────────────────────────────────┐
│  Cloudflare Worker (Stateless)     │
│  ┌───────────────────────────────┐  │
│  │  Entry Point & Routing       │  │
│  └──────────────┬────────────────┘  │
│                 ▼                    │
│  ┌───────────────────────────────┐  │
│  │  Authentication & Authorization│ │
│  └──────────────┬────────────────┘  │
│                 ▼                    │
│  ┌───────────────────────────────┐  │
│  │  Validation Pipeline           │  │
│  │  • Schema Validation           │  │
│  │  • Security Scanning           │  │
│  │  • Policy Enforcement          │  │
│  │  • Dependency Checking         │  │
│  └──────────────┬────────────────┘  │
│                 ▼                    │
│  ┌───────────────────────────────┐  │
│  │  Tool Execution               │  │
│  │  • Read-Only Tools            │  │
│  │  • Write-Controlled Tools     │  │
│  │  • Workflow Tools              │  │
│  └──────────────┬────────────────┘  │
│                 ▼                    │
│  ┌───────────────────────────────┐  │
│  │  Audit Logging & Response     │  │
│  └──────────────┬────────────────┘  │
└─────────────────┼────────────────────┘
                  │
        ┌─────────┴─────────┐
        ▼                   ▼
┌───────────────┐   ┌──────────────┐
│ GitHub API    │   │ GitHub       │
│               │   │ Actions      │
└───────────────┘   └──────────────┘
```

## Quick Start

### Prerequisites

- Node.js 18+
- Wrangler CLI
- GitHub Personal Access Token with appropriate permissions
- Cloudflare account with Workers and KV enabled

### Installation

```bash
# Install dependencies
npm install

# Configure Wrangler
wrangler login

# Set required secrets
wrangler secret put GITHUB_TOKEN
wrangler secret put GITHUB_WEBHOOK_SECRET
wrangler secret put JWT_SECRET
wrangler secret put ENCRYPTION_KEY

# Validate configuration
npm run validate-config

# Deploy to production
npm run deploy
```

### Local Development

```bash
# Start local development server
npm run dev

# The worker will be available at http://localhost:8787
```

## Configuration

### Environment Variables

See `.env.example` for all available configuration options.

### Tool Manifest

Configure available tools in `src/config/tools-manifest.json`:

```json
{
  "tools": [
    {
      "name": "list_repositories",
      "category": "read-only",
      "description": "List repositories accessible to the authenticated user",
      "requiredPermissions": ["read:org", "repo"]
    }
  ]
}
```

### Policy Rules

Define authorization policies in `src/config/policy-rules.json`:

```json
{
  "policies": [
    {
      "name": "write-restrictions",
      "tools": ["create_branch", "create_commit"],
      "conditions": {
        "repository": {
          "allowedPatterns": ["*"],
          "blockedPatterns": ["protected-*"]
        },
        "branch": {
          "blockedPatterns": ["main", "master", "production"]
        }
      }
    }
  ]
}
```

## Security Features

### 1. Authentication

- JWT token validation
- GitHub permission verification
- Token expiration handling

### 2. Authorization

- RBAC with fine-grained permissions
- Repository-level access control
- Branch protection rules

### 3. Validation

- JSON schema validation for all requests
- Secret detection (regex + entropy analysis)
- Dependency vulnerability checking via OSV.dev
- Code policy enforcement

### 4. Rate Limiting

- Distributed rate limiting with Cloudflare KV
- Configurable windows and thresholds
- Per-client rate tracking

### 5. Audit Trail

- Every action logged with correlation ID
- Structured JSON logging
- Configurable retention period

## Available Tools

### Read-Only Tools

- `list_repositories` - List accessible repositories
- `fetch_file` - Fetch file contents from a repository
- `list_files` - List files in a directory
- `get_repository_info` - Get repository metadata

### Write-Controlled Tools

- `create_branch` - Create a new branch
- `create_commit` - Create commits with file changes
- `batch_create_commits` - Handle 100+ files in batch operations

### Workflow Tools

- `trigger_workflow` - Trigger GitHub Actions workflows
- `get_workflow_status` - Check workflow execution status
- `get_workflow_logs` - Fetch workflow execution logs

## API Reference

See [docs/API.md](docs/API.md) for detailed API documentation.

## Deployment

### Production Deployment

```bash
# Deploy to production
npm run deploy

# Deploy to staging
wrangler deploy --env staging
```

### GitHub Actions Integration

For long-running tasks, the worker delegates to GitHub Actions. Configure:

1. Add workflow file to your repository (`.github/workflows/execution-handler.yml`)
2. Set `GITHUB_WEBHOOK_SECRET` in your repository settings
3. Configure the worker URL in workflow dispatch

See [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md) for complete deployment guide.

## Monitoring

### Health Check

```bash
curl https://your-worker-url.workers.dev/health
```

Expected response:

```json
{
  "status": "healthy",
  "timestamp": "2024-01-01T00:00:00Z",
  "version": "1.0.0"
}
```

### Logs

All logs are emitted in structured JSON format:

```json
{
  "level": "info",
  "message": "Request received",
  "correlationId": "abc-123",
  "tool": "list_repositories",
  "userId": "user-123",
  "timestamp": "2024-01-01T00:00:00Z"
}
```

## Testing

```bash
# Run all tests
npm test

# Run tests with coverage
npm run test:coverage

# Run specific test file
npx vitest tests/unit/auth.test.js
```

## Error Handling

All errors follow a consistent format:

```json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request payload",
    "details": [
      {
        "field": "repository",
        "message": "Repository name is required"
      }
    ],
    "correlationId": "abc-123"
  }
}
```

## Security Considerations

1. **Never commit secrets** - Use Wrangler secrets for all sensitive data
2. **Use principle of least privilege** - GitHub tokens should have minimal required permissions
3. **Enable audit logging** - Track all operations for compliance
4. **Regular secret rotation** - Rotate JWT and encryption keys regularly
5. **Monitor rate limits** - Set appropriate thresholds to prevent abuse

## Troubleshooting

### Common Issues

**Worker returns 401 Unauthorized**
- Check GITHUB_TOKEN is set correctly
- Verify token has required permissions
- Check token hasn't expired

**Rate limit errors**
- Review rate limiting configuration
- Check KV namespace is properly configured
- Monitor usage patterns

**Validation failures**
- Review validation logs for specific errors
- Check schema definitions in tools-manifest.json
- Verify secret patterns in secret-patterns.json

## Contributing

Contributions are welcome! Please ensure:

1. All tests pass
2. Code follows existing patterns and style
3. New features include tests
4. Documentation is updated

## License

MIT License - see LICENSE file for details

## Support

For issues and questions:
- GitHub Issues: [repository-url]/issues
- Documentation: [docs/](docs/)