X4G4T

X4G4T: Zero-latency, headless policy firewall and Data Leakage Prevention (DLP) proxy for AI agents and Model Context Protocol (MCP) servers.

Documentation

TAC-SPEC CONTAINMENT GATEWAY • X4G4T [X-FOUR-GATE] • APACHE 2.0 OPEN SOURCE

Tactical AI Agent Security Firewall & Gateway. X4G4T (X-Four-Gate)

Autonomous coding agents (Claude Code, Cursor, Windsurf, Devin) and agentic frameworks (LangChain, CrewAI, AutoGen) execute real shell commands, mutate production databases, call financial APIs, and handle cloud credentials. X4G4T is the defense-grade, ultra-low-latency inline firewall that inspects dynamic tool arguments, substitutes master LLM keys with zero-trust vaulting, halts SSRF exploits, and enforces sub-millisecond guardrails before state mutations occur.

$ git clone https://github.com/aryix-hq/X4G4T.git && cd X4G4T && docker compose up -d

Clone Repo ↗

<0.2ms AST Engine

Pure in-memory traversal at 8,561,735 evals/sec. Zero DB overhead on hot path.

Zero-Trust Key Vault

Agents use local tokens; real OpenAI/Claude/Gemini keys injected only upon ALLOW.

Native MCP Proxy

Parses JSON-RPC 2.0 tools/call frames for Cursor, Claude Desktop, and local MCP tools.

ISO 27001 + DPDP

Cryptographic SHA-256 hash chains paired with AES-256 Crypto-Shredding erasure.

Autonomous Attack Surface

Giving Autonomous AI Agents Direct Production Access Without an Inline Firewall is Root Access on Day One.

Over the past two years, enterprises adopted LLMs for passive text generation and summarization. Today, autonomous agents are equipped with tools to execute wire transfers, mutate relational databases, deploy Kubernetes workloads, and read developer files. When prompt injection or model hallucination strikes, traditional API gateways and WAFs are completely blind.

GATE 01

Master Key Exfiltration

Adversarial prompt injection tricks agents into reading local .env files or dumping system environment variables, exposing high-value cloud and LLM provider keys.

GATE 02

Destructive Operations

Hallucinated parameters or runaway loops execute high-impact mutations—running DROP TABLE, deleting S3 buckets, or issuing $50,000 refunds instead of $50.

GATE 03

In-Flight PII Leakage

Agents inadvertently scrape or forward customer credit cards, US SSNs, Indian Aadhaar numbers, and internal tokens directly into external commercial model training contexts.

GATE 04

SSRF & Metadata Probing

Autonomous web scrapers probe local loopback addresses (127.0.0.1) or query AWS/GCP cloud instance metadata services (169.254.169.254) to steal temporary STS tokens.

Security DimensionTraditional API Gateways / WAFs (Kong, Cloudflare)X4G4T Tactical FirewallThe Security Impact
Argument InspectionBlind to JSON tool semantics: Inspects generic HTTP paths, methods, and IP rate limits.Deep AST dot-path extraction: Evaluates numeric bounds (amount <= 500), regex, and enum values in <0.2ms.Blocks hallucinated arguments and unauthorized parameter states before execution.
LLM Credential VaultingRaw Key Exposure: Keys (e.g. sk-proj-*) stored in local developer .env or container environment.Zero-Trust Dynamic Injection: Agents use dummy tokens; gateway attaches real vaulted provider keys at network egress.Developers and agents never see production credentials; zero prompt-injection key theft.
Model Context Protocol (MCP)Unsupported: Cannot parse JSON-RPC 2.0 frames or translate policy blocks into MCP error schemas.Native JSON-RPC 2.0 Proxy: Intercepts tools/call frames and returns standard RFC-compliant error payloads.Zero friction for Cursor, Claude Desktop, and standalone enterprise MCP servers.
Human-in-the-Loop (HITL)Binary Allow/Drop: Either completely permits execution or throws a fatal 403 network drop.Multi-Channel Intercept: Suspends with 202 HELD and sends interactive Slack cards & email for 1-click approval.Critical actions (e.g., transfers > $10k) require explicit human sign-off without breaking agent loops.
Audit & Data PrivacyUnencrypted flat access logs: Persists raw customer payloads, creating severe GDPR Art. 17 / DPDP violations.ISO 27001 Hash Chain + Crypto-Shredding: SHA-256 ledger chaining with ephemeral AES-256 keys for instant GDPR erasure.Mathematically destroys personal data without breaking audit log continuity.

Tactical Topology

Centralized Gateway & Zero-Trust Reverse Proxy Architecture

X4G4T operates as a high-throughput, low-latency containment plane positioned directly between your autonomous agent runtimes and upstream LLM providers or enterprise downstream APIs.

x4g4t-containment-topology.svg

PORT:4000 (TACTICAL INGRESS)

Polyglot AI Agents

Coding Agents

Claude Code, Cursor, Windsurf, Devin

Agent Frameworks

LangChain, AutoGen, CrewAI, LlamaIndex

MCP Clients

Claude Desktop, Cursor MCP (JSON-RPC 2.0)

X4G4T Inline Engine (:4000) Overhead: <5ms

1

Gate 1: Dual-Mode Auth & IAM Token Translation

In-memory SHA-256 token cache + Clerk/Okta/Azure AD JWT verification.

2

Gate 2: Zero-Trust LLM Key Vault & Egress Injection

Vaults master OpenAI/Claude/Gemini/Vertex keys; injects at edge upon ALLOW.

3

Gate 3: Sub-Millisecond AST Evaluator (<0.2ms)

Deep dot-path checks, numerical bounds, enum verification, and regex matching.

4

Gate 4: Enterprise DLP Sanitizer & SSRF Shield

Luhn CC, SSN, Aadhaar scrub + blocks 169.254.169.254 & loopbacks.

5

Tamper-Evident Daily Audit Queue (BullMQ)

Async dispatch to daily-rotated Elasticsearch indices + Prometheus /metrics.

On REQUIRE_APPROVAL: HTTP 202 HELD → Slack Block Kit & Email

Downstream Targets

Upstream LLMs

OpenAI, Anthropic, Gemini, Vertex AI, Ollama

Enterprise APIs

Stripe, Salesforce, Workday, Slack, SendGrid

Cloud Infrastructure

PostgreSQL, Redis, AWS STS, Kubernetes API

Hot-Path Ingestion Latency Budget (Target vs. Measured)

Stage / Pipeline ComponentUnderlying MechanismTarget SLAEmpirical Measured
Header & Zod ParsingZod schema validation & dot-path tokenization< 1.0 ms0.035 ms
Authentication & RBACIn-memory SHA-256 hash map (5-min TTL)< 0.5 ms0.012 ms
Policy AST EvaluationPure TypeScript in-memory operator AST< 1.0 ms0.00012 ms (0.12 µs)
DLP Sanitizer & SSRF CheckLuhn validator & CIDR ipaddr.js loopback check< 0.5 ms0.018 ms
Audit Queue DispatchNon-blocking BullMQ Redis LPUSH< 2.0 ms0.080 ms
Total Ingestion Gateway OverheadExcluding downstream target network transit< 5.0 ms0.066 ms (P50) / 1.34 ms (P99)

Tactical Defense Pillars

Engineered for Zero-Trust Agent Governance

Every pillar of X4G4T is built on deterministic software engineering principles—eliminating runtime hallucinations, securing cloud credentials, and guaranteeing verifiable audit trails.

Sub-Millisecond AST Engine

Pure in-memory Abstract Syntax Tree evaluator executes in <0.2ms (0.12µs mean latency) with 8.5M+ evals/sec. Validates nested dot-notation fields, numerical thresholds, regex patterns, and IAM roles.

Zero-Trust Key Injection

Eliminates raw LLM key distribution. Developers and agents talk to the gateway with local proxy tokens. The gateway injects vaulted OPENAI_API_KEY or Claude credentials only when an action is ALLOWED.

Native MCP JSON-RPC Proxy

Seamless proxy for Model Context Protocol. Intercepts JSON-RPC 2.0 tools/call frames from Cursor and Claude Desktop, translating security violations into standard RFC-compliant error objects.

In-Flight DLP & SSRF Shield

Real-time redaction of Credit Cards (Luhn algorithm), US SSNs, Indian Aadhaar numbers, AWS secrets, and RSA private keys. Blocks loopback (127.0.0.1) and cloud metadata services (169.254.169.254).

Emergency AI Kill-Switch

1-click administrative global kill-switch immediately halts all autonomous agent execution enterprise-wide with HTTP 503 AI_LOCKDOWN_ACTIVE in under 0.5ms before DB queries.

Multi-Channel Slack HITL

Suspends high-impact actions with HTTP 202 HELD. Dispatches interactive Slack Block Kit cards and SMTP emails with 1-click approve/reject buttons, resuming agent loops seamlessly.

Audit & Crypto-Shredding

Sequential SHA-256 hash chaining (ISO/IEC 27001 A.8.15) paired with ephemeral AES-256 subject key Crypto-Shredding satisfies GDPR Art. 17 & DPDP Sec. 12 right to erasure without breaking audit chains.

Turn-Key Observability

Pre-provisioned Prometheus scrapers and Grafana dashboards with 17 real-time telemetry panels tracking P50/P90/P99 latencies, DLP redactions, token injection rates, and Redis/Postgres health.

Deployment Architecture

7 Tactical Services. Zero Configuration. Up in 30 Seconds.

X4G4T ships with a complete, production-grade Docker Compose stack orchestrating all control plane and ingestion services over an isolated internal bridge network (x4g4t-net).

Run complete turn-key stack: MIL-SPEC CONCURRENCY

$ git clone https://github.com/aryix-hq/X4G4T.git

$ cd X4G4T

$ docker compose up -d

Container NamePortImage / StackPrimary Architectural Role
x4g4t-proxy:4000Fastify / TypeScriptSub-millisecond AI policy firewall, SSRF protection, DLP sanitizer, MCP frame inspector, upstream key injector.
x4g4t-web:3000Next.js 14 App RouterEnterprise control plane with Clerk/RBAC authentication, policy visual builder, and human-in-the-loop triage console.
x4g4t-postgres:5432postgres:16-alpineTenant isolation, SHA-256 hashed API keys, compiled AST policies, and HITL approval states. Auto-seeds schema.
x4g4t-redis:6379redis:7-alpineSliding-window rate limiting via atomic Lua script + BullMQ asynchronous background audit log queue.
x4g4t-elasticsearch:9200elasticsearch:8.13.4Immutable, fire-and-forget audit sink with automated daily index rotation (x4g4t-logs-YYYY.MM.DD).
x4g4t-prometheus:9090prom/prometheus:v2.51.2Real-time scraper polling Fastify proxy /metrics endpoint every 5 seconds.
x4g4t-grafana:3001grafana:10.4.2Auto-provisioned dashboards with 17 panels for P50/P90/P99 latency histograms, threat counts, and live gauges.

Cloud-Native Kubernetes Deployment (EKS, GKE, AKS, Kind)

Deploy production manifests with a single command: ./scripts/deploy-k8s.sh --namespace prod-x4g4t

View Deployment Docs ↗

Developer Quickstart

Integrate in Under 2 Minutes

Whether you use LangChain, Python agent loops, Cursor, or Claude Desktop MCP, simply point your agent's egress URL to the X4G4T gateway.

Python / LangChain Agent Gateway Call POST /v1/gateway/execute

# Point agent tool executions to X4G4T (X-Four-Gate)
import requests

response = requests.post(
    "http://localhost:4000/v1/gateway/execute",
    headers={
        "Authorization": "Bearer sec_live_x4g4t_demo",
        "Content-Type": "application/json",
        "x-iam-user-id": "usr_engineer_42",
        "x-iam-roles": "developer,billing_operator"
    },
    json={
        "agent_id": "claude_code_autonomous_session",
        "tool_name": "issue_customer_refund",
        "arguments": {
            "customer_id": "cus_9941a",
            "amount": 150.00,
            "currency": "USD"
        },
        "downstream_url": "https://api.stripe.com/v1/refunds"
    }
)

# Result evaluated in pure AST in <0.2ms:
if response.status_code == 200:
    print("ALLOWED & Forwarded to Stripe:", response.json())
elif response.status_code == 202:
    print("HELD for Human Approval in Slack:", response.json())
elif response.status_code == 422:
    print("BLOCKED by X4G4T Gate Policy:", response.json())

Claude Desktop & Cursor MCP Proxy Config claude_desktop_config.json

{
  "mcpServers": {
    "enterprise-postgres-guard": {
      "command": "npx",
      "args": [
        "-y",
        "@x4g4t/mcp-proxy",
        "--gateway-url", "http://localhost:4000/v1/gateway/mcp",
        "--token", "sec_live_usr_x4g4t_demo"
      ],
      "env": {
        "X4G4T_TARGET_MCP": "http://internal-postgres-mcp:8080",
        "X4G4T_FAIL_CLOSED": "true"
      }
    }
  }
}
/*
  X4G4T automatically intercepts all tools/call
  frames from Cursor / Claude Desktop. Blocks destructive
  SQL (DROP, TRUNCATE, ALTER) in <0.2ms and returns standard
  JSON-RPC 2.0 error code -32001 to the AI model.
*/

Institutional Governance

Built for Global Enterprise Compliance Frameworks

Autonomous AI systems must comply with statutory data protection and security management mandates. X4G4T is purpose-engineered to fulfill the technical controls of international standards.

ISO/IEC 27001:2022

Controls A.5.15, A.8.12, A.8.15, A.8.24

Strict RBAC separation, automated Data Leakage Prevention (DLP) scrubbing, tamper-evident SHA-256 ledger chaining, and AES-256-GCM encryption for stored parameters.

ISO/IEC 42001:2023

Artificial Intelligence Management (AIMS)

Directly satisfies Controls B.6.2 (AI Impact Assessment), B.7.4 (Human Autonomy Limits & HITL Overrides), and B.9.3 (Causal Decision Traceability: Model + Prompt Hash + Argument + Action).

India DPDP Act 2023

Section 6, Section 8, Section 12

Mandatory Purpose Limitation verification, reasonable security safeguards against data breaches, and single-click Data Principal erasure via mathematical Crypto-Shredding.

EU GDPR (2016/679)

Article 17 & Article 25

Resolves the audit immutability vs. right-to-be-forgotten paradox by destroying ephemeral subject keys, leaving compliance hash chains intact while rendering personal data provably unrecoverable.

OWASP Top 10 for LLMs

LLM02, LLM06, LLM07, LLM08

Prevents Sensitive Information Disclosure (LLM06), Insecure Plugin/Tool Design (LLM07), Excessive Agency (LLM08), and downstream prompt-injected SSRF attacks (LLM02).

SOC 2 Type II Ready

Security, Confidentiality & Availability

Immutable Elasticsearch audit logging, distributed sliding-window rate limiting, fail-closed production defaults, and strict Separation of Duties (SoD) between developers and SecOps.

Open-Core Framework

Open-Source Community Core vs. Enterprise Commercial Edition

X4G4T is 100% free and open-source under Apache 2.0. For enterprises with global multi-cluster footprints, custom regulatory mandates, or dedicated SLAs, ARYIX provides commercial engineering support.

Capability / Architecture FeatureCommunity Core (Apache 2.0)Enterprise Edition & Support
Fastify Proxy AI Gateway✅ Included✅ Included
Pure In-Memory AST Evaluator (<0.2ms)✅ Included✅ Included
Zero-Trust LLM Key Injection (OpenAI, Claude, Gemini)✅ Included✅ Included
In-Flight DLP Sanitizer & SSRF Shield✅ Included✅ Included
Native MCP JSON-RPC 2.0 Interception✅ Included✅ Included
Multi-Channel Human-in-the-Loop (Slack & Email)✅ Included✅ Included
Emergency AI Global Lockdown Kill-Switch✅ Included✅ Included
Turn-Key Docker Compose & Kubernetes Scripts✅ Included✅ Included
Enterprise SSO (SAML 2.0, Okta, Entra ID, SCIM)Community OIDC✅ Full SAML / SCIM
Multi-Region Anycast Sync & Distributed EdgeSingle Cluster✅ Global Anycast Mesh
WORM Cold Storage (AWS S3 Object Lock, 7-Year)Daily Indices✅ Immutable WORM S3
Dedicated SLA Support & Custom ConnectorsGitHub Community✅ 24/7/365 Dedicated SLA

Technical FAQ

Frequently Asked Questions

Q: What is X4G4T and what does the name stand for?

X4G4T (pronounced 'X-Four-Gate') is an open-source, defense-grade runtime security firewall, zero-trust credential vault, and containment gateway designed for autonomous AI agents and Model Context Protocol (MCP) servers. The name reflects a cryptic, defense-contractor architecture: four perimeter defense gates (Authentication/RBAC, Pure AST Evaluation, In-Flight DLP/SSRF Sanitization, and Cryptographic Hash Auditing) that seal enterprise infrastructure from unbounded autonomous agent loops, prompt injections, and rogue tool mutations.

Q: Why do autonomous AI agents require a tactical inline firewall?

Autonomous agents (Claude Code, Cursor, Windsurf, Devin, LangChain, AutoGen) do not simply generate prose—they hold tool execution authority. They execute shell binaries, mutate production databases, trigger wire transfers, and handle secrets. Without an inline containment gateway, adversarial prompt injection or model hallucination can force agents to exfiltrate master LLM keys from environment variables, trigger catastrophic DROP TABLE commands, leak confidential PII, or probe internal cloud metadata endpoints (169.254.169.254). X4G4T intercepts and evaluates every tool call in pure in-memory AST in under 0.2ms before state mutations can occur.

Q: How does X4G4T execute Zero-Trust Upstream Key Injection?

Under military-grade operational security, raw master keys (OpenAI sk-proj-*, Anthropic sk-ant-*, Google Gemini, AWS STS credentials) are classified as critical assets that must never reside in developer workstations, local.env files, or agent containers. Agents authenticate to X4G4T using scoped, revocable proxy tokens. X4G4T stores master secrets within an encrypted, isolated key vault and injects genuine provider credentials at the network egress perimeter only after the agent's payload passes all deterministic AST guardrails.

Q: How does X4G4T integrate natively with Model Context Protocol (MCP)?

X4G4T implements native JSON-RPC 2.0 protocol interception. Tool discovery frames (tools/list, initialize, ping) pass through transparently to upstream MCP servers designated by headers. When an agent fires an execution frame (tools/call), X4G4T isolates params.name and params.arguments, executes AST guardrail verification, and either permits forwarding or converts policy violations into standard JSON-RPC 2.0 error payloads (code: -32001) without crashing the agent runtime.

Q: How does X4G4T reconcile ISO 27001 audit immutability with GDPR Article 17 Right to Erasure?

X4G4T utilizes mathematical Crypto-Shredding. Audit metadata (agent ID, tool signature, verdict, timestamp) forms a continuous, tamper-evident SHA-256 hash chain fulfilling ISO/IEC 27001:2022 Control A.8.15. However, sensitive argument payloads containing personal identity identifiers are encrypted using an ephemeral AES-256-GCM subject key derived via HMAC-SHA256. Upon receiving an erasure request under GDPR Art. 17 or the India DPDP Act Sec. 12, the subject key is destroyed. The personal payload becomes mathematically unrecoverable white noise while the audit ledger's hash chain remains verifiable and unbroken.

Q: What are the latency budgets and performance benchmarks for X4G4T?

Empirical Vitest benchmarks demonstrate that X4G4T's pure TypeScript in-memory AST engine executes evaluations in an average of 0.00012ms (0.12 microseconds) with throughput exceeding 8.5 million evaluations per second. On the Fastify proxy ingestion hot path, end-to-end P50 latency is 0.066ms, P95 is 0.295ms, and P99 is 1.346ms—far surpassing our strict 15ms SLA ceiling by more than 11x.

Q: How can engineering and SecOps teams deploy X4G4T?

X4G4T delivers a complete, turn-key Docker Compose stack orchestrating 7 microservices over an isolated network (x4g4t-net): Fastify Gateway (:4000), Next.js Web Control Plane (:3000), PostgreSQL 16 (:5432), Redis 7 (:6379), Elasticsearch 8.13 (:9200), Prometheus 2.51 (:9090), and Grafana 10.4.2 (:3001). A single command 'docker compose up -d' boots the entire stack in under 30 seconds. For enterprise clusters (EKS, GKE, AKS, or air-gapped bare-metal), we provide idempotent Kubernetes manifests and an automated deploy script (./scripts/deploy-k8s.sh).

TAC-CONTAINMENT • APACHE 2.0 OPEN SOURCE

Secure Your Autonomous AI Agents with X4G4T.

Deploy X4G4T (X-Four-Gate) in under 30 seconds with Docker Compose, or partner with ARYIX for institutional architecture advisory, enterprise single sign-on, and custom compliance integrations.