π‘οΈ AegisGate MCP
Secure MCP server framework β 23 layers of defense, zero dependencies.
A hardened, zero-dependency MCP server written in pure Go. Build your MCP server on a foundation that has security built in from line one β not bolted on after a breach.
Apache 2.0 Β· 23 security layers Β· 79 regex patterns + CharCNN-BiLSTM (v13) ML detection Β· Zero CVEs Β· Zero external module dependencies
Quick Start Β· Security Layers Β· RBAC Β· Architecture Β· Protocol Β· Docs Β· Releases
β If AegisGate MCP helps you secure your AI agents, please consider β starring this repo. It helps others discover it.
AegisGate Securityβ’ is a trademark of AegisGate Security, LLC, filed with the USPTO. "AegisGate MCP" is an unregistered product name. See Trademark below.
Why AegisGate MCP?
38% of MCP servers have no authentication. 590+ security advisories. 3 critical CVEs in the official MCP SDKs in 6 months β including CVSS 9.8 remote code execution and the "Mother of All AI Supply Chains" flaw affecting 150M+ downloads.
The official MCP SDKs give you the protocol. They don't give you security. No authentication. No audit logging. No threat detection. No rate limiting. No RBAC. Every server built on a bare SDK starts with a blank security posture and it's on you to build it β or skip it, as 38% of servers do.
AegisGate MCP is the secure alternative. Build your MCP server on a foundation that has security built in from line one β not bolted on after a breach.
23 security layers. 79 regex patterns. Zero dependencies. Zero CVEs. Apache 2.0.
Need proxy mode, OAuth, SIEM, or compliance frameworks? See When to Upgrade to AegisGate Platform below β or explore AegisGate Rampart for local AI API proxy protection.
Overview
AegisGate MCP is a hardened, zero-dependency MCP server written in pure Go. It sits between AI agents and the tools they call, applying 23 layers of defense to every request β from authentication and RBAC to neural threat detection and chain analysis.
Standard MCP servers assume a trusted local environment. In production β whether that's a cloud SaaS platform, an enterprise data pipeline, or an air-gapped plant network β agents may execute commands, query databases, or interact with critical systems. A single unauthorized or malicious tool call can cause data exfiltration, process disruption, or worse. AegisGate MCP wraps every tool call in defense-in-depth, all with zero external module dependencies so it can run air-gapped.
Quick Start
Build
go build -o mcp-server ./cmd/mcp-server
Run
# Basic TCP server on :8081
./mcp-server
# With authentication and audit logging
./mcp-server --token my-secret --audit /var/log/mcp-audit.json
# With demo tools (ping, system_info, echo)
./mcp-server --demo
# stdio mode for local MCP clients (Claude Desktop, Cursor)
./mcp-server --transport stdio --demo
# Streamable HTTP mode (MCP 2025-06-18)
./mcp-server --transport http --addr :8081 --demo
# TLS + mutual TLS
./mcp-server --tls --tls-cert server.pem --tls-key server.key --tls-client-ca ca.pem
# Config file + health endpoint
./mcp-server --config /etc/mcp/config.json --health-addr :8082
Docker
# Build and run (ML-enabled, ~127 MB, 0 CVEs)
docker build --target ml -t aegisgate-mcp .
docker run -p 8081:8081 aegisgate-mcp --demo
# With authentication and audit logging
docker run -p 8081:8081 \
-e MCP_AUTH_TOKEN=your-secret-token \
-e MCP_DEMO_TOOLS=true \
aegisgate-mcp
# Distroless heuristic-only build (~10 MB, 0 CVEs, zero OS packages)
docker build --build-arg CGO_ENABLED=0 --target lite -t aegisgate-mcp:lite .
docker run -p 8081:8081 aegisgate-mcp:lite --demo
The ML image uses debian:bookworm-slim with libgnutls30 purged (shared
libraries and dpkg metadata removed), eliminating all 6 Trivy CVEs while
keeping the glibc and ONNX Runtime dependencies required for neural
inference. The lite image is true distroless
(gcr.io/distroless/static-debian12:nonroot) β zero OS packages, zero
CVEs, ~10 MB. Both targets include a built-in --health-check flag for
Docker HEALTHCHECK (no wget/curl needed). Multi-arch builds support
both linux/amd64 and linux/arm64.
ML Threat Detection (L3)
AegisGate MCP includes the same CharCNN-BiLSTM v13 neural model used by AegisGate Platform and Rampart β vendored with zero external module dependencies. The model provides:
- Semantic attack detection β catches prompt injection and jailbreak attempts that bypass regex pattern matching
- Evasion resistance β detects obfuscation techniques (leetspeak, Unicode homoglyphs, character transposition, vowel deletion, word reversal)
- Two-tier blocking β scores β₯0.95 block independently; scores 0.50β0.94 block only if L1 (regex) or L2 (input scanner) corroboration is present
- Shadow mode β log predictions without blocking (for calibration)
- Heuristic fallback β when CGO is unavailable, heuristic scoring provides baseline detection without ONNX
Library Usage
AegisGate MCP can be embedded as a Go library:
package main
import (
"context"
"log"
mcp "github.com/aegisgatesecurity/aegisgate-mcp"
)
func main() {
cfg := mcp.DefaultServerConfig()
cfg.AuthToken = "my-secret-token"
cfg.AuditLogPath = "/var/log/mcp-audit.json"
cfg.RateLimitRPM = 120
cfg.ScanResponses = true
server, err := mcp.NewSecuredMCPServer(cfg)
if err != nil {
log.Fatal(err)
}
// Register a custom tool
// Note: tools are automatically scanned for prompt-injection poisoning
// at registration time. If the description or inputSchema contains
// malicious patterns, RegisterTool returns *ToolPoisoningError.
server.RegisterTool("my_tool", "Does something useful", 40, map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"param1": map[string]interface{}{"type": "string"},
},
"required": []interface{}{"param1"},
})
server.RegisterToolHandler("my_tool", func(ctx context.Context, params map[string]interface{}) (interface{}, error) {
return "result", nil
})
// Register a resource (MCP resources/list, resources/read)
server.RegisterResource("config://app/info", "App Info", "App config as JSON", "application/json",
func(ctx context.Context, uri string) (*mcp.ResourceContent, error) {
return &mcp.ResourceContent{URI: uri, Text: `{"version":"1.0"}`, MimeType: "application/json"}, nil
})
// Register a prompt (MCP prompts/list, prompts/get)
server.RegisterPrompt("code_review", "Generate a code review prompt",
[]mcp.PromptArgument{{Name: "filename", Required: true}},
func(ctx context.Context, args map[string]string) (*mcp.GetPromptResult, error) {
return &mcp.GetPromptResult{
Messages: []mcp.PromptMessage{{Role: "user", Content: "Review " + args["filename"]}},
}, nil
})
// Load built-in policy rules
server.LoadDefaultPolicies()
// Start the server
if err := server.Start(context.Background()); err != nil {
log.Fatal(err)
}
defer server.Stop()
}
See examples/simple-server/ for a complete working example that registers a tool, resource, and prompt.
ML Model Hot-Swap
Reload the neural threat detection model at runtime without restarting the server:
// Swap to a new ONNX model file (verifies SHA-256 hash)
err := server.ReloadMLModel("/path/to/new_model.onnx")
if err != nil {
log.Printf("model reload failed: %v", err)
}
Tool Poisoning Detection
All tools registered via RegisterTool() are automatically scanned for prompt injection in their descriptions and inputSchema. To scan manually:
err := server.ScanToolForPoisoning("my_tool", description, inputSchema)
if err != nil {
// err is *ToolPoisoningError β do not register this tool
}
Security Layers
AegisGate MCP applies 23 security layers to every request, in order:
Detection Pattern Categories (79 patterns)
AegisGate MCP scans all tool parameters and responses with 79 regex patterns across 8 categories:
Configuration Priority
Configuration is resolved in order of highest to lowest priority:
- CLI flags β override everything
- Environment variables β override config file
- JSON config file (
--config) β overrides built-in defaults - Built-in defaults
CLI Flags
All CLI flags have environment variable equivalents:
JSON Config File
{
"address": ":8081",
"auth_token": "my-secret-token",
"audit_log_path": "/var/log/mcp-audit.json",
"max_sessions": 100,
"max_connections": 1000,
"rate_limit_rpm": 120,
"exec_timeout_seconds": 30,
"scan_responses": true,
"block_on_pii": true,
"block_on_secrets": true,
"block_on_xss": true,
"block_on_prompt_inject": true,
"redact_enabled": true,
"redact_pii": true,
"redact_secrets": true,
"redact_placeholder": "[REDACTED]",
"tls_enabled": true,
"tls_cert_file": "/etc/ssl/mcp/server.pem",
"tls_key_file": "/etc/ssl/mcp/server.key",
"tls_client_ca_file": "/etc/ssl/mcp/ca.pem",
"tls_min_version": "1.3",
"demo_tools": true
}
Transport Modes
Health Endpoints
When --health-addr is set, a separate HTTP listener provides observability endpoints:
RBAC Roles
AegisGate MCP enforces a 4-tier role hierarchy. Roles are ordered: restricted < standard < privileged < admin.
Role comparison uses AgentRole.AtLeast() β a privileged agent can access any tool that requires standard or restricted, but not tools that require admin.
Policy Engine
The Policy Engine evaluates allow/deny rules before any tool executes. Rules support:
- Tool name matching β exact names and wildcard patterns
- Agent role conditions β apply rules only to specific roles
- Risk score thresholds β trigger on
RiskAbovevalues - Priorities β higher-priority rules evaluated first
- Time windows β restrict tools to specific time ranges
- Parameter patterns β match against tool call parameters
- Actions β allow, deny (with reason), log level, risk modifiers
Built-in Policy Rules
Loaded via LoadDefaultPolicies():
Custom rules can be added programmatically:
server.AddPolicyRule(mcp.PolicyRule{
ID: "block-after-hours",
Name: "Block Dangerous Tools After Hours",
Description: "No high-risk tools outside business hours",
Condition: mcp.RuleCondition{
ToolNames: []string{"shell_command", "file_delete"},
TimeWindow: &mcp.TimeWindow{
Start: "08:00",
End: "18:00",
},
},
Action: mcp.RuleAction{
Allow: false,
DenyReason: "High-risk tools only available during business hours",
LogLevel: "warn",
},
Priority: 75,
Enabled: true,
})
Chain Analysis
The Chain Analyzer tracks sequences of tool calls within a session (rolling window of 20 calls) and flags suspicious patterns:
When any flag is raised, the chain risk is set to High and the event is logged at WARN level with the session ID, flags, and call count.
AegisGate MCP supports ECDSA P-256 message signing to prevent request forgery and tampering.
Clients sign the canonical JSON of each request (with Signature and KeyID fields zeroed out)
and include the signature in the request header.
Server Setup
server, _ := mcp.NewSecuredMCPServer(cfg)
// Register a trusted client public key (SEC1 encoded)
server.AddTrustedKey("agent-001", clientPubKeySEC1)
Client Signing (example)
import (
"crypto/ecdsa"
"crypto/sha256"
"crypto/rand"
"encoding/hex"
)
func signRequest(privKey *ecdsa.PrivateKey, canonicalJSON []byte) string {
hash := sha256.Sum256(canonicalJSON)
sig, _ := ecdsa.SignASN1(rand.Reader, privKey, hash[:])
return hex.EncodeToString(sig)
}
The server verifies the signature using ecdsa.VerifyASN1 against the trusted public key.
If no KeyID or Signature is present, verification is skipped β allowing interoperability
with unsigned clients while enforcing signatures for clients that provide them.
Test Coverage
Running Tests
# Non-CGO test suite (heuristic-only, no ONNX)
CGO_ENABLED=0 go test ./... -count=1 -timeout 120s
# CGO test suite (full ML, requires libonnxruntime.so)
CGO_ENABLED=1 CGO_LDFLAGS="-L$(pwd)/lib/amd64 -lonnxruntime" go test ./... -count=1 -timeout 120s
# With race detector (CGO only β -race requires CGO)
CGO_ENABLED=1 CGO_LDFLAGS="-L$(pwd)/lib/amd64 -lonnxruntime" go test -race -count=1 -timeout 300s ./...
# Load/stress/burst/crush/chaos tests (behind build tag)
go test -tags=load -count=1 -timeout 600s -v ./...
# Benchmarks (regression tracking)
go test -bench=. -benchmem -benchtime=5s ./...
# Fuzz testing (run for 60 seconds per target)
go test -fuzz=FuzzHandleRequest -fuzztime=60s ./...
Performance Characteristics
Validated via the k6-style load test suite (//go:build load):
Core Performance
k6-Style Stress / Burst / Crush Results
AegisGate MCP has zero external module dependencies. The go.mod file contains
no require directives. All third-party code (ONNX Runtime bindings, Unicode
normalization, ML model) is vendored into internal/, lib/, and models/.
module github.com/aegisgatesecurity/aegisgate-mcp
go 1.26.9
// Zero external module dependencies (no `require` directives).
// All third-party code is vendored into internal/ β see NOTICE for details.
Vendored components (see NOTICE for full attribution):
Why this matters:
- Air-gapped deployment β no
go mod downloadneeded, no supply chain risk - No transitive dependencies β nothing to audit beyond vendored code
- Reproducible builds β the binary is identical across builds
- Minimal attack surface β all third-party code is visible and auditable
- Fast compilation β no dependency resolution overhead
Architecture
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β AegisGate MCP Server β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β TCP Mode: β
β ββββββββββββ ββββββββββββββββ βββββββββββββ ββββββββββββββββ β
β β TCP βββββΆβ Auth βββββΆβ GuardrailsβββββΆβ Response β β
β β Client β β Middleware β β (Rate + β β Scan β β
β β β β (Token + β β Chain) β β (PII/Secrets β β
β β (TLS/ β β Signature + β β β β /XSS/Inject)β β
β β mTLS) β β Session) β β β β β β
β ββββββββββββ ββββββββββββββββ βββββββββββββ ββββββββ¬ββββββββ β
β β β
β βΌ β
β stdio Mode: ββββββββββββββββββββββββ β
β ββββββββββββ (same security chain, β Request Handler β β
β β stdin / β stdin/stdout instead β ββββββββββββββββββ β β
β β stdout β of TCP) β β RBAC Check β β β
β ββββββββββββ β ββββββββββββββββββ€ β β
β β β Policy Engine β β β
β β ββββββββββββββββββ€ β β
β β β Param Validateβ β β
β β ββββββββββββββββββ€ β β
β β β Tool Registry β β β
β β β + Exec Timeoutβ β β
β β ββββββββββββββββββ β β
β ββββββββββββββββββββββββ β
β β
β Health Endpoint (separate HTTP listener): β
β ββββββββββββββββββββββββββββββββββββββββββ β
β β GET /healthz β liveness β β
β β GET /readyz β readiness β β
β β GET /stats β server statistics β β
β ββββββββββββββββββββββββββββββββββββββββββ β
β β
β Audit Log: all MCP actions β file + in-memory (queryable) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Request flow:
- TCP Client connects (optionally over TLS/mTLS) or stdio sends JSON-RPC via stdin
- Auth Middleware validates bearer token/API key (constant-time), verifies ECDSA signature, creates/validates session
- Guardrails enforce rate limits, session limits, and run chain analysis
- Response Scan (pre-execution parameter validation happens in handler)
- Request Handler checks RBAC permissions, evaluates Policy Engine rules, validates required parameters against
inputSchema, executes tool with timeout - Response Scan (post-execution) scans tool output for PII, secrets, XSS, prompt injection; redacts if enabled
- Audit Log records the complete action chain
MCP Protocol Support
AegisGate MCP implements the following JSON-RPC methods (MCP Protocol 2025-06-18):
Streamable HTTP session management (v1.2.2+):
POST /mcpwithinitializeβ response includesMcp-Session-IdheaderPOST /mcpwith subsequent requests β must includeMcp-Session-IdheaderDELETE /mcpwithMcp-Session-Idheader β terminates session (204 No Content)- Sessions expire after 30 minutes of inactivity
AegisGate MCP serves any environment where AI agents interact with tools β from cloud SaaS platforms to enterprise data pipelines to OT/ICS plant networks. The same 21 security layers apply regardless of deployment context.
General Deployments
- Cloud SaaS β protect user-facing AI features from prompt injection and data exfiltration
- Enterprise data access β enforce RBAC and audit logging on agent-driven database queries
- CI/CD automation β restrict what AI-assisted pipelines can execute
- Air-gapped networks β zero dependencies means the server runs with no internet access
OT/ICS Environments
In an OT/ICS environment, AegisGate MCP sits between AI agents and critical infrastructure tools:
AI Agent (Claude, Cursor, custom)
β
βΌ
ββββββββββββββββββββ
β AegisGate MCP β β 23 security layers
β (TLS/mTLS) β
ββββββββββ¬ββββββββββ
β
ββββββΌβββββ¬βββββ¬βββββ
βΌ βΌ βΌ βΌ βΌ
SCADA PLC Hist Tag Log
Read Status Query DB Analyzer
Typical deployment scenarios:
- Read-only monitoring agent β
restrictedrole, can query SCADA status and historian data but cannot issue commands - Maintenance agent β
standardrole, can read files and search code during troubleshooting - Operations agent β
privilegedrole, can interact with most tools but cannot execute shell commands - Admin agent β
adminrole, full access for authorized maintenance windows
Security features particularly relevant to OT/ICS:
- TLS/mTLS encrypts all traffic on the plant network
- Time-window policies restrict high-risk tools to maintenance windows
- Chain analysis detects if an agent reads sensitive process data then attempts an external network write (exfiltration)
- Audit logging provides a complete chain of custody for compliance (NERC CIP, IEC 62443)
- Air-gapped operation β zero dependencies means the server can be deployed on isolated networks with no internet access
Demo Tools
Enable demo tools with the --demo flag or by calling RegisterDemoTools() in library mode.
These are safe, read-only tools that do not access the filesystem, network, or any external resources.
Example β system_info response:
{
"go_version": "go1.26.9",
"os": "linux",
"arch": "amd64",
"cpus": 8,
"goroutines": 12,
"timestamp": "2026-10-08T08:58:00Z"
}
Documentation
Detailed documentation is available in the docs/ directory:
Changelog
See CHANGELOG.md for version history and notable changes.
Platform Interop (Optional)
AegisGate MCP can optionally integrate with AegisGate Platform for pattern pulling and event forwarding:
- Pattern Pull: Fetch canonical detection patterns from Platform's telemetry endpoint with ETag caching
- Event Forwarding: Send security events to Platform's telemetry receiver in canonical contract format
- Tool Description Screening: Enhanced with 34 dangerous function patterns from AegisGate Scanner
All interop features are air-gap compatible β fully disabled when platform_url is not configured. No network calls, no telemetry, no external dependencies.
When to Upgrade to AegisGate Platform
AegisGate MCP is a standalone secure MCP server framework β perfect for building and running MCP servers with security built in. It's free, open source, and has zero external dependencies.
When your needs grow beyond a single server, AegisGate Platform is the natural upgrade path:
Think of it this way: AegisGate MCP is the secure foundation you build MCP servers on. AegisGate Platform is the enterprise gateway that secures all AI traffic across your organization β including MCP, HTTP, A2A, and ACP.
Other AegisGate products:
- AegisGate Rampart β Free local proxy for developers using Claude, Cursor, or Copilot
- AegisGate Lens β Free browser extension for everyday AI conversations
License
Apache-2.0. See LICENSE for the full text and NOTICE for attribution.
Security
See SECURITY.md for vulnerability reporting.
Contributing
See CONTRIBUTING.md. All commits must be signed off (git commit -s) per the DCO.
IP Notice
AegisGate's core technologies are patent pending with the USPTO (Provisional App. Nos. 64/153,573β64/153,577, filed September 12, 2026; 64/174,824, filed October 12, 2026; and 64/180,722, filed October 20, 2026). Source code is Β© 2025-2026 AegisGate Security, LLC. Licensed under Apache 2.0.
Trademark
AegisGate Securityβ’ is a trademark of AegisGate Security, LLC, filed with the United States Patent and Trademark Office (USPTO). The mark was published for opposition on October 13, 2026.
AegisGate MCP is an unregistered product name of AegisGate Security, LLC. The β’ symbol is not used for this product name, as it has not been separately filed as a trademark application. Use of the "AegisGate Security" mark is governed by the Lanham Act (15 U.S.C. Β§ 1126) and applicable state trademark law.
Permission is granted to use the AegisGate name and marks in connection with the unmodified open-source software distribution as published on GitHub. Use of the AegisGate name, logo, or other brand assets in derivative works, commercial products, service offerings, or marketing materials requires prior written permission from AegisGate Security, LLC.
Contact: [email protected]
π AegisGate Security Β· π¬ Discord Β· βοΈ [email protected] Β· π @aegisgate Β· π± Telegram Β· π @[email protected]
Made with π€ by AegisGate Security developers to secure the AI attack surface.