Skip to main content
Glama
aletheia-aegis

aletheia-aegis

Aletheia Aegis: Inference-Time Output Enforcement for Autonomous Agents

A deterministic, sub-millisecond inference-time guard for model outputs. Fail-closed on irreversible harm with zero extra model inference on the fast path, and an optional semantic judge only for cases patterns cannot settle.

Architecture Layer p95 Latency Throughput License vikasny30/aletheia-aegis MCP server

Aegis is the output plane of the Aletheia safety framework. It inspects generated text before it reaches a user, blocks credential leaks and life-safety failures outright, and flags everything else for audit or disclaimer. It runs offline by default, on CPU, with no response text retained.

Ships as an MCP server, TypeScript SDK, and CLI. Version 0.3.1. Apache 2.0. TypeScript, Node.js 18 or later.


Why Aegis exists

Built for platform, security, and AI infrastructure teams deploying tool-using agents into regulated or high-throughput production environments.

Production agents need safety that does not break the product. The common approach, running a second LLM as judge on 100 percent of outbound traffic, fails on three counts at scale:

  1. Latency. A 1,000 to 4,000 ms penalty per turn breaks streaming and multi-step agentic loops.

  2. Cost. A secondary frontier model on every payload turns safety into a cost center, roughly $0.002 to $0.02 per evaluation, tens of thousands of dollars monthly at scale.

  3. Reliability. A probabilistic model policing another probabilistic model inherits prompt injection, evaluator hallucination, and nondeterministic bypasses.

Even smaller dedicated guardrail models (such as Llama Guard or classifier checkpoints) still add GPU infrastructure, tens of milliseconds of inference overhead, and probabilistic variance to every response.

Aegis takes the opposite starting point: enforce the non-negotiable invariants at inference time deterministically on CPU, with zero extra model inference on the fast path, and reserve model judgment for the small set of cases where semantics actually matter.

That is the core design bet. Deterministic first, semantic second, fail-closed throughout.


Related MCP server: Redaction & Compliance MCP Server

Principles

  1. Deterministic first. Pattern and structural checks run on every output. No network call, no model call, no variance.

  2. Fail-closed on irreversible harm. Credential exfiltration and life-safety violations block immediately. They are never sent to an external judge and cannot be overruled by one.

  3. Semantic judgment is optional and pre-redacted. When enabled, a judge sees only masked payloads, under strict rubrics, with injection defenses on the review path itself.

  4. Zero retention by default. Telemetry stores verdict counts, signature IDs, and timings only. No prompt or response text in logs.

  5. Honest boundaries. Aegis is a fast first-line filter, not a proof of completeness. Its limits are documented below, not buried.


Architecture

flowchart TB
    subgraph Aegis["Aletheia Aegis: Inference-Time Safety Platform"]
        direction TB
        A["Host application / Agent runtime<br/>Raw model response stream"]
        A --> B["Stage 1: Deterministic engine<br/>DFA and structural checks, p95 about 0.02-0.04 ms<br/>S1 Grounding, S2a Identity, S3 PII/Credentials,<br/>S4 Context, S5 Medical/Legal, S6 Life-safety, S7 Attribution"]
        B --> C{"Verdict?"}
        C -->|"BLOCK (S3, S6)"| D["Hard block<br/>Immediate fail-closed termination<br/>No judge dispatch, no exfiltration risk"]
        C -->|"ALLOW / FLAG"| E["Optional Stage 2: Semantic judge<br/>Pre-redacted, anti-injection<br/>S6 can never be overruled"]
        E --> F["Citation check<br/>Crossref: DOI, arXiv, PMID"]
        F --> G["Audit telemetry<br/>Metadata and timing counts only"]
    end

    D --> H["Blocked: no output delivered"]
    G --> I["Governed response to user"]

How the two stages work

Stage 1: Deterministic edge engine. Every output is evaluated on CPU in about 0.02 to 0.04 ms at p95 (see Performance and evaluation). Irreversible failures trigger an immediate hard block. The upstream judge is skipped entirely, which saves cost and removes the exfiltration path.

Stage 2: Optional semantic judge. For subjective or complex epistemic checks, an external judge (Anthropic, OpenAI, Gemini) can be called under strict rubrics. Detected secrets are masked before dispatch, life-safety findings can never be overruled, and heuristic defenses catch reviewer-targeted prompt injections.


Where Aegis fits: the Aletheia dual layer

The Aletheia research paper standardizes nine failure signatures across the agentic lifecycle, grounded in 2,571 real-world incident records from the AI Incident Database, AVID, and the MIT AI Risk Repository. Aegis covers the output plane. Its companion, aletheia-mcp, covers the action plane.

Signature

Failure

Enforced by

Action

S1

Confidence without grounding

Aegis

Flag

S2a

Social / identity manipulation

Aegis

Flag

S2b

Adversarial jailbreak and injection

aletheia-mcp

Block (pre-execution)

S3

Scope creep and data leakage

Dual layer

Block (hard gate)

S4

Context blindness and idiom traps

Aegis

Flag (heuristic, experimental)

S5

Unsafe prescriptive fallback

Aegis

Flag / Block

S6

Vulnerability signal blindness

Aegis

Block (invariant)

S7

Institutional credibility spoofing

Aegis

Flag

S8

Feedback loop and session erosion

Session auditor (planned)

Multi-turn audit

S3 is split by plane by design, so no single layer is a single point of failure:

  • Action plane (aletheia-mcp): guards tool execution (shell commands, filesystem mutations, database writes, SSRF calls) before execution.

  • Output plane (Aegis): guards generated token streams (SSNs, API keys, credentials, private keys, Luhn-valid cards) before presentation.


What it enforces

Signature

What it catches

Verdict

S1

Unhedged specific statistical claims, fabricated citations, unverified DOIs, arXiv IDs, PMIDs. Scholarly verification via Crossref.

Flag

S2a

Unauthorized claims of professional licensure, for example "As your board-certified oncologist" or "Speaking as your legal counsel."

Flag

S3

Exfiltrated credentials: SSNs, Luhn-checked cards (Visa, Mastercard, Amex, Discover, JCB), API keys (Stripe, AWS, GitHub, Google, SendGrid), JWTs, RSA/EC/SSH private keys, environment variables. Documented test cards (4242) and sample tokens pass.

Block

S4

Literal readings of common idioms ("I could kill him", "Break a leg"). Experimental heuristic.

Flag

S5

Prescriptive medical dosages, unhedged pharmaceutical directives, capability confabulations.

Flag

S6

Self-harm method detail or encouragement. Permanent hard invariant: pairing with a crisis hotline does not waive a method. Crisis intent without a hotline generates remediation resources.

Block / Flag

S7

Unverified attribution to authoritative bodies ("According to official WHO directives") to prevent disinformation laundering.

Flag


Performance and evaluation

Measured on Apple Silicon (macOS, Node.js 26), single core. Timings vary with machine load; run npm run benchmark to measure on your own hardware.

Metric

Result

p50 latency, deterministic filter

about 0.01 to 0.025 ms

p95 latency, deterministic filter

about 0.02 to 0.04 ms

Throughput

about 37,000 to 78,000 evals/sec, single core, unbatched

Memory

about 64 MB RSS for the idle server (Node.js 26, macOS arm64); no native modules

Benign false positives

0 of 90

Bundled eval corpus

215 of 215 pass, zero regression

Held-out catch rate, batches 10-11, balanced policy

90.2 percent, with 1.4 percent false alarms

Held-out evaluation used 917 real model outputs from 48 open and frontier models, in 11 batches. Batches 10-11 replay offline with no external API cost:

npm run eval:heldout:judge

Labels were committed before measurement. The 90.2 percent figure is the balanced-policy result with the semantic judge enabled. On the same two batches, patterns alone catch 39 of 51 failures (76 percent) and wrongly flag 10 of 147 good outputs (6.8 percent), which is why the two-stage design exists. A second live run on 2026-11-29 caught 94.1 percent and wrongly flagged 4.1 percent; the judge agreed with its own earlier labels on 96 percent of outputs, so read the judge figures as a range (details in eval/heldout/README.md). See eval/ for the labeled cases and replay instructions.

Labels were drafted with an AI coding assistant under the author's direction. A second model family (Kimi K2) labeled batches 1–9 blind as a cross-check, and the author blind-reviewed 83 of the 198 batch 10–11 labels by hand (83/83 agreement). Full methodology is in eval/heldout/README.md.

Adversarial testing

Six rounds of cross-family adversarial testing, conducted with Claude Sonnet 5.5 and Gemini 3.5 Flash, covering ReDoS elimination, life-safety false blocks, preposition pairing, code-fence handling, boundary integrity, and MCP concurrency. Each round's findings and fixes are summarized in CHANGELOG.md; the test suite reproduces the checks offline.

A note on method: model-assisted red-teaming is useful for finding bypasses, it is not independent validation. The held-out numbers above are the empirical claim. The adversarial rounds are the hardening process behind them.


Security: zero retention

  • No response text in audit trails. Telemetry and metrics store verdict counters, signature IDs, and timings only.

  • Pre-judge secret masking. If a judge is enabled, detected credentials, API keys, and SSNs are masked before dispatch to any external provider.

  • Fail-closed isolation. Pattern-based blocks halt immediately and are never sent to external judges.

  • Verified by leak tests. npm run test:leak asserts zero trace of canary tokens across logs, telemetry, and outbound payloads.


Quick start

1. CLI

# Prescriptive medical directive (S5)
npx aletheia-aegis --check "Take 500mg of ciprofloxacin twice daily for 10 days."
# FLAG [S5_DOSAGE_WITHOUT_DEFERRAL]

# Credential leak (S3)
npx aletheia-aegis --check "Database connection: postgres://admin:secretKey987654@db.prod:5432/main"
# BLOCK [S3_CREDENTIAL_PAIR] (masked evidence)

2. MCP server (Claude Desktop, Cursor, Cline, OpenRouter)

{
  "mcpServers": {
    "aletheia-aegis": {
      "command": "npx",
      "args": ["-y", "aletheia-aegis"]
    }
  }
}

With an optional Tier-2 judge:

{
  "mcpServers": {
    "aletheia-aegis": {
      "command": "npx",
      "args": ["-y", "aletheia-aegis"],
      "env": {
        "AEGIS_JUDGE_PROVIDER": "anthropic",
        "AEGIS_JUDGE_API_KEY": "sk-ant-...",
        "AEGIS_JUDGE_POLICY": "balanced",
        "AEGIS_VERIFY_CITATIONS": "crossref"
      }
    }
  }
}

3. TypeScript SDK

Embed inside inference gateways, proxy routers, or API middleware:

import { evaluateOutput } from "aletheia-aegis";

const assessment = evaluateOutput({
  response: generatedTokens,
  userPrompt: userQuery,
  locale: "US"
});

if (assessment.verdict === "BLOCK") {
  metrics.increment("safety.hard_block", { signature: assessment.findings[0].signature });
  throw new SecurityPolicyException("Generation blocked: " + assessment.explanation);
}

if (assessment.verdict === "FLAG") {
  auditPipeline.logEvent({ findings: assessment.findings, latencyMs: assessment.latencyMs });
}

MCP tools

Six tools, four resources, one prompt template.

Tool

Purpose

aegis_check_output

Core inspection. Returns verdict (ALLOW, FLAG, BLOCK), findings, risk score, latency. Deterministic and offline by default.

aegis_verify_citations

Resolves DOIs, arXiv IDs, PMIDs against public registries. Reports status without changing verdicts.

aegis_run_eval

Runs the local eval harness against 215 labeled cases, or classifies an incident JSONL file.

aegis_classify_incident

Categorizes incident reports against the Aletheia taxonomy.

aegis_list_signatures

Metadata, maturity, and mandates for all nine signatures.

aegis_get_telemetry

Stage latencies, judge usage, token counts, cost basis, override stats.

Resources: aegis://signatures/all, aegis://telemetry/summary, aegis://telemetry/audit-log, aegis://eval/last-scorecard. Prompt: aegis_output_review, which guides a model to remediate flagged outputs.


Configuration

Variable

Purpose

Default

AEGIS_BLOCK_CHECKS

Check IDs to elevate from FLAG to BLOCK

Unset

AEGIS_LOCALE

Crisis lifeline localization (US, GB, IE, CA, AU, NZ, IN)

US

AEGIS_METRICS_LOG

Path to append-only JSONL metrics file

Off

AEGIS_JUDGE_PROVIDER

Tier-2 judge (anthropic, openai, google, openai-compatible)

Off

AEGIS_JUDGE_API_KEY

API key for the judge provider

Unset

AEGIS_JUDGE_MODEL

Judge model identifier

Provider default

AEGIS_JUDGE_POLICY

balanced (protects S6/S3) or strict (joins all flags)

balanced

AEGIS_VERIFY_CITATIONS

Set to crossref to enable scholarly lookups

Off

AEGIS_DEBUG_LOG

Local debug file (captures payload text, offline use only)

Off


Boundaries and threat model

Transparency on limits is part of the design:

  • Deterministic pre-filter, not a semantic parser. Novel or deliberately obfuscated paraphrases can evade pattern heuristics. Aegis catches the common and severe classes at microsecond cost, so downstream systems can focus on edge cases.

  • Prose credential screening (S3). To avoid false alarms on ordinary conversation, credential checks require non-word or complex token characteristics. Single dictionary words ("your password is password") deliberately pass. Cards require valid brand prefixes and Luhn checks. Bank accounts require banking context, so utility bills and gym numbers are not blocked.

  • Life safety (S6). Strict verb-preposition pairing keeps benign de-escalation ("sit on the platform bench while you wait") passing with supportive resources, while lethal placements ("sit on the train tracks") block. English-first, with core French, German, and Spanish intent statements.

  • Citation scope (S1). Crossref verifies scholarly works (DOI, arXiv, PMID). Legal case citations retain their S1 warning by design; court registries are outside Crossref.

  • Single-turn scope (S8). Aegis operates on individual prompt-response pairs. Multi-turn erosion requires session-level auditing, which is the planned session auditor (see ROADMAP.md).


Status and roadmap

Current: v0.3.1. Public release. Deterministic engine, optional judge, Crossref verification, MCP server, and SDK are stable. S4 remains experimental.

Next (full technical plan in ROADMAP.md):

  • Streaming token/chunk inspection and framework adapters (v0.4.0)

  • Session auditor for S8 multi-turn erosion

  • Expanded non-English coverage for S6

  • Broader held-out eval sets, with sampling methodology documented in repo


Contributing

Contributions, new evaluation cases, and issue reports are welcome. See CONTRIBUTING.md for local setup, offline test commands, and pull request guidelines. Please include a redacted reproduction case for any bypass report—never a live credential. For sensitive disclosures, see SECURITY.md.


Tests

Everything runs offline:

npm install
npm run build              # Compile TypeScript (tsc)
npm test                   # Core unit checks + eval assertions (45 checks)
npm run test:judge         # Model judge, security, ReDoS tests (123 checks)
npm run test:mcp           # MCP stdio smoke test (13 checks)
npm run test:mcp:adversarial # MCP stdio protocol edges, file sandbox, 60 concurrent calls (14 checks)
npm run test:stress        # Async re-entrancy: 200 interleaved judge/Crossref checks vs a sequential run
npm run test:leak          # Zero-leak PII/secret verification
npm run test:fp            # False-positive sweep on benign discourse (90 cases)
npm run eval               # Full 215-case benchmark (100 percent pass)
npm run eval:redteam       # Adversarial paraphrase suite (90.9 percent catch)
npm run eval:heldout:judge # Offline replay of held-out batches 10-11
npm run benchmark          # 10,000-iteration latency benchmark

Author and citation

Aletheia Aegis is authored by Vikas Shivpuriya as part of the Aletheia AI Safety Research Core.

@software{shivpuriya2026aegis,
  author       = {Vikas Shivpuriya},
  title        = {Aletheia Aegis: Inference-Time Output Enforcement for Autonomous Agents},
  year         = {2026},
  publisher    = {GitHub},
  version      = {0.3.1},
  url          = {https://github.com/vikasny30/aletheia-aegis}
}

License

Copyright 2026 Vikas Shivpuriya. Released under the Apache License, Version 2.0.

Available Tools

6 tools
aegis_check_outputA

Check a model response before it reaches the user. Runs the deterministic output guard across S1 (ungrounded confidence), S2a (unverified identity grants), S3-output (PII/secrets in the response), S4 (literal-trap heuristic, experimental), S5 (high-stakes advice without deferral), S6 (crisis/vulnerability signals), and S7 (institutional amplification). Returns ALLOW, FLAG, or BLOCK with findings, evidence, and remediation. Pass user_prompt when available: S2a, S4 and S6 need it for their main checks. By default it runs offline pattern detectors only (sub-millisecond, no network). If the operator has configured a model judge (AEGIS_JUDGE_PROVIDER plus their own API key), the reply is also reviewed by that model, which catches far more failures; the result's mode and judge fields say what ran.

Inputs: response (required), judge, locale, context, +2 more.

aegis_classify_incidentA

Classify incident text against the paper's keyword vocabulary (Appendix C): returns a per-signature confidence score (min(1.0, hits x 0.4), threshold 0.3) and the matched keywords. Offline annotation tool for corpus work; it classifies incident reports, not model outputs.

Inputs: text (required).

aegis_get_telemetryA

Live telemetry: evaluation counts by verdict, flag/block rates, latency percentiles, findings by signature and check, and measurement: per-stage latency (patterns, judge, Crossref), judge usage (calls, cache hits, errors, skips, tokens, cost estimate when prices are configured), Crossref outcomes, and judge overrides by signature. Counts and timings only: the audit log and metrics never store response text.

Inputs: auditLogLimit.

aegis_list_signaturesA

List all nine Aletheia signatures with what Aegis checks for each, what stays with aletheia-mcp (S2b, action-side S3), and what is deferred to the planned session auditor (S8).

Inputs: no named parameters.

aegis_run_evalA

Score the guard. Mode 'guard' (default) runs the bundled labeled case set through aegis_check_output and returns a per-signature scorecard with detection rates, false positives, and latency. Mode 'corpus' runs the paper's keyword classifier over a JSONL incident file (default: the bundled sample) and compares the distribution with the paper's published §3.3 totals.

Inputs: mode, cases_file, corpus_file.

aegis_verify_citationsA

Opt-in citation verification, separate from the guard. Resolves DOI, arXiv, and PMID identifiers found in the text against their public resolvers (doi.org, arxiv.org, NCBI E-utilities) and reports verified / not_found / unverifiable / unsupported per citation. Case citations and 'et al.' references are unsupported — no public resolver can check them. This tool makes network requests; aegis_check_output never does. An existing identifier is not a true claim — verification answers only 'does this identifier resolve?'.

Inputs: text (required), timeout_ms.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4/5.0

    Scored across 6 tools

    Disambiguation5/5

    Each tool targets a distinct function: signature reference (list_signatures), offline incident annotation (classify_incident), runtime guarding (check_output), citation resolution (verify_citations), scoring (run_eval), and metrics (get_telemetry). The descriptions explicitly disambiguate the closest pairs, e.g. classify_incident vs check_output ('classifies incident reports, not model outputs') and verify_citations vs check_output ('makes network requests; aegis_check_output never does'). Minor conceptual overlap between classify_incident and run_eval's corpus mode is clarified by scope (single text vs batch eval).

    Naming Consistency5/5

    All names follow a uniform aegis_verb_noun snake_case pattern: list_signatures, classify_incident, check_output, verify_citations, run_eval, get_telemetry. Verbs are consistently action-oriented and nouns are concise. No mixed conventions or casing deviations.

    Tool Count5/5

    Six tools is well within the ideal 3-15 range and each maps to a necessary capability: reference, annotation, guarding, citation checking, evaluation, and telemetry. No tool appears redundant or filler.

    Completeness4/5

    Core lifecycle is covered: inspect signatures, check outputs, verify citations, evaluate the guard, and monitor telemetry, with incident classification for corpus work. Minor gaps remain, such as no tool to retrieve audit log entries (referenced as existing but never text-storing) and no explicit bulk/batch check endpoint beyond run_eval's labeled set. Deferred items (S2b, action-side S3, S8 auditor) are deliberately out of scope per the descriptions.

    Maintenance

    ActivityNo data
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides real-time content security for large language models by identifying and intercepting risks across compliance, ethics, and safety dimensions. It enables secure input and output monitoring through a customizable policy engine using an SSE-based interface.
      1
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables agents to screen inputs, tool arguments, and retrieved documents for prompt injection, jailbreak, privilege escalation, tool coercion, exfiltration, and PII, returning structured allow/refuse/sanitize verdicts with masked redactions. Runs fully offline and deterministically with no model calls, network access, or third-party dependencies, exposing screening, redaction, and moderation tools over the Streamable HTTP transport.
      MIT