Skip to content

About

MCP middleware gateway between [ARTEX](https://github.com/bulletdev/artex) and external scanner backends

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

 █████╗ ██████╗ ████████╗███████╗██╗  ██╗
██╔══██╗██╔══██╗╚══██╔══╝██╔════╝╚██╗██╔╝
███████║██████╔╝   ██║   █████╗   ╚███╔╝
██╔══██║██╔══██╗   ██║   ██╔══╝   ██╔██╗
██║  ██║██║  ██║   ██║   ███████╗██╔╝ ██╗
╚═╝  ╚═╝╚═╝  ╚═╝   ╚═╝   ╚══════╝╚═╝  ╚═╝
    ███╗   ███╗██╗██████╗ ██████╗ ██╗     ███████╗██╗    ██╗ █████╗ ██████╗ ███████╗
    ████╗ ████║██║██╔══██╗██╔══██╗██║     ██╔════╝██║    ██║██╔══██╗██╔══██╗██╔════╝
    ██╔████╔██║██║██║  ██║██║  ██║██║     █████╗  ██║ █╗ ██║███████║██████╔╝█████╗
    ██║╚██╔╝██║██║██║  ██║██║  ██║██║     ██╔══╝  ██║███╗██║██╔══██║██╔══██╗██╔══╝
    ██║ ╚═╝ ██║██║██████╔╝██████╔╝███████╗███████╗╚███╔███╔╝██║  ██║██║  ██║███████╗
    ╚═╝     ╚═╝╚═╝╚═════╝ ╚═════╝ ╚══════╝╚══════╝ ╚══╝╚══╝ ╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝
                     MCP Middleware Gateway -- effront

Codacy Badge Go Version Redis MCP Protocol Docker License: AGPL v3

CI Security Scan Staticcheck CodeQL Semgrep


+===========================================================================+
|  ARTEX MIDDLEWARE -- Go MCP Gateway                                       |
+===========================================================================+
|  Generic MCP middleware between ARTEX AI workers and external scanner     |
|  backends. 11-step dispatch pipeline, L1/L2 cache, circuit breaker,       |
|  rate limiter, scan queue. Backend-agnostic -- plug in any scanner via    |
|  the dispatch.Backend interface. AnarCry subprocess as first backend.     |
|  Battle-tested architecture from prostaff-riot-gateway.                   |
+===========================================================================+

Features (click to expand)
+---------------------------------------------------------------------------+
|  [x] MCP Protocol        -- JSON-RPC 2.0 over Streamable HTTP             |
|  [x] 30 MCP Tools        -- 20 individual + 5 compound + 5 utility        |
|  [x] 11-Step Pipeline    -- auth, cache, circuit breaker, dispatch        |
|  [x] L1 LRU Cache        -- in-memory with TTL, negative cache, GC        |
|  [x] L2 Redis Cache      -- shared across instances, graceful degradation |
|  [x] Circuit Breaker     -- per {target_host}:{group}, 3-state machine    |
|  [x] Rate Limiting       -- dual token bucket (per-sec + per-min)         |
|  [x] Scan Queue          -- semaphore-based concurrency control           |
|  [x] Generic Backend     -- dispatch.Backend interface, plug any scanner  |
|  [x] Dynamic Tool Discovery  -- backend.DiscoverTools() populates catalog |
|  [x] Per-Backend Cache Keys  -- backend.CacheKey() for custom derivation  |
|  [x] Per-Backend Breaker Groups  -- backend.BreakerGroup() per tool       |
|  [x] Finding Normalization   -- structured output for LLM consumption     |
|  [x] Retry with Backoff  -- progressive 0/500ms/2s on subprocess failure  |
|  [x] Unreachable Detection   -- fast-fail on target connectivity errors   |
|  [x] Request ID Propagation  -- X-Request-ID for log correlation          |
|  [x] Structured JSON Logging -- slog JSON, compatible with aggregators    |
|  [x] Graceful Shutdown   -- 30s drain for in-flight scans                 |
|  [x] Health Endpoint     -- redis, queue, circuit breakers, backend       |
|  [x] Docker Ready        -- multi-stage build, Alpine final image         |
+---------------------------------------------------------------------------+

Table of Contents

+------------------------------------------------------+
|  01 - Quick Start                                    |
|  02 - Technology Stack                               |
|  03 - Architecture                                   |
|  04 - Request Pipeline                               |
|  05 - MCP Protocol                                   |
|  06 - Tool Catalog                                   |
|  07 - Cache TTLs                                     |
|  08 - Configuration                                  |
|  09 - CI/CD                                          |
|  10 - Adding a New Backend                           |
|  11 - Project Structure                              |
|  12 - Ethical Use                                    |
+------------------------------------------------------+

01 - Quick Start

cp .env.example .env
go build -o middleware ./cmd/server
# Minimal -- just the middleware + AnarCry JAR
ANARCRY_JAR=/path/to/anarcry.jar ./middleware

# With Redis L2 cache
ANARCRY_JAR=/path/to/anarcry.jar REDIS_URL=redis://localhost:6379/2 ./middleware

# With API key protection
ANARCRY_JAR=/path/to/anarcry.jar GATEWAY_API_KEY=your-secret-key ./middleware

Health check:

curl http://localhost:9090/health
{
  "status": "ok",
  "version": "0.1.0",
  "redis": "ok",
  "queue": {"in_flight": 0, "max_concurrent": 4},
  "circuit_breakers": {},
  "backend": {"name": "anarcry", "available": true, "version": "2.5.0"}
}

Docker

docker build -t artex-middleware .
docker run -p 9090:9090 \
  -v /path/to/anarcry.jar:/opt/anarcry/anarcry.jar:ro \
  artex-middleware

See DEPLOY-artex-anarcry.md in the AnarCry repo for the full Docker Compose stack (ARTEX + Middleware + Redis + PostgreSQL).


02 - Technology Stack

+======================+====================================================+
|  LAYER               |  TECHNOLOGY                                        |
+======================+====================================================+
|  Language            |  Go 1.22+ (developed with 1.26)                    |
|  MCP Protocol        |  JSON-RPC 2.0 over Streamable HTTP (2025-06-18)    |
|  HTTP Router         |  net/http ServeMux (Go 1.22+ method routing)       |
|  Rate Limiting       |  golang.org/x/time/rate (dual token bucket)        |
|  Cache L1            |  Custom LRU (sync.RWMutex + container/list + TTL)  |
|  Cache L2            |  Redis 7 (go-redis/v9)                             |
|  Circuit Breaker     |  Custom 3-state machine with failure time window   |
|  Config              |  godotenv + os.Getenv                              |
|  Logging             |  log/slog (JSON handler, stdlib Go 1.21+)          |
|  Container           |  Docker multi-stage (Alpine final image)           |
+======================+====================================================+

03 - Architecture

ARTEX AI Workers                    artex-middleware                     Scanner Backends
+-------------------+         +-----------------------------+         +-------------------+
|                   |  MCP    |                             |         |                   |
|  Worker agents    | ------> |   11-step pipeline          | ------> |   (Java scanner)  |
|  call MCP tools:  | JSON-RPC|                             | subprocess                  |
|                   | over    |  1. Request ID              |  java   |   44 attack       |
|  scan_sqli        | HTTP    |  2. Auth (API key)          |  -jar   |   modules         |
|  scan_xss         |         |  3. Tool validation         |  ...    |                   |
|  scan_ssrf        |         |  4. L1 negative cache       |         +-------------------+
|  scan_recon       |         |  5. L1 positive cache       |
|  crawl_target     |         |  6. L2 Redis cache          |         +-------------------+
|  fuzz_endpoint    |         |  7. Circuit breaker         |         |   Your Backend    |
|  ...              |         |  8. Rate limiter            | ------> |   (REST, gRPC,    |
|                   |         |  9. Scan queue              |  any    |    subprocess,    |
+-------------------+         | 10. Backend dispatch        | protocol|    ...)           |
                              | 11. Error handling          |         +-------------------+
                              +-----------------------------+
                                        |
                                   Redis (L2)
                              optional, degrades gracefully

04 - Request Pipeline

 1. X-Request-ID         -> read from header or generate UUID v4
 2. Auth validation       -> API key check on initialize (optional)
 3. Tool validation       -> verify tool exists + required params present
 4. L1 negative cache     -> 404/unreachable cached? fast-fail
 5. L1 positive cache     -> LRU hit? return in < 2ms
 6. L2 Redis cache        -> populate L1, return if hit
 7. Circuit breaker       -> {target_host}:{group} open? reject
 8. Rate limiter          -> dual token bucket (per-sec + per-min)
 9. Scan queue            -> semaphore acquire (max concurrent scans)
10. Backend dispatch      -> tool -> backend.Dispatch() with retry
11. Error handling        -> typed errors (timeout, unreachable, crash, rate limit)
    On success            -> populate L1 + L2, return normalized findings
    On target unreachable -> cache negative in L1, return error
    On persistent failure -> trip circuit breaker, return error

Circuit Breaker States

     +---------+     failures >= threshold     +--------+
     | CLOSED  | ---------------------------> |  OPEN  |
     |  (allow |                              | (reject|
     |   all)  | <--------------------------- |  all)  |
     +---------+     probe succeeds            +--------+
                                                   |
                                     cooldown elapsed
                                                   |
                                                   v
                                             +-----------+
                                             | HALF-OPEN |
                                             | (allow 1  |
                                             |  probe)   |
                                             +-----------+
                                              /         \
                                   success  /           \ failure
                                           v             v
                                       CLOSED          OPEN

Failure counting uses a time window -- stale failures from hours ago don't trip the breaker.


05 - MCP Protocol

Endpoints

POST   /mcp      -- JSON-RPC 2.0 (initialize, notifications/initialized,
                    tools/list, tools/call)
DELETE /mcp      -- Close MCP session
GET    /health   -- Health check (no auth required)

Handshake

# 1. Initialize -- get session ID
curl -sD - -X POST http://localhost:9090/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
      "protocolVersion": "2025-06-18",
      "clientInfo": {"name": "artex", "version": "0.2"}
    }
  }'

# Response header: Mcp-Session-Id: <uuid>

# 2. List available tools
curl -s -X POST http://localhost:9090/mcp \
  -H "Content-Type: application/json" \
  -H "Mcp-Session-Id: <session-id>" \
  -d '{"jsonrpc": "2.0", "id": 2, "method": "tools/list"}'

# 3. Call a tool
curl -s -X POST http://localhost:9090/mcp \
  -H "Content-Type: application/json" \
  -H "Mcp-Session-Id: <session-id>" \
  -d '{
    "jsonrpc": "2.0",
    "id": 3,
    "method": "tools/call",
    "params": {
      "name": "scan_sqli",
      "arguments": {"url": "https://target.example.com/api/users?id=1"}
    }
  }'

# 4. Close session
curl -X DELETE http://localhost:9090/mcp \
  -H "Mcp-Session-Id: <session-id>"

Register in ARTEX

TOKEN=$(curl -s -X POST http://localhost:8787/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"..."}' | jq -r '.token')

curl -X POST http://localhost:8787/api/mcp \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "name": "anarcry",
    "transport": "http",
    "url": "http://middleware:9090/mcp",
    "enabled": true
  }'

06 - Tool Catalog

Tools are discovered dynamically from the backend via backend.DiscoverTools(). The AnarCry subprocess backend exposes 30 tools:

Individual Scan Tools (20)

Tool AnarCry Module Breaker Group
scan_sqli SQLi injection
scan_xss XSS xss
scan_ssrf SSRF ssrf
scan_ssti SSTI injection
scan_idor IDOR authz
scan_lfi LFI injection
scan_rce CmdInjection injection
scan_xxe XXE injection
scan_cors CORS config
scan_csrf CSRF authz
scan_jwt JWT authn
scan_auth_bypass OAuth authn
scan_open_redirect OpenRedirect other
scan_smuggling ReqSmuggling transport
scan_crlf CRLF injection
scan_graphql GraphQL api
scan_websocket WebSocket transport
scan_cache_poison CachePoisoning transport
scan_race_condition RaceCondition other
scan_prototype_pollution ProtoPollution xss

Compound Scan Tools (5)

Tool AnarCry Modules Description
scan_recon Crawler, Infra Recon -- crawl + infrastructure fingerprint
scan_config Headers, Actuator Config and information leak scan
scan_authn JWT, OAuth Authentication attack surface
scan_crypto TLS, PQC Cryptographic and PQC readiness checks
scan_api IDOR, MassAssign, GraphQL API-specific vulnerability scan

Utility Tools (5)

Tool Description
fuzz_endpoint HTTP fuzzer -- sniper, battering-ram, pitchfork, cluster-bomb
crawl_target Crawl and discover endpoints and paths
validate_finding Validate a finding with an exploitation pass
query_kb Query vulnerability knowledge base (local, never cached)
get_oast_url Get OAST callback URL for blind vulnerability detection

07 - Cache TTLs

Per-group TTLs for the 11-step pipeline cache layers:

+=======================+==========+==========+==============+
|  Breaker Group        |  L1 TTL  |  L2 TTL  |  Neg (L1)    |
+=======================+==========+==========+==============+
|  recon                |  30 min  |   2 h    |  5 min       |
|  injection            |  10 min  |  30 min  |  2 min       |
|  xss                  |  10 min  |  30 min  |  2 min       |
|  ssrf                 |  10 min  |  30 min  |  2 min       |
|  authn                |  10 min  |  30 min  |  2 min       |
|  authz                |  10 min  |  30 min  |  2 min       |
|  transport            |  10 min  |  30 min  |  2 min       |
|  api                  |  10 min  |  30 min  |  2 min       |
|  config               |  30 min  |   2 h    |  5 min       |
|  fuzz                 |   5 min  |  15 min  |  2 min       |
|  exploit              |   5 min  |  15 min  |  2 min       |
|  other (default)      |  10 min  |  30 min  |  2 min       |
+=======================+==========+==========+==============+

Recon and config scans have longer TTLs because infrastructure changes slowly. Fuzz and exploit results have shorter TTLs because they're more context-sensitive. Negative cache prevents repeated probes against unreachable targets.

L2 Redis is optional -- when unavailable, the middleware degrades to L1-only caching.


08 - Configuration

All configuration via environment variables. See .env.example for the full list.

# Gateway
GATEWAY_PORT=9090                  # Server port
GATEWAY_API_KEY=                   # Optional API key to gate MCP initialize
LOG_LEVEL=info                     # debug | info | warn | error

# Backend (AnarCry subprocess)
ANARCRY_JAR=/opt/anarcry/anarcry.jar  # Path to AnarCry shadow JAR
ANARCRY_JAVA=java                  # Java binary
ANARCRY_TIMEOUT=120s               # Per-scan timeout
ANARCRY_MAX_RETRIES=3              # Retry count with progressive backoff

# Concurrency
SCAN_MAX_CONCURRENT=4              # Max concurrent scans (semaphore)
SCAN_RATE_PER_SECOND=4             # Token bucket -- per-second rate
SCAN_RATE_BURST=4                  # Token bucket -- burst size
SCAN_RATE_PER_MINUTE=30            # Token bucket -- per-minute rate

# Cache
CACHE_ENABLED=true                 # Enable L1/L2 caching
CACHE_L1_MAX_SIZE=5000             # Max L1 LRU entries
REDIS_URL=redis://localhost:6379/2 # Redis URL for L2 cache

# Circuit Breaker
CB_THRESHOLD=3                     # Consecutive failures to open circuit
CB_TIMEOUT=60s                     # Failure counting time window
CB_COOLDOWN=30s                    # Seconds before half-open probe

09 - CI/CD

Workflows (.github/workflows/):

+---------------------------------------------------------------------------+
|  ci.yml              -- Build, vet, test, govulncheck, staticcheck        |
|                         on push/PR to main and develop                    |
|  security-scan.yml   -- CodeQL, Semgrep, TruffleHog secret scan           |
|                         on push/PR + weekly Monday 9AM UTC                |
|  dependency-review.yml -- Dependency review on PRs to main                |
+---------------------------------------------------------------------------+
Workflow Trigger Jobs
CI push/PR to main, develop Build & Vet, Test (with Redis service), govulncheck, staticcheck
Security Scan push/PR + weekly schedule CodeQL (Go), Semgrep (auto rules), TruffleHog (verified secrets)
Dependency Review PR to main Scan go.mod changes for known vulnerabilities

All workflows post summary comments on PRs. Security scan runs weekly even without code changes to catch newly disclosed vulnerabilities in dependencies.

Local Development

# Build
go build -o middleware ./cmd/server

# Vet
go vet ./...

# Test
go test -v -race ./...

# Vulnerability check
go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...

# Static analysis
go install honnef.co/go/tools/cmd/staticcheck@latest
staticcheck ./...

10 - Adding a New Backend

The middleware is designed to be backend-agnostic. The AnarCry subprocess is just the first implementation. To plug in a new scanner:

1. Implement the Backend interface

// internal/dispatch/backend.go
type Backend interface {
    Name() string
    Dispatch(ctx context.Context, tool string, args json.RawMessage) (*Result, error)
    Available() bool
    Version() string
    DiscoverTools() []Tool
    BreakerGroup(tool string) string
    CacheKey(tool string, args json.RawMessage) (cacheKey, negativeKey, targetHost string)
}
Method Purpose
Name() Backend identifier for health/logs
Dispatch() Execute a tool call, return normalized findings
Available() Liveness check (used by /health)
Version() Backend version string (cached)
DiscoverTools() Return the MCP tool catalog this backend exposes
BreakerGroup(tool) Map a tool to its failure domain for circuit breaking
CacheKey(tool, args) Derive cache key, negative key, and target host from tool args

2. Create your implementation

// internal/dispatch/mybackend.go
type MyBackend struct { /* ... */ }

func (b *MyBackend) Name() string { return "my-scanner" }

func (b *MyBackend) DiscoverTools() []Tool {
    return []Tool{
        {Name: "my_scan", Description: "My custom scan", InputSchema: mySchema()},
    }
}

func (b *MyBackend) BreakerGroup(tool string) string {
    // Group tools into failure domains
    return "default"
}

func (b *MyBackend) CacheKey(tool string, args json.RawMessage) (string, string, string) {
    // Extract target from YOUR tool's argument schema
    var p struct { Target string `json:"target"` }
    json.Unmarshal(args, &p)
    host := extractHost(p.Target)
    return fmt.Sprintf("scan:%s:%s", host, tool), fmt.Sprintf("neg:%s:%s", host, tool), host
}

func (b *MyBackend) Dispatch(ctx context.Context, tool string, args json.RawMessage) (*Result, error) {
    // Call your scanner, normalize output to Result
}

3. Wire it in main.go

backend := dispatch.NewMyBackend(cfg.MyBackendConfig, logger)

The pipeline (cache, circuit breaker, rate limiting, scan queue) works identically for any backend. Tool catalog is populated from backend.DiscoverTools() automatically.


11 - Project Structure

artex-middleware/
+-- cmd/server/main.go               Entry point, dep wiring, graceful shutdown
+-- internal/
|   +-- config/
|   |   +-- config.go                Typed config from env vars with defaults
|   +-- mcp/
|   |   +-- server.go                MCP HTTP handler (initialize, tools/list,
|   |   |                            tools/call, session management)
|   |   +-- jsonrpc.go               JSON-RPC 2.0 types, error codes, helpers
|   |   +-- session.go               Session manager (sync.Map, UUID v4)
|   |   +-- tools.go                 Tool catalog with registration + validation
|   +-- middleware/
|   |   +-- requestid.go             X-Request-ID injection (read or generate UUID)
|   +-- cache/
|   |   +-- memory.go                L1 LRU: sync.RWMutex + container/list,
|   |   |                            Get/Set/IsNegative/SetNegative, background GC
|   |   +-- redis.go                 L2 Redis: graceful degradation (nil client on
|   |   |                            failure), synchronous Set with 500ms timeout
|   |   +-- ttl.go                   Per-group TTL maps (L1, L2, negative)
|   +-- circuit/
|   |   +-- breaker.go               3-state machine (Closed/Open/HalfOpen) with
|   |   |                            failure time window and cooldown
|   |   +-- target_breakers.go       Per {target_host}:{group} breaker registry
|   +-- ratelimit/
|   |   +-- limiter.go               Dual token bucket (per-second + per-minute)
|   |   +-- queue.go                 Semaphore-based scan queue (Acquire/Release)
|   +-- dispatch/
|   |   +-- backend.go               Generic Backend interface + Tool/Result types
|   |   +-- subprocess.go            AnarCry subprocess dispatcher (tool->module
|   |   |                            mapping, retry with backoff, unreachable
|   |   |                            detection, version caching)
|   |   +-- normalize.go             Finding normalization for LLM consumption
|   |   +-- errors.go                Typed errors (ScanTimeout, TargetUnreachable,
|   |                                ScanCrash, RateLimit)
|   +-- handlers/
|   |   +-- base.go                  11-step dispatch pipeline (implements
|   |   |                            mcp.Pipeline interface)
|   |   +-- health.go                GET /health with version, redis, queue,
|   |                                circuit breakers, backend status
|   +-- webutils/
|       +-- json.go                  WriteJSON, RawJSON, ErrorJSON helpers
+-- .github/workflows/
|   +-- ci.yml                       Build, vet, test, govulncheck, staticcheck
|   +-- security-scan.yml            CodeQL + Semgrep + TruffleHog (weekly + push/PR)
|   +-- dependency-review.yml        Dependency review on PRs
+-- Dockerfile                       Multi-stage: Go builder + eclipse-temurin Alpine
+-- .env.example                     All env vars documented
+-- SECURITY.md                      Security policy and responsible disclosure
+-- CODE_OF_CONDUCT.md               Contributor Covenant v2.1
+-- CONTRIBUTING.md                  Contribution guide with Backend interface docs

12 - Ethical Use

artex-middleware is designed for authorized security testing only:

  • Always obtain written authorization before scanning
  • Configure scope boundaries in ScanConfig to prevent out-of-scope probing
  • Never scan targets without explicit permission
  • Findings are for defensive purposes -- helping teams fix vulnerabilities
  • The middleware enforces rate limiting and circuit breaking to prevent abuse

Last Updated: 2026-11-29 Go Version: 1.22+ (developed with 1.26) MCP Protocol: JSON-RPC 2.0 over Streamable HTTP, protocol version 2025-06-18 Cache Strategy: L1 LRU (in-memory + TTL + GC) + L2 Redis + negative cache Architecture: Based on the production-tested prostaff-riot-gateway pattern

About

MCP middleware gateway between [ARTEX](https://github.com/bulletdev/artex) and external scanner backends

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages