Developer Documentation

G8KEPR Documentation

Complete API reference, CLI commands, SDKs, and integration guides. Get started in 5 minutes.

Getting Started

Get G8KEPR protecting your APIs and AI agents in under 5 minutes.

G8KEPR Architecture Overview

Web Apps
Mobile
AI Agents
APIs
G8KEPR
API Security

OWASP Top 10

MCP Security

AI Tool Control

AI Gateway

Multi-LLM Routing

Observability

Metrics & Logs

Your APIs
Databases
LLM Providers

Installation

Install G8KEPR CLIbash
# Install G8KEPR CLI via npm
npm install -g @g8kepr/cli

# Or via Homebrew (macOS/Linux)
brew install g8kepr/tap/g8kepr

# Or download binary directly
curl -sSL https://get.g8kepr.com | sh

# Verify installation
g8kepr --version

Authentication

Authenticatebash
# Login with your API key
g8kepr auth login

# Or set API key directly
export G8KEPR_API_KEY=g8k_live_YOUR_API_KEY

# Verify authentication
g8kepr auth whoami

Quick Start

Quick Start Commandsbash
# Check system health
g8kepr health status

# View security posture overview
g8kepr posture status

# List recent threats detected
g8kepr threats list --limit 10

# Check compliance status
g8kepr compliance status

# View gateway status
g8kepr gateway status

API Key Types

  • g8k_live_* - Production keys (full access)
  • g8k_test_* - Test/sandbox keys (no billing)
  • g8k_rstr_* - Restricted keys (limited permissions)

API Key Authentication Flow

Your App
1. Send KeyAuthorization: Bearer
G8KEPRValidate & Authorize
3. Check Permsscopes, limits
Your API
g8k_live_*Production - Full access
g8k_test_*Sandbox - No billing
g8k_rstr_*Restricted - Limited

See It In Action

g8kepr-quickstart ~ zsh
$pip install g8kepr-cli
→ Installing g8kepr-cli@2.4.1...
✓ Successfully installed g8kepr-cli-2.4.1
$g8kepr auth login
→ Opening browser for authentication...
✓ Successfully authenticated as team@company.com
→ Organization: acme-corp
→ Credentials saved to ~/.g8kepr/config.json
$g8kepr health status
┌─────────────────────────────────────┐
│ System Health │
├─────────────────────────────────────┤
│ Status: ✓ Healthy │
│ API Gateway: ✓ Online │
│ Database: ✓ Connected │
│ Redis: ✓ Connected │
└─────────────────────────────────────┘
$g8kepr posture status
┌─────────────────────────────────────┐
│ Security Posture Score │
├─────────────────────────────────────┤
│ Overall Score: 87/100 (Good) │
│ Threats Blocked: 1,247 (24h) │
│ Compliance: SOC2 ✓ ISO ✓ │
│ MCP Sessions: 42 active │
└─────────────────────────────────────┘
$

How Requests Flow

Request Flow Through G8KEPR

Client
G8KEPRInspect & Protect
Your API
1Rate Limiting
2Threat Detection
3Auth Validation
4Forward Request

CLI Reference

Complete command reference for the G8KEPR CLI tool.

Global Options

Global Optionstext
g8kepr [command] [options]

Global Options:
  --api-key, -k        API key (or set G8KEPR_API_KEY env var)
  --api-url            API URL (or set G8KEPR_API_URL env var)
  --organization, -o   Organization ID (or set G8KEPR_ORGANIZATION_ID env var)
  --format, -f         Output format: json, table, text (default: table)
  --verbose, -v        Verbose output for debugging
  --debug              Enable debug mode
  --help, -h           Show help
  --version            Show version

Authentication Commands

authbash
# Login interactively (opens browser)
g8kepr auth login

# Login with API key directly
g8kepr auth login --api-key g8k_live_YOUR_KEY

# Show current authenticated user/tenant
g8kepr auth whoami

# Logout and clear credentials
g8kepr auth logout

API Key Management

keysbash
# List all API keys
g8kepr keys list
g8kepr keys list --active  # Only active keys

# Create new API key
g8kepr keys create \
  --name "Production Key" \
  --scopes read,write \
  --expires 90d

# Get key details
g8kepr keys info key_abc123

# Rotate an existing key
g8kepr keys rotate key_abc123

# Revoke API key
g8kepr keys revoke key_abc123

# View key usage statistics
g8kepr keys stats key_abc123 --period 30d

Threat Detection Commands

threatsbash
# List recent threats
g8kepr threats list
g8kepr threats list --days 30 --severity critical
g8kepr threats list --type sql_injection --blocked

# Scan a request payload for threats
g8kepr threats scan --payload '{"query": "SELECT * FROM users"}'
g8kepr threats scan --file request.json

# View threat statistics
g8kepr threats stats --period 7d

# View/update threat detection config
g8kepr threats config
g8kepr threats config --set detection_level=strict

# List detection patterns
g8kepr threats patterns
g8kepr threats patterns --category jailbreak

# Block/unblock IP addresses
g8kepr threats block --ip 192.168.1.100 --reason "Malicious activity"
g8kepr threats unblock --ip 192.168.1.100

# Show most attacked endpoints
g8kepr threats top-attacks --period 24h --limit 10

# Export threats to file
g8kepr threats export --format json --output threats.json

Gateway Commands

gatewaybash
# Show gateway health status
g8kepr gateway status

# List configured routes
g8kepr gateway routes

# List AI providers
g8kepr gateway providers

# View routing metrics
g8kepr gateway metrics --period 1h

Compliance Commands

compliancebash
# Check compliance status
g8kepr compliance status

# List supported frameworks
g8kepr compliance frameworks

# Run compliance check for specific framework
g8kepr compliance check --framework soc2
g8kepr compliance check --framework iso27001

# Generate compliance evidence
g8kepr compliance evidence --framework hipaa --output evidence.zip

Audit Commands

auditbash
# List audit events
g8kepr audit list --period 7d

# View specific audit event
g8kepr audit show evt_abc123

# Search audit logs
g8kepr audit search --user admin@company.com --action delete

# Export audit trail
g8kepr audit export --start 2024-01-01 --end 2024-01-31 --output audit.json

Analytics Commands

analyticsbash
# View request analytics
g8kepr analytics requests --period 24h

# View threat analytics
g8kepr analytics threats --period 7d --group-by type

# View API usage analytics
g8kepr analytics usage --period 30d

# Export analytics data
g8kepr analytics export --format csv --output analytics.csv

Security Posture Commands

posturebash
# View security posture score
g8kepr posture score

# Get posture summary
g8kepr posture summary

# List posture recommendations
g8kepr posture recommendations

# View posture history
g8kepr posture history --period 30d

Health & Admin Commands

health & adminbash
# Check system health
g8kepr health check
g8kepr health check --verbose

# View configuration
g8kepr config show
g8kepr config set log_level=debug

# Export data (threats, logs, analytics)
g8kepr export threats --format json --output threats.json
g8kepr export logs --period 7d --output logs.json

# Admin commands (requires admin role)
g8kepr admin users list
g8kepr admin tenants list

CLI In Action: Viewing Threats

g8kepr-threats ~ zsh
$g8kepr threats list --severity critical,high --limit 5
→ Fetching threats...
┌──────────────────────────────────────────────────────────────────────┐
│ TIME │ SEVERITY │ TYPE │ SOURCE IP │
├──────────────────────────────────────────────────────────────────────┤
│ 2024-01-15 14:32:01 │ CRITICAL │ sql_injection │ 192.168.1.105 │
│ 2024-01-15 14:28:45 │ HIGH │ path_traversal │ 10.0.0.55 │
│ 2024-01-15 14:25:12 │ HIGH │ xss │ 172.16.0.12 │
│ 2024-01-15 14:20:33 │ CRITICAL │ command_inj │ 192.168.1.200 │
│ 2024-01-15 14:15:08 │ HIGH │ ssrf │ 10.0.0.77 │
└──────────────────────────────────────────────────────────────────────┘
✓ 5 threats found (47 total in last 24h)
$g8kepr threats stats --period 24h
→ Threat Statistics (Last 24 hours)
Total Threats: 47
Critical: 8 (17%)
High: 15 (32%)
Medium: 18 (38%)
Low: 6 (13%)
Top Attack Types:
sql_injection: 12
jailbreak: 9
xss: 8
path_traversal: 7
$

API Security

G8KEPR protects your REST, GraphQL, and gRPC APIs from 40+ attack types.

Threat Detection Pipeline

Ingress

Request received

Pattern Match

2,300+ signatures

SQLi, XSS
ML Analysis

Behavioral detection

Anomalies
Policy Check

Rules evaluation

Rate limits
Decision

Allow / Block

SQL Injection
XSS
Path Traversal
Rate Limit
Auth Failure

Live Traffic Monitor

Live Request Monitor
1,247 req/min99.2% allowed0.8% blocked
GET/api/users20012ms✓ Clean
POST/api/orders20145ms✓ Clean
GET/api/users?id=1 OR 1=14032msSQL Injection
PUT/api/products/12320038ms✓ Clean
POST/api/login4291msRate Limited
GET/api/health2005ms✓ Clean

Protection Rules

Rule IDDescriptionDefault
sql_injectionSQL injection detectionblock
xssCross-site scriptingblock
command_injectionOS command injectionblock
path_traversalDirectory traversalblock
xxeXML external entityblock
ssrfServer-side request forgeryblock
ldap_injectionLDAP injectionblock
nosql_injectionNoSQL injectionblock
jwt_validationJWT token validationlog
rate_limitRequest rate limitingblock
payload_sizeRequest size limitblock
content_typeContent-Type validationlog

Configure via API

Full endpoint configurationbash
# Create endpoint with full configuration
curl -X POST https://api.g8kepr.com/v1/endpoints \
  -H "Authorization: Bearer $G8KEPR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Production API",
    "upstream_url": "https://api.yourcompany.com",
    "protection_level": "strict",
    "rules": {
      "sql_injection": {"enabled": true, "action": "block"},
      "xss": {"enabled": true, "action": "block"},
      "command_injection": {"enabled": true, "action": "block"},
      "rate_limit": {
        "enabled": true,
        "action": "block",
        "config": {
          "requests_per_minute": 1000,
          "burst_limit": 50,
          "by": "ip"
        }
      },
      "payload_size": {
        "enabled": true,
        "action": "block",
        "config": {"max_bytes": 10485760}
      }
    },
    "allowed_methods": ["GET", "POST", "PUT", "DELETE"],
    "allowed_origins": ["https://app.yourcompany.com"],
    "tags": ["production", "critical"]
  }'

GraphQL Protection

GraphQL protectionbash
# Configure GraphQL-specific protection
curl -X PATCH https://api.g8kepr.com/v1/endpoints/{endpoint_id}/graphql \
  -H "Authorization: Bearer $G8KEPR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "enabled": true,
    "max_query_depth": 10,
    "max_query_complexity": 1000,
    "max_aliases": 5,
    "introspection_enabled": false,
    "field_suggestions": false,
    "batching_limit": 10,
    "persisted_queries_only": false,
    "blocked_fields": ["__schema", "__type"],
    "cost_analysis": {
      "enabled": true,
      "max_cost": 1000,
      "default_field_cost": 1,
      "default_list_multiplier": 10
    }
  }'

Protection Levels

  • permissive - Log only, no blocking (for testing)
  • standard - Balanced protection (recommended)
  • strict - Maximum security, may have false positives

MCP Security

Secure AI agent tool calls with Model Context Protocol (MCP) security.

MCP Security Flow

AI AgentClaude, GPT, etc.
Policy Engine
Allow
Review
Block
MCP Tools

MCP Setup In Action

mcp-setup ~ zsh
$g8kepr mcp tools register --name filesystem --operations read,write,list
✓ Tool registered: filesystem
→ Operations: read, write, list
→ Tool ID: tool_fs_abc123
$g8kepr mcp policies create --name "dev-agent" --file policy.yaml
→ Validating policy...
✓ Policy created: dev-agent
→ Policy ID: pol_dev_xyz789
→ Rules: 5 allow, 2 deny, 1 require_approval
$g8kepr mcp activity --period 1h
→ Last hour MCP activity:
Total calls: 247
✓ Allowed: 231 (93.5%)
⚠ Review pending: 12 (4.9%)
✗ Blocked: 4 (1.6%)
→ Top tools: filesystem (89), postgres (72), shell (blocked)
$

Claude Desktop Configuration

claude_desktop_config.json (macOS: ~/Library/Application Support/Claude/)json
{
  "mcpServers": {
    "g8kepr-proxy": {
      "command": "npx",
      "args": ["-y", "@g8kepr/mcp-proxy"],
      "env": {
        "G8KEPR_API_KEY": "g8k_live_YOUR_API_KEY",
        "G8KEPR_API_URL": "https://api.g8kepr.com",
        "G8KEPR_ORGANIZATION_ID": "org_your_org_id"
      }
    },
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/data"],
      "proxy": "g8kepr-proxy"
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "POSTGRES_CONNECTION": "postgresql://user:pass@localhost/db"
      },
      "proxy": "g8kepr-proxy"
    }
  }
}

Register MCP Tools

Register MCP toolsbash
# Register filesystem tool with restrictions
curl -X POST https://api.g8kepr.com/v1/mcp/tools \
  -H "Authorization: Bearer $G8KEPR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "tool_name": "filesystem",
    "description": "File system operations",
    "operations": ["read", "write", "list"],
    "config": {
      "allowed_paths": [
        "/data/**",
        "/config/*.json",
        "/tmp/g8kepr/**"
      ],
      "denied_paths": [
        "/etc/**",
        "/root/**",
        "**/.env",
        "**/*.key",
        "**/*.pem"
      ],
      "max_file_size": "10MB",
      "allowed_extensions": [".txt", ".json", ".csv", ".md"]
    }
  }'

# Register database tool
curl -X POST https://api.g8kepr.com/v1/mcp/tools \
  -H "Authorization: Bearer $G8KEPR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "tool_name": "postgres",
    "description": "PostgreSQL database access",
    "operations": ["query", "execute"],
    "config": {
      "allowed_operations": ["SELECT"],
      "denied_operations": ["DROP", "DELETE", "TRUNCATE", "ALTER"],
      "max_rows": 1000,
      "timeout_ms": 30000,
      "allowed_tables": ["users", "orders", "products"],
      "denied_tables": ["audit_logs", "credentials"]
    }
  }'

Create MCP Policies

Create MCP policybash
# Create comprehensive MCP policy
curl -X POST https://api.g8kepr.com/v1/mcp/policies \
  -H "Authorization: Bearer $G8KEPR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "production-agent-policy",
    "description": "Policy for production AI agents",
    "rules": [
      {
        "tool": "filesystem",
        "operation": "read",
        "action": "allow",
        "conditions": {"path_pattern": "/data/**"}
      },
      {
        "tool": "filesystem",
        "operation": "write",
        "action": "require_approval",
        "conditions": {"path_pattern": "/data/**"},
        "approval_timeout": 300
      },
      {
        "tool": "filesystem",
        "operation": "*",
        "action": "deny",
        "conditions": {"path_pattern": "/etc/**"}
      },
      {
        "tool": "postgres",
        "operation": "query",
        "action": "allow",
        "conditions": {"tables": ["users", "orders"]}
      },
      {
        "tool": "shell",
        "operation": "*",
        "action": "deny"
      }
    ],
    "rate_limits": {
      "requests_per_minute": 100,
      "requests_per_hour": 1000
    },
    "logging": {
      "log_all_requests": true,
      "log_parameters": true,
      "redact_sensitive": true
    }
  }'

MCP Threat Detection

Threat TypeDescriptionDetection
path_traversalAccess files outside allowed pathsPattern matching
sql_injection_mcpSQL injection via database toolsQuery analysis
command_injection_mcpShell commands in tool argsPattern matching
prompt_injectionManipulate agent behaviorML detection
data_exfiltrationUnusual data access patternsBehavioral
privilege_escalationBypass permission policiesPolicy engine
sensitive_data_accessAccess to secrets/credentialsPattern matching

AI Gateway

Route requests to multiple LLM providers through a unified API with intelligent routing.

AI Gateway - Intelligent Routing

Your App
openai.chat()
AI Gateway
Cost Optimized
🟢OpenAI
🟣Anthropic
🔵Google
🟠Mistral
60%

Cost Savings

99.9%

Uptime

<50ms

Latency Added

Supported Providers

ProviderProvider IDModelsPricing
OpenAIopenaigpt-4o, gpt-4o-mini, gpt-4-turbo, o1-preview, o1-miniPer token
Anthropicanthropicclaude-3-5-sonnet, claude-3-5-haiku, claude-3-opusPer token
Google Geminigeminigemini-1.5-pro, gemini-1.5-flash, gemini-1.5-flash-8bPer token
Groq (FREE)groqllama-3.3-70b, llama-3.1-70b, mixtral-8x7b, deepseek-r1$0.00

Free Tier with Groq

Groq is the default provider and offers completely free inference. Perfect for development and cost-sensitive workloads. Rate limits: 30 req/min, 14,400 req/day.

Provider Modes

ModeDescriptionCost
GROQFree tier using Groq (default)$0.00
BYOKBring Your Own Key - customer pays provider directlyProvider rates
PLATFORMPlatform-managed keys with markupProvider + 20%

Configure Providers

Add providers (BYOK mode)bash
# Add OpenAI (BYOK mode)
curl -X POST https://api.g8kepr.com/v1/ai-gateway/providers \
  -H "Authorization: Bearer $G8KEPR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "provider": "openai",
    "api_key": "sk-your-openai-key",
    "enabled": true,
    "config": {
      "default_model": "gpt-4o",
      "max_tokens_limit": 4096
    }
  }'

# Add Anthropic (BYOK mode)
curl -X POST https://api.g8kepr.com/v1/ai-gateway/providers \
  -H "Authorization: Bearer $G8KEPR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "provider": "anthropic",
    "api_key": "sk-ant-your-key",
    "enabled": true,
    "config": {
      "default_model": "claude-3-5-sonnet-20241022",
      "max_tokens_limit": 4096
    }
  }'

# Add Google Gemini (BYOK mode)
curl -X POST https://api.g8kepr.com/v1/ai-gateway/providers \
  -H "Authorization: Bearer $G8KEPR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "provider": "gemini",
    "api_key": "your-google-api-key",
    "enabled": true,
    "config": {
      "default_model": "gemini-1.5-pro"
    }
  }'

Routing Strategies

StrategyDescription
PRIORITYFirst available provider in priority order
ROUND_ROBINEven distribution across providers
LEAST_COSTRoute to cheapest available provider
LEAST_LATENCYRoute to fastest provider
LOAD_BALANCEDBalance based on current load
SEMANTICRoute based on prompt type (coding→Claude, creative→GPT-4)

Configure Routing

Configure routingbash
# Configure intelligent routing
curl -X POST https://api.g8kepr.com/v1/ai-gateway/routing \
  -H "Authorization: Bearer $G8KEPR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "strategy": "LEAST_COST",
    "fallback_chain": ["groq", "anthropic", "openai"],
    "rules": [
      {
        "condition": {"model_contains": "gpt-4"},
        "route_to": "openai",
        "fallback": ["anthropic"]
      },
      {
        "condition": {"model_contains": "claude"},
        "route_to": "anthropic",
        "fallback": ["openai"]
      },
      {
        "condition": {"task_type": "code_generation"},
        "route_to": "anthropic",
        "model_override": "claude-3-opus-20240229"
      },
      {
        "condition": {"task_type": "simple_qa"},
        "route_to": "groq",
        "model_override": "llama-3-70b-8192"
      }
    ],
    "cost_limits": {
      "max_cost_per_request": 0.50,
      "daily_budget": 100.00,
      "monthly_budget": 2000.00
    },
    "performance": {
      "timeout_ms": 60000,
      "retry_count": 2,
      "retry_delay_ms": 1000
    }
  }'

Usage Example

Use AI Gatewaybash
# Use the AI Gateway (OpenAI-compatible)
curl https://ai.g8kepr.io/v1/chat/completions \
  -H "Authorization: Bearer $G8KEPR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {"role": "user", "content": "Hello!"}
    ],
    "max_tokens": 100
  }'

# Or set as environment variable for SDKs
export OPENAI_BASE_URL=https://ai.g8kepr.io/v1
export OPENAI_API_KEY=g8k_live_YOUR_API_KEY

# Python example
python -c "
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
    model='gpt-4o',
    messages=[{'role': 'user', 'content': 'Hello!'}]
)
print(response.choices[0].message.content)
"

Integration

G8KEPR provides a REST API and OpenAI-compatible AI Gateway. Use any HTTP client or existing OpenAI SDKs.

Direct HTTP Integration

REST API
api.g8kepr.com/v1
Any HTTP client
Bearer token auth
JSON responses
AI Gateway
OpenAI-compatible
Drop-in replacement
Use existing SDKs
No code changes
CLI Tool
pip install g8kepr-cli
Full API access
Automation ready
CI/CD friendly

REST API with Python

Python with requestspython
import requests

API_KEY = "g8k_live_YOUR_API_KEY"
BASE_URL = "https://api.g8kepr.com/v1"

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

# Get security posture
response = requests.get(f"{BASE_URL}/security-posture", headers=headers)
posture = response.json()
print(f"Security Score: {posture['score']}/100")

# List recent threats
response = requests.get(
    f"{BASE_URL}/threats",
    headers=headers,
    params={"limit": 10, "severity": "high"}
)
threats = response.json()["threats"]
for threat in threats:
    print(f"- {threat['type']}: {threat['description']}")

# Check compliance status
response = requests.get(f"{BASE_URL}/compliance/status", headers=headers)
compliance = response.json()
print(f"SOC2: {compliance['soc2']['status']}")
print(f"ISO27001: {compliance['iso27001']['status']}")

REST API with JavaScript

JavaScript with fetchtypescript
const API_KEY = 'g8k_live_YOUR_API_KEY';
const BASE_URL = 'https://api.g8kepr.com/v1';

const headers = {
  'Authorization': `Bearer ${API_KEY}`,
  'Content-Type': 'application/json'
};

// Get security posture
const postureRes = await fetch(`${BASE_URL}/security-posture`, { headers });
const posture = await postureRes.json();
console.log(`Security Score: ${posture.score}/100`);

// List recent threats
const threatsRes = await fetch(
  `${BASE_URL}/threats?limit=10&severity=high`,
  { headers }
);
const { threats } = await threatsRes.json();
threats.forEach(t => console.log(`- ${t.type}: ${t.description}`));

// Check compliance status
const compRes = await fetch(`${BASE_URL}/compliance/status`, { headers });
const compliance = await compRes.json();
console.log(`SOC2: ${compliance.soc2.status}`);

AI Gateway (OpenAI-Compatible)

Use any OpenAI SDK by changing the base URL. No code changes needed beyond configuration.

AI Gateway with OpenAI SDKpython
# Python - using OpenAI SDK with G8KEPR AI Gateway
from openai import OpenAI

client = OpenAI(
    api_key="g8k_live_YOUR_API_KEY",
    base_url="https://api.g8kepr.com/v1/gateway"
)

# Works exactly like OpenAI - but with protection & routing
response = client.chat.completions.create(
    model="gpt-4o",  # or "claude-3-5-sonnet", "llama-3.3-70b"
    messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)

# FREE tier with Groq models
response = client.chat.completions.create(
    model="llama-3.3-70b-versatile",  # FREE via Groq
    messages=[{"role": "user", "content": "Explain quantum computing"}]
)
AI Gateway with Node.jstypescript
// Node.js - using OpenAI SDK with G8KEPR AI Gateway
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'g8k_live_YOUR_API_KEY',
  baseURL: 'https://api.g8kepr.com/v1/gateway'
});

const completion = await client.chat.completions.create({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: 'Hello!' }]
});
console.log(completion.choices[0].message.content);

Zero Code Changes

The AI Gateway is 100% OpenAI-compatible. Just change your base URL and API key - all your existing code works instantly with multi-provider routing, cost optimization, and enterprise security built in.

Official SDKs

For the best developer experience, use our official type-safe SDKs with full IDE support and autocompletion.

🐍Python SDK
pip install g8kepr
📦TypeScript SDK
npm install @g8kepr/sdk

Python SDK Example

Python SDK - Full Type Safetypython
from g8kepr import G8KEPRClient

# Initialize the client
client = G8KEPRClient(
    base_url="https://api.g8kepr.com",
    api_key="g8k_live_YOUR_API_KEY"
)

# List threats with full type safety
response = client.threats.list(severity="high", limit=10)
if response.ok:
    for threat in response.data["threats"]:
        print(f"- {threat['type']}: {threat['severity']}")

# Check compliance status
compliance = client.compliance.status()
print(f"SOC2: {compliance.data['soc2']['status']}")
print(f"ISO27001: {compliance.data['iso27001']['status']}")

# Get security posture score
posture = client.posture.score()
print(f"Security Score: {posture.data['score']}/100")

# AI Gateway usage
gateway = client.gateway.providers()
print(f"Active providers: {len(gateway.data['providers'])}")

# Async client for high-throughput applications
from g8kepr import AsyncG8KEPRClient

async with AsyncG8KEPRClient(
    base_url="https://api.g8kepr.com",
    api_key="g8k_live_YOUR_API_KEY"
) as client:
    response = await client.get("/api/threats")

TypeScript SDK Example

TypeScript SDK - Full Type Safetytypescript
import { G8KEPRClient } from '@g8kepr/sdk';

// Initialize the client with full type inference
const client = new G8KEPRClient({
  baseUrl: 'https://api.g8kepr.com',
  apiKey: 'g8k_live_YOUR_API_KEY'
});

// List threats - fully typed response
const { data, error } = await client.threats.list({ severity: 'high', limit: 10 });
if (data) {
  data.threats.forEach(threat => {
    console.log(`- ${threat.type}: ${threat.severity}`);
  });
}

// Check compliance status
const compliance = await client.compliance.status();
console.log(`SOC2: ${compliance.data?.soc2.status}`);
console.log(`ISO27001: ${compliance.data?.iso27001.status}`);

// Get security posture
const posture = await client.posture.score();
console.log(`Security Score: ${posture.data?.score}/100`);

// Gateway management
const providers = await client.gateway.providers();
console.log(`Active providers: ${providers.data?.providers.length}`);

// Generate compliance report
const report = await client.reports.generate({
  template_id: 'soc2-evidence-package',
  format: 'pdf'
});

SDK Features

Both SDKs provide: full type safety, automatic authentication, request/response validation, built-in retry logic, and comprehensive error handling. Generated from our OpenAPI spec.

API Reference

Base URL: https://api.g8kepr.com/v1

Authentication

Authenticationbash
# All requests require Bearer token authentication
curl https://api.g8kepr.com/v1/endpoints \
  -H "Authorization: Bearer g8k_live_YOUR_API_KEY"

# Or use X-API-Key header
curl https://api.g8kepr.com/v1/endpoints \
  -H "X-API-Key: g8k_live_YOUR_API_KEY"

Endpoints API

MethodPathDescription
GET/endpointsList all endpoints
POST/endpointsCreate endpoint
GET/endpoints/:idGet endpoint
PATCH/endpoints/:idUpdate endpoint
DELETE/endpoints/:idDelete endpoint
GET/endpoints/:id/metricsGet metrics
PATCH/endpoints/:id/rulesUpdate rules

MCP API

MethodPathDescription
GET/mcp/toolsList registered tools
POST/mcp/toolsRegister tool
GET/mcp/policiesList policies
POST/mcp/policiesCreate policy
GET/mcp/activityGet activity logs
GET/mcp/sessionsList active sessions

Reports API

MethodPathDescription
GET/reports/typesList report types
POST/reports/generateGenerate report
GET/reports/:idGet report status
GET/reports/:id/downloadDownload report
GET/reports/schedulesList schedules
POST/reports/schedulesCreate schedule

HTTP Status Codes

CodeDescription
200Success
201Created
400Bad Request - Invalid parameters
401Unauthorized - Invalid/missing API key
403Forbidden - Insufficient permissions
404Not Found
429Rate Limited
500Internal Server Error

Reports & Compliance

28 enterprise report templates across 6 categories.

Report Generation Workflow

1
Select Template
SOC 2
ISO 27001
Executive
2
Configure
Date Range
Format: PDF
Recipients
3
Generate
Collect Data
Build Sections
Render Output
4
Deliver
Download
Email
Schedule

Compliance Framework Coverage

🔒
SOC 2
64/64 controls
🌐
ISO 27001
93/93 controls
🏥
HIPAA
48/48 controls
💳
PCI DSS
312/312 controls
🏛️
NIST CSF
106/106 controls
🇪🇺
GDPR
22/22 controls

Report Generation In Action

g8kepr-reports ~ zsh
$g8kepr reports generate --type executive_security_posture --format pdf
→ Collecting security posture data...
→ Building executive summary...
→ Generating visualizations...
→ Rendering PDF...
✓ Report generated: executive_security_posture_20240115.pdf
→ Size: 2.4 MB
→ Pages: 12
→ Download: https://reports.g8kepr.io/rpt_abc123
$g8kepr reports generate --type soc2_evidence_package --format zip
→ Collecting SOC 2 evidence...
→ Mapping 64 TSC criteria...
→ Gathering control screenshots...
→ Exporting audit logs...
→ Packaging evidence bundle...
✓ Evidence package generated: soc2_evidence_20240115.zip
→ Size: 45.7 MB
→ Files: 87 evidence artifacts
$

All Report Types

Report Type IDNameFormats
Executive Reports (4)
executive_security_postureExecutive Security PosturePDF, HTML
monthly_security_summaryMonthly Security SummaryPDF, HTML
compliance_dashboardCompliance DashboardPDF, HTML, JSON
risk_assessmentRisk AssessmentPDF, HTML
Compliance Evidence (8)
soc2_evidence_packageSOC 2 Evidence PackagePDF, ZIP
iso27001_audit_packageISO 27001 Audit PackagePDF, ZIP
hipaa_security_reportHIPAA Security ReportPDF, ZIP
pci_dss_assessmentPCI DSS AssessmentPDF, ZIP
nist_csf_reportNIST CSF ReportPDF, JSON
gdpr_article30_reportGDPR Article 30 ReportPDF, CSV
fedramp_authorization_packageFedRAMP Authorization PackagePDF, ZIP
cmmc2_assessmentCMMC 2.0 AssessmentPDF, ZIP
Threat Intelligence (4)
threat_intelligence_briefThreat Intelligence BriefPDF, HTML
mitre_attack_coverageMITRE ATT&CK CoveragePDF, JSON
incident_investigationIncident InvestigationPDF, HTML, JSON
attack_pattern_analysisAttack Pattern AnalysisPDF, JSON
Operational (4)
api_performanceAPI Performance ReportPDF, HTML, CSV
usage_analyticsUsage AnalyticsPDF, CSV, XLSX
sla_complianceSLA Compliance ReportPDF, HTML
anomaly_detection_summaryAnomaly Detection SummaryPDF, JSON
Audit & Forensics (4)
audit_trail_exportAudit Trail ExportPDF, JSON, CSV
access_control_auditAccess Control AuditPDF, CSV
change_management_logChange Management LogPDF, CSV
dsar_reportDSAR Report (GDPR/CCPA)PDF, JSON
AI/ML Security (4)
ai_risk_managementAI Risk Management (NIST AI RMF)PDF, HTML
llm_security_assessmentLLM Security AssessmentPDF, JSON
mcp_security_auditMCP Security AuditPDF, JSON
eu_ai_act_complianceEU AI Act CompliancePDF, HTML

Generate Reports via API

Generate reportsbash
# Generate Executive Security Posture report
curl -X POST https://api.g8kepr.com/v1/reports/generate \
  -H "Authorization: Bearer $G8KEPR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "report_type": "executive_security_posture",
    "format": "pdf",
    "parameters": {
      "period_start": "2024-01-01",
      "period_end": "2024-01-31",
      "include_recommendations": true,
      "classification": "confidential"
    }
  }'

# Generate SOC 2 Evidence Package
curl -X POST https://api.g8kepr.com/v1/reports/generate \
  -H "Authorization: Bearer $G8KEPR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "report_type": "soc2_evidence_package",
    "format": "zip",
    "parameters": {
      "period_start": "2024-01-01",
      "period_end": "2024-12-31",
      "trust_service_criteria": ["CC1", "CC2", "CC3", "CC4", "CC5", "CC6", "CC7", "CC8", "CC9"],
      "include_screenshots": true,
      "include_config_exports": true
    }
  }'

# Generate MITRE ATT&CK Coverage report
curl -X POST https://api.g8kepr.com/v1/reports/generate \
  -H "Authorization: Bearer $G8KEPR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "report_type": "mitre_attack_coverage",
    "format": "json",
    "parameters": {
      "include_techniques": true,
      "include_gaps": true,
      "attack_version": "14.1"
    }
  }'

# Check report status
curl https://api.g8kepr.com/v1/reports/rpt_abc123 \
  -H "Authorization: Bearer $G8KEPR_API_KEY"

# Download completed report
curl https://api.g8kepr.com/v1/reports/rpt_abc123/download \
  -H "Authorization: Bearer $G8KEPR_API_KEY" \
  -o report.pdf

Schedule Reports

Schedule reportsbash
# Schedule monthly executive report
curl -X POST https://api.g8kepr.com/v1/reports/schedules \
  -H "Authorization: Bearer $G8KEPR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Monthly Board Report",
    "report_type": "executive_security_posture",
    "format": "pdf",
    "cron": "0 9 1 * *",
    "timezone": "America/New_York",
    "recipients": [
      {"email": "ciso@company.com", "name": "CISO"},
      {"email": "board@company.com", "name": "Board Distribution"}
    ],
    "parameters": {
      "include_recommendations": true,
      "period": "last_month"
    }
  }'

# Schedule weekly threat brief
curl -X POST https://api.g8kepr.com/v1/reports/schedules \
  -H "Authorization: Bearer $G8KEPR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Weekly Threat Brief",
    "report_type": "threat_intelligence_brief",
    "format": "pdf",
    "cron": "0 8 * * 1",
    "timezone": "UTC",
    "recipients": [
      {"email": "security-team@company.com"}
    ],
    "parameters": {
      "period": "last_week",
      "severity_threshold": "medium"
    }
  }'

Integrations

Docker Deployment Architecture

Docker Host
g8kepr-gateway
Image:g8kepr/gateway:latest
Port:8080:8080
CPU:500m
Memory:512Mi
redis
Image:redis:7-alpine
Port:6379
Volume:redis-data
Memory:256Mi
your-api
Image:your-app:latest
Port:3000
Depends:g8kepr-gateway
Network:g8kepr-net
Internet
:8080
:3000

Docker

Docker deploymentyaml
# Pull and run the G8KEPR backend
docker pull g8kepr/backend:latest

docker run -d \
  --name g8kepr \
  -p 8000:8000 \
  -e DATABASE_URL=postgresql://user:pass@db:5432/g8kepr \
  -e REDIS_URL=redis://redis:6379 \
  -e G8KEPR_API_KEY=g8k_live_YOUR_API_KEY \
  -e LOG_LEVEL=info \
  g8kepr/backend:latest

# With docker-compose
version: '3.8'
services:
  g8kepr:
    image: g8kepr/backend:latest
    ports:
      - "8000:8000"
    environment:
      DATABASE_URL: postgresql://user:pass@db:5432/g8kepr
      REDIS_URL: redis://redis:6379
      G8KEPR_API_KEY: ${G8KEPR_API_KEY}
      LOG_LEVEL: info
    depends_on:
      - db
      - redis
  db:
    image: postgres:15
    environment:
      POSTGRES_DB: g8kepr
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
  redis:
    image: redis:7

Kubernetes Deployment

Kubernetes Cluster
namespace: g8kepr
Ingressnginx-ingress
Serviceg8kepr-svc
Deploymentreplicas: 3
HPA3-10 pods
3Replicas
500mCPU/pod
512MiMemory/pod
99.9%SLA

Kubernetes

Kubernetes deploymentbash
# Create secrets
kubectl create secret generic g8kepr-secrets \
  --from-literal=api-key=g8k_live_YOUR_API_KEY \
  --from-literal=database-url=postgresql://user:pass@db:5432/g8kepr

# Apply deployment
kubectl apply -f - <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:
  name: g8kepr-backend
  labels:
    app: g8kepr
spec:
  replicas: 3
  selector:
    matchLabels:
      app: g8kepr
  template:
    metadata:
      labels:
        app: g8kepr
    spec:
      containers:
      - name: g8kepr
        image: g8kepr/backend:latest
        ports:
        - containerPort: 8000
        env:
        - name: G8KEPR_API_KEY
          valueFrom:
            secretKeyRef:
              name: g8kepr-secrets
              key: api-key
        - name: DATABASE_URL
          valueFrom:
            secretKeyRef:
              name: g8kepr-secrets
              key: database-url
        - name: REDIS_URL
          value: "redis://redis-service:6379"
        - name: LOG_LEVEL
          value: "info"
        resources:
          requests:
            memory: "256Mi"
            cpu: "100m"
          limits:
            memory: "1Gi"
            cpu: "1000m"
        livenessProbe:
          httpGet:
            path: /health
            port: 8000
          initialDelaySeconds: 10
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /ready
            port: 8000
          initialDelaySeconds: 5
          periodSeconds: 5
---
apiVersion: v1
kind: Service
metadata:
  name: g8kepr-gateway
spec:
  selector:
    app: g8kepr
  ports:
  - port: 80
    targetPort: 8080
  type: LoadBalancer
EOF

Webhook Event Flow

G8KEPREvent Triggered
POST /webhook
Your ServerProcess Event
threat.detected
request.blocked
rate_limit.exceeded
report.generated

Webhook Events

Webhooksbash
# Configure webhook
curl -X POST https://api.g8kepr.com/v1/webhooks \
  -H "Authorization: Bearer $G8KEPR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Security Events Webhook",
    "url": "https://your-app.com/webhooks/g8kepr",
    "secret": "whsec_your_signing_secret",
    "events": [
      "threat.detected",
      "threat.blocked",
      "policy.violation",
      "mcp.tool_call",
      "mcp.blocked",
      "report.generated",
      "alert.triggered"
    ],
    "headers": {
      "Authorization": "Bearer your-token"
    }
  }'

# Webhook payload example
{
  "id": "evt_abc123",
  "type": "threat.blocked",
  "created": "2024-01-15T10:30:00Z",
  "data": {
    "request_id": "req_xyz789",
    "endpoint_id": "ep_abc123",
    "threat_type": "sql_injection",
    "severity": "high",
    "source_ip": "192.168.1.100",
    "path": "/api/users",
    "method": "POST",
    "blocked": true,
    "details": {
      "pattern_matched": "' OR '1'='1",
      "location": "body.query"
    }
  }
}

Configuration

Configuration File Structure

g8kepr.yaml
tenant:your-tenant
protection:standard
rate_limit:1000/min
alerts:enabled
.env
G8KEPR_API_KEY=g8k_live_***
G8KEPR_API_URL=https://api.g8kepr.com
G8KEPR_ORGANIZATION_ID=org_123
G8KEPR_OUTPUT_FORMAT=table

CLI Environment Variables

VariableDescriptionDefault
G8KEPR_API_URLAPI server URLhttps://api.g8kepr.com
G8KEPR_API_KEYAPI key for authenticationRequired
G8KEPR_ORGANIZATION_IDOrganization/tenant IDFrom auth
G8KEPR_OUTPUT_FORMATOutput format (json, table, text)table
G8KEPR_COLOREnable colored outputtrue
G8KEPR_TIMEOUTRequest timeout in seconds30
G8KEPR_RETRIESNumber of retry attempts3
G8KEPR_VERBOSEEnable verbose loggingfalse
G8KEPR_DEBUGEnable debug modefalse
G8KEPR_ACCESS_TOKENOAuth access token (auto-managed)From login
G8KEPR_REFRESH_TOKENOAuth refresh token (auto-managed)From login

Configuration File

g8kepr.yamlyaml
# g8kepr.yaml
api_key: g8k_live_YOUR_API_KEY
tenant: your-tenant

server:
  port: 8080
  timeout_ms: 30000
  max_body_size: 10MB

upstream:
  url: https://api.yourcompany.com
  timeout_ms: 25000
  retry_count: 2
  retry_delay_ms: 100

protection:
  level: standard
  fail_open: false

  rules:
    sql_injection:
      enabled: true
      action: block
    xss:
      enabled: true
      action: block
    rate_limit:
      enabled: true
      action: block
      requests_per_minute: 1000
      burst_limit: 50

logging:
  level: info
  format: json
  include_body: false
  redact_sensitive: true

metrics:
  enabled: true
  port: 9090
  path: /metrics

Troubleshooting

Debug Commands

Debug commandsbash
# Check CLI version and auth
g8kepr --version
g8kepr auth whoami

# Test connectivity
g8kepr test connection

# Debug specific request
g8kepr debug request req_abc123

# View recent errors
g8kepr logs errors --limit 50

# Export debug bundle
g8kepr debug bundle --output ./debug-bundle.zip

# Health check endpoints
curl https://api.g8kepr.com/health
curl http://localhost:8080/health  # Local gateway

Common Issues

401 Unauthorized

# Verify API key
g8kepr auth whoami

# Check key format (should start with g8k_live_ or g8k_test_)
echo $G8KEPR_API_KEY

# Test with curl
curl -I https://api.g8kepr.com/v1/endpoints \
  -H "Authorization: Bearer $G8KEPR_API_KEY"

Requests Being Blocked

# View blocked requests
g8kepr logs blocked --period 1h

# Check protection level
g8kepr endpoints get ep_abc123 | grep protection_level

# Switch to permissive mode temporarily
g8kepr endpoints update ep_abc123 --protection permissive

# Add to allowlist
g8kepr allowlist add --pattern "/api/health/*" --reason "Health checks"

High Latency

# Check G8KEPR latency metrics
g8kepr endpoints metrics ep_abc123 --metric latency

# View P99 latency
g8kepr metrics latency --percentile 99 --period 1h

# Check upstream response times
g8kepr metrics upstream --period 1h

# Enable fail-open if critical
export G8KEPR_FAIL_OPEN=true

Quick Reference

Base URLs

API: api.g8kepr.com/v1
AI Gateway: ai.g8kepr.io/v1
Proxy: *.g8kepr.io/proxy
Docs: api.g8kepr.com/docs

Key Prefixes

Production: g8k_live_*
Test: g8k_test_*
Restricted: g8k_rstr_*
Webhook: whsec_*

CLI Quick Commands

g8kepr auth login
g8kepr endpoints list
g8kepr logs stream -f
g8kepr reports types

Rate Limits

Free: 10K req/day
Pro: 1M req/month
Enterprise: Unlimited
API calls: 1K/min

Ready to Get Started?

Start securing your APIs and AI agents in minutes. No credit card required.