Skip to content

API - Usage Examples

This document provides comprehensive examples for using the AI Security Gateway API.

📘 Documentation Scope: This guide covers the 20 most commonly used API endpoints for command-line and scripting workflows. Complete API reference with all 150+ endpoints will be added in future releases.

API Authentication for Clients

All API endpoints require authentication (except health checks and OAuth flow endpoints). This section shows how to obtain and use authentication tokens for command-line and scripting use.

Quick Start: Admin Login

bash
# Step 1: Login with admin credentials to get JWT token
JWT_TOKEN=$(curl -s -X POST http://localhost:8080/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"yourpassword"}' | jq -r '.data.token')

# Step 2: Use token in all API requests
curl -s -H "Authorization: Bearer $JWT_TOKEN" \
  http://localhost:8080/api/v1/dashboard | jq

Authentication Methods

For API users, you only need the resulting token. Choose one method:

bash
# Login to get JWT token
curl -X POST http://localhost:8080/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"admin"}' | jq

# Response:
{
  "success": true,
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "user": {
      "id": 1,
      "username": "admin",
      "role": "admin"
    },
    "expires_at": "2026-02-04T12:00:00Z"
  }
}

# Save token for reuse
export JWT_TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

Option 2: OAuth Session Token (For OAuth Users)

bash
# Navigate to web UI and login via OAuth provider
open http://localhost:8080/

# After OAuth login, extract session token from:
# - Browser localStorage: localStorage.getItem('session_token')
# - Or from OAuth callback response

# Use identically to JWT tokens
export JWT_TOKEN="<oauth-session-token>"

curl -s -H "Authorization: Bearer $JWT_TOKEN" \
  http://localhost:8080/api/v1/proxies/ | jq

Option 3: API Key (For Service Accounts)

bash
# Create API key via admin endpoint or web UI
# Then use with X-API-Key header

curl -s -H "X-API-Key: YOUR_API_KEY" \
  http://localhost:8080/api/v1/proxies/ | jq

See Also:


Server Setup (For Administrators Only)

Note: This section is for administrators setting up the server. API clients do NOT need these environment variables.

bash
# REQUIRED: JWT token signing secret (server-side only)
export JWT_SECRET="your-secure-jwt-secret-min-32-chars"

# REQUIRED: OAuth provider secrets encryption key (server-side only)
export ENCRYPTION_KEY="your-32-character-encryption-key"

# Generate secure values:
export JWT_SECRET=$(openssl rand -base64 32)
export ENCRYPTION_KEY=$(openssl rand -base64 32 | cut -c1-32)

# Optional: OAuth provider configuration (if using OAuth)
export OAUTH_GITHUB_CLIENT_ID="your-github-client-id"
export OAUTH_GITHUB_CLIENT_SECRET="your-github-client-secret"

Starting the Server (Administrator Setup)

Note: This section is for administrators. API clients only need a token (see Authentication section above).

bash
# Ensure required environment variables are set
export JWT_SECRET=$(openssl rand -base64 32)
export ENCRYPTION_KEY=$(openssl rand -base64 32 | cut -c1-32)

# Start the unified admin server (port 8080 by default)
./build/unified-admin

# Or with custom port
./build/unified-admin -addr :9090

Example Core Endpoints

Note: All examples below assume $JWT_TOKEN is set with a valid JWT token from OAuth authentication.

Health & Dashboard

bash
# Health check (public endpoint, no auth required)
curl -s http://localhost:8080/api/v1/health | jq

# Get dashboard metrics (requires auth)
curl -s http://localhost:8080/api/v1/dashboard \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

MCP Vulnerability Scanning

Start a Vulnerability Scan

bash
# Start scan for a configured MCP proxy
curl -X POST http://localhost:8080/api/v1/mcp/scan \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "proxy_id": 1,
    "policy": "critical-security"
  }' | jq

# Start scan for a custom URL
curl -X POST http://localhost:8080/api/v1/mcp/scan \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "target_url": "http://example.com/mcp",
    "policy": "critical-security"
  }' | jq

Check Scan Status

bash
# Get scan status
curl -s http://localhost:8080/api/v1/mcp/scan/123 \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Get latest scan result
curl -s "http://localhost:8080/api/v1/mcp/scan/latest?proxy_id=1" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

Get Scan Results

bash
# Get full scan result
curl -s http://localhost:8080/api/v1/mcp/scan/123/result \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Download PDF report
curl -s http://localhost:8080/api/v1/mcp/scan/123/pdf \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -o scan_report.pdf

MCP Rug Pull Detection

Get Tool Changes

bash
# Get tool change history for a proxy
curl -s "http://localhost:8080/api/v1/mcp/tools/1/changes?limit=50" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Get tool baseline
curl -s http://localhost:8080/api/v1/mcp/tools/1/baseline \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

Manually Trigger Change Detection

bash
# Detect tool changes for a proxy
curl -X POST http://localhost:8080/api/v1/mcp/tools/1/detect-changes \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

Export Dashboard Data

bash
# Export dashboard data (requires auth)
curl -s http://localhost:8080/api/v1/dashboard/export \
  -H "Authorization: Bearer $JWT_TOKEN" | jq > dashboard.json

Multi-Proxy Management

List & Filter Proxies

bash
# List all proxy configurations
curl -s http://localhost:8080/api/v1/proxies/ \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Filter by type
curl -s "http://localhost:8080/api/v1/proxies/?type=mcp" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq
curl -s "http://localhost:8080/api/v1/proxies/?type=llm" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Filter by enabled status
curl -s "http://localhost:8080/api/v1/proxies/?enabled=true" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Search proxies
curl -s "http://localhost:8080/api/v1/proxies/?search=production" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

Create Proxy Configurations

bash
# Create MCP proxy
curl -s -X POST http://localhost:8080/api/v1/proxies/ \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "production-mcp",
    "type": "mcp",
    "transport": "http",
    "description": "Production MCP server proxy",
    "target": "http://localhost:3000",
    "port": 8081,
    "enabled": true,
    "auto_start": false,
    "policy_names": ["critical-security", "mcp-advanced-security"],
    "tags": ["production", "main"]
  }' | jq

# Create LLM proxy
curl -s -X POST http://localhost:8080/api/v1/proxies/ \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "openai-gpt4",
    "type": "llm",
    "transport": "http",
    "description": "OpenAI GPT-4 API proxy",
    "target": "https://api.openai.com",
    "port": 8082,
    "enabled": true,
    "auto_start": true,
    "policy_names": ["llm-security"],
    "tags": ["openai", "gpt-4"]
  }' | jq

Manage Proxy Configuration

bash
# Get specific proxy (requires authentication)
curl -s http://localhost:8080/api/v1/proxies/1 \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Update proxy configuration (requires admin authentication)
curl -s -X PUT http://localhost:8080/api/v1/proxies/1 \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "production-mcp-updated",
    "enabled": true,
    "auto_start": true,
    "description": "Updated description"
  }' | jq

# Delete proxy (requires admin authentication)
curl -s -X DELETE http://localhost:8080/api/v1/proxies/1 \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

Proxy Lifecycle Control Examples

bash
# Start proxy (requires admin authentication)
curl -s -X POST http://localhost:8080/api/v1/proxies/1/start \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Stop proxy (requires admin authentication)
curl -s -X POST http://localhost:8080/api/v1/proxies/1/stop \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Restart proxy (requires admin authentication)
curl -s -X POST http://localhost:8080/api/v1/proxies/1/restart \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Get proxy status (requires authentication)
curl -s http://localhost:8080/api/v1/proxies/1/status \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Get all proxy statuses (requires authentication)
curl -s http://localhost:8080/api/v1/proxies/status \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

Proxy Monitoring

bash
# Get request logs (last 100) (requires authentication)
curl -s "http://localhost:8080/api/v1/proxies/1/logs?limit=100" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Get statistics (last 24 hours) (requires authentication)
curl -s "http://localhost:8080/api/v1/proxies/1/stats?hours=24" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Get statistics for last week (requires authentication)
curl -s "http://localhost:8080/api/v1/proxies/1/stats?hours=168" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

Policy Management Examples

Assign Policies to Proxies

bash
# Get assigned and available policies (requires authentication)
curl -s http://localhost:8080/api/v1/proxies/1/policies \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Assign multiple policies (requires admin authentication)
curl -s -X POST http://localhost:8080/api/v1/proxies/1/policies \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "policy_names": ["critical-security", "mcp-advanced-security"]
  }' | jq

# Add single policy (requires admin authentication)
curl -s -X PUT http://localhost:8080/api/v1/proxies/1/policies/standard-security \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Remove policy (requires admin authentication)
curl -s -X DELETE http://localhost:8080/api/v1/proxies/1/policies/standard-security \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

MCP Tool Management Examples

🔒 Security Note: All discovered tools are disabled by default. After discovery, you must explicitly enable each tool.

bash
# List tools for MCP proxy (requires authentication)
curl -s http://localhost:8080/api/v1/proxies/1/tools \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Discover tools from MCP server (requires admin authentication, all will be disabled by default)
curl -s -X POST http://localhost:8080/api/v1/proxies/1/tools/discover \
  -H "Authorization: Bearer $JWT_TOKEN" | jq
# Note: All discovered tools have "enabled": false by default

# Enable a safe tool (requires admin authentication, required after discovery)
curl -s -X PUT http://localhost:8080/api/v1/proxies/1/tools/safe_calculator \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"enabled": true}' | jq

# Disable a dangerous tool (requires admin authentication, though already disabled by default)
curl -s -X PUT http://localhost:8080/api/v1/proxies/1/tools/execute_command \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"enabled": false}' | jq

# Bulk update tools (requires admin authentication)
curl -s -X PUT http://localhost:8080/api/v1/proxies/1/tools/bulk \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "tool_names": ["read_file", "write_file", "execute_command"],
    "enabled": false
  }' | jq

# Get tool statistics (requires authentication)
curl -s http://localhost:8080/api/v1/proxies/1/tools/stats \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

Token Usage (LLM Proxies)

bash
# Get token usage for last 30 days (default) (requires authentication)
curl -s "http://localhost:8080/api/v1/proxies/2/tokens" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Get token usage for last 7 days (requires authentication)
curl -s "http://localhost:8080/api/v1/proxies/2/tokens?days=7" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Get token usage for last 90 days (requires authentication)
curl -s "http://localhost:8080/api/v1/proxies/2/tokens?days=90" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# LLM dashboard with aggregate token usage (public endpoint)
curl -s http://localhost:8080/api/v1/llm/tokens | jq

Alert Management

Query Alerts

bash
# Get all alerts (default pagination) (requires authentication)
curl -s http://localhost:8080/api/v1/system/alerts \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Get critical alerts (requires authentication)
curl -s "http://localhost:8080/api/v1/system/alerts?severity=Critical" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Get critical and high severity alerts (requires authentication)
curl -s "http://localhost:8080/api/v1/system/alerts?severity=Critical,High" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Filter by proxy type (requires authentication)
curl -s "http://localhost:8080/api/v1/system/alerts?proxy_type=mcp" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq
curl -s "http://localhost:8080/api/v1/system/alerts?proxy_type=llm" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Filter by status (requires authentication)
curl -s "http://localhost:8080/api/v1/system/alerts?status=open" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq
curl -s "http://localhost:8080/api/v1/system/alerts?status=open,investigating" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Filter by policy name (requires authentication)
curl -s "http://localhost:8080/api/v1/system/alerts?policy_name=critical-security" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

Time-based Filtering

bash
# Last hour (requires authentication)
curl -s "http://localhost:8080/api/v1/system/alerts?time_range=1h" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Last 6 hours (requires authentication)
curl -s "http://localhost:8080/api/v1/system/alerts?time_range=6h" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Last 24 hours (requires authentication)
curl -s "http://localhost:8080/api/v1/system/alerts?time_range=24h" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Last 7 days (requires authentication)
curl -s "http://localhost:8080/api/v1/system/alerts?time_range=7d" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Last 30 days (requires authentication)
curl -s "http://localhost:8080/api/v1/system/alerts?time_range=30d" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Custom date range (requires authentication)
curl -s "http://localhost:8080/api/v1/system/alerts?date_from=2025-12-01&date_to=2025-12-31" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

Search & Sort

bash
# Search alerts (requires authentication)
curl -s "http://localhost:8080/api/v1/system/alerts?search=injection" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Sort by severity (descending) (requires authentication)
curl -s "http://localhost:8080/api/v1/system/alerts?sort=severity&order=desc" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Sort by date (ascending) (requires authentication)
curl -s "http://localhost:8080/api/v1/system/alerts?sort=created_at&order=asc" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

Pagination

bash
# Page 1, 20 results per page (default) (requires authentication)
curl -s "http://localhost:8080/api/v1/system/alerts?page=1" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Page 2, 50 results per page (requires authentication)
curl -s "http://localhost:8080/api/v1/system/alerts?page=2&limit=50" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Maximum 100 per page (requires authentication)
curl -s "http://localhost:8080/api/v1/system/alerts?limit=100" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

Update Alert Status

bash
# Mark as investigating (requires admin authentication)
curl -s -X PUT http://localhost:8080/api/v1/system/alerts/123/status \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"status": "investigating"}' | jq

# Mark as resolved (requires admin authentication)
curl -s -X PUT http://localhost:8080/api/v1/system/alerts/123/status \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"status": "resolved"}' | jq

# Mark as false positive (requires admin authentication)
curl -s -X PUT http://localhost:8080/api/v1/system/alerts/123/status \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"status": "false_positive"}' | jq

System Settings

Get & Update Settings

bash
# Get all settings
curl -s http://localhost:8080/api/v1/system/settings | jq

# Update settings
curl -s -X PUT http://localhost:8080/api/v1/system/settings \
  -H "Content-Type: application/json" \
  -d '{
    "general": {
      "system_name": "Production Gateway",
      "log_level": "info"
    },
    "security": {
      "threat_threshold": "medium",
      "auto_block": true
    }
  }' | jq

# Reset to defaults
curl -s -X POST http://localhost:8080/api/v1/system/settings/reset | jq

Export & Import

bash
# Export settings
curl -s http://localhost:8080/api/v1/system/settings/export > settings.json

# Import settings
curl -s -X POST http://localhost:8080/api/v1/system/settings/import \
  -H "Content-Type: application/json" \
  -d @settings.json | jq

Database Operations

Backup & Restore

bash
# Create backup
curl -s -X POST http://localhost:8080/api/v1/system/database/backup | jq

# List backups
curl -s http://localhost:8080/api/v1/system/database/backups | jq

# Download backup
curl -O http://localhost:8080/api/v1/system/backup/1/download

# Restore from backup
curl -s -X POST http://localhost:8080/api/v1/system/backup/1/restore | jq

# Verify backup
curl -s -X POST http://localhost:8080/api/v1/system/backup/1/verify | jq

# Delete backup
curl -s -X DELETE http://localhost:8080/api/v1/system/backup/1/delete | jq

Database Maintenance

bash
# Test connection
curl -s -X POST http://localhost:8080/api/v1/system/database/test | jq

# Optimize database
curl -s -X POST http://localhost:8080/api/v1/system/database/optimize | jq

Integration Testing

bash
# Test all integrations
curl -s -X POST http://localhost:8080/api/v1/system/integrations/test | jq

# Test SIEM
curl -s -X POST http://localhost:8080/api/v1/system/integrations/siem/test | jq

# Test Slack
curl -s -X POST http://localhost:8080/api/v1/system/integrations/slack/test | jq

# Test Email
curl -s -X POST http://localhost:8080/api/v1/system/integrations/email/test | jq

Policy Validation & Testing

Validate Policy

bash
curl -s -X POST http://localhost:8080/api/v1/policies/validate \
  -H "Content-Type: application/json" \
  -d '{
    "policy": {
      "policyName": "test-policy",
      "version": "1.0.3-beta",
      "policy_type": "mcp",
      "rules": [
        {
          "id": "TEST_001",
          "name": "Test Rule",
          "patterns": ["test.*pattern"],
          "severity": "Medium"
        }
      ]
    }
  }' | jq

Test Policy Against Content

bash
curl -s -X POST http://localhost:8080/api/v1/policies/test \
  -H "Content-Type: application/json" \
  -d '{
    "policy": {
      "policyName": "injection-test",
      "rules": [...]
    },
    "test_content": [
      "safe code here",
      "dangerous code with injection"
    ]
  }' | jq

Analyze Patterns

bash
curl -s -X POST http://localhost:8080/api/v1/policies/patterns/analyze \
  -H "Content-Type: application/json" \
  -d '{
    "patterns": [
      "exec\\s*\\(",
      "system\\s*\\(",
      ".*injection.*"
    ]
  }' | jq

Policy Performance

bash
# Get overall performance metrics
curl -s http://localhost:8080/api/v1/policies/performance | jq

# Get metrics for specific policy
curl -s http://localhost:8080/api/v1/policies/critical-security/metrics | jq

# Get compiled engine status
curl -s http://localhost:8080/api/v1/policies/compiled/status | jq

# Recompile all policies
curl -s -X POST http://localhost:8080/api/v1/policies/compiled/recompile | jq

# Recompile specific policy
curl -s -X POST http://localhost:8080/api/v1/policies/compiled/critical-security/recompile | jq

System Information

bash
# Get system info (CPU, memory, disk, uptime)
curl -s http://localhost:8080/api/v1/system/info | jq

# Download system logs
curl -O http://localhost:8080/api/v1/system/logs/download

Complex Workflow Examples

Complete Proxy Setup Workflow

bash
# 1. Create proxy configuration
PROXY_ID=$(curl -s -X POST http://localhost:8080/api/v1/proxies/ \
  -H "Content-Type: application/json" \
  -d '{
    "name": "new-mcp-proxy",
    "type": "mcp",
    "target": "http://localhost:3000",
    "port": 8081,
    "enabled": true
  }' | jq -r '.data.id')

# 2. Assign security policies
curl -s -X POST http://localhost:8080/api/v1/proxies/$PROXY_ID/policies \
  -H "Content-Type: application/json" \
  -d '{"policy_names": ["critical-security", "mcp-advanced-security"]}' | jq

# 3. Start the proxy
curl -s -X POST http://localhost:8080/api/v1/proxies/$PROXY_ID/start | jq

# 4. Verify it's running
curl -s http://localhost:8080/api/v1/proxies/$PROXY_ID/status | jq

Alert Monitoring Workflow

bash
# 1. Get critical alerts from last hour
curl -s "http://localhost:8080/api/v1/system/alerts?severity=Critical&time_range=1h" | jq

# 2. Update alert status to investigating
curl -s -X PUT http://localhost:8080/api/v1/system/alerts/123/status \
  -H "Content-Type: application/json" \
  -d '{"status": "investigating"}' | jq

# 3. Get related alerts by policy
curl -s "http://localhost:8080/api/v1/system/alerts?policy_name=critical-security&status=open" | jq

Maintenance Workflow

bash
# 1. Create database backup
curl -s -X POST http://localhost:8080/api/v1/system/database/backup | jq

# 2. Optimize database
curl -s -X POST http://localhost:8080/api/v1/system/database/optimize | jq

# 3. Test all integrations
curl -s -X POST http://localhost:8080/api/v1/system/integrations/test | jq

# 4. Export settings
curl -s http://localhost:8080/api/v1/system/settings/export > settings-backup.json

WebSocket Real-Time Notifications

javascript
// Connect to WebSocket for real-time updates
// Note: Authentication via JWT token in query parameter or initial message
const token = 'your-jwt-token-here';
const ws = new WebSocket(`ws://localhost:8080/ws?token=${token}`);

ws.onopen = () => {
  console.log('Connected to WebSocket');
  
  // Alternative: Send authentication message after connection
  // ws.send(JSON.stringify({ type: 'auth', token: token }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Received:', data);

  // Handle different notification types
  switch (data.type) {
    case 'new_alert':
      console.log('New security alert:', data.payload);
      break;
    case 'proxy_status':
      console.log('Proxy status update:', data.payload);
      break;
    case 'tool_discovered':
      console.log('New MCP tool discovered:', data.payload);
      break;
    case 'token_usage':
      console.log('LLM token usage update:', data.payload);
      break;
    default:
      console.log('Unknown notification type:', data.type);
  }
};

ws.onerror = (error) => {
  console.error('WebSocket error:', error);
};

ws.onclose = (event) => {
  console.log('WebSocket connection closed:', event.code, event.reason);
  
  // Implement reconnection logic
  setTimeout(() => {
    console.log('Attempting to reconnect...');
    // Recreate WebSocket connection
  }, 5000);
};

WebSocket Notification Types

The WebSocket connection sends real-time notifications for:

  • new_alert: Security alert triggered by a proxy
  • proxy_status: Proxy start/stop/restart events
  • tool_discovered: New MCP tool enumerated
  • token_usage: LLM token consumption update
  • user_activity: OAuth user login/logout events
  • system_event: System-level events (backup complete, settings changed)

OAuth User Access Control

OAuth User Management

bash
# List all OAuth users
curl -s http://localhost:8080/api/v1/oauth/users | jq

# List with pagination
curl -s "http://localhost:8080/api/v1/oauth/users?page=1&page_size=20" | jq

# Filter by user group
curl -s "http://localhost:8080/api/v1/oauth/users?group_id=5" | jq

# Filter by OAuth provider
curl -s "http://localhost:8080/api/v1/oauth/users?provider_id=2" | jq

# Filter by role
curl -s "http://localhost:8080/api/v1/oauth/users?role=admin" | jq

# Search by email or name
curl -s "http://localhost:8080/api/v1/oauth/users?search=alice@company.com" | jq

# Filter active users only
curl -s "http://localhost:8080/api/v1/oauth/users?active=true" | jq

# Combined filters
curl -s "http://localhost:8080/api/v1/oauth/users?group_id=5&role=user&active=true&page=1" | jq

# Get specific user by ID
curl -s http://localhost:8080/api/v1/oauth/users/123 | jq

# Get user by identity (email)
curl -s http://localhost:8080/api/v1/oauth/users/identity/alice@company.com | jq

# Get OAuth user statistics
curl -s http://localhost:8080/api/v1/oauth/users/stats | jq

Response Example:

json
{
  "success": true,
  "data": {
    "users": [
      {
        "id": 1,
        "user_identity": "alice@company.com",
        "user_email": "alice@company.com",
        "user_name": "Alice Smith",
        "user_role": "user",
        "user_group_id": 5,
        "org_domain": "company.com",
        "provider_id": 2,
        "active": true,
        "last_login_at": "2025-12-04T10:30:00Z",
        "created_at": "2025-11-01T08:00:00Z",
        "updated_at": "2025-12-04T10:30:00Z",
        "user_group": {
          "id": 5,
          "name": "Engineering Team",
          "description": "Engineers with production access",
          "active": true
        },
        "provider": {
          "id": 2,
          "provider_type": "github",
          "provider_name": "GitHub OAuth"
        }
      }
    ],
    "total": 45,
    "page": 1,
    "page_size": 20
  }
}

Update OAuth Users

bash
# Update user's group assignment and role
curl -s -X PUT http://localhost:8080/api/v1/oauth/users/123 \
  -H "Content-Type: application/json" \
  -d '{
    "user_group_id": 5,
    "user_role": "power_user"
  }' | jq

# Deactivate user (soft delete)
curl -s -X DELETE http://localhost:8080/api/v1/oauth/users/123 | jq

# Reactivate user
curl -s -X POST http://localhost:8080/api/v1/oauth/users/123/activate | jq

# Bulk update user groups (assign multiple users to a group)
curl -s -X POST http://localhost:8080/api/v1/oauth/users/bulk/group \
  -H "Content-Type: application/json" \
  -d '{
    "user_ids": [123, 124, 125],
    "user_group_id": 5
  }' | jq

User Group Assignment Rules

bash
# List all user group rules (requires admin authentication)
curl -s http://localhost:8080/api/v1/oauth/rules \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Filter by user group (requires admin authentication)
curl -s "http://localhost:8080/api/v1/oauth/rules?group_id=5" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Filter by rule type (requires admin authentication)
curl -s "http://localhost:8080/api/v1/oauth/rules?rule_type=email_domain" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Filter by OAuth provider (requires admin authentication)
curl -s "http://localhost:8080/api/v1/oauth/rules?provider_id=2" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Filter active rules only (requires admin authentication)
curl -s "http://localhost:8080/api/v1/oauth/rules?active=true" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Search rules (requires admin authentication)
curl -s "http://localhost:8080/api/v1/oauth/rules?search=company.com" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Get specific rule (requires admin authentication)
curl -s http://localhost:8080/api/v1/oauth/rules/10 \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Get rule statistics (requires admin authentication)
curl -s http://localhost:8080/api/v1/oauth/rules/stats \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

Response Example:

json
{
  "success": true,
  "data": {
    "rules": [
      {
        "id": 10,
        "user_group_id": 5,
        "rule_type": "email_domain",
        "rule_value": "company.com",
        "provider_id": null,
        "priority": 10,
        "active": true,
        "description": "Auto-assign company employees to Engineering Team",
        "created_at": "2025-11-15T08:00:00Z",
        "updated_at": "2025-12-04T08:00:00Z",
        "user_group": {
          "id": 5,
          "name": "Engineering Team",
          "description": "Engineers with production access",
          "active": true
        }
      }
    ],
    "total": 8,
    "page": 1,
    "page_size": 20
  }
}

Create & Manage User Group Rules

bash
# Create email domain rule (auto-assign @company.com to Engineering Team) (requires admin authentication)
curl -s -X POST http://localhost:8080/api/v1/oauth/rules \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "user_group_id": 5,
    "rule_type": "email_domain",
    "rule_value": "company.com",
    "priority": 10,
    "active": true,
    "description": "Auto-assign company employees"
  }' | jq

# Create email pattern rule (regex matching) (requires admin authentication)
curl -s -X POST http://localhost:8080/api/v1/oauth/rules \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "user_group_id": 6,
    "rule_type": "email_pattern",
    "rule_value": "contractor-.*@company.com",
    "priority": 5,
    "active": true,
    "description": "Auto-assign contractors"
  }' | jq

# Create provider-based rule (all GitHub users) (requires admin authentication)
curl -s -X POST http://localhost:8080/api/v1/oauth/rules \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "user_group_id": 7,
    "rule_type": "provider",
    "rule_value": "github",
    "provider_id": 2,
    "priority": 8,
    "active": true,
    "description": "All GitHub OAuth users"
  }' | jq

# Create org domain rule (requires admin authentication)
curl -s -X POST http://localhost:8080/api/v1/oauth/rules \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "user_group_id": 8,
    "rule_type": "org_domain",
    "rule_value": "company.com",
    "priority": 7,
    "active": true,
    "description": "Match organization domain from OAuth metadata"
  }' | jq

# Update existing rule (requires admin authentication)
curl -s -X PUT http://localhost:8080/api/v1/oauth/rules/10 \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "rule_value": "newdomain.com",
    "priority": 15,
    "description": "Updated domain"
  }' | jq

# Update rule priority (requires admin authentication)
curl -s -X PUT http://localhost:8080/api/v1/oauth/rules/10/priority \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"priority": 20}' | jq

# Activate rule (requires admin authentication)
curl -s -X POST http://localhost:8080/api/v1/oauth/rules/10/activate \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Deactivate rule (requires admin authentication)
curl -s -X POST http://localhost:8080/api/v1/oauth/rules/10/deactivate \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Delete rule (requires admin authentication)
curl -s -X DELETE http://localhost:8080/api/v1/oauth/rules/10 \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Bulk create rules (requires admin authentication)
curl -s -X POST http://localhost:8080/api/v1/oauth/rules/bulk \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "rules": [
      {
        "user_group_id": 5,
        "rule_type": "email_domain",
        "rule_value": "company.com",
        "priority": 10,
        "active": true
      },
      {
        "user_group_id": 6,
        "rule_type": "email_domain",
        "rule_value": "partner.com",
        "priority": 8,
        "active": true
      }
    ]
  }' | jq

# Bulk update priorities (requires admin authentication)
# Note: This endpoint may not be available - update priorities individually or via bulk update
curl -s -X PUT http://localhost:8080/api/v1/oauth/rules/10 \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"priority": 20}' | jq

Proxy OAuth Configuration

bash
# Get OAuth configuration for a specific proxy (requires admin authentication)
curl -s http://localhost:8080/api/v1/proxies/3/oauth \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Update proxy OAuth configuration (requires admin authentication)
curl -s -X PUT http://localhost:8080/api/v1/proxies/3/oauth \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "oauth_access_mode": "group_only",
    "oauth_require_group_assignment": true,
    "oauth_rate_limit_per_user": 60
  }' | jq

# Get list of OAuth users with access to proxy (requires admin authentication)
curl -s http://localhost:8080/api/v1/proxies/3/oauth/users \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Test if a specific user can access the proxy (requires admin authentication)
curl -s -X POST http://localhost:8080/api/v1/proxies/3/oauth/test \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"user_identity": "alice@company.com"}' | jq

Proxy OAuth Config Response:

json
{
  "success": true,
  "data": {
    "proxy_id": 3,
    "proxy_name": "Production MCP Proxy",
    "oauth_access_mode": "group_only",
    "oauth_require_group_assignment": true,
    "oauth_rate_limit_per_user": 60,
    "allowed_user_groups": [
      {
        "id": 5,
        "name": "Engineering Team",
        "user_count": 12
      },
      {
        "id": 7,
        "name": "DevOps Team",
        "user_count": 8
      }
    ]
  }
}

OAuth Analytics

bash
# Get OAuth user analytics
curl -s http://localhost:8080/api/v1/oauth/analytics/users | jq

# Get user group rule analytics
curl -s http://localhost:8080/api/v1/oauth/analytics/rules | jq

# Get OAuth access patterns (with time range)
curl -s "http://localhost:8080/api/v1/oauth/analytics/access?time_range=24h" | jq
curl -s "http://localhost:8080/api/v1/oauth/analytics/access?time_range=7d" | jq

# Get OAuth provider distribution
curl -s http://localhost:8080/api/v1/oauth/analytics/providers | jq

# Get user group analytics
curl -s http://localhost:8080/api/v1/oauth/analytics/groups | jq

# Get OAuth activity timeline (last 7 days by default)
curl -s http://localhost:8080/api/v1/oauth/analytics/timeline | jq

# Get timeline for specific number of days
curl -s "http://localhost:8080/api/v1/oauth/analytics/timeline?days=30" | jq

OAuth User Analytics Response:

json
{
  "success": true,
  "data": {
    "total_users": 150,
    "active_users": 142,
    "inactive_users": 8,
    "users_without_group": 12,
    "by_role": {
      "user": 120,
      "power_user": 25,
      "admin": 5
    },
    "by_group": {
      "Engineering Team": 45,
      "QA Team": 22,
      "DevOps Team": 18,
      "Marketing Team": 35,
      "Unassigned": 12
    },
    "by_provider": {
      "github": 80,
      "google": 55,
      "okta": 15
    },
    "recent_logins_24h": 98,
    "new_users_7d": 12
  }
}

OAuth Access Analytics Response:

json
{
  "success": true,
  "data": {
    "time_range": "24h",
    "total_access_attempts": 5420,
    "successful_access": 5200,
    "denied_access": 220,
    "rate_limited": 45,
    "by_proxy": {
      "Production MCP Proxy": {
        "attempts": 2100,
        "allowed": 2050,
        "denied": 50
      },
      "Dev LLM Proxy": {
        "attempts": 3320,
        "allowed": 3150,
        "denied": 170
      }
    },
    "denial_reasons": {
      "no_group_assignment": 120,
      "group_lacks_access": 75,
      "user_inactive": 25
    }
  }
}

Complete OAuth Setup Workflow

bash
# Step 1: Create a user group (requires admin authentication)
curl -s -X POST http://localhost:8080/api/v1/user-groups \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Engineering Team",
    "description": "Engineers with production access",
    "active": true
  }' | jq

# Step 2: Assign proxy access to the user group (requires admin authentication)
curl -s -X POST http://localhost:8080/api/v1/user-groups/5/proxy-access \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "proxy_id": 3,
    "permissions": "read,write",
    "rate_limit": 100,
    "active": true
  }' | jq

# Step 3: Create automatic assignment rule (requires admin authentication)
curl -s -X POST http://localhost:8080/api/v1/oauth/rules \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "user_group_id": 5,
    "rule_type": "email_domain",
    "rule_value": "company.com",
    "priority": 10,
    "active": true,
    "description": "Auto-assign @company.com to Engineering Team"
  }' | jq

# Step 4: Configure proxy OAuth access mode (requires admin authentication)
curl -s -X PUT http://localhost:8080/api/v1/proxies/3/oauth \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "oauth_access_mode": "group_only",
    "oauth_require_group_assignment": true,
    "oauth_rate_limit_per_user": 60
  }' | jq

# Step 5: Verify setup - check user analytics (requires admin authentication)
curl -s http://localhost:8080/api/v1/oauth/analytics/users \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Step 6: Test access for a specific user (requires admin authentication)
curl -s -X POST http://localhost:8080/api/v1/proxies/3/oauth/test \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"user_identity": "alice@company.com"}' | jq

# Step 7: Monitor access patterns (requires admin authentication)
curl -s "http://localhost:8080/api/v1/oauth/analytics/access?time_range=1h" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

OAuth Troubleshooting Queries

bash
# Find users without group assignments
curl -s "http://localhost:8080/api/v1/oauth/users?search=&page=1" | jq '.data.users[] | select(.user_group_id == null)'

# Find inactive users
curl -s "http://localhost:8080/api/v1/oauth/users?active=false" | jq

# Find all rules for a specific group
curl -s "http://localhost:8080/api/v1/oauth/rules?group_id=5" | jq

# Check which proxies a user group can access
curl -s http://localhost:8080/api/v1/user-groups/5/proxies | jq

# Get recent denied access attempts
curl -s "http://localhost:8080/api/v1/oauth/analytics/access?time_range=1h" | jq '.data.denial_reasons'

# List users in a specific group

## Team Usage Analytics

Get token usage and MCP access statistics grouped by user groups (teams). All endpoints require admin authentication.

### Get All Teams Usage

```bash
# Get usage statistics for all teams (last 30 days)
curl -s "http://localhost:8080/api/v1/teams/usage?days=30" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Get API usage for last 7 days
curl -s "http://localhost:8080/api/v1/teams/usage?days=7" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Get usage for last 90 days
curl -s "http://localhost:8080/api/v1/teams/usage?days=90" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

Response:

json
{
  "success": true,
  "data": [
    {
      "user_group_id": 1,
      "user_group_name": "Engineering Team",
      "total_tokens": 1250000,
      "total_cost": 45.67,
      "request_count": 3420,
      "llm_requests": 3200,
      "mcp_requests": 220,
      "unique_tools": 8,
      "tool_usage": [
        {
          "tool_name": "file_search",
          "usage_count": 150,
          "unique_users": 12
        },
        {
          "tool_name": "code_analysis",
          "usage_count": 70,
          "unique_users": 8
        }
      ]
    },
    {
      "user_group_id": 2,
      "user_group_name": "Marketing Team",
      "total_tokens": 890000,
      "total_cost": 32.15,
      "request_count": 2100,
      "llm_requests": 2000,
      "mcp_requests": 100,
      "unique_tools": 5,
      "tool_usage": []
    }
  ]
}

Get Specific Team Usage

bash
# Get combined token usage and MCP stats for team ID 1 (last 30 days)
curl -s "http://localhost:8080/api/v1/teams/1/usage?days=30" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

# Get token usage for last 7 days
curl -s "http://localhost:8080/api/v1/teams/1/usage?days=7" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

Response:

json
{
  "success": true,
  "data": {
    "user_group_id": 1,
    "user_group_name": "Engineering Team",
    "total_tokens": 1250000,
    "total_cost": 45.67,
    "request_count": 3420,
    "llm_requests": 3200,
    "mcp_requests": 220,
    "unique_tools": 8,
    "tool_usage": [
      {
        "tool_name": "file_search",
        "usage_count": 150,
        "unique_users": 12
      },
      {
        "tool_name": "code_analysis",
        "usage_count": 70,
        "unique_users": 8
      }
    ],
    "period_days": 30
  }
}

Get Team Token Breakdown

bash
# Get detailed token usage breakdown by model and provider for team ID 1
curl -s "http://localhost:8080/api/v1/teams/1/tokens?days=30" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

Response:

json
{
  "success": true,
  "data": {
    "user_group_id": 1,
    "user_group_name": "Engineering Team",
    "total_tokens": 1250000,
    "total_cost": 45.67,
    "request_count": 3420,
    "llm_requests": 3200,
    "period_days": 30,
    "model_breakdown": [
      {
        "provider": "openai",
        "model": "gpt-4",
        "total_tokens": 800000,
        "total_cost": 32.00,
        "request_count": 2000
      },
      {
        "provider": "anthropic",
        "model": "claude-3-opus",
        "total_tokens": 450000,
        "total_cost": 13.67,
        "request_count": 1200
      }
    ],
    "provider_breakdown": [
      {
        "provider": "openai",
        "total_tokens": 800000,
        "total_cost": 32.00,
        "request_count": 2000
      },
      {
        "provider": "anthropic",
        "total_tokens": 450000,
        "total_cost": 13.67,
        "request_count": 1200
      }
    ]
  }
}

Get Team MCP Statistics

bash
# Get MCP tool access statistics for team ID 1
curl -s "http://localhost:8080/api/v1/teams/1/mcp-stats?days=30" \
  -H "Authorization: Bearer $JWT_TOKEN" | jq

Response:

json
{
  "success": true,
  "data": {
    "user_group_id": 1,
    "user_group_name": "Engineering Team",
    "total_mcp_requests": 220,
    "unique_tools": 8,
    "tool_usage": [
      {
        "tool_name": "file_search",
        "usage_count": 150,
        "unique_users": 12
      },
      {
        "tool_name": "code_analysis",
        "usage_count": 70,
        "unique_users": 8
      }
    ]
  }
}

Notes:

  • All team analytics endpoints require admin role authentication
  • Token usage is tracked per user group via UserGroupID field in TokenUsage records
  • MCP access statistics are aggregated from ProxyRequestAudit records using the direct UserGroupID field for optimal performance
  • MCP requests include both protocol requests (e.g., "initialize", "tools/list") and actual tool calls (e.g., "file_search", "code_analysis")
    • total_mcp_requests counts all MCP requests (both protocol and tool calls)
    • tool_usage only includes actual tool calls (where mcp_tool is set)
  • Teams with MCP usage but no token usage will still appear in results with zero token values
  • Results are sorted by total cost (descending) for all teams endpoint
  • The days parameter accepts any positive integer (common values: 7, 30, 90)
  • A database migration automatically backfills user_group_id for existing audit logs on server startup curl -s "http://localhost:8080/api/v1/oauth/users?group_id=5" | jq

Find all active rules sorted by priority

curl -s "http://localhost:8080/api/v1/oauth/rules?active=true" | jq '.data.rules | sort_by(.priority) | reverse'